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, BorrowMut};
32 use core::str::pattern::{Pattern, Searcher, ReverseSearcher, DoubleEndedSearcher};
35 use core::iter::FusedIterator;
36 use core::unicode::conversions;
38 use crate::borrow::ToOwned;
39 use crate::boxed::Box;
40 use crate::slice::{Concat, Join, SliceIndex};
41 use crate::string::String;
44 #[stable(feature = "rust1", since = "1.0.0")]
45 pub use core::str::{FromStr, Utf8Error};
47 #[stable(feature = "rust1", since = "1.0.0")]
48 pub use core::str::{Lines, LinesAny};
49 #[stable(feature = "rust1", since = "1.0.0")]
50 pub use core::str::{Split, RSplit};
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use core::str::{SplitN, RSplitN};
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use core::str::{SplitTerminator, RSplitTerminator};
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub use core::str::{Matches, RMatches};
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub use core::str::{MatchIndices, RMatchIndices};
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub use core::str::SplitWhitespace;
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub use core::str::pattern;
67 #[stable(feature = "encode_utf16", since = "1.8.0")]
68 pub use core::str::EncodeUtf16;
69 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
70 pub use core::str::SplitAsciiWhitespace;
71 #[stable(feature = "str_escape", since = "1.34.0")]
72 pub use core::str::{EscapeDebug, EscapeDefault, EscapeUnicode};
74 /// Note: `str` in `Concat<str>` is not meaningful here.
75 /// This type parameter of the trait only exists to enable another impl.
76 #[unstable(feature = "slice_concat_ext", issue = "27747")]
77 impl<S: Borrow<str>> Concat<str> for [S] {
80 fn concat(slice: &Self) -> String {
85 #[unstable(feature = "slice_concat_ext", issue = "27747")]
86 impl<S: Borrow<str>> Join<str> for [S] {
89 fn join(slice: &Self, sep: &str) -> String {
91 String::from_utf8_unchecked( join_generic_copy(slice, sep.as_bytes()) )
96 macro_rules! spezialize_for_lengths {
97 ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
98 let mut target = $target;
100 let sep_bytes = $separator;
101 match $separator.len() {
103 // loops with hardcoded sizes run much faster
104 // specialize the cases with small separator lengths
107 copy_slice_and_advance!(target, sep_bytes);
108 copy_slice_and_advance!(target, s.borrow().as_ref());
113 // arbitrary non-zero size fallback
115 copy_slice_and_advance!(target, sep_bytes);
116 copy_slice_and_advance!(target, s.borrow().as_ref());
123 macro_rules! copy_slice_and_advance {
124 ($target:expr, $bytes:expr) => {
125 let len = $bytes.len();
126 let (head, tail) = {$target}.split_at_mut(len);
127 head.copy_from_slice($bytes);
132 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
133 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
134 // For this reason SliceConcat<T> is not specialized for T: Copy and SliceConcat<str> is the
135 // only user of this function. It is left in place for the time when that is fixed.
137 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
138 // [T] and str both impl AsRef<[T]> for some T
139 // => s.borrow().as_ref() and we always have slices
140 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
143 B: AsRef<[T]> + ?Sized,
146 let sep_len = sep.len();
147 let mut iter = slice.iter();
149 // the first slice is the only one without a separator preceding it
150 let first = match iter.next() {
151 Some(first) => first,
152 None => return vec![],
155 // compute the exact total length of the joined Vec
156 // if the `len` calculation overflows, we'll panic
157 // we would have run out of memory anyway and the rest of the function requires
158 // the entire Vec pre-allocated for safety
159 let len = sep_len.checked_mul(iter.len()).and_then(|n| {
161 .map(|s| s.borrow().as_ref().len())
162 .try_fold(n, usize::checked_add)
163 }).expect("attempt to join into collection with len > usize::MAX");
165 // crucial for safety
166 let mut result = Vec::with_capacity(len);
167 assert!(result.capacity() >= len);
169 result.extend_from_slice(first.borrow().as_ref());
173 let pos = result.len();
174 let target = result.get_unchecked_mut(pos..len);
176 // copy separator and slices over without bounds checks
177 // generate loops with hardcoded offsets for small separators
178 // massive improvements possible (~ x2)
179 spezialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
186 #[stable(feature = "rust1", since = "1.0.0")]
187 impl Borrow<str> for String {
189 fn borrow(&self) -> &str {
194 #[stable(feature = "string_borrow_mut", since = "1.36.0")]
195 impl BorrowMut<str> for String {
197 fn borrow_mut(&mut self) -> &mut str {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl ToOwned for str {
206 fn to_owned(&self) -> String {
207 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
210 fn clone_into(&self, target: &mut String) {
211 let mut b = mem::take(target).into_bytes();
212 self.as_bytes().clone_into(&mut b);
213 *target = unsafe { String::from_utf8_unchecked(b) }
217 /// Methods for string slices.
218 #[lang = "str_alloc"]
221 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
228 /// let s = "this is a string";
229 /// let boxed_str = s.to_owned().into_boxed_str();
230 /// let boxed_bytes = boxed_str.into_boxed_bytes();
231 /// assert_eq!(*boxed_bytes, *s.as_bytes());
233 #[stable(feature = "str_box_extras", since = "1.20.0")]
235 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
239 /// Replaces all matches of a pattern with another string.
241 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
242 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
243 /// replaces them with the replacement string slice.
245 /// [`String`]: string/struct.String.html
252 /// let s = "this is old";
254 /// assert_eq!("this is new", s.replace("old", "new"));
257 /// When the pattern doesn't match:
260 /// let s = "this is old";
261 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
263 #[must_use = "this returns the replaced string as a new allocation, \
264 without modifying the original"]
265 #[stable(feature = "rust1", since = "1.0.0")]
267 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
268 let mut result = String::new();
269 let mut last_end = 0;
270 for (start, part) in self.match_indices(from) {
271 result.push_str(unsafe { self.get_unchecked(last_end..start) });
273 last_end = start + part.len();
275 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
279 /// Replaces first N matches of a pattern with another string.
281 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
282 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
283 /// replaces them with the replacement string slice at most `count` times.
285 /// [`String`]: string/struct.String.html
292 /// let s = "foo foo 123 foo";
293 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
294 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
295 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
298 /// When the pattern doesn't match:
301 /// let s = "this is old";
302 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
304 #[must_use = "this returns the replaced string as a new allocation, \
305 without modifying the original"]
306 #[stable(feature = "str_replacen", since = "1.16.0")]
307 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
308 // Hope to reduce the times of re-allocation
309 let mut result = String::with_capacity(32);
310 let mut last_end = 0;
311 for (start, part) in self.match_indices(pat).take(count) {
312 result.push_str(unsafe { self.get_unchecked(last_end..start) });
314 last_end = start + part.len();
316 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
320 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
322 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
325 /// Since some characters can expand into multiple characters when changing
326 /// the case, this function returns a [`String`] instead of modifying the
327 /// parameter in-place.
329 /// [`String`]: string/struct.String.html
338 /// assert_eq!("hello", s.to_lowercase());
341 /// A tricky example, with sigma:
346 /// assert_eq!("σ", sigma.to_lowercase());
348 /// // but at the end of a word, it's ς, not σ:
349 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
351 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
354 /// Languages without case are not changed:
357 /// let new_year = "农历新年";
359 /// assert_eq!(new_year, new_year.to_lowercase());
361 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
362 pub fn to_lowercase(&self) -> String {
363 let mut s = String::with_capacity(self.len());
364 for (i, c) in self[..].char_indices() {
366 // Σ maps to σ, except at the end of a word where it maps to ς.
367 // This is the only conditional (contextual) but language-independent mapping
368 // in `SpecialCasing.txt`,
369 // so hard-code it rather than have a generic "condition" mechanism.
370 // See https://github.com/rust-lang/rust/issues/26035
371 map_uppercase_sigma(self, i, &mut s)
373 match conversions::to_lower(c) {
374 [a, '\0', _] => s.push(a),
389 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
390 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
391 // for the definition of `Final_Sigma`.
392 debug_assert!('Σ'.len_utf8() == 2);
393 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
394 !case_ignoreable_then_cased(from[i + 2..].chars());
395 to.push_str(if is_word_final { "ς" } else { "σ" });
398 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
399 use core::unicode::derived_property::{Cased, Case_Ignorable};
400 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
407 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
409 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
412 /// Since some characters can expand into multiple characters when changing
413 /// the case, this function returns a [`String`] instead of modifying the
414 /// parameter in-place.
416 /// [`String`]: string/struct.String.html
425 /// assert_eq!("HELLO", s.to_uppercase());
428 /// Scripts without case are not changed:
431 /// let new_year = "农历新年";
433 /// assert_eq!(new_year, new_year.to_uppercase());
436 /// One character can become multiple:
438 /// let s = "tschüß";
440 /// assert_eq!("TSCHÜSS", s.to_uppercase());
442 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
443 pub fn to_uppercase(&self) -> String {
444 let mut s = String::with_capacity(self.len());
445 for c in self[..].chars() {
446 match conversions::to_upper(c) {
447 [a, '\0', _] => s.push(a),
462 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
464 /// [`String`]: string/struct.String.html
465 /// [`Box<str>`]: boxed/struct.Box.html
472 /// let string = String::from("birthday gift");
473 /// let boxed_str = string.clone().into_boxed_str();
475 /// assert_eq!(boxed_str.into_string(), string);
477 #[stable(feature = "box_str", since = "1.4.0")]
479 pub fn into_string(self: Box<str>) -> String {
480 let slice = Box::<[u8]>::from(self);
481 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
484 /// Creates a new [`String`] by repeating a string `n` times.
488 /// This function will panic if the capacity would overflow.
490 /// [`String`]: string/struct.String.html
497 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
500 /// A panic upon overflow:
504 /// // this will panic at runtime
505 /// "0123456789abcdef".repeat(usize::max_value());
508 #[stable(feature = "repeat_str", since = "1.16.0")]
509 pub fn repeat(&self, n: usize) -> String {
510 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
513 /// Returns a copy of this string where each character is mapped to its
514 /// ASCII upper case equivalent.
516 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
517 /// but non-ASCII letters are unchanged.
519 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
521 /// To uppercase ASCII characters in addition to non-ASCII characters, use
522 /// [`to_uppercase`].
527 /// let s = "Grüße, Jürgen ❤";
529 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
532 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
533 /// [`to_uppercase`]: #method.to_uppercase
534 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
536 pub fn to_ascii_uppercase(&self) -> String {
537 let mut bytes = self.as_bytes().to_vec();
538 bytes.make_ascii_uppercase();
539 // make_ascii_uppercase() preserves the UTF-8 invariant.
540 unsafe { String::from_utf8_unchecked(bytes) }
543 /// Returns a copy of this string where each character is mapped to its
544 /// ASCII lower case equivalent.
546 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
547 /// but non-ASCII letters are unchanged.
549 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
551 /// To lowercase ASCII characters in addition to non-ASCII characters, use
552 /// [`to_lowercase`].
557 /// let s = "Grüße, Jürgen ❤";
559 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
562 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
563 /// [`to_lowercase`]: #method.to_lowercase
564 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
566 pub fn to_ascii_lowercase(&self) -> String {
567 let mut bytes = self.as_bytes().to_vec();
568 bytes.make_ascii_lowercase();
569 // make_ascii_lowercase() preserves the UTF-8 invariant.
570 unsafe { String::from_utf8_unchecked(bytes) }
574 /// Converts a boxed slice of bytes to a boxed string slice without checking
575 /// that the string contains valid UTF-8.
582 /// let smile_utf8 = Box::new([226, 152, 186]);
583 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
585 /// assert_eq!("☺", &*smile);
587 #[stable(feature = "str_box_extras", since = "1.20.0")]
589 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
590 Box::from_raw(Box::into_raw(v) as *mut str)