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