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