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