core/str/mod.rs
1//! String manipulation.
2//!
3//! For more details, see the [`std::str`] module.
4//!
5//! [`std::str`]: ../../std/str/index.html
6
7#![stable(feature = "rust1", since = "1.0.0")]
8
9mod converts;
10mod count;
11mod error;
12mod iter;
13mod traits;
14mod validations;
15
16#[cfg(not(feature = "ferrocene_subset"))]
17use self::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
18#[cfg(not(feature = "ferrocene_subset"))]
19use crate::char::{self, EscapeDebugExtArgs};
20#[cfg(not(feature = "ferrocene_subset"))]
21use crate::ops::Range;
22#[cfg(not(feature = "ferrocene_subset"))]
23use crate::slice::{self, SliceIndex};
24#[cfg(not(feature = "ferrocene_subset"))]
25use crate::ub_checks::assert_unsafe_precondition;
26#[cfg(not(feature = "ferrocene_subset"))]
27use crate::{ascii, mem};
28
29// Ferrocene addition: imports for certified subset
30#[cfg(feature = "ferrocene_subset")]
31#[rustfmt::skip]
32use {
33 self::pattern::{Pattern, ReverseSearcher, Searcher},
34 crate::{char, mem, slice::SliceIndex},
35};
36
37pub mod pattern;
38
39mod lossy;
40#[unstable(feature = "str_from_raw_parts", issue = "119206")]
41pub use converts::{from_raw_parts, from_raw_parts_mut};
42#[stable(feature = "rust1", since = "1.0.0")]
43pub use converts::{from_utf8, from_utf8_unchecked};
44#[stable(feature = "str_mut_extras", since = "1.20.0")]
45pub use converts::{from_utf8_mut, from_utf8_unchecked_mut};
46#[stable(feature = "rust1", since = "1.0.0")]
47#[cfg(not(feature = "ferrocene_subset"))]
48pub use error::{ParseBoolError, Utf8Error};
49#[stable(feature = "encode_utf16", since = "1.8.0")]
50#[cfg(not(feature = "ferrocene_subset"))]
51pub use iter::EncodeUtf16;
52#[stable(feature = "rust1", since = "1.0.0")]
53#[allow(deprecated)]
54#[cfg(not(feature = "ferrocene_subset"))]
55pub use iter::LinesAny;
56#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
57#[cfg(not(feature = "ferrocene_subset"))]
58pub use iter::SplitAsciiWhitespace;
59#[stable(feature = "split_inclusive", since = "1.51.0")]
60pub use iter::SplitInclusive;
61#[stable(feature = "rust1", since = "1.0.0")]
62#[cfg(not(feature = "ferrocene_subset"))]
63pub use iter::{Bytes, CharIndices, Chars, Lines, SplitWhitespace};
64#[stable(feature = "str_escape", since = "1.34.0")]
65#[cfg(not(feature = "ferrocene_subset"))]
66pub use iter::{EscapeDebug, EscapeDefault, EscapeUnicode};
67#[stable(feature = "str_match_indices", since = "1.5.0")]
68#[cfg(not(feature = "ferrocene_subset"))]
69pub use iter::{MatchIndices, RMatchIndices};
70#[cfg(not(feature = "ferrocene_subset"))]
71use iter::{MatchIndicesInternal, MatchesInternal, SplitInternal, SplitNInternal};
72#[stable(feature = "str_matches", since = "1.2.0")]
73#[cfg(not(feature = "ferrocene_subset"))]
74pub use iter::{Matches, RMatches};
75#[stable(feature = "rust1", since = "1.0.0")]
76#[cfg(not(feature = "ferrocene_subset"))]
77pub use iter::{RSplit, RSplitTerminator, Split, SplitTerminator};
78#[stable(feature = "rust1", since = "1.0.0")]
79#[cfg(not(feature = "ferrocene_subset"))]
80pub use iter::{RSplitN, SplitN};
81#[stable(feature = "utf8_chunks", since = "1.79.0")]
82#[cfg(not(feature = "ferrocene_subset"))]
83pub use lossy::{Utf8Chunk, Utf8Chunks};
84#[stable(feature = "rust1", since = "1.0.0")]
85pub use traits::FromStr;
86#[unstable(feature = "str_internals", issue = "none")]
87pub use validations::{next_code_point, utf8_char_width};
88
89#[stable(feature = "rust1", since = "1.0.0")]
90#[cfg(feature = "ferrocene_subset")]
91#[rustfmt::skip]
92pub use {
93 error::Utf8Error,
94 iter::{Bytes, CharIndices, Chars},
95};
96
97#[cfg(feature = "ferrocene_subset")]
98#[rustfmt::skip]
99use iter::SplitInternal;
100
101#[inline(never)]
102#[cold]
103#[track_caller]
104#[rustc_allow_const_fn_unstable(const_eval_select)]
105#[cfg(not(panic = "immediate-abort"))]
106const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
107 crate::intrinsics::const_eval_select((s, begin, end), slice_error_fail_ct, slice_error_fail_rt)
108}
109
110#[cfg(panic = "immediate-abort")]
111#[cfg(not(feature = "ferrocene_subset"))]
112const fn slice_error_fail(s: &str, begin: usize, end: usize) -> ! {
113 slice_error_fail_ct(s, begin, end)
114}
115
116#[track_caller]
117#[ferrocene::annotation("Cannot be covered as this only runs during compilation.")]
118const fn slice_error_fail_ct(_: &str, _: usize, _: usize) -> ! {
119 panic!("failed to slice string");
120}
121
122#[track_caller]
123fn slice_error_fail_rt(s: &str, begin: usize, end: usize) -> ! {
124 const MAX_DISPLAY_LENGTH: usize = 256;
125 let trunc_len = s.floor_char_boundary(MAX_DISPLAY_LENGTH);
126 let s_trunc = &s[..trunc_len];
127 let ellipsis = if trunc_len < s.len() { "[...]" } else { "" };
128
129 // 1. out of bounds
130 if begin > s.len() || end > s.len() {
131 let oob_index = if begin > s.len() { begin } else { end };
132 panic!("byte index {oob_index} is out of bounds of `{s_trunc}`{ellipsis}");
133 }
134
135 // 2. begin <= end
136 assert!(
137 begin <= end,
138 "begin <= end ({} <= {}) when slicing `{}`{}",
139 begin,
140 end,
141 s_trunc,
142 ellipsis
143 );
144
145 // 3. character boundary
146 let index = if !s.is_char_boundary(begin) { begin } else { end };
147 // find the character
148 let char_start = s.floor_char_boundary(index);
149 // `char_start` must be less than len and a char boundary
150 let ch = s[char_start..].chars().next().unwrap();
151 let char_range = char_start..char_start + ch.len_utf8();
152 panic!(
153 "byte index {} is not a char boundary; it is inside {:?} (bytes {:?}) of `{}`{}",
154 index, ch, char_range, s_trunc, ellipsis
155 );
156}
157
158impl str {
159 /// Returns the length of `self`.
160 ///
161 /// This length is in bytes, not [`char`]s or graphemes. In other words,
162 /// it might not be what a human considers the length of the string.
163 ///
164 /// [`char`]: prim@char
165 ///
166 /// # Examples
167 ///
168 /// ```
169 /// let len = "foo".len();
170 /// assert_eq!(3, len);
171 ///
172 /// assert_eq!("ƒoo".len(), 4); // fancy f!
173 /// assert_eq!("ƒoo".chars().count(), 3);
174 /// ```
175 #[stable(feature = "rust1", since = "1.0.0")]
176 #[rustc_const_stable(feature = "const_str_len", since = "1.39.0")]
177 #[rustc_diagnostic_item = "str_len"]
178 #[rustc_no_implicit_autorefs]
179 #[must_use]
180 #[inline]
181 pub const fn len(&self) -> usize {
182 self.as_bytes().len()
183 }
184
185 /// Returns `true` if `self` has a length of zero bytes.
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// let s = "";
191 /// assert!(s.is_empty());
192 ///
193 /// let s = "not empty";
194 /// assert!(!s.is_empty());
195 /// ```
196 #[stable(feature = "rust1", since = "1.0.0")]
197 #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")]
198 #[rustc_no_implicit_autorefs]
199 #[must_use]
200 #[inline]
201 pub const fn is_empty(&self) -> bool {
202 self.len() == 0
203 }
204
205 /// Converts a slice of bytes to a string slice.
206 ///
207 /// A string slice ([`&str`]) is made of bytes ([`u8`]), and a byte slice
208 /// ([`&[u8]`][byteslice]) is made of bytes, so this function converts between
209 /// the two. Not all byte slices are valid string slices, however: [`&str`] requires
210 /// that it is valid UTF-8. `from_utf8()` checks to ensure that the bytes are valid
211 /// UTF-8, and then does the conversion.
212 ///
213 /// [`&str`]: str
214 /// [byteslice]: prim@slice
215 ///
216 /// If you are sure that the byte slice is valid UTF-8, and you don't want to
217 /// incur the overhead of the validity check, there is an unsafe version of
218 /// this function, [`from_utf8_unchecked`], which has the same
219 /// behavior but skips the check.
220 ///
221 /// If you need a `String` instead of a `&str`, consider
222 /// [`String::from_utf8`][string].
223 ///
224 /// [string]: ../std/string/struct.String.html#method.from_utf8
225 ///
226 /// Because you can stack-allocate a `[u8; N]`, and you can take a
227 /// [`&[u8]`][byteslice] of it, this function is one way to have a
228 /// stack-allocated string. There is an example of this in the
229 /// examples section below.
230 ///
231 /// [byteslice]: slice
232 ///
233 /// # Errors
234 ///
235 /// Returns `Err` if the slice is not UTF-8 with a description as to why the
236 /// provided slice is not UTF-8.
237 ///
238 /// # Examples
239 ///
240 /// Basic usage:
241 ///
242 /// ```
243 /// // some bytes, in a vector
244 /// let sparkle_heart = vec![240, 159, 146, 150];
245 ///
246 /// // We can use the ? (try) operator to check if the bytes are valid
247 /// let sparkle_heart = str::from_utf8(&sparkle_heart)?;
248 ///
249 /// assert_eq!("💖", sparkle_heart);
250 /// # Ok::<_, std::str::Utf8Error>(())
251 /// ```
252 ///
253 /// Incorrect bytes:
254 ///
255 /// ```
256 /// // some invalid bytes, in a vector
257 /// let sparkle_heart = vec![0, 159, 146, 150];
258 ///
259 /// assert!(str::from_utf8(&sparkle_heart).is_err());
260 /// ```
261 ///
262 /// See the docs for [`Utf8Error`] for more details on the kinds of
263 /// errors that can be returned.
264 ///
265 /// A "stack allocated string":
266 ///
267 /// ```
268 /// // some bytes, in a stack-allocated array
269 /// let sparkle_heart = [240, 159, 146, 150];
270 ///
271 /// // We know these bytes are valid, so just use `unwrap()`.
272 /// let sparkle_heart: &str = str::from_utf8(&sparkle_heart).unwrap();
273 ///
274 /// assert_eq!("💖", sparkle_heart);
275 /// ```
276 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
277 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
278 #[rustc_diagnostic_item = "str_inherent_from_utf8"]
279 pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
280 converts::from_utf8(v)
281 }
282
283 /// Converts a mutable slice of bytes to a mutable string slice.
284 ///
285 /// # Examples
286 ///
287 /// Basic usage:
288 ///
289 /// ```
290 /// // "Hello, Rust!" as a mutable vector
291 /// let mut hellorust = vec![72, 101, 108, 108, 111, 44, 32, 82, 117, 115, 116, 33];
292 ///
293 /// // As we know these bytes are valid, we can use `unwrap()`
294 /// let outstr = str::from_utf8_mut(&mut hellorust).unwrap();
295 ///
296 /// assert_eq!("Hello, Rust!", outstr);
297 /// ```
298 ///
299 /// Incorrect bytes:
300 ///
301 /// ```
302 /// // Some invalid bytes in a mutable vector
303 /// let mut invalid = vec![128, 223];
304 ///
305 /// assert!(str::from_utf8_mut(&mut invalid).is_err());
306 /// ```
307 /// See the docs for [`Utf8Error`] for more details on the kinds of
308 /// errors that can be returned.
309 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
310 #[rustc_const_stable(feature = "const_str_from_utf8", since = "1.87.0")]
311 #[rustc_diagnostic_item = "str_inherent_from_utf8_mut"]
312 pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
313 converts::from_utf8_mut(v)
314 }
315
316 /// Converts a slice of bytes to a string slice without checking
317 /// that the string contains valid UTF-8.
318 ///
319 /// See the safe version, [`from_utf8`], for more information.
320 ///
321 /// # Safety
322 ///
323 /// The bytes passed in must be valid UTF-8.
324 ///
325 /// # Examples
326 ///
327 /// Basic usage:
328 ///
329 /// ```
330 /// // some bytes, in a vector
331 /// let sparkle_heart = vec![240, 159, 146, 150];
332 ///
333 /// let sparkle_heart = unsafe {
334 /// str::from_utf8_unchecked(&sparkle_heart)
335 /// };
336 ///
337 /// assert_eq!("💖", sparkle_heart);
338 /// ```
339 #[inline]
340 #[must_use]
341 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
342 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
343 #[rustc_diagnostic_item = "str_inherent_from_utf8_unchecked"]
344 pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
345 // SAFETY: converts::from_utf8_unchecked has the same safety requirements as this function.
346 unsafe { converts::from_utf8_unchecked(v) }
347 }
348
349 /// Converts a slice of bytes to a string slice without checking
350 /// that the string contains valid UTF-8; mutable version.
351 ///
352 /// See the immutable version, [`from_utf8_unchecked()`] for documentation and safety requirements.
353 ///
354 /// # Examples
355 ///
356 /// Basic usage:
357 ///
358 /// ```
359 /// let mut heart = vec![240, 159, 146, 150];
360 /// let heart = unsafe { str::from_utf8_unchecked_mut(&mut heart) };
361 ///
362 /// assert_eq!("💖", heart);
363 /// ```
364 #[inline]
365 #[must_use]
366 #[stable(feature = "inherent_str_constructors", since = "1.87.0")]
367 #[rustc_const_stable(feature = "inherent_str_constructors", since = "1.87.0")]
368 #[rustc_diagnostic_item = "str_inherent_from_utf8_unchecked_mut"]
369 pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
370 // SAFETY: converts::from_utf8_unchecked_mut has the same safety requirements as this function.
371 unsafe { converts::from_utf8_unchecked_mut(v) }
372 }
373
374 /// Checks that `index`-th byte is the first byte in a UTF-8 code point
375 /// sequence or the end of the string.
376 ///
377 /// The start and end of the string (when `index == self.len()`) are
378 /// considered to be boundaries.
379 ///
380 /// Returns `false` if `index` is greater than `self.len()`.
381 ///
382 /// # Examples
383 ///
384 /// ```
385 /// let s = "Löwe 老虎 Léopard";
386 /// assert!(s.is_char_boundary(0));
387 /// // start of `老`
388 /// assert!(s.is_char_boundary(6));
389 /// assert!(s.is_char_boundary(s.len()));
390 ///
391 /// // second byte of `ö`
392 /// assert!(!s.is_char_boundary(2));
393 ///
394 /// // third byte of `老`
395 /// assert!(!s.is_char_boundary(8));
396 /// ```
397 #[must_use]
398 #[stable(feature = "is_char_boundary", since = "1.9.0")]
399 #[rustc_const_stable(feature = "const_is_char_boundary", since = "1.86.0")]
400 #[inline]
401 pub const fn is_char_boundary(&self, index: usize) -> bool {
402 // 0 is always ok.
403 // Test for 0 explicitly so that it can optimize out the check
404 // easily and skip reading string data for that case.
405 // Note that optimizing `self.get(..index)` relies on this.
406 if index == 0 {
407 return true;
408 }
409
410 if index >= self.len() {
411 // For `true` we have two options:
412 //
413 // - index == self.len()
414 // Empty strings are valid, so return true
415 // - index > self.len()
416 // In this case return false
417 //
418 // The check is placed exactly here, because it improves generated
419 // code on higher opt-levels. See PR #84751 for more details.
420 index == self.len()
421 } else {
422 self.as_bytes()[index].is_utf8_char_boundary()
423 }
424 }
425
426 /// Finds the closest `x` not exceeding `index` where [`is_char_boundary(x)`] is `true`.
427 ///
428 /// This method can help you truncate a string so that it's still valid UTF-8, but doesn't
429 /// exceed a given number of bytes. Note that this is done purely at the character level
430 /// and can still visually split graphemes, even though the underlying characters aren't
431 /// split. For example, the emoji 🧑🔬 (scientist) could be split so that the string only
432 /// includes 🧑 (person) instead.
433 ///
434 /// [`is_char_boundary(x)`]: Self::is_char_boundary
435 ///
436 /// # Examples
437 ///
438 /// ```
439 /// let s = "❤️🧡💛💚💙💜";
440 /// assert_eq!(s.len(), 26);
441 /// assert!(!s.is_char_boundary(13));
442 ///
443 /// let closest = s.floor_char_boundary(13);
444 /// assert_eq!(closest, 10);
445 /// assert_eq!(&s[..closest], "❤️🧡");
446 /// ```
447 #[stable(feature = "round_char_boundary", since = "1.91.0")]
448 #[rustc_const_stable(feature = "round_char_boundary", since = "1.91.0")]
449 #[inline]
450 pub const fn floor_char_boundary(&self, index: usize) -> usize {
451 if index >= self.len() {
452 self.len()
453 } else {
454 let mut i = index;
455 while i > 0 {
456 if self.as_bytes()[i].is_utf8_char_boundary() {
457 break;
458 }
459 i -= 1;
460 }
461
462 // The character boundary will be within four bytes of the index
463 debug_assert!(i >= index.saturating_sub(3));
464
465 i
466 }
467 }
468
469 /// Finds the closest `x` not below `index` where [`is_char_boundary(x)`] is `true`.
470 ///
471 /// If `index` is greater than the length of the string, this returns the length of the string.
472 ///
473 /// This method is the natural complement to [`floor_char_boundary`]. See that method
474 /// for more details.
475 ///
476 /// [`floor_char_boundary`]: str::floor_char_boundary
477 /// [`is_char_boundary(x)`]: Self::is_char_boundary
478 ///
479 /// # Examples
480 ///
481 /// ```
482 /// let s = "❤️🧡💛💚💙💜";
483 /// assert_eq!(s.len(), 26);
484 /// assert!(!s.is_char_boundary(13));
485 ///
486 /// let closest = s.ceil_char_boundary(13);
487 /// assert_eq!(closest, 14);
488 /// assert_eq!(&s[..closest], "❤️🧡💛");
489 /// ```
490 #[stable(feature = "round_char_boundary", since = "1.91.0")]
491 #[rustc_const_stable(feature = "round_char_boundary", since = "1.91.0")]
492 #[inline]
493 #[cfg(not(feature = "ferrocene_subset"))]
494 pub const fn ceil_char_boundary(&self, index: usize) -> usize {
495 if index >= self.len() {
496 self.len()
497 } else {
498 let mut i = index;
499 while i < self.len() {
500 if self.as_bytes()[i].is_utf8_char_boundary() {
501 break;
502 }
503 i += 1;
504 }
505
506 // The character boundary will be within four bytes of the index
507 debug_assert!(i <= index + 3);
508
509 i
510 }
511 }
512
513 /// Converts a string slice to a byte slice. To convert the byte slice back
514 /// into a string slice, use the [`from_utf8`] function.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// let bytes = "bors".as_bytes();
520 /// assert_eq!(b"bors", bytes);
521 /// ```
522 #[stable(feature = "rust1", since = "1.0.0")]
523 #[rustc_const_stable(feature = "str_as_bytes", since = "1.39.0")]
524 #[must_use]
525 #[inline(always)]
526 #[allow(unused_attributes)]
527 pub const fn as_bytes(&self) -> &[u8] {
528 // SAFETY: const sound because we transmute two types with the same layout
529 unsafe { mem::transmute(self) }
530 }
531
532 /// Converts a mutable string slice to a mutable byte slice.
533 ///
534 /// # Safety
535 ///
536 /// The caller must ensure that the content of the slice is valid UTF-8
537 /// before the borrow ends and the underlying `str` is used.
538 ///
539 /// Use of a `str` whose contents are not valid UTF-8 is undefined behavior.
540 ///
541 /// # Examples
542 ///
543 /// Basic usage:
544 ///
545 /// ```
546 /// let mut s = String::from("Hello");
547 /// let bytes = unsafe { s.as_bytes_mut() };
548 ///
549 /// assert_eq!(b"Hello", bytes);
550 /// ```
551 ///
552 /// Mutability:
553 ///
554 /// ```
555 /// let mut s = String::from("🗻∈🌏");
556 ///
557 /// unsafe {
558 /// let bytes = s.as_bytes_mut();
559 ///
560 /// bytes[0] = 0xF0;
561 /// bytes[1] = 0x9F;
562 /// bytes[2] = 0x8D;
563 /// bytes[3] = 0x94;
564 /// }
565 ///
566 /// assert_eq!("🍔∈🌏", s);
567 /// ```
568 #[stable(feature = "str_mut_extras", since = "1.20.0")]
569 #[rustc_const_stable(feature = "const_str_as_mut", since = "1.83.0")]
570 #[must_use]
571 #[inline(always)]
572 pub const unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
573 // SAFETY: the cast from `&str` to `&[u8]` is safe since `str`
574 // has the same layout as `&[u8]` (only std can make this guarantee).
575 // The pointer dereference is safe since it comes from a mutable reference which
576 // is guaranteed to be valid for writes.
577 unsafe { &mut *(self as *mut str as *mut [u8]) }
578 }
579
580 /// Converts a string slice to a raw pointer.
581 ///
582 /// As string slices are a slice of bytes, the raw pointer points to a
583 /// [`u8`]. This pointer will be pointing to the first byte of the string
584 /// slice.
585 ///
586 /// The caller must ensure that the returned pointer is never written to.
587 /// If you need to mutate the contents of the string slice, use [`as_mut_ptr`].
588 ///
589 /// [`as_mut_ptr`]: str::as_mut_ptr
590 ///
591 /// # Examples
592 ///
593 /// ```
594 /// let s = "Hello";
595 /// let ptr = s.as_ptr();
596 /// ```
597 #[stable(feature = "rust1", since = "1.0.0")]
598 #[rustc_const_stable(feature = "rustc_str_as_ptr", since = "1.32.0")]
599 #[rustc_never_returns_null_ptr]
600 #[rustc_as_ptr]
601 #[must_use]
602 #[inline(always)]
603 pub const fn as_ptr(&self) -> *const u8 {
604 self as *const str as *const u8
605 }
606
607 /// Converts a mutable string slice to a raw pointer.
608 ///
609 /// As string slices are a slice of bytes, the raw pointer points to a
610 /// [`u8`]. This pointer will be pointing to the first byte of the string
611 /// slice.
612 ///
613 /// It is your responsibility to make sure that the string slice only gets
614 /// modified in a way that it remains valid UTF-8.
615 #[stable(feature = "str_as_mut_ptr", since = "1.36.0")]
616 #[rustc_const_stable(feature = "const_str_as_mut", since = "1.83.0")]
617 #[rustc_never_returns_null_ptr]
618 #[rustc_as_ptr]
619 #[must_use]
620 #[inline(always)]
621 pub const fn as_mut_ptr(&mut self) -> *mut u8 {
622 self as *mut str as *mut u8
623 }
624
625 /// Returns a subslice of `str`.
626 ///
627 /// This is the non-panicking alternative to indexing the `str`. Returns
628 /// [`None`] whenever equivalent indexing operation would panic.
629 ///
630 /// # Examples
631 ///
632 /// ```
633 /// let v = String::from("🗻∈🌏");
634 ///
635 /// assert_eq!(Some("🗻"), v.get(0..4));
636 ///
637 /// // indices not on UTF-8 sequence boundaries
638 /// assert!(v.get(1..).is_none());
639 /// assert!(v.get(..8).is_none());
640 ///
641 /// // out of bounds
642 /// assert!(v.get(..42).is_none());
643 /// ```
644 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
645 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
646 #[inline]
647 #[cfg(not(feature = "ferrocene_subset"))]
648 pub const fn get<I: [const] SliceIndex<str>>(&self, i: I) -> Option<&I::Output> {
649 i.get(self)
650 }
651
652 /// Returns a mutable subslice of `str`.
653 ///
654 /// This is the non-panicking alternative to indexing the `str`. Returns
655 /// [`None`] whenever equivalent indexing operation would panic.
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// let mut v = String::from("hello");
661 /// // correct length
662 /// assert!(v.get_mut(0..5).is_some());
663 /// // out of bounds
664 /// assert!(v.get_mut(..42).is_none());
665 /// assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));
666 ///
667 /// assert_eq!("hello", v);
668 /// {
669 /// let s = v.get_mut(0..2);
670 /// let s = s.map(|s| {
671 /// s.make_ascii_uppercase();
672 /// &*s
673 /// });
674 /// assert_eq!(Some("HE"), s);
675 /// }
676 /// assert_eq!("HEllo", v);
677 /// ```
678 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
679 #[rustc_const_unstable(feature = "const_index", issue = "143775")]
680 #[inline]
681 #[cfg(not(feature = "ferrocene_subset"))]
682 pub const fn get_mut<I: [const] SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output> {
683 i.get_mut(self)
684 }
685
686 /// Returns an unchecked subslice of `str`.
687 ///
688 /// This is the unchecked alternative to indexing the `str`.
689 ///
690 /// # Safety
691 ///
692 /// Callers of this function are responsible that these preconditions are
693 /// satisfied:
694 ///
695 /// * The starting index must not exceed the ending index;
696 /// * Indexes must be within bounds of the original slice;
697 /// * Indexes must lie on UTF-8 sequence boundaries.
698 ///
699 /// Failing that, the returned string slice may reference invalid memory or
700 /// violate the invariants communicated by the `str` type.
701 ///
702 /// # Examples
703 ///
704 /// ```
705 /// let v = "🗻∈🌏";
706 /// unsafe {
707 /// assert_eq!("🗻", v.get_unchecked(0..4));
708 /// assert_eq!("∈", v.get_unchecked(4..7));
709 /// assert_eq!("🌏", v.get_unchecked(7..11));
710 /// }
711 /// ```
712 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
713 #[inline]
714 pub unsafe fn get_unchecked<I: SliceIndex<str>>(&self, i: I) -> &I::Output {
715 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
716 // the slice is dereferenceable because `self` is a safe reference.
717 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
718 unsafe { &*i.get_unchecked(self) }
719 }
720
721 /// Returns a mutable, unchecked subslice of `str`.
722 ///
723 /// This is the unchecked alternative to indexing the `str`.
724 ///
725 /// # Safety
726 ///
727 /// Callers of this function are responsible that these preconditions are
728 /// satisfied:
729 ///
730 /// * The starting index must not exceed the ending index;
731 /// * Indexes must be within bounds of the original slice;
732 /// * Indexes must lie on UTF-8 sequence boundaries.
733 ///
734 /// Failing that, the returned string slice may reference invalid memory or
735 /// violate the invariants communicated by the `str` type.
736 ///
737 /// # Examples
738 ///
739 /// ```
740 /// let mut v = String::from("🗻∈🌏");
741 /// unsafe {
742 /// assert_eq!("🗻", v.get_unchecked_mut(0..4));
743 /// assert_eq!("∈", v.get_unchecked_mut(4..7));
744 /// assert_eq!("🌏", v.get_unchecked_mut(7..11));
745 /// }
746 /// ```
747 #[stable(feature = "str_checked_slicing", since = "1.20.0")]
748 #[inline]
749 #[cfg(not(feature = "ferrocene_subset"))]
750 pub unsafe fn get_unchecked_mut<I: SliceIndex<str>>(&mut self, i: I) -> &mut I::Output {
751 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
752 // the slice is dereferenceable because `self` is a safe reference.
753 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
754 unsafe { &mut *i.get_unchecked_mut(self) }
755 }
756
757 /// Creates a string slice from another string slice, bypassing safety
758 /// checks.
759 ///
760 /// This is generally not recommended, use with caution! For a safe
761 /// alternative see [`str`] and [`Index`].
762 ///
763 /// [`Index`]: crate::ops::Index
764 ///
765 /// This new slice goes from `begin` to `end`, including `begin` but
766 /// excluding `end`.
767 ///
768 /// To get a mutable string slice instead, see the
769 /// [`slice_mut_unchecked`] method.
770 ///
771 /// [`slice_mut_unchecked`]: str::slice_mut_unchecked
772 ///
773 /// # Safety
774 ///
775 /// Callers of this function are responsible that three preconditions are
776 /// satisfied:
777 ///
778 /// * `begin` must not exceed `end`.
779 /// * `begin` and `end` must be byte positions within the string slice.
780 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
781 ///
782 /// # Examples
783 ///
784 /// ```
785 /// let s = "Löwe 老虎 Léopard";
786 ///
787 /// unsafe {
788 /// assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
789 /// }
790 ///
791 /// let s = "Hello, world!";
792 ///
793 /// unsafe {
794 /// assert_eq!("world", s.slice_unchecked(7, 12));
795 /// }
796 /// ```
797 #[stable(feature = "rust1", since = "1.0.0")]
798 #[deprecated(since = "1.29.0", note = "use `get_unchecked(begin..end)` instead")]
799 #[must_use]
800 #[inline]
801 #[cfg(not(feature = "ferrocene_subset"))]
802 pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str {
803 // SAFETY: the caller must uphold the safety contract for `get_unchecked`;
804 // the slice is dereferenceable because `self` is a safe reference.
805 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
806 unsafe { &*(begin..end).get_unchecked(self) }
807 }
808
809 /// Creates a string slice from another string slice, bypassing safety
810 /// checks.
811 ///
812 /// This is generally not recommended, use with caution! For a safe
813 /// alternative see [`str`] and [`IndexMut`].
814 ///
815 /// [`IndexMut`]: crate::ops::IndexMut
816 ///
817 /// This new slice goes from `begin` to `end`, including `begin` but
818 /// excluding `end`.
819 ///
820 /// To get an immutable string slice instead, see the
821 /// [`slice_unchecked`] method.
822 ///
823 /// [`slice_unchecked`]: str::slice_unchecked
824 ///
825 /// # Safety
826 ///
827 /// Callers of this function are responsible that three preconditions are
828 /// satisfied:
829 ///
830 /// * `begin` must not exceed `end`.
831 /// * `begin` and `end` must be byte positions within the string slice.
832 /// * `begin` and `end` must lie on UTF-8 sequence boundaries.
833 #[stable(feature = "str_slice_mut", since = "1.5.0")]
834 #[deprecated(since = "1.29.0", note = "use `get_unchecked_mut(begin..end)` instead")]
835 #[inline]
836 #[cfg(not(feature = "ferrocene_subset"))]
837 pub unsafe fn slice_mut_unchecked(&mut self, begin: usize, end: usize) -> &mut str {
838 // SAFETY: the caller must uphold the safety contract for `get_unchecked_mut`;
839 // the slice is dereferenceable because `self` is a safe reference.
840 // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is.
841 unsafe { &mut *(begin..end).get_unchecked_mut(self) }
842 }
843
844 /// Divides one string slice into two at an index.
845 ///
846 /// The argument, `mid`, should be a byte offset from the start of the
847 /// string. It must also be on the boundary of a UTF-8 code point.
848 ///
849 /// The two slices returned go from the start of the string slice to `mid`,
850 /// and from `mid` to the end of the string slice.
851 ///
852 /// To get mutable string slices instead, see the [`split_at_mut`]
853 /// method.
854 ///
855 /// [`split_at_mut`]: str::split_at_mut
856 ///
857 /// # Panics
858 ///
859 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is past
860 /// the end of the last code point of the string slice. For a non-panicking
861 /// alternative see [`split_at_checked`](str::split_at_checked).
862 ///
863 /// # Examples
864 ///
865 /// ```
866 /// let s = "Per Martin-Löf";
867 ///
868 /// let (first, last) = s.split_at(3);
869 ///
870 /// assert_eq!("Per", first);
871 /// assert_eq!(" Martin-Löf", last);
872 /// ```
873 #[inline]
874 #[must_use]
875 #[stable(feature = "str_split_at", since = "1.4.0")]
876 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
877 #[cfg(not(feature = "ferrocene_subset"))]
878 pub const fn split_at(&self, mid: usize) -> (&str, &str) {
879 match self.split_at_checked(mid) {
880 None => slice_error_fail(self, 0, mid),
881 Some(pair) => pair,
882 }
883 }
884
885 /// Divides one mutable string slice into two at an index.
886 ///
887 /// The argument, `mid`, should be a byte offset from the start of the
888 /// string. It must also be on the boundary of a UTF-8 code point.
889 ///
890 /// The two slices returned go from the start of the string slice to `mid`,
891 /// and from `mid` to the end of the string slice.
892 ///
893 /// To get immutable string slices instead, see the [`split_at`] method.
894 ///
895 /// [`split_at`]: str::split_at
896 ///
897 /// # Panics
898 ///
899 /// Panics if `mid` is not on a UTF-8 code point boundary, or if it is past
900 /// the end of the last code point of the string slice. For a non-panicking
901 /// alternative see [`split_at_mut_checked`](str::split_at_mut_checked).
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// let mut s = "Per Martin-Löf".to_string();
907 /// {
908 /// let (first, last) = s.split_at_mut(3);
909 /// first.make_ascii_uppercase();
910 /// assert_eq!("PER", first);
911 /// assert_eq!(" Martin-Löf", last);
912 /// }
913 /// assert_eq!("PER Martin-Löf", s);
914 /// ```
915 #[inline]
916 #[must_use]
917 #[stable(feature = "str_split_at", since = "1.4.0")]
918 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
919 #[cfg(not(feature = "ferrocene_subset"))]
920 pub const fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str) {
921 // is_char_boundary checks that the index is in [0, .len()]
922 if self.is_char_boundary(mid) {
923 // SAFETY: just checked that `mid` is on a char boundary.
924 unsafe { self.split_at_mut_unchecked(mid) }
925 } else {
926 slice_error_fail(self, 0, mid)
927 }
928 }
929
930 /// Divides one string slice into two at an index.
931 ///
932 /// The argument, `mid`, should be a valid byte offset from the start of the
933 /// string. It must also be on the boundary of a UTF-8 code point. The
934 /// method returns `None` if that’s not the case.
935 ///
936 /// The two slices returned go from the start of the string slice to `mid`,
937 /// and from `mid` to the end of the string slice.
938 ///
939 /// To get mutable string slices instead, see the [`split_at_mut_checked`]
940 /// method.
941 ///
942 /// [`split_at_mut_checked`]: str::split_at_mut_checked
943 ///
944 /// # Examples
945 ///
946 /// ```
947 /// let s = "Per Martin-Löf";
948 ///
949 /// let (first, last) = s.split_at_checked(3).unwrap();
950 /// assert_eq!("Per", first);
951 /// assert_eq!(" Martin-Löf", last);
952 ///
953 /// assert_eq!(None, s.split_at_checked(13)); // Inside “ö”
954 /// assert_eq!(None, s.split_at_checked(16)); // Beyond the string length
955 /// ```
956 #[inline]
957 #[must_use]
958 #[stable(feature = "split_at_checked", since = "1.80.0")]
959 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
960 #[cfg(not(feature = "ferrocene_subset"))]
961 pub const fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)> {
962 // is_char_boundary checks that the index is in [0, .len()]
963 if self.is_char_boundary(mid) {
964 // SAFETY: just checked that `mid` is on a char boundary.
965 Some(unsafe { self.split_at_unchecked(mid) })
966 } else {
967 None
968 }
969 }
970
971 /// Divides one mutable string slice into two at an index.
972 ///
973 /// The argument, `mid`, should be a valid byte offset from the start of the
974 /// string. It must also be on the boundary of a UTF-8 code point. The
975 /// method returns `None` if that’s not the case.
976 ///
977 /// The two slices returned go from the start of the string slice to `mid`,
978 /// and from `mid` to the end of the string slice.
979 ///
980 /// To get immutable string slices instead, see the [`split_at_checked`] method.
981 ///
982 /// [`split_at_checked`]: str::split_at_checked
983 ///
984 /// # Examples
985 ///
986 /// ```
987 /// let mut s = "Per Martin-Löf".to_string();
988 /// if let Some((first, last)) = s.split_at_mut_checked(3) {
989 /// first.make_ascii_uppercase();
990 /// assert_eq!("PER", first);
991 /// assert_eq!(" Martin-Löf", last);
992 /// }
993 /// assert_eq!("PER Martin-Löf", s);
994 ///
995 /// assert_eq!(None, s.split_at_mut_checked(13)); // Inside “ö”
996 /// assert_eq!(None, s.split_at_mut_checked(16)); // Beyond the string length
997 /// ```
998 #[inline]
999 #[must_use]
1000 #[stable(feature = "split_at_checked", since = "1.80.0")]
1001 #[rustc_const_stable(feature = "const_str_split_at", since = "1.86.0")]
1002 #[cfg(not(feature = "ferrocene_subset"))]
1003 pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut str, &mut str)> {
1004 // is_char_boundary checks that the index is in [0, .len()]
1005 if self.is_char_boundary(mid) {
1006 // SAFETY: just checked that `mid` is on a char boundary.
1007 Some(unsafe { self.split_at_mut_unchecked(mid) })
1008 } else {
1009 None
1010 }
1011 }
1012
1013 /// Divides one string slice into two at an index.
1014 ///
1015 /// # Safety
1016 ///
1017 /// The caller must ensure that `mid` is a valid byte offset from the start
1018 /// of the string and falls on the boundary of a UTF-8 code point.
1019 #[inline]
1020 #[cfg(not(feature = "ferrocene_subset"))]
1021 const unsafe fn split_at_unchecked(&self, mid: usize) -> (&str, &str) {
1022 let len = self.len();
1023 let ptr = self.as_ptr();
1024 // SAFETY: caller guarantees `mid` is on a char boundary.
1025 unsafe {
1026 (
1027 from_utf8_unchecked(slice::from_raw_parts(ptr, mid)),
1028 from_utf8_unchecked(slice::from_raw_parts(ptr.add(mid), len - mid)),
1029 )
1030 }
1031 }
1032
1033 /// Divides one string slice into two at an index.
1034 ///
1035 /// # Safety
1036 ///
1037 /// The caller must ensure that `mid` is a valid byte offset from the start
1038 /// of the string and falls on the boundary of a UTF-8 code point.
1039 #[cfg(not(feature = "ferrocene_subset"))]
1040 const unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut str, &mut str) {
1041 let len = self.len();
1042 let ptr = self.as_mut_ptr();
1043 // SAFETY: caller guarantees `mid` is on a char boundary.
1044 unsafe {
1045 (
1046 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr, mid)),
1047 from_utf8_unchecked_mut(slice::from_raw_parts_mut(ptr.add(mid), len - mid)),
1048 )
1049 }
1050 }
1051
1052 /// Returns an iterator over the [`char`]s of a string slice.
1053 ///
1054 /// As a string slice consists of valid UTF-8, we can iterate through a
1055 /// string slice by [`char`]. This method returns such an iterator.
1056 ///
1057 /// It's important to remember that [`char`] represents a Unicode Scalar
1058 /// Value, and might not match your idea of what a 'character' is. Iteration
1059 /// over grapheme clusters may be what you actually want. This functionality
1060 /// is not provided by Rust's standard library, check crates.io instead.
1061 ///
1062 /// # Examples
1063 ///
1064 /// Basic usage:
1065 ///
1066 /// ```
1067 /// let word = "goodbye";
1068 ///
1069 /// let count = word.chars().count();
1070 /// assert_eq!(7, count);
1071 ///
1072 /// let mut chars = word.chars();
1073 ///
1074 /// assert_eq!(Some('g'), chars.next());
1075 /// assert_eq!(Some('o'), chars.next());
1076 /// assert_eq!(Some('o'), chars.next());
1077 /// assert_eq!(Some('d'), chars.next());
1078 /// assert_eq!(Some('b'), chars.next());
1079 /// assert_eq!(Some('y'), chars.next());
1080 /// assert_eq!(Some('e'), chars.next());
1081 ///
1082 /// assert_eq!(None, chars.next());
1083 /// ```
1084 ///
1085 /// Remember, [`char`]s might not match your intuition about characters:
1086 ///
1087 /// [`char`]: prim@char
1088 ///
1089 /// ```
1090 /// let y = "y̆";
1091 ///
1092 /// let mut chars = y.chars();
1093 ///
1094 /// assert_eq!(Some('y'), chars.next()); // not 'y̆'
1095 /// assert_eq!(Some('\u{0306}'), chars.next());
1096 ///
1097 /// assert_eq!(None, chars.next());
1098 /// ```
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 #[inline]
1101 #[rustc_diagnostic_item = "str_chars"]
1102 pub fn chars(&self) -> Chars<'_> {
1103 Chars { iter: self.as_bytes().iter() }
1104 }
1105
1106 /// Returns an iterator over the [`char`]s of a string slice, and their
1107 /// positions.
1108 ///
1109 /// As a string slice consists of valid UTF-8, we can iterate through a
1110 /// string slice by [`char`]. This method returns an iterator of both
1111 /// these [`char`]s, as well as their byte positions.
1112 ///
1113 /// The iterator yields tuples. The position is first, the [`char`] is
1114 /// second.
1115 ///
1116 /// # Examples
1117 ///
1118 /// Basic usage:
1119 ///
1120 /// ```
1121 /// let word = "goodbye";
1122 ///
1123 /// let count = word.char_indices().count();
1124 /// assert_eq!(7, count);
1125 ///
1126 /// let mut char_indices = word.char_indices();
1127 ///
1128 /// assert_eq!(Some((0, 'g')), char_indices.next());
1129 /// assert_eq!(Some((1, 'o')), char_indices.next());
1130 /// assert_eq!(Some((2, 'o')), char_indices.next());
1131 /// assert_eq!(Some((3, 'd')), char_indices.next());
1132 /// assert_eq!(Some((4, 'b')), char_indices.next());
1133 /// assert_eq!(Some((5, 'y')), char_indices.next());
1134 /// assert_eq!(Some((6, 'e')), char_indices.next());
1135 ///
1136 /// assert_eq!(None, char_indices.next());
1137 /// ```
1138 ///
1139 /// Remember, [`char`]s might not match your intuition about characters:
1140 ///
1141 /// [`char`]: prim@char
1142 ///
1143 /// ```
1144 /// let yes = "y̆es";
1145 ///
1146 /// let mut char_indices = yes.char_indices();
1147 ///
1148 /// assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
1149 /// assert_eq!(Some((1, '\u{0306}')), char_indices.next());
1150 ///
1151 /// // note the 3 here - the previous character took up two bytes
1152 /// assert_eq!(Some((3, 'e')), char_indices.next());
1153 /// assert_eq!(Some((4, 's')), char_indices.next());
1154 ///
1155 /// assert_eq!(None, char_indices.next());
1156 /// ```
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 #[inline]
1159 pub fn char_indices(&self) -> CharIndices<'_> {
1160 CharIndices { front_offset: 0, iter: self.chars() }
1161 }
1162
1163 /// Returns an iterator over the bytes of a string slice.
1164 ///
1165 /// As a string slice consists of a sequence of bytes, we can iterate
1166 /// through a string slice by byte. This method returns such an iterator.
1167 ///
1168 /// # Examples
1169 ///
1170 /// ```
1171 /// let mut bytes = "bors".bytes();
1172 ///
1173 /// assert_eq!(Some(b'b'), bytes.next());
1174 /// assert_eq!(Some(b'o'), bytes.next());
1175 /// assert_eq!(Some(b'r'), bytes.next());
1176 /// assert_eq!(Some(b's'), bytes.next());
1177 ///
1178 /// assert_eq!(None, bytes.next());
1179 /// ```
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 #[inline]
1182 pub fn bytes(&self) -> Bytes<'_> {
1183 Bytes(self.as_bytes().iter().copied())
1184 }
1185
1186 /// Splits a string slice by whitespace.
1187 ///
1188 /// The iterator returned will return string slices that are sub-slices of
1189 /// the original string slice, separated by any amount of whitespace.
1190 ///
1191 /// 'Whitespace' is defined according to the terms of the Unicode Derived
1192 /// Core Property `White_Space`. If you only want to split on ASCII whitespace
1193 /// instead, use [`split_ascii_whitespace`].
1194 ///
1195 /// [`split_ascii_whitespace`]: str::split_ascii_whitespace
1196 ///
1197 /// # Examples
1198 ///
1199 /// Basic usage:
1200 ///
1201 /// ```
1202 /// let mut iter = "A few words".split_whitespace();
1203 ///
1204 /// assert_eq!(Some("A"), iter.next());
1205 /// assert_eq!(Some("few"), iter.next());
1206 /// assert_eq!(Some("words"), iter.next());
1207 ///
1208 /// assert_eq!(None, iter.next());
1209 /// ```
1210 ///
1211 /// All kinds of whitespace are considered:
1212 ///
1213 /// ```
1214 /// let mut iter = " Mary had\ta\u{2009}little \n\t lamb".split_whitespace();
1215 /// assert_eq!(Some("Mary"), iter.next());
1216 /// assert_eq!(Some("had"), iter.next());
1217 /// assert_eq!(Some("a"), iter.next());
1218 /// assert_eq!(Some("little"), iter.next());
1219 /// assert_eq!(Some("lamb"), iter.next());
1220 ///
1221 /// assert_eq!(None, iter.next());
1222 /// ```
1223 ///
1224 /// If the string is empty or all whitespace, the iterator yields no string slices:
1225 /// ```
1226 /// assert_eq!("".split_whitespace().next(), None);
1227 /// assert_eq!(" ".split_whitespace().next(), None);
1228 /// ```
1229 #[must_use = "this returns the split string as an iterator, \
1230 without modifying the original"]
1231 #[stable(feature = "split_whitespace", since = "1.1.0")]
1232 #[rustc_diagnostic_item = "str_split_whitespace"]
1233 #[inline]
1234 #[cfg(not(feature = "ferrocene_subset"))]
1235 pub fn split_whitespace(&self) -> SplitWhitespace<'_> {
1236 SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) }
1237 }
1238
1239 /// Splits a string slice by ASCII whitespace.
1240 ///
1241 /// The iterator returned will return string slices that are sub-slices of
1242 /// the original string slice, separated by any amount of ASCII whitespace.
1243 ///
1244 /// This uses the same definition as [`char::is_ascii_whitespace`].
1245 /// To split by Unicode `Whitespace` instead, use [`split_whitespace`].
1246 ///
1247 /// [`split_whitespace`]: str::split_whitespace
1248 ///
1249 /// # Examples
1250 ///
1251 /// Basic usage:
1252 ///
1253 /// ```
1254 /// let mut iter = "A few words".split_ascii_whitespace();
1255 ///
1256 /// assert_eq!(Some("A"), iter.next());
1257 /// assert_eq!(Some("few"), iter.next());
1258 /// assert_eq!(Some("words"), iter.next());
1259 ///
1260 /// assert_eq!(None, iter.next());
1261 /// ```
1262 ///
1263 /// Various kinds of ASCII whitespace are considered
1264 /// (see [`char::is_ascii_whitespace`]):
1265 ///
1266 /// ```
1267 /// let mut iter = " Mary had\ta little \n\t lamb".split_ascii_whitespace();
1268 /// assert_eq!(Some("Mary"), iter.next());
1269 /// assert_eq!(Some("had"), iter.next());
1270 /// assert_eq!(Some("a"), iter.next());
1271 /// assert_eq!(Some("little"), iter.next());
1272 /// assert_eq!(Some("lamb"), iter.next());
1273 ///
1274 /// assert_eq!(None, iter.next());
1275 /// ```
1276 ///
1277 /// If the string is empty or all ASCII whitespace, the iterator yields no string slices:
1278 /// ```
1279 /// assert_eq!("".split_ascii_whitespace().next(), None);
1280 /// assert_eq!(" ".split_ascii_whitespace().next(), None);
1281 /// ```
1282 #[must_use = "this returns the split string as an iterator, \
1283 without modifying the original"]
1284 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
1285 #[inline]
1286 #[cfg(not(feature = "ferrocene_subset"))]
1287 pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_> {
1288 let inner =
1289 self.as_bytes().split(IsAsciiWhitespace).filter(BytesIsNotEmpty).map(UnsafeBytesToStr);
1290 SplitAsciiWhitespace { inner }
1291 }
1292
1293 /// Returns an iterator over the lines of a string, as string slices.
1294 ///
1295 /// Lines are split at line endings that are either newlines (`\n`) or
1296 /// sequences of a carriage return followed by a line feed (`\r\n`).
1297 ///
1298 /// Line terminators are not included in the lines returned by the iterator.
1299 ///
1300 /// Note that any carriage return (`\r`) not immediately followed by a
1301 /// line feed (`\n`) does not split a line. These carriage returns are
1302 /// thereby included in the produced lines.
1303 ///
1304 /// The final line ending is optional. A string that ends with a final line
1305 /// ending will return the same lines as an otherwise identical string
1306 /// without a final line ending.
1307 ///
1308 /// An empty string returns an empty iterator.
1309 ///
1310 /// # Examples
1311 ///
1312 /// Basic usage:
1313 ///
1314 /// ```
1315 /// let text = "foo\r\nbar\n\nbaz\r";
1316 /// let mut lines = text.lines();
1317 ///
1318 /// assert_eq!(Some("foo"), lines.next());
1319 /// assert_eq!(Some("bar"), lines.next());
1320 /// assert_eq!(Some(""), lines.next());
1321 /// // Trailing carriage return is included in the last line
1322 /// assert_eq!(Some("baz\r"), lines.next());
1323 ///
1324 /// assert_eq!(None, lines.next());
1325 /// ```
1326 ///
1327 /// The final line does not require any ending:
1328 ///
1329 /// ```
1330 /// let text = "foo\nbar\n\r\nbaz";
1331 /// let mut lines = text.lines();
1332 ///
1333 /// assert_eq!(Some("foo"), lines.next());
1334 /// assert_eq!(Some("bar"), lines.next());
1335 /// assert_eq!(Some(""), lines.next());
1336 /// assert_eq!(Some("baz"), lines.next());
1337 ///
1338 /// assert_eq!(None, lines.next());
1339 /// ```
1340 ///
1341 /// An empty string returns an empty iterator:
1342 ///
1343 /// ```
1344 /// let text = "";
1345 /// let mut lines = text.lines();
1346 ///
1347 /// assert_eq!(lines.next(), None);
1348 /// ```
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 #[inline]
1351 #[cfg(not(feature = "ferrocene_subset"))]
1352 pub fn lines(&self) -> Lines<'_> {
1353 Lines(self.split_inclusive('\n').map(LinesMap))
1354 }
1355
1356 /// Returns an iterator over the lines of a string.
1357 #[stable(feature = "rust1", since = "1.0.0")]
1358 #[deprecated(since = "1.4.0", note = "use lines() instead now", suggestion = "lines")]
1359 #[inline]
1360 #[allow(deprecated)]
1361 #[cfg(not(feature = "ferrocene_subset"))]
1362 pub fn lines_any(&self) -> LinesAny<'_> {
1363 LinesAny(self.lines())
1364 }
1365
1366 /// Returns an iterator of `u16` over the string encoded
1367 /// as native endian UTF-16 (without byte-order mark).
1368 ///
1369 /// # Examples
1370 ///
1371 /// ```
1372 /// let text = "Zażółć gęślą jaźń";
1373 ///
1374 /// let utf8_len = text.len();
1375 /// let utf16_len = text.encode_utf16().count();
1376 ///
1377 /// assert!(utf16_len <= utf8_len);
1378 /// ```
1379 #[must_use = "this returns the encoded string as an iterator, \
1380 without modifying the original"]
1381 #[stable(feature = "encode_utf16", since = "1.8.0")]
1382 #[cfg(not(feature = "ferrocene_subset"))]
1383 pub fn encode_utf16(&self) -> EncodeUtf16<'_> {
1384 EncodeUtf16 { chars: self.chars(), extra: 0 }
1385 }
1386
1387 /// Returns `true` if the given pattern matches a sub-slice of
1388 /// this string slice.
1389 ///
1390 /// Returns `false` if it does not.
1391 ///
1392 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1393 /// function or closure that determines if a character matches.
1394 ///
1395 /// [`char`]: prim@char
1396 /// [pattern]: self::pattern
1397 ///
1398 /// # Examples
1399 ///
1400 /// ```
1401 /// let bananas = "bananas";
1402 ///
1403 /// assert!(bananas.contains("nana"));
1404 /// assert!(!bananas.contains("apples"));
1405 /// ```
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 #[inline]
1408 #[cfg(not(feature = "ferrocene_subset"))]
1409 pub fn contains<P: Pattern>(&self, pat: P) -> bool {
1410 pat.is_contained_in(self)
1411 }
1412
1413 /// Returns `true` if the given pattern matches a prefix of this
1414 /// string slice.
1415 ///
1416 /// Returns `false` if it does not.
1417 ///
1418 /// The [pattern] can be a `&str`, in which case this function will return true if
1419 /// the `&str` is a prefix of this string slice.
1420 ///
1421 /// The [pattern] can also be a [`char`], a slice of [`char`]s, or a
1422 /// function or closure that determines if a character matches.
1423 /// These will only be checked against the first character of this string slice.
1424 /// Look at the second example below regarding behavior for slices of [`char`]s.
1425 ///
1426 /// [`char`]: prim@char
1427 /// [pattern]: self::pattern
1428 ///
1429 /// # Examples
1430 ///
1431 /// ```
1432 /// let bananas = "bananas";
1433 ///
1434 /// assert!(bananas.starts_with("bana"));
1435 /// assert!(!bananas.starts_with("nana"));
1436 /// ```
1437 ///
1438 /// ```
1439 /// let bananas = "bananas";
1440 ///
1441 /// // Note that both of these assert successfully.
1442 /// assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
1443 /// assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
1444 /// ```
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 #[rustc_diagnostic_item = "str_starts_with"]
1447 pub fn starts_with<P: Pattern>(&self, pat: P) -> bool {
1448 pat.is_prefix_of(self)
1449 }
1450
1451 /// Returns `true` if the given pattern matches a suffix of this
1452 /// string slice.
1453 ///
1454 /// Returns `false` if it does not.
1455 ///
1456 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1457 /// function or closure that determines if a character matches.
1458 ///
1459 /// [`char`]: prim@char
1460 /// [pattern]: self::pattern
1461 ///
1462 /// # Examples
1463 ///
1464 /// ```
1465 /// let bananas = "bananas";
1466 ///
1467 /// assert!(bananas.ends_with("anas"));
1468 /// assert!(!bananas.ends_with("nana"));
1469 /// ```
1470 #[stable(feature = "rust1", since = "1.0.0")]
1471 #[rustc_diagnostic_item = "str_ends_with"]
1472 pub fn ends_with<P: Pattern>(&self, pat: P) -> bool
1473 where
1474 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1475 {
1476 pat.is_suffix_of(self)
1477 }
1478
1479 /// Returns the byte index of the first character of this string slice that
1480 /// matches the pattern.
1481 ///
1482 /// Returns [`None`] if the pattern doesn't match.
1483 ///
1484 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1485 /// function or closure that determines if a character matches.
1486 ///
1487 /// [`char`]: prim@char
1488 /// [pattern]: self::pattern
1489 ///
1490 /// # Examples
1491 ///
1492 /// Simple patterns:
1493 ///
1494 /// ```
1495 /// let s = "Löwe 老虎 Léopard Gepardi";
1496 ///
1497 /// assert_eq!(s.find('L'), Some(0));
1498 /// assert_eq!(s.find('é'), Some(14));
1499 /// assert_eq!(s.find("pard"), Some(17));
1500 /// ```
1501 ///
1502 /// More complex patterns using point-free style and closures:
1503 ///
1504 /// ```
1505 /// let s = "Löwe 老虎 Léopard";
1506 ///
1507 /// assert_eq!(s.find(char::is_whitespace), Some(5));
1508 /// assert_eq!(s.find(char::is_lowercase), Some(1));
1509 /// assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
1510 /// assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));
1511 /// ```
1512 ///
1513 /// Not finding the pattern:
1514 ///
1515 /// ```
1516 /// let s = "Löwe 老虎 Léopard";
1517 /// let x: &[_] = &['1', '2'];
1518 ///
1519 /// assert_eq!(s.find(x), None);
1520 /// ```
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 #[inline]
1523 pub fn find<P: Pattern>(&self, pat: P) -> Option<usize> {
1524 pat.into_searcher(self).next_match().map(|(i, _)| i)
1525 }
1526
1527 /// Returns the byte index for the first character of the last match of the pattern in
1528 /// this string slice.
1529 ///
1530 /// Returns [`None`] if the pattern doesn't match.
1531 ///
1532 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1533 /// function or closure that determines if a character matches.
1534 ///
1535 /// [`char`]: prim@char
1536 /// [pattern]: self::pattern
1537 ///
1538 /// # Examples
1539 ///
1540 /// Simple patterns:
1541 ///
1542 /// ```
1543 /// let s = "Löwe 老虎 Léopard Gepardi";
1544 ///
1545 /// assert_eq!(s.rfind('L'), Some(13));
1546 /// assert_eq!(s.rfind('é'), Some(14));
1547 /// assert_eq!(s.rfind("pard"), Some(24));
1548 /// ```
1549 ///
1550 /// More complex patterns with closures:
1551 ///
1552 /// ```
1553 /// let s = "Löwe 老虎 Léopard";
1554 ///
1555 /// assert_eq!(s.rfind(char::is_whitespace), Some(12));
1556 /// assert_eq!(s.rfind(char::is_lowercase), Some(20));
1557 /// ```
1558 ///
1559 /// Not finding the pattern:
1560 ///
1561 /// ```
1562 /// let s = "Löwe 老虎 Léopard";
1563 /// let x: &[_] = &['1', '2'];
1564 ///
1565 /// assert_eq!(s.rfind(x), None);
1566 /// ```
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 #[inline]
1569 #[cfg(not(feature = "ferrocene_subset"))]
1570 pub fn rfind<P: Pattern>(&self, pat: P) -> Option<usize>
1571 where
1572 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1573 {
1574 pat.into_searcher(self).next_match_back().map(|(i, _)| i)
1575 }
1576
1577 /// Returns an iterator over substrings of this string slice, separated by
1578 /// characters matched by a pattern.
1579 ///
1580 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1581 /// function or closure that determines if a character matches.
1582 ///
1583 /// If there are no matches the full string slice is returned as the only
1584 /// item in the iterator.
1585 ///
1586 /// [`char`]: prim@char
1587 /// [pattern]: self::pattern
1588 ///
1589 /// # Iterator behavior
1590 ///
1591 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1592 /// allows a reverse search and forward/reverse search yields the same
1593 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1594 ///
1595 /// If the pattern allows a reverse search but its results might differ
1596 /// from a forward search, the [`rsplit`] method can be used.
1597 ///
1598 /// [`rsplit`]: str::rsplit
1599 ///
1600 /// # Examples
1601 ///
1602 /// Simple patterns:
1603 ///
1604 /// ```
1605 /// let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
1606 /// assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);
1607 ///
1608 /// let v: Vec<&str> = "".split('X').collect();
1609 /// assert_eq!(v, [""]);
1610 ///
1611 /// let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
1612 /// assert_eq!(v, ["lion", "", "tiger", "leopard"]);
1613 ///
1614 /// let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
1615 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1616 ///
1617 /// let v: Vec<&str> = "AABBCC".split("DD").collect();
1618 /// assert_eq!(v, ["AABBCC"]);
1619 ///
1620 /// let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
1621 /// assert_eq!(v, ["abc", "def", "ghi"]);
1622 ///
1623 /// let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
1624 /// assert_eq!(v, ["lion", "tiger", "leopard"]);
1625 /// ```
1626 ///
1627 /// If the pattern is a slice of chars, split on each occurrence of any of the characters:
1628 ///
1629 /// ```
1630 /// let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
1631 /// assert_eq!(v, ["2020", "11", "03", "23", "59"]);
1632 /// ```
1633 ///
1634 /// A more complex pattern, using a closure:
1635 ///
1636 /// ```
1637 /// let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
1638 /// assert_eq!(v, ["abc", "def", "ghi"]);
1639 /// ```
1640 ///
1641 /// If a string contains multiple contiguous separators, you will end up
1642 /// with empty strings in the output:
1643 ///
1644 /// ```
1645 /// let x = "||||a||b|c".to_string();
1646 /// let d: Vec<_> = x.split('|').collect();
1647 ///
1648 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1649 /// ```
1650 ///
1651 /// Contiguous separators are separated by the empty string.
1652 ///
1653 /// ```
1654 /// let x = "(///)".to_string();
1655 /// let d: Vec<_> = x.split('/').collect();
1656 ///
1657 /// assert_eq!(d, &["(", "", "", ")"]);
1658 /// ```
1659 ///
1660 /// Separators at the start or end of a string are neighbored
1661 /// by empty strings.
1662 ///
1663 /// ```
1664 /// let d: Vec<_> = "010".split("0").collect();
1665 /// assert_eq!(d, &["", "1", ""]);
1666 /// ```
1667 ///
1668 /// When the empty string is used as a separator, it separates
1669 /// every character in the string, along with the beginning
1670 /// and end of the string.
1671 ///
1672 /// ```
1673 /// let f: Vec<_> = "rust".split("").collect();
1674 /// assert_eq!(f, &["", "r", "u", "s", "t", ""]);
1675 /// ```
1676 ///
1677 /// Contiguous separators can lead to possibly surprising behavior
1678 /// when whitespace is used as the separator. This code is correct:
1679 ///
1680 /// ```
1681 /// let x = " a b c".to_string();
1682 /// let d: Vec<_> = x.split(' ').collect();
1683 ///
1684 /// assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);
1685 /// ```
1686 ///
1687 /// It does _not_ give you:
1688 ///
1689 /// ```,ignore
1690 /// assert_eq!(d, &["a", "b", "c"]);
1691 /// ```
1692 ///
1693 /// Use [`split_whitespace`] for this behavior.
1694 ///
1695 /// [`split_whitespace`]: str::split_whitespace
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 #[inline]
1698 #[cfg(not(feature = "ferrocene_subset"))]
1699 pub fn split<P: Pattern>(&self, pat: P) -> Split<'_, P> {
1700 Split(SplitInternal {
1701 start: 0,
1702 end: self.len(),
1703 matcher: pat.into_searcher(self),
1704 allow_trailing_empty: true,
1705 finished: false,
1706 })
1707 }
1708
1709 /// Returns an iterator over substrings of this string slice, separated by
1710 /// characters matched by a pattern.
1711 ///
1712 /// Differs from the iterator produced by `split` in that `split_inclusive`
1713 /// leaves the matched part as the terminator of the substring.
1714 ///
1715 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1716 /// function or closure that determines if a character matches.
1717 ///
1718 /// [`char`]: prim@char
1719 /// [pattern]: self::pattern
1720 ///
1721 /// # Examples
1722 ///
1723 /// ```
1724 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
1725 /// .split_inclusive('\n').collect();
1726 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);
1727 /// ```
1728 ///
1729 /// If the last element of the string is matched,
1730 /// that element will be considered the terminator of the preceding substring.
1731 /// That substring will be the last item returned by the iterator.
1732 ///
1733 /// ```
1734 /// let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
1735 /// .split_inclusive('\n').collect();
1736 /// assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1737 /// ```
1738 #[stable(feature = "split_inclusive", since = "1.51.0")]
1739 #[inline]
1740 pub fn split_inclusive<P: Pattern>(&self, pat: P) -> SplitInclusive<'_, P> {
1741 SplitInclusive(SplitInternal {
1742 start: 0,
1743 end: self.len(),
1744 matcher: pat.into_searcher(self),
1745 allow_trailing_empty: false,
1746 finished: false,
1747 })
1748 }
1749
1750 /// Returns an iterator over substrings of the given string slice, separated
1751 /// by characters matched by a pattern and yielded in reverse order.
1752 ///
1753 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1754 /// function or closure that determines if a character matches.
1755 ///
1756 /// [`char`]: prim@char
1757 /// [pattern]: self::pattern
1758 ///
1759 /// # Iterator behavior
1760 ///
1761 /// The returned iterator requires that the pattern supports a reverse
1762 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
1763 /// search yields the same elements.
1764 ///
1765 /// For iterating from the front, the [`split`] method can be used.
1766 ///
1767 /// [`split`]: str::split
1768 ///
1769 /// # Examples
1770 ///
1771 /// Simple patterns:
1772 ///
1773 /// ```
1774 /// let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
1775 /// assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);
1776 ///
1777 /// let v: Vec<&str> = "".rsplit('X').collect();
1778 /// assert_eq!(v, [""]);
1779 ///
1780 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
1781 /// assert_eq!(v, ["leopard", "tiger", "", "lion"]);
1782 ///
1783 /// let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
1784 /// assert_eq!(v, ["leopard", "tiger", "lion"]);
1785 /// ```
1786 ///
1787 /// A more complex pattern, using a closure:
1788 ///
1789 /// ```
1790 /// let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
1791 /// assert_eq!(v, ["ghi", "def", "abc"]);
1792 /// ```
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 #[inline]
1795 #[cfg(not(feature = "ferrocene_subset"))]
1796 pub fn rsplit<P: Pattern>(&self, pat: P) -> RSplit<'_, P>
1797 where
1798 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1799 {
1800 RSplit(self.split(pat).0)
1801 }
1802
1803 /// Returns an iterator over substrings of the given string slice, separated
1804 /// by characters matched by a pattern.
1805 ///
1806 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1807 /// function or closure that determines if a character matches.
1808 ///
1809 /// [`char`]: prim@char
1810 /// [pattern]: self::pattern
1811 ///
1812 /// Equivalent to [`split`], except that the trailing substring
1813 /// is skipped if empty.
1814 ///
1815 /// [`split`]: str::split
1816 ///
1817 /// This method can be used for string data that is _terminated_,
1818 /// rather than _separated_ by a pattern.
1819 ///
1820 /// # Iterator behavior
1821 ///
1822 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
1823 /// allows a reverse search and forward/reverse search yields the same
1824 /// elements. This is true for, e.g., [`char`], but not for `&str`.
1825 ///
1826 /// If the pattern allows a reverse search but its results might differ
1827 /// from a forward search, the [`rsplit_terminator`] method can be used.
1828 ///
1829 /// [`rsplit_terminator`]: str::rsplit_terminator
1830 ///
1831 /// # Examples
1832 ///
1833 /// ```
1834 /// let v: Vec<&str> = "A.B.".split_terminator('.').collect();
1835 /// assert_eq!(v, ["A", "B"]);
1836 ///
1837 /// let v: Vec<&str> = "A..B..".split_terminator(".").collect();
1838 /// assert_eq!(v, ["A", "", "B", ""]);
1839 ///
1840 /// let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
1841 /// assert_eq!(v, ["A", "B", "C", "D"]);
1842 /// ```
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 #[inline]
1845 #[cfg(not(feature = "ferrocene_subset"))]
1846 pub fn split_terminator<P: Pattern>(&self, pat: P) -> SplitTerminator<'_, P> {
1847 SplitTerminator(SplitInternal { allow_trailing_empty: false, ..self.split(pat).0 })
1848 }
1849
1850 /// Returns an iterator over substrings of `self`, separated by characters
1851 /// matched by a pattern and yielded in reverse order.
1852 ///
1853 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1854 /// function or closure that determines if a character matches.
1855 ///
1856 /// [`char`]: prim@char
1857 /// [pattern]: self::pattern
1858 ///
1859 /// Equivalent to [`split`], except that the trailing substring is
1860 /// skipped if empty.
1861 ///
1862 /// [`split`]: str::split
1863 ///
1864 /// This method can be used for string data that is _terminated_,
1865 /// rather than _separated_ by a pattern.
1866 ///
1867 /// # Iterator behavior
1868 ///
1869 /// The returned iterator requires that the pattern supports a
1870 /// reverse search, and it will be double ended if a forward/reverse
1871 /// search yields the same elements.
1872 ///
1873 /// For iterating from the front, the [`split_terminator`] method can be
1874 /// used.
1875 ///
1876 /// [`split_terminator`]: str::split_terminator
1877 ///
1878 /// # Examples
1879 ///
1880 /// ```
1881 /// let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
1882 /// assert_eq!(v, ["B", "A"]);
1883 ///
1884 /// let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
1885 /// assert_eq!(v, ["", "B", "", "A"]);
1886 ///
1887 /// let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
1888 /// assert_eq!(v, ["D", "C", "B", "A"]);
1889 /// ```
1890 #[stable(feature = "rust1", since = "1.0.0")]
1891 #[inline]
1892 #[cfg(not(feature = "ferrocene_subset"))]
1893 pub fn rsplit_terminator<P: Pattern>(&self, pat: P) -> RSplitTerminator<'_, P>
1894 where
1895 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
1896 {
1897 RSplitTerminator(self.split_terminator(pat).0)
1898 }
1899
1900 /// Returns an iterator over substrings of the given string slice, separated
1901 /// by a pattern, restricted to returning at most `n` items.
1902 ///
1903 /// If `n` substrings are returned, the last substring (the `n`th substring)
1904 /// will contain the remainder of the string.
1905 ///
1906 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1907 /// function or closure that determines if a character matches.
1908 ///
1909 /// [`char`]: prim@char
1910 /// [pattern]: self::pattern
1911 ///
1912 /// # Iterator behavior
1913 ///
1914 /// The returned iterator will not be double ended, because it is
1915 /// not efficient to support.
1916 ///
1917 /// If the pattern allows a reverse search, the [`rsplitn`] method can be
1918 /// used.
1919 ///
1920 /// [`rsplitn`]: str::rsplitn
1921 ///
1922 /// # Examples
1923 ///
1924 /// Simple patterns:
1925 ///
1926 /// ```
1927 /// let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
1928 /// assert_eq!(v, ["Mary", "had", "a little lambda"]);
1929 ///
1930 /// let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
1931 /// assert_eq!(v, ["lion", "", "tigerXleopard"]);
1932 ///
1933 /// let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
1934 /// assert_eq!(v, ["abcXdef"]);
1935 ///
1936 /// let v: Vec<&str> = "".splitn(1, 'X').collect();
1937 /// assert_eq!(v, [""]);
1938 /// ```
1939 ///
1940 /// A more complex pattern, using a closure:
1941 ///
1942 /// ```
1943 /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
1944 /// assert_eq!(v, ["abc", "defXghi"]);
1945 /// ```
1946 #[stable(feature = "rust1", since = "1.0.0")]
1947 #[inline]
1948 #[cfg(not(feature = "ferrocene_subset"))]
1949 pub fn splitn<P: Pattern>(&self, n: usize, pat: P) -> SplitN<'_, P> {
1950 SplitN(SplitNInternal { iter: self.split(pat).0, count: n })
1951 }
1952
1953 /// Returns an iterator over substrings of this string slice, separated by a
1954 /// pattern, starting from the end of the string, restricted to returning at
1955 /// most `n` items.
1956 ///
1957 /// If `n` substrings are returned, the last substring (the `n`th substring)
1958 /// will contain the remainder of the string.
1959 ///
1960 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
1961 /// function or closure that determines if a character matches.
1962 ///
1963 /// [`char`]: prim@char
1964 /// [pattern]: self::pattern
1965 ///
1966 /// # Iterator behavior
1967 ///
1968 /// The returned iterator will not be double ended, because it is not
1969 /// efficient to support.
1970 ///
1971 /// For splitting from the front, the [`splitn`] method can be used.
1972 ///
1973 /// [`splitn`]: str::splitn
1974 ///
1975 /// # Examples
1976 ///
1977 /// Simple patterns:
1978 ///
1979 /// ```
1980 /// let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
1981 /// assert_eq!(v, ["lamb", "little", "Mary had a"]);
1982 ///
1983 /// let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
1984 /// assert_eq!(v, ["leopard", "tiger", "lionX"]);
1985 ///
1986 /// let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
1987 /// assert_eq!(v, ["leopard", "lion::tiger"]);
1988 /// ```
1989 ///
1990 /// A more complex pattern, using a closure:
1991 ///
1992 /// ```
1993 /// let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
1994 /// assert_eq!(v, ["ghi", "abc1def"]);
1995 /// ```
1996 #[stable(feature = "rust1", since = "1.0.0")]
1997 #[inline]
1998 #[cfg(not(feature = "ferrocene_subset"))]
1999 pub fn rsplitn<P: Pattern>(&self, n: usize, pat: P) -> RSplitN<'_, P>
2000 where
2001 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2002 {
2003 RSplitN(self.splitn(n, pat).0)
2004 }
2005
2006 /// Splits the string on the first occurrence of the specified delimiter and
2007 /// returns prefix before delimiter and suffix after delimiter.
2008 ///
2009 /// # Examples
2010 ///
2011 /// ```
2012 /// assert_eq!("cfg".split_once('='), None);
2013 /// assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
2014 /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
2015 /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
2016 /// ```
2017 #[stable(feature = "str_split_once", since = "1.52.0")]
2018 #[inline]
2019 #[cfg(not(feature = "ferrocene_subset"))]
2020 pub fn split_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)> {
2021 let (start, end) = delimiter.into_searcher(self).next_match()?;
2022 // SAFETY: `Searcher` is known to return valid indices.
2023 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2024 }
2025
2026 /// Splits the string on the last occurrence of the specified delimiter and
2027 /// returns prefix before delimiter and suffix after delimiter.
2028 ///
2029 /// # Examples
2030 ///
2031 /// ```
2032 /// assert_eq!("cfg".rsplit_once('='), None);
2033 /// assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
2034 /// assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
2035 /// assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
2036 /// ```
2037 #[stable(feature = "str_split_once", since = "1.52.0")]
2038 #[inline]
2039 #[cfg(not(feature = "ferrocene_subset"))]
2040 pub fn rsplit_once<P: Pattern>(&self, delimiter: P) -> Option<(&'_ str, &'_ str)>
2041 where
2042 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2043 {
2044 let (start, end) = delimiter.into_searcher(self).next_match_back()?;
2045 // SAFETY: `Searcher` is known to return valid indices.
2046 unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) }
2047 }
2048
2049 /// Returns an iterator over the disjoint matches of a pattern within the
2050 /// given string slice.
2051 ///
2052 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2053 /// function or closure that determines if a character matches.
2054 ///
2055 /// [`char`]: prim@char
2056 /// [pattern]: self::pattern
2057 ///
2058 /// # Iterator behavior
2059 ///
2060 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2061 /// allows a reverse search and forward/reverse search yields the same
2062 /// elements. This is true for, e.g., [`char`], but not for `&str`.
2063 ///
2064 /// If the pattern allows a reverse search but its results might differ
2065 /// from a forward search, the [`rmatches`] method can be used.
2066 ///
2067 /// [`rmatches`]: str::rmatches
2068 ///
2069 /// # Examples
2070 ///
2071 /// ```
2072 /// let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
2073 /// assert_eq!(v, ["abc", "abc", "abc"]);
2074 ///
2075 /// let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
2076 /// assert_eq!(v, ["1", "2", "3"]);
2077 /// ```
2078 #[stable(feature = "str_matches", since = "1.2.0")]
2079 #[inline]
2080 #[cfg(not(feature = "ferrocene_subset"))]
2081 pub fn matches<P: Pattern>(&self, pat: P) -> Matches<'_, P> {
2082 Matches(MatchesInternal(pat.into_searcher(self)))
2083 }
2084
2085 /// Returns an iterator over the disjoint matches of a pattern within this
2086 /// string slice, yielded in reverse order.
2087 ///
2088 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2089 /// function or closure that determines if a character matches.
2090 ///
2091 /// [`char`]: prim@char
2092 /// [pattern]: self::pattern
2093 ///
2094 /// # Iterator behavior
2095 ///
2096 /// The returned iterator requires that the pattern supports a reverse
2097 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2098 /// search yields the same elements.
2099 ///
2100 /// For iterating from the front, the [`matches`] method can be used.
2101 ///
2102 /// [`matches`]: str::matches
2103 ///
2104 /// # Examples
2105 ///
2106 /// ```
2107 /// let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
2108 /// assert_eq!(v, ["abc", "abc", "abc"]);
2109 ///
2110 /// let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
2111 /// assert_eq!(v, ["3", "2", "1"]);
2112 /// ```
2113 #[stable(feature = "str_matches", since = "1.2.0")]
2114 #[inline]
2115 #[cfg(not(feature = "ferrocene_subset"))]
2116 pub fn rmatches<P: Pattern>(&self, pat: P) -> RMatches<'_, P>
2117 where
2118 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2119 {
2120 RMatches(self.matches(pat).0)
2121 }
2122
2123 /// Returns an iterator over the disjoint matches of a pattern within this string
2124 /// slice as well as the index that the match starts at.
2125 ///
2126 /// For matches of `pat` within `self` that overlap, only the indices
2127 /// corresponding to the first match are returned.
2128 ///
2129 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2130 /// function or closure that determines if a character matches.
2131 ///
2132 /// [`char`]: prim@char
2133 /// [pattern]: self::pattern
2134 ///
2135 /// # Iterator behavior
2136 ///
2137 /// The returned iterator will be a [`DoubleEndedIterator`] if the pattern
2138 /// allows a reverse search and forward/reverse search yields the same
2139 /// elements. This is true for, e.g., [`char`], but not for `&str`.
2140 ///
2141 /// If the pattern allows a reverse search but its results might differ
2142 /// from a forward search, the [`rmatch_indices`] method can be used.
2143 ///
2144 /// [`rmatch_indices`]: str::rmatch_indices
2145 ///
2146 /// # Examples
2147 ///
2148 /// ```
2149 /// let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
2150 /// assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);
2151 ///
2152 /// let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
2153 /// assert_eq!(v, [(1, "abc"), (4, "abc")]);
2154 ///
2155 /// let v: Vec<_> = "ababa".match_indices("aba").collect();
2156 /// assert_eq!(v, [(0, "aba")]); // only the first `aba`
2157 /// ```
2158 #[stable(feature = "str_match_indices", since = "1.5.0")]
2159 #[inline]
2160 #[cfg(not(feature = "ferrocene_subset"))]
2161 pub fn match_indices<P: Pattern>(&self, pat: P) -> MatchIndices<'_, P> {
2162 MatchIndices(MatchIndicesInternal(pat.into_searcher(self)))
2163 }
2164
2165 /// Returns an iterator over the disjoint matches of a pattern within `self`,
2166 /// yielded in reverse order along with the index of the match.
2167 ///
2168 /// For matches of `pat` within `self` that overlap, only the indices
2169 /// corresponding to the last match are returned.
2170 ///
2171 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2172 /// function or closure that determines if a character matches.
2173 ///
2174 /// [`char`]: prim@char
2175 /// [pattern]: self::pattern
2176 ///
2177 /// # Iterator behavior
2178 ///
2179 /// The returned iterator requires that the pattern supports a reverse
2180 /// search, and it will be a [`DoubleEndedIterator`] if a forward/reverse
2181 /// search yields the same elements.
2182 ///
2183 /// For iterating from the front, the [`match_indices`] method can be used.
2184 ///
2185 /// [`match_indices`]: str::match_indices
2186 ///
2187 /// # Examples
2188 ///
2189 /// ```
2190 /// let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
2191 /// assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);
2192 ///
2193 /// let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
2194 /// assert_eq!(v, [(4, "abc"), (1, "abc")]);
2195 ///
2196 /// let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
2197 /// assert_eq!(v, [(2, "aba")]); // only the last `aba`
2198 /// ```
2199 #[stable(feature = "str_match_indices", since = "1.5.0")]
2200 #[inline]
2201 #[cfg(not(feature = "ferrocene_subset"))]
2202 pub fn rmatch_indices<P: Pattern>(&self, pat: P) -> RMatchIndices<'_, P>
2203 where
2204 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2205 {
2206 RMatchIndices(self.match_indices(pat).0)
2207 }
2208
2209 /// Returns a string slice with leading and trailing whitespace removed.
2210 ///
2211 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2212 /// Core Property `White_Space`, which includes newlines.
2213 ///
2214 /// # Examples
2215 ///
2216 /// ```
2217 /// let s = "\n Hello\tworld\t\n";
2218 ///
2219 /// assert_eq!("Hello\tworld", s.trim());
2220 /// ```
2221 #[inline]
2222 #[must_use = "this returns the trimmed string as a slice, \
2223 without modifying the original"]
2224 #[stable(feature = "rust1", since = "1.0.0")]
2225 #[rustc_diagnostic_item = "str_trim"]
2226 #[cfg(not(feature = "ferrocene_subset"))]
2227 pub fn trim(&self) -> &str {
2228 self.trim_matches(char::is_whitespace)
2229 }
2230
2231 /// Returns a string slice with leading whitespace removed.
2232 ///
2233 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2234 /// Core Property `White_Space`, which includes newlines.
2235 ///
2236 /// # Text directionality
2237 ///
2238 /// A string is a sequence of bytes. `start` in this context means the first
2239 /// position of that byte string; for a left-to-right language like English or
2240 /// Russian, this will be left side, and for right-to-left languages like
2241 /// Arabic or Hebrew, this will be the right side.
2242 ///
2243 /// # Examples
2244 ///
2245 /// Basic usage:
2246 ///
2247 /// ```
2248 /// let s = "\n Hello\tworld\t\n";
2249 /// assert_eq!("Hello\tworld\t\n", s.trim_start());
2250 /// ```
2251 ///
2252 /// Directionality:
2253 ///
2254 /// ```
2255 /// let s = " English ";
2256 /// assert!(Some('E') == s.trim_start().chars().next());
2257 ///
2258 /// let s = " עברית ";
2259 /// assert!(Some('ע') == s.trim_start().chars().next());
2260 /// ```
2261 #[inline]
2262 #[must_use = "this returns the trimmed string as a new slice, \
2263 without modifying the original"]
2264 #[stable(feature = "trim_direction", since = "1.30.0")]
2265 #[rustc_diagnostic_item = "str_trim_start"]
2266 #[cfg(not(feature = "ferrocene_subset"))]
2267 pub fn trim_start(&self) -> &str {
2268 self.trim_start_matches(char::is_whitespace)
2269 }
2270
2271 /// Returns a string slice with trailing whitespace removed.
2272 ///
2273 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2274 /// Core Property `White_Space`, which includes newlines.
2275 ///
2276 /// # Text directionality
2277 ///
2278 /// A string is a sequence of bytes. `end` in this context means the last
2279 /// position of that byte string; for a left-to-right language like English or
2280 /// Russian, this will be right side, and for right-to-left languages like
2281 /// Arabic or Hebrew, this will be the left side.
2282 ///
2283 /// # Examples
2284 ///
2285 /// Basic usage:
2286 ///
2287 /// ```
2288 /// let s = "\n Hello\tworld\t\n";
2289 /// assert_eq!("\n Hello\tworld", s.trim_end());
2290 /// ```
2291 ///
2292 /// Directionality:
2293 ///
2294 /// ```
2295 /// let s = " English ";
2296 /// assert!(Some('h') == s.trim_end().chars().rev().next());
2297 ///
2298 /// let s = " עברית ";
2299 /// assert!(Some('ת') == s.trim_end().chars().rev().next());
2300 /// ```
2301 #[inline]
2302 #[must_use = "this returns the trimmed string as a new slice, \
2303 without modifying the original"]
2304 #[stable(feature = "trim_direction", since = "1.30.0")]
2305 #[rustc_diagnostic_item = "str_trim_end"]
2306 #[cfg(not(feature = "ferrocene_subset"))]
2307 pub fn trim_end(&self) -> &str {
2308 self.trim_end_matches(char::is_whitespace)
2309 }
2310
2311 /// Returns a string slice with leading whitespace removed.
2312 ///
2313 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2314 /// Core Property `White_Space`.
2315 ///
2316 /// # Text directionality
2317 ///
2318 /// A string is a sequence of bytes. 'Left' in this context means the first
2319 /// position of that byte string; for a language like Arabic or Hebrew
2320 /// which are 'right to left' rather than 'left to right', this will be
2321 /// the _right_ side, not the left.
2322 ///
2323 /// # Examples
2324 ///
2325 /// Basic usage:
2326 ///
2327 /// ```
2328 /// let s = " Hello\tworld\t";
2329 ///
2330 /// assert_eq!("Hello\tworld\t", s.trim_left());
2331 /// ```
2332 ///
2333 /// Directionality:
2334 ///
2335 /// ```
2336 /// let s = " English";
2337 /// assert!(Some('E') == s.trim_left().chars().next());
2338 ///
2339 /// let s = " עברית";
2340 /// assert!(Some('ע') == s.trim_left().chars().next());
2341 /// ```
2342 #[must_use = "this returns the trimmed string as a new slice, \
2343 without modifying the original"]
2344 #[inline]
2345 #[stable(feature = "rust1", since = "1.0.0")]
2346 #[deprecated(since = "1.33.0", note = "superseded by `trim_start`", suggestion = "trim_start")]
2347 #[cfg(not(feature = "ferrocene_subset"))]
2348 pub fn trim_left(&self) -> &str {
2349 self.trim_start()
2350 }
2351
2352 /// Returns a string slice with trailing whitespace removed.
2353 ///
2354 /// 'Whitespace' is defined according to the terms of the Unicode Derived
2355 /// Core Property `White_Space`.
2356 ///
2357 /// # Text directionality
2358 ///
2359 /// A string is a sequence of bytes. 'Right' in this context means the last
2360 /// position of that byte string; for a language like Arabic or Hebrew
2361 /// which are 'right to left' rather than 'left to right', this will be
2362 /// the _left_ side, not the right.
2363 ///
2364 /// # Examples
2365 ///
2366 /// Basic usage:
2367 ///
2368 /// ```
2369 /// let s = " Hello\tworld\t";
2370 ///
2371 /// assert_eq!(" Hello\tworld", s.trim_right());
2372 /// ```
2373 ///
2374 /// Directionality:
2375 ///
2376 /// ```
2377 /// let s = "English ";
2378 /// assert!(Some('h') == s.trim_right().chars().rev().next());
2379 ///
2380 /// let s = "עברית ";
2381 /// assert!(Some('ת') == s.trim_right().chars().rev().next());
2382 /// ```
2383 #[must_use = "this returns the trimmed string as a new slice, \
2384 without modifying the original"]
2385 #[inline]
2386 #[stable(feature = "rust1", since = "1.0.0")]
2387 #[deprecated(since = "1.33.0", note = "superseded by `trim_end`", suggestion = "trim_end")]
2388 #[cfg(not(feature = "ferrocene_subset"))]
2389 pub fn trim_right(&self) -> &str {
2390 self.trim_end()
2391 }
2392
2393 /// Returns a string slice with all prefixes and suffixes that match a
2394 /// pattern repeatedly removed.
2395 ///
2396 /// The [pattern] can be a [`char`], a slice of [`char`]s, or a function
2397 /// or closure that determines if a character matches.
2398 ///
2399 /// [`char`]: prim@char
2400 /// [pattern]: self::pattern
2401 ///
2402 /// # Examples
2403 ///
2404 /// Simple patterns:
2405 ///
2406 /// ```
2407 /// assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
2408 /// assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");
2409 ///
2410 /// let x: &[_] = &['1', '2'];
2411 /// assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");
2412 /// ```
2413 ///
2414 /// A more complex pattern, using a closure:
2415 ///
2416 /// ```
2417 /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
2418 /// ```
2419 #[must_use = "this returns the trimmed string as a new slice, \
2420 without modifying the original"]
2421 #[stable(feature = "rust1", since = "1.0.0")]
2422 #[cfg(not(feature = "ferrocene_subset"))]
2423 pub fn trim_matches<P: Pattern>(&self, pat: P) -> &str
2424 where
2425 for<'a> P::Searcher<'a>: DoubleEndedSearcher<'a>,
2426 {
2427 let mut i = 0;
2428 let mut j = 0;
2429 let mut matcher = pat.into_searcher(self);
2430 if let Some((a, b)) = matcher.next_reject() {
2431 i = a;
2432 j = b; // Remember earliest known match, correct it below if
2433 // last match is different
2434 }
2435 if let Some((_, b)) = matcher.next_reject_back() {
2436 j = b;
2437 }
2438 // SAFETY: `Searcher` is known to return valid indices.
2439 unsafe { self.get_unchecked(i..j) }
2440 }
2441
2442 /// Returns a string slice with all prefixes that match a pattern
2443 /// repeatedly removed.
2444 ///
2445 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2446 /// function or closure that determines if a character matches.
2447 ///
2448 /// [`char`]: prim@char
2449 /// [pattern]: self::pattern
2450 ///
2451 /// # Text directionality
2452 ///
2453 /// A string is a sequence of bytes. `start` in this context means the first
2454 /// position of that byte string; for a left-to-right language like English or
2455 /// Russian, this will be left side, and for right-to-left languages like
2456 /// Arabic or Hebrew, this will be the right side.
2457 ///
2458 /// # Examples
2459 ///
2460 /// ```
2461 /// assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
2462 /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");
2463 ///
2464 /// let x: &[_] = &['1', '2'];
2465 /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
2466 /// ```
2467 #[must_use = "this returns the trimmed string as a new slice, \
2468 without modifying the original"]
2469 #[stable(feature = "trim_direction", since = "1.30.0")]
2470 #[cfg(not(feature = "ferrocene_subset"))]
2471 pub fn trim_start_matches<P: Pattern>(&self, pat: P) -> &str {
2472 let mut i = self.len();
2473 let mut matcher = pat.into_searcher(self);
2474 if let Some((a, _)) = matcher.next_reject() {
2475 i = a;
2476 }
2477 // SAFETY: `Searcher` is known to return valid indices.
2478 unsafe { self.get_unchecked(i..self.len()) }
2479 }
2480
2481 /// Returns a string slice with the prefix removed.
2482 ///
2483 /// If the string starts with the pattern `prefix`, returns the substring after the prefix,
2484 /// wrapped in `Some`. Unlike [`trim_start_matches`], this method removes the prefix exactly once.
2485 ///
2486 /// If the string does not start with `prefix`, returns `None`.
2487 ///
2488 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2489 /// function or closure that determines if a character matches.
2490 ///
2491 /// [`char`]: prim@char
2492 /// [pattern]: self::pattern
2493 /// [`trim_start_matches`]: Self::trim_start_matches
2494 ///
2495 /// # Examples
2496 ///
2497 /// ```
2498 /// assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
2499 /// assert_eq!("foo:bar".strip_prefix("bar"), None);
2500 /// assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
2501 /// ```
2502 #[must_use = "this returns the remaining substring as a new slice, \
2503 without modifying the original"]
2504 #[stable(feature = "str_strip", since = "1.45.0")]
2505 #[cfg(not(feature = "ferrocene_subset"))]
2506 pub fn strip_prefix<P: Pattern>(&self, prefix: P) -> Option<&str> {
2507 prefix.strip_prefix_of(self)
2508 }
2509
2510 /// Returns a string slice with the suffix removed.
2511 ///
2512 /// If the string ends with the pattern `suffix`, returns the substring before the suffix,
2513 /// wrapped in `Some`. Unlike [`trim_end_matches`], this method removes the suffix exactly once.
2514 ///
2515 /// If the string does not end with `suffix`, returns `None`.
2516 ///
2517 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2518 /// function or closure that determines if a character matches.
2519 ///
2520 /// [`char`]: prim@char
2521 /// [pattern]: self::pattern
2522 /// [`trim_end_matches`]: Self::trim_end_matches
2523 ///
2524 /// # Examples
2525 ///
2526 /// ```
2527 /// assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
2528 /// assert_eq!("bar:foo".strip_suffix("bar"), None);
2529 /// assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
2530 /// ```
2531 #[must_use = "this returns the remaining substring as a new slice, \
2532 without modifying the original"]
2533 #[stable(feature = "str_strip", since = "1.45.0")]
2534 #[cfg(not(feature = "ferrocene_subset"))]
2535 pub fn strip_suffix<P: Pattern>(&self, suffix: P) -> Option<&str>
2536 where
2537 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2538 {
2539 suffix.strip_suffix_of(self)
2540 }
2541
2542 /// Returns a string slice with the prefix and suffix removed.
2543 ///
2544 /// If the string starts with the pattern `prefix` and ends with the pattern `suffix`, returns
2545 /// the substring after the prefix and before the suffix, wrapped in `Some`.
2546 /// Unlike [`trim_start_matches`] and [`trim_end_matches`], this method removes both the prefix
2547 /// and suffix exactly once.
2548 ///
2549 /// If the string does not start with `prefix` or does not end with `suffix`, returns `None`.
2550 ///
2551 /// Each [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2552 /// function or closure that determines if a character matches.
2553 ///
2554 /// [`char`]: prim@char
2555 /// [pattern]: self::pattern
2556 /// [`trim_start_matches`]: Self::trim_start_matches
2557 /// [`trim_end_matches`]: Self::trim_end_matches
2558 ///
2559 /// # Examples
2560 ///
2561 /// ```
2562 /// #![feature(strip_circumfix)]
2563 ///
2564 /// assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
2565 /// assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
2566 /// assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
2567 /// ```
2568 #[must_use = "this returns the remaining substring as a new slice, \
2569 without modifying the original"]
2570 #[unstable(feature = "strip_circumfix", issue = "147946")]
2571 #[cfg(not(feature = "ferrocene_subset"))]
2572 pub fn strip_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> Option<&str>
2573 where
2574 for<'a> S::Searcher<'a>: ReverseSearcher<'a>,
2575 {
2576 self.strip_prefix(prefix)?.strip_suffix(suffix)
2577 }
2578
2579 /// Returns a string slice with the optional prefix removed.
2580 ///
2581 /// If the string starts with the pattern `prefix`, returns the substring after the prefix.
2582 /// Unlike [`strip_prefix`], this method always returns `&str` for easy method chaining,
2583 /// instead of returning [`Option<&str>`].
2584 ///
2585 /// If the string does not start with `prefix`, returns the original string unchanged.
2586 ///
2587 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2588 /// function or closure that determines if a character matches.
2589 ///
2590 /// [`char`]: prim@char
2591 /// [pattern]: self::pattern
2592 /// [`strip_prefix`]: Self::strip_prefix
2593 ///
2594 /// # Examples
2595 ///
2596 /// ```
2597 /// #![feature(trim_prefix_suffix)]
2598 ///
2599 /// // Prefix present - removes it
2600 /// assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
2601 /// assert_eq!("foofoo".trim_prefix("foo"), "foo");
2602 ///
2603 /// // Prefix absent - returns original string
2604 /// assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");
2605 ///
2606 /// // Method chaining example
2607 /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2608 /// ```
2609 #[must_use = "this returns the remaining substring as a new slice, \
2610 without modifying the original"]
2611 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2612 #[cfg(not(feature = "ferrocene_subset"))]
2613 pub fn trim_prefix<P: Pattern>(&self, prefix: P) -> &str {
2614 prefix.strip_prefix_of(self).unwrap_or(self)
2615 }
2616
2617 /// Returns a string slice with the optional suffix removed.
2618 ///
2619 /// If the string ends with the pattern `suffix`, returns the substring before the suffix.
2620 /// Unlike [`strip_suffix`], this method always returns `&str` for easy method chaining,
2621 /// instead of returning [`Option<&str>`].
2622 ///
2623 /// If the string does not end with `suffix`, returns the original string unchanged.
2624 ///
2625 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2626 /// function or closure that determines if a character matches.
2627 ///
2628 /// [`char`]: prim@char
2629 /// [pattern]: self::pattern
2630 /// [`strip_suffix`]: Self::strip_suffix
2631 ///
2632 /// # Examples
2633 ///
2634 /// ```
2635 /// #![feature(trim_prefix_suffix)]
2636 ///
2637 /// // Suffix present - removes it
2638 /// assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
2639 /// assert_eq!("foofoo".trim_suffix("foo"), "foo");
2640 ///
2641 /// // Suffix absent - returns original string
2642 /// assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");
2643 ///
2644 /// // Method chaining example
2645 /// assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
2646 /// ```
2647 #[must_use = "this returns the remaining substring as a new slice, \
2648 without modifying the original"]
2649 #[unstable(feature = "trim_prefix_suffix", issue = "142312")]
2650 #[cfg(not(feature = "ferrocene_subset"))]
2651 pub fn trim_suffix<P: Pattern>(&self, suffix: P) -> &str
2652 where
2653 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2654 {
2655 suffix.strip_suffix_of(self).unwrap_or(self)
2656 }
2657
2658 /// Returns a string slice with all suffixes that match a pattern
2659 /// repeatedly removed.
2660 ///
2661 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2662 /// function or closure that determines if a character matches.
2663 ///
2664 /// [`char`]: prim@char
2665 /// [pattern]: self::pattern
2666 ///
2667 /// # Text directionality
2668 ///
2669 /// A string is a sequence of bytes. `end` in this context means the last
2670 /// position of that byte string; for a left-to-right language like English or
2671 /// Russian, this will be right side, and for right-to-left languages like
2672 /// Arabic or Hebrew, this will be the left side.
2673 ///
2674 /// # Examples
2675 ///
2676 /// Simple patterns:
2677 ///
2678 /// ```
2679 /// assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
2680 /// assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");
2681 ///
2682 /// let x: &[_] = &['1', '2'];
2683 /// assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");
2684 /// ```
2685 ///
2686 /// A more complex pattern, using a closure:
2687 ///
2688 /// ```
2689 /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
2690 /// ```
2691 #[must_use = "this returns the trimmed string as a new slice, \
2692 without modifying the original"]
2693 #[stable(feature = "trim_direction", since = "1.30.0")]
2694 #[cfg(not(feature = "ferrocene_subset"))]
2695 pub fn trim_end_matches<P: Pattern>(&self, pat: P) -> &str
2696 where
2697 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2698 {
2699 let mut j = 0;
2700 let mut matcher = pat.into_searcher(self);
2701 if let Some((_, b)) = matcher.next_reject_back() {
2702 j = b;
2703 }
2704 // SAFETY: `Searcher` is known to return valid indices.
2705 unsafe { self.get_unchecked(0..j) }
2706 }
2707
2708 /// Returns a string slice with all prefixes that match a pattern
2709 /// repeatedly removed.
2710 ///
2711 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2712 /// function or closure that determines if a character matches.
2713 ///
2714 /// [`char`]: prim@char
2715 /// [pattern]: self::pattern
2716 ///
2717 /// # Text directionality
2718 ///
2719 /// A string is a sequence of bytes. 'Left' in this context means the first
2720 /// position of that byte string; for a language like Arabic or Hebrew
2721 /// which are 'right to left' rather than 'left to right', this will be
2722 /// the _right_ side, not the left.
2723 ///
2724 /// # Examples
2725 ///
2726 /// ```
2727 /// assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
2728 /// assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");
2729 ///
2730 /// let x: &[_] = &['1', '2'];
2731 /// assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
2732 /// ```
2733 #[stable(feature = "rust1", since = "1.0.0")]
2734 #[deprecated(
2735 since = "1.33.0",
2736 note = "superseded by `trim_start_matches`",
2737 suggestion = "trim_start_matches"
2738 )]
2739 #[cfg(not(feature = "ferrocene_subset"))]
2740 pub fn trim_left_matches<P: Pattern>(&self, pat: P) -> &str {
2741 self.trim_start_matches(pat)
2742 }
2743
2744 /// Returns a string slice with all suffixes that match a pattern
2745 /// repeatedly removed.
2746 ///
2747 /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a
2748 /// function or closure that determines if a character matches.
2749 ///
2750 /// [`char`]: prim@char
2751 /// [pattern]: self::pattern
2752 ///
2753 /// # Text directionality
2754 ///
2755 /// A string is a sequence of bytes. 'Right' in this context means the last
2756 /// position of that byte string; for a language like Arabic or Hebrew
2757 /// which are 'right to left' rather than 'left to right', this will be
2758 /// the _left_ side, not the right.
2759 ///
2760 /// # Examples
2761 ///
2762 /// Simple patterns:
2763 ///
2764 /// ```
2765 /// assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
2766 /// assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");
2767 ///
2768 /// let x: &[_] = &['1', '2'];
2769 /// assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");
2770 /// ```
2771 ///
2772 /// A more complex pattern, using a closure:
2773 ///
2774 /// ```
2775 /// assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
2776 /// ```
2777 #[stable(feature = "rust1", since = "1.0.0")]
2778 #[deprecated(
2779 since = "1.33.0",
2780 note = "superseded by `trim_end_matches`",
2781 suggestion = "trim_end_matches"
2782 )]
2783 #[cfg(not(feature = "ferrocene_subset"))]
2784 pub fn trim_right_matches<P: Pattern>(&self, pat: P) -> &str
2785 where
2786 for<'a> P::Searcher<'a>: ReverseSearcher<'a>,
2787 {
2788 self.trim_end_matches(pat)
2789 }
2790
2791 /// Parses this string slice into another type.
2792 ///
2793 /// Because `parse` is so general, it can cause problems with type
2794 /// inference. As such, `parse` is one of the few times you'll see
2795 /// the syntax affectionately known as the 'turbofish': `::<>`. This
2796 /// helps the inference algorithm understand specifically which type
2797 /// you're trying to parse into.
2798 ///
2799 /// `parse` can parse into any type that implements the [`FromStr`] trait.
2800 ///
2801 /// # Errors
2802 ///
2803 /// Will return [`Err`] if it's not possible to parse this string slice into
2804 /// the desired type.
2805 ///
2806 /// [`Err`]: FromStr::Err
2807 ///
2808 /// # Examples
2809 ///
2810 /// Basic usage:
2811 ///
2812 /// ```
2813 /// let four: u32 = "4".parse().unwrap();
2814 ///
2815 /// assert_eq!(4, four);
2816 /// ```
2817 ///
2818 /// Using the 'turbofish' instead of annotating `four`:
2819 ///
2820 /// ```
2821 /// let four = "4".parse::<u32>();
2822 ///
2823 /// assert_eq!(Ok(4), four);
2824 /// ```
2825 ///
2826 /// Failing to parse:
2827 ///
2828 /// ```
2829 /// let nope = "j".parse::<u32>();
2830 ///
2831 /// assert!(nope.is_err());
2832 /// ```
2833 #[inline]
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 pub fn parse<F: FromStr>(&self) -> Result<F, F::Err> {
2836 FromStr::from_str(self)
2837 }
2838
2839 /// Checks if all characters in this string are within the ASCII range.
2840 ///
2841 /// An empty string returns `true`.
2842 ///
2843 /// # Examples
2844 ///
2845 /// ```
2846 /// let ascii = "hello!\n";
2847 /// let non_ascii = "Grüße, Jürgen ❤";
2848 ///
2849 /// assert!(ascii.is_ascii());
2850 /// assert!(!non_ascii.is_ascii());
2851 /// ```
2852 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2853 #[rustc_const_stable(feature = "const_slice_is_ascii", since = "1.74.0")]
2854 #[must_use]
2855 #[inline]
2856 #[cfg(not(feature = "ferrocene_subset"))]
2857 pub const fn is_ascii(&self) -> bool {
2858 // We can treat each byte as character here: all multibyte characters
2859 // start with a byte that is not in the ASCII range, so we will stop
2860 // there already.
2861 self.as_bytes().is_ascii()
2862 }
2863
2864 /// If this string slice [`is_ascii`](Self::is_ascii), returns it as a slice
2865 /// of [ASCII characters](`ascii::Char`), otherwise returns `None`.
2866 #[unstable(feature = "ascii_char", issue = "110998")]
2867 #[must_use]
2868 #[inline]
2869 #[cfg(not(feature = "ferrocene_subset"))]
2870 pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
2871 // Like in `is_ascii`, we can work on the bytes directly.
2872 self.as_bytes().as_ascii()
2873 }
2874
2875 /// Converts this string slice into a slice of [ASCII characters](ascii::Char),
2876 /// without checking whether they are valid.
2877 ///
2878 /// # Safety
2879 ///
2880 /// Every character in this string must be ASCII, or else this is UB.
2881 #[unstable(feature = "ascii_char", issue = "110998")]
2882 #[must_use]
2883 #[inline]
2884 #[cfg(not(feature = "ferrocene_subset"))]
2885 pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
2886 assert_unsafe_precondition!(
2887 check_library_ub,
2888 "as_ascii_unchecked requires that the string is valid ASCII",
2889 (it: &str = self) => it.is_ascii()
2890 );
2891
2892 // SAFETY: the caller promised that every byte of this string slice
2893 // is ASCII.
2894 unsafe { self.as_bytes().as_ascii_unchecked() }
2895 }
2896
2897 /// Checks that two strings are an ASCII case-insensitive match.
2898 ///
2899 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
2900 /// but without allocating and copying temporaries.
2901 ///
2902 /// # Examples
2903 ///
2904 /// ```
2905 /// assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
2906 /// assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
2907 /// assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
2908 /// ```
2909 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2910 #[rustc_const_stable(feature = "const_eq_ignore_ascii_case", since = "1.89.0")]
2911 #[must_use]
2912 #[inline]
2913 pub const fn eq_ignore_ascii_case(&self, other: &str) -> bool {
2914 self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
2915 }
2916
2917 /// Converts this string to its ASCII upper case equivalent in-place.
2918 ///
2919 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2920 /// but non-ASCII letters are unchanged.
2921 ///
2922 /// To return a new uppercased value without modifying the existing one, use
2923 /// [`to_ascii_uppercase()`].
2924 ///
2925 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
2926 ///
2927 /// # Examples
2928 ///
2929 /// ```
2930 /// let mut s = String::from("Grüße, Jürgen ❤");
2931 ///
2932 /// s.make_ascii_uppercase();
2933 ///
2934 /// assert_eq!("GRüßE, JüRGEN ❤", s);
2935 /// ```
2936 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2937 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2938 #[inline]
2939 #[cfg(not(feature = "ferrocene_subset"))]
2940 pub const fn make_ascii_uppercase(&mut self) {
2941 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2942 let me = unsafe { self.as_bytes_mut() };
2943 me.make_ascii_uppercase()
2944 }
2945
2946 /// Converts this string to its ASCII lower case equivalent in-place.
2947 ///
2948 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2949 /// but non-ASCII letters are unchanged.
2950 ///
2951 /// To return a new lowercased value without modifying the existing one, use
2952 /// [`to_ascii_lowercase()`].
2953 ///
2954 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
2955 ///
2956 /// # Examples
2957 ///
2958 /// ```
2959 /// let mut s = String::from("GRÜßE, JÜRGEN ❤");
2960 ///
2961 /// s.make_ascii_lowercase();
2962 ///
2963 /// assert_eq!("grÜße, jÜrgen ❤", s);
2964 /// ```
2965 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2966 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
2967 #[inline]
2968 #[cfg(not(feature = "ferrocene_subset"))]
2969 pub const fn make_ascii_lowercase(&mut self) {
2970 // SAFETY: changing ASCII letters only does not invalidate UTF-8.
2971 let me = unsafe { self.as_bytes_mut() };
2972 me.make_ascii_lowercase()
2973 }
2974
2975 /// Returns a string slice with leading ASCII whitespace removed.
2976 ///
2977 /// 'Whitespace' refers to the definition used by
2978 /// [`u8::is_ascii_whitespace`].
2979 ///
2980 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
2981 ///
2982 /// # Examples
2983 ///
2984 /// ```
2985 /// assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
2986 /// assert_eq!(" ".trim_ascii_start(), "");
2987 /// assert_eq!("".trim_ascii_start(), "");
2988 /// ```
2989 #[must_use = "this returns the trimmed string as a new slice, \
2990 without modifying the original"]
2991 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2992 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
2993 #[inline]
2994 #[cfg(not(feature = "ferrocene_subset"))]
2995 pub const fn trim_ascii_start(&self) -> &str {
2996 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
2997 // UTF-8.
2998 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_start()) }
2999 }
3000
3001 /// Returns a string slice with trailing ASCII whitespace removed.
3002 ///
3003 /// 'Whitespace' refers to the definition used by
3004 /// [`u8::is_ascii_whitespace`].
3005 ///
3006 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3007 ///
3008 /// # Examples
3009 ///
3010 /// ```
3011 /// assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
3012 /// assert_eq!(" ".trim_ascii_end(), "");
3013 /// assert_eq!("".trim_ascii_end(), "");
3014 /// ```
3015 #[must_use = "this returns the trimmed string as a new slice, \
3016 without modifying the original"]
3017 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3018 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3019 #[inline]
3020 #[cfg(not(feature = "ferrocene_subset"))]
3021 pub const fn trim_ascii_end(&self) -> &str {
3022 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3023 // UTF-8.
3024 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii_end()) }
3025 }
3026
3027 /// Returns a string slice with leading and trailing ASCII whitespace
3028 /// removed.
3029 ///
3030 /// 'Whitespace' refers to the definition used by
3031 /// [`u8::is_ascii_whitespace`].
3032 ///
3033 /// [`u8::is_ascii_whitespace`]: u8::is_ascii_whitespace
3034 ///
3035 /// # Examples
3036 ///
3037 /// ```
3038 /// assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
3039 /// assert_eq!(" ".trim_ascii(), "");
3040 /// assert_eq!("".trim_ascii(), "");
3041 /// ```
3042 #[must_use = "this returns the trimmed string as a new slice, \
3043 without modifying the original"]
3044 #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3045 #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
3046 #[inline]
3047 #[cfg(not(feature = "ferrocene_subset"))]
3048 pub const fn trim_ascii(&self) -> &str {
3049 // SAFETY: Removing ASCII characters from a `&str` does not invalidate
3050 // UTF-8.
3051 unsafe { core::str::from_utf8_unchecked(self.as_bytes().trim_ascii()) }
3052 }
3053
3054 /// Returns an iterator that escapes each char in `self` with [`char::escape_debug`].
3055 ///
3056 /// Note: only extended grapheme codepoints that begin the string will be
3057 /// escaped.
3058 ///
3059 /// # Examples
3060 ///
3061 /// As an iterator:
3062 ///
3063 /// ```
3064 /// for c in "❤\n!".escape_debug() {
3065 /// print!("{c}");
3066 /// }
3067 /// println!();
3068 /// ```
3069 ///
3070 /// Using `println!` directly:
3071 ///
3072 /// ```
3073 /// println!("{}", "❤\n!".escape_debug());
3074 /// ```
3075 ///
3076 ///
3077 /// Both are equivalent to:
3078 ///
3079 /// ```
3080 /// println!("❤\\n!");
3081 /// ```
3082 ///
3083 /// Using `to_string`:
3084 ///
3085 /// ```
3086 /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
3087 /// ```
3088 #[must_use = "this returns the escaped string as an iterator, \
3089 without modifying the original"]
3090 #[stable(feature = "str_escape", since = "1.34.0")]
3091 #[cfg(not(feature = "ferrocene_subset"))]
3092 pub fn escape_debug(&self) -> EscapeDebug<'_> {
3093 let mut chars = self.chars();
3094 EscapeDebug {
3095 inner: chars
3096 .next()
3097 .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL))
3098 .into_iter()
3099 .flatten()
3100 .chain(chars.flat_map(CharEscapeDebugContinue)),
3101 }
3102 }
3103
3104 /// Returns an iterator that escapes each char in `self` with [`char::escape_default`].
3105 ///
3106 /// # Examples
3107 ///
3108 /// As an iterator:
3109 ///
3110 /// ```
3111 /// for c in "❤\n!".escape_default() {
3112 /// print!("{c}");
3113 /// }
3114 /// println!();
3115 /// ```
3116 ///
3117 /// Using `println!` directly:
3118 ///
3119 /// ```
3120 /// println!("{}", "❤\n!".escape_default());
3121 /// ```
3122 ///
3123 ///
3124 /// Both are equivalent to:
3125 ///
3126 /// ```
3127 /// println!("\\u{{2764}}\\n!");
3128 /// ```
3129 ///
3130 /// Using `to_string`:
3131 ///
3132 /// ```
3133 /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
3134 /// ```
3135 #[must_use = "this returns the escaped string as an iterator, \
3136 without modifying the original"]
3137 #[stable(feature = "str_escape", since = "1.34.0")]
3138 #[cfg(not(feature = "ferrocene_subset"))]
3139 pub fn escape_default(&self) -> EscapeDefault<'_> {
3140 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
3141 }
3142
3143 /// Returns an iterator that escapes each char in `self` with [`char::escape_unicode`].
3144 ///
3145 /// # Examples
3146 ///
3147 /// As an iterator:
3148 ///
3149 /// ```
3150 /// for c in "❤\n!".escape_unicode() {
3151 /// print!("{c}");
3152 /// }
3153 /// println!();
3154 /// ```
3155 ///
3156 /// Using `println!` directly:
3157 ///
3158 /// ```
3159 /// println!("{}", "❤\n!".escape_unicode());
3160 /// ```
3161 ///
3162 ///
3163 /// Both are equivalent to:
3164 ///
3165 /// ```
3166 /// println!("\\u{{2764}}\\u{{a}}\\u{{21}}");
3167 /// ```
3168 ///
3169 /// Using `to_string`:
3170 ///
3171 /// ```
3172 /// assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
3173 /// ```
3174 #[must_use = "this returns the escaped string as an iterator, \
3175 without modifying the original"]
3176 #[stable(feature = "str_escape", since = "1.34.0")]
3177 #[cfg(not(feature = "ferrocene_subset"))]
3178 pub fn escape_unicode(&self) -> EscapeUnicode<'_> {
3179 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
3180 }
3181
3182 /// Returns the range that a substring points to.
3183 ///
3184 /// Returns `None` if `substr` does not point within `self`.
3185 ///
3186 /// Unlike [`str::find`], **this does not search through the string**.
3187 /// Instead, it uses pointer arithmetic to find where in the string
3188 /// `substr` is derived from.
3189 ///
3190 /// This is useful for extending [`str::split`] and similar methods.
3191 ///
3192 /// Note that this method may return false positives (typically either
3193 /// `Some(0..0)` or `Some(self.len()..self.len())`) if `substr` is a
3194 /// zero-length `str` that points at the beginning or end of another,
3195 /// independent, `str`.
3196 ///
3197 /// # Examples
3198 /// ```
3199 /// #![feature(substr_range)]
3200 ///
3201 /// let data = "a, b, b, a";
3202 /// let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());
3203 ///
3204 /// assert_eq!(iter.next(), Some(0..1));
3205 /// assert_eq!(iter.next(), Some(3..4));
3206 /// assert_eq!(iter.next(), Some(6..7));
3207 /// assert_eq!(iter.next(), Some(9..10));
3208 /// ```
3209 #[must_use]
3210 #[unstable(feature = "substr_range", issue = "126769")]
3211 #[cfg(not(feature = "ferrocene_subset"))]
3212 pub fn substr_range(&self, substr: &str) -> Option<Range<usize>> {
3213 self.as_bytes().subslice_range(substr.as_bytes())
3214 }
3215
3216 /// Returns the same string as a string slice `&str`.
3217 ///
3218 /// This method is redundant when used directly on `&str`, but
3219 /// it helps dereferencing other string-like types to string slices,
3220 /// for example references to `Box<str>` or `Arc<str>`.
3221 #[inline]
3222 #[unstable(feature = "str_as_str", issue = "130366")]
3223 pub const fn as_str(&self) -> &str {
3224 self
3225 }
3226}
3227
3228#[stable(feature = "rust1", since = "1.0.0")]
3229#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3230impl const AsRef<[u8]> for str {
3231 #[inline]
3232 fn as_ref(&self) -> &[u8] {
3233 self.as_bytes()
3234 }
3235}
3236
3237#[stable(feature = "rust1", since = "1.0.0")]
3238#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3239impl const Default for &str {
3240 /// Creates an empty str
3241 #[inline]
3242 fn default() -> Self {
3243 ""
3244 }
3245}
3246
3247#[stable(feature = "default_mut_str", since = "1.28.0")]
3248#[rustc_const_unstable(feature = "const_default", issue = "143894")]
3249#[cfg(not(feature = "ferrocene_subset"))]
3250impl const Default for &mut str {
3251 /// Creates an empty mutable str
3252 #[inline]
3253 fn default() -> Self {
3254 // SAFETY: The empty string is valid UTF-8.
3255 unsafe { from_utf8_unchecked_mut(&mut []) }
3256 }
3257}
3258
3259#[cfg(not(feature = "ferrocene_subset"))]
3260impl_fn_for_zst! {
3261 /// A nameable, cloneable fn type
3262 #[derive(Clone)]
3263 struct LinesMap impl<'a> Fn = |line: &'a str| -> &'a str {
3264 let Some(line) = line.strip_suffix('\n') else { return line };
3265 let Some(line) = line.strip_suffix('\r') else { return line };
3266 line
3267 };
3268
3269 #[derive(Clone)]
3270 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
3271 c.escape_debug_ext(EscapeDebugExtArgs {
3272 escape_grapheme_extended: false,
3273 escape_single_quote: true,
3274 escape_double_quote: true
3275 })
3276 };
3277
3278 #[derive(Clone)]
3279 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
3280 c.escape_unicode()
3281 };
3282 #[derive(Clone)]
3283 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
3284 c.escape_default()
3285 };
3286
3287 #[derive(Clone)]
3288 struct IsWhitespace impl Fn = |c: char| -> bool {
3289 c.is_whitespace()
3290 };
3291
3292 #[derive(Clone)]
3293 struct IsAsciiWhitespace impl Fn = |byte: &u8| -> bool {
3294 byte.is_ascii_whitespace()
3295 };
3296
3297 #[derive(Clone)]
3298 struct IsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b str| -> bool {
3299 !s.is_empty()
3300 };
3301
3302 #[derive(Clone)]
3303 struct BytesIsNotEmpty impl<'a, 'b> Fn = |s: &'a &'b [u8]| -> bool {
3304 !s.is_empty()
3305 };
3306
3307 #[derive(Clone)]
3308 struct UnsafeBytesToStr impl<'a> Fn = |bytes: &'a [u8]| -> &'a str {
3309 // SAFETY: not safe
3310 unsafe { from_utf8_unchecked(bytes) }
3311 };
3312}
3313
3314// This is required to make `impl From<&str> for Box<dyn Error>` and `impl<E> From<E> for Box<dyn Error>` not overlap.
3315#[stable(feature = "error_in_core_neg_impl", since = "1.65.0")]
3316#[cfg(not(feature = "ferrocene_subset"))]
3317impl !crate::error::Error for &str {}