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