1 //! Unicode string slices.
3 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
5 //! The `&str` type is one of the two main string types, the other being `String`.
6 //! Unlike its `String` counterpart, its contents are borrowed.
10 //! A basic string declaration of `&str` type:
13 //! let hello_world = "Hello, World!";
16 //! Here we have declared a string literal, also known as a string slice.
17 //! String literals have a static lifetime, which means the string `hello_world`
18 //! is guaranteed to be valid for the duration of the entire program.
19 //! We can explicitly specify `hello_world`'s lifetime as well:
22 //! let hello_world: &'static str = "Hello, world!";
25 #![stable(feature = "rust1", since = "1.0.0")]
27 // Many of the usings in this module are only used in the test configuration.
28 // It's cleaner to just turn off the unused_imports warning than to fix them.
29 #![allow(unused_imports)]
31 use core::borrow::Borrow;
32 use core::fmt::{self, Write};
34 use core::iter::{Chain, Flatten, FlatMap};
35 use core::str::pattern::{Pattern, Searcher, ReverseSearcher, DoubleEndedSearcher};
40 use core::iter::FusedIterator;
41 use core::unicode::conversions;
43 use crate::borrow::ToOwned;
44 use crate::boxed::Box;
45 use crate::slice::{SliceConcatExt, SliceIndex};
46 use crate::string::String;
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{FromStr, Utf8Error};
52 #[stable(feature = "rust1", since = "1.0.0")]
53 pub use core::str::{Lines, LinesAny};
54 #[stable(feature = "rust1", since = "1.0.0")]
55 pub use core::str::{Split, RSplit};
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub use core::str::{SplitN, RSplitN};
58 #[stable(feature = "rust1", since = "1.0.0")]
59 pub use core::str::{SplitTerminator, RSplitTerminator};
60 #[stable(feature = "rust1", since = "1.0.0")]
61 pub use core::str::{Matches, RMatches};
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{MatchIndices, RMatchIndices};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::SplitWhitespace;
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::pattern;
72 #[stable(feature = "encode_utf16", since = "1.8.0")]
73 pub use core::str::EncodeUtf16;
74 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
75 pub use core::str::SplitAsciiWhitespace;
77 #[unstable(feature = "slice_concat_ext",
78 reason = "trait should not have to exist",
80 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
83 fn concat(&self) -> String {
87 fn join(&self, sep: &str) -> String {
89 String::from_utf8_unchecked( join_generic_copy(self, sep.as_bytes()) )
93 fn connect(&self, sep: &str) -> String {
98 macro_rules! spezialize_for_lengths {
99 ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
100 let mut target = $target;
102 let sep_bytes = $separator;
103 match $separator.len() {
105 // loops with hardcoded sizes run much faster
106 // specialize the cases with small separator lengths
109 copy_slice_and_advance!(target, sep_bytes);
110 copy_slice_and_advance!(target, s.borrow().as_ref());
115 // arbitrary non-zero size fallback
117 copy_slice_and_advance!(target, sep_bytes);
118 copy_slice_and_advance!(target, s.borrow().as_ref());
125 macro_rules! copy_slice_and_advance {
126 ($target:expr, $bytes:expr) => {
127 let len = $bytes.len();
128 let (head, tail) = {$target}.split_at_mut(len);
129 head.copy_from_slice($bytes);
134 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
135 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
136 // For this reason SliceConcatExt<T> is not specialized for T: Copy and SliceConcatExt<str> is the
137 // only user of this function. It is left in place for the time when that is fixed.
139 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
140 // [T] and str both impl AsRef<[T]> for some T
141 // => s.borrow().as_ref() and we always have slices
142 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
145 B: AsRef<[T]> + ?Sized,
148 let sep_len = sep.len();
149 let mut iter = slice.iter();
151 // the first slice is the only one without a separator preceding it
152 let first = match iter.next() {
153 Some(first) => first,
154 None => return vec![],
157 // compute the exact total length of the joined Vec
158 // if the `len` calculation overflows, we'll panic
159 // we would have run out of memory anyway and the rest of the function requires
160 // the entire Vec pre-allocated for safety
161 let len = sep_len.checked_mul(iter.len()).and_then(|n| {
163 .map(|s| s.borrow().as_ref().len())
164 .try_fold(n, usize::checked_add)
165 }).expect("attempt to join into collection with len > usize::MAX");
167 // crucial for safety
168 let mut result = Vec::with_capacity(len);
169 assert!(result.capacity() >= len);
171 result.extend_from_slice(first.borrow().as_ref());
175 let pos = result.len();
176 let target = result.get_unchecked_mut(pos..len);
178 // copy separator and slices over without bounds checks
179 // generate loops with hardcoded offsets for small separators
180 // massive improvements possible (~ x2)
181 spezialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
188 #[stable(feature = "rust1", since = "1.0.0")]
189 impl Borrow<str> for String {
191 fn borrow(&self) -> &str {
196 #[stable(feature = "rust1", since = "1.0.0")]
197 impl ToOwned for str {
200 fn to_owned(&self) -> String {
201 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
204 fn clone_into(&self, target: &mut String) {
205 let mut b = mem::replace(target, String::new()).into_bytes();
206 self.as_bytes().clone_into(&mut b);
207 *target = unsafe { String::from_utf8_unchecked(b) }
211 /// Methods for string slices.
212 #[lang = "str_alloc"]
215 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
222 /// let s = "this is a string";
223 /// let boxed_str = s.to_owned().into_boxed_str();
224 /// let boxed_bytes = boxed_str.into_boxed_bytes();
225 /// assert_eq!(*boxed_bytes, *s.as_bytes());
227 #[stable(feature = "str_box_extras", since = "1.20.0")]
229 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
233 /// Replaces all matches of a pattern with another string.
235 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
236 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
237 /// replaces them with the replacement string slice.
239 /// [`String`]: string/struct.String.html
246 /// let s = "this is old";
248 /// assert_eq!("this is new", s.replace("old", "new"));
251 /// When the pattern doesn't match:
254 /// let s = "this is old";
255 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
257 #[must_use = "this returns the replaced string as a new allocation, \
258 without modifying the original"]
259 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
262 let mut result = String::new();
263 let mut last_end = 0;
264 for (start, part) in self.match_indices(from) {
265 result.push_str(unsafe { self.get_unchecked(last_end..start) });
267 last_end = start + part.len();
269 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
273 /// Replaces first N matches of a pattern with another string.
275 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
276 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
277 /// replaces them with the replacement string slice at most `count` times.
279 /// [`String`]: string/struct.String.html
286 /// let s = "foo foo 123 foo";
287 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
288 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
289 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
292 /// When the pattern doesn't match:
295 /// let s = "this is old";
296 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
298 #[must_use = "this returns the replaced string as a new allocation, \
299 without modifying the original"]
300 #[stable(feature = "str_replacen", since = "1.16.0")]
301 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
302 // Hope to reduce the times of re-allocation
303 let mut result = String::with_capacity(32);
304 let mut last_end = 0;
305 for (start, part) in self.match_indices(pat).take(count) {
306 result.push_str(unsafe { self.get_unchecked(last_end..start) });
308 last_end = start + part.len();
310 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
314 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
316 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
319 /// Since some characters can expand into multiple characters when changing
320 /// the case, this function returns a [`String`] instead of modifying the
321 /// parameter in-place.
323 /// [`String`]: string/struct.String.html
332 /// assert_eq!("hello", s.to_lowercase());
335 /// A tricky example, with sigma:
340 /// assert_eq!("σ", sigma.to_lowercase());
342 /// // but at the end of a word, it's ς, not σ:
343 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
345 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
348 /// Languages without case are not changed:
351 /// let new_year = "农历新年";
353 /// assert_eq!(new_year, new_year.to_lowercase());
355 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
356 pub fn to_lowercase(&self) -> String {
357 let mut s = String::with_capacity(self.len());
358 for (i, c) in self[..].char_indices() {
360 // Σ maps to σ, except at the end of a word where it maps to ς.
361 // This is the only conditional (contextual) but language-independent mapping
362 // in `SpecialCasing.txt`,
363 // so hard-code it rather than have a generic "condition" mechanism.
364 // See https://github.com/rust-lang/rust/issues/26035
365 map_uppercase_sigma(self, i, &mut s)
367 match conversions::to_lower(c) {
368 [a, '\0', _] => s.push(a),
383 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
384 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
385 // for the definition of `Final_Sigma`.
386 debug_assert!('Σ'.len_utf8() == 2);
387 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
388 !case_ignoreable_then_cased(from[i + 2..].chars());
389 to.push_str(if is_word_final { "ς" } else { "σ" });
392 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
393 use core::unicode::derived_property::{Cased, Case_Ignorable};
394 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
401 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
403 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
406 /// Since some characters can expand into multiple characters when changing
407 /// the case, this function returns a [`String`] instead of modifying the
408 /// parameter in-place.
410 /// [`String`]: string/struct.String.html
419 /// assert_eq!("HELLO", s.to_uppercase());
422 /// Scripts without case are not changed:
425 /// let new_year = "农历新年";
427 /// assert_eq!(new_year, new_year.to_uppercase());
429 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
430 pub fn to_uppercase(&self) -> String {
431 let mut s = String::with_capacity(self.len());
432 for c in self[..].chars() {
433 match conversions::to_upper(c) {
434 [a, '\0', _] => s.push(a),
449 /// Escapes each char in `s` with [`char::escape_debug`].
451 /// Note: only extended grapheme codepoints that begin the string will be
454 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
455 #[unstable(feature = "str_escape",
456 reason = "return type may change to be an iterator",
458 pub fn escape_debug(&self) -> EscapeDebug {
459 let mut chars = self.chars();
462 .map(|first| first.escape_debug_ext(true))
465 .chain(chars.flat_map(CharEscapeDebugContinue))
469 /// Escapes each char in `s` with [`char::escape_default`].
471 /// [`char::escape_default`]: primitive.char.html#method.escape_default
472 #[unstable(feature = "str_escape",
473 reason = "return type may change to be an iterator",
475 pub fn escape_default(&self) -> EscapeDefault {
476 EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) }
479 /// Escapes each char in `s` with [`char::escape_unicode`].
481 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
482 #[unstable(feature = "str_escape",
483 reason = "return type may change to be an iterator",
485 pub fn escape_unicode(&self) -> EscapeUnicode {
486 EscapeUnicode { inner: self.chars().flat_map(CharEscapeUnicode) }
489 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
491 /// [`String`]: string/struct.String.html
492 /// [`Box<str>`]: boxed/struct.Box.html
499 /// let string = String::from("birthday gift");
500 /// let boxed_str = string.clone().into_boxed_str();
502 /// assert_eq!(boxed_str.into_string(), string);
504 #[stable(feature = "box_str", since = "1.4.0")]
506 pub fn into_string(self: Box<str>) -> String {
507 let slice = Box::<[u8]>::from(self);
508 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
511 /// Creates a new [`String`] by repeating a string `n` times.
515 /// This function will panic if the capacity would overflow.
517 /// [`String`]: string/struct.String.html
524 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
527 /// A panic upon overflow:
531 /// // this will panic at runtime
532 /// "0123456789abcdef".repeat(usize::max_value());
535 #[stable(feature = "repeat_str", since = "1.16.0")]
536 pub fn repeat(&self, n: usize) -> String {
537 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
540 /// Returns a copy of this string where each character is mapped to its
541 /// ASCII upper case equivalent.
543 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
544 /// but non-ASCII letters are unchanged.
546 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
548 /// To uppercase ASCII characters in addition to non-ASCII characters, use
549 /// [`to_uppercase`].
554 /// let s = "Grüße, Jürgen ❤";
556 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
559 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
560 /// [`to_uppercase`]: #method.to_uppercase
561 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
563 pub fn to_ascii_uppercase(&self) -> String {
564 let mut bytes = self.as_bytes().to_vec();
565 bytes.make_ascii_uppercase();
566 // make_ascii_uppercase() preserves the UTF-8 invariant.
567 unsafe { String::from_utf8_unchecked(bytes) }
570 /// Returns a copy of this string where each character is mapped to its
571 /// ASCII lower case equivalent.
573 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
574 /// but non-ASCII letters are unchanged.
576 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
578 /// To lowercase ASCII characters in addition to non-ASCII characters, use
579 /// [`to_lowercase`].
584 /// let s = "Grüße, Jürgen ❤";
586 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
589 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
590 /// [`to_lowercase`]: #method.to_lowercase
591 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
593 pub fn to_ascii_lowercase(&self) -> String {
594 let mut bytes = self.as_bytes().to_vec();
595 bytes.make_ascii_lowercase();
596 // make_ascii_lowercase() preserves the UTF-8 invariant.
597 unsafe { String::from_utf8_unchecked(bytes) }
601 /// Converts a boxed slice of bytes to a boxed string slice without checking
602 /// that the string contains valid UTF-8.
609 /// let smile_utf8 = Box::new([226, 152, 186]);
610 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
612 /// assert_eq!("☺", &*smile);
614 #[stable(feature = "str_box_extras", since = "1.20.0")]
616 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
617 Box::from_raw(Box::into_raw(v) as *mut str)
622 struct CharEscapeDebugContinue impl Fn = |c: char| -> char::EscapeDebug {
623 c.escape_debug_ext(false)
627 struct CharEscapeUnicode impl Fn = |c: char| -> char::EscapeUnicode {
631 struct CharEscapeDefault impl Fn = |c: char| -> char::EscapeDefault {
636 macro_rules! escape_types {
638 struct $Name: ident<'a> {
642 #[unstable(feature = "str_escape", issue = "27791")]
643 #[derive(Clone, Debug)]
644 pub struct $Name<'a> {
648 #[unstable(feature = "str_escape", issue = "27791")]
649 impl<'a> fmt::Display for $Name<'a> {
650 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
651 self.clone().try_for_each(|c| f.write_char(c))
655 #[unstable(feature = "str_escape", issue = "27791")]
656 impl<'a> Iterator for $Name<'a> {
660 fn next(&mut self) -> Option<char> { self.inner.next() }
663 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
666 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where
667 Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
669 self.inner.try_fold(init, fold)
673 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
674 where Fold: FnMut(Acc, Self::Item) -> Acc,
676 self.inner.fold(init, fold)
680 #[unstable(feature = "str_escape", issue = "27791")]
681 impl<'a> FusedIterator for $Name<'a> {}
686 struct EscapeDebug<'a> {
688 Flatten<option::IntoIter<char::EscapeDebug>>,
689 FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>
692 struct EscapeUnicode<'a> {
693 inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>,
695 struct EscapeDefault<'a> {
696 inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>,