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::{SliceConcatExt, 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 #[unstable(feature = "slice_concat_ext",
75 reason = "trait should not have to exist",
77 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
80 fn concat(&self) -> String {
84 fn join(&self, sep: &str) -> String {
86 String::from_utf8_unchecked( join_generic_copy(self, sep.as_bytes()) )
91 macro_rules! spezialize_for_lengths {
92 ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
93 let mut target = $target;
95 let sep_bytes = $separator;
96 match $separator.len() {
98 // loops with hardcoded sizes run much faster
99 // specialize the cases with small separator lengths
102 copy_slice_and_advance!(target, sep_bytes);
103 copy_slice_and_advance!(target, s.borrow().as_ref());
108 // arbitrary non-zero size fallback
110 copy_slice_and_advance!(target, sep_bytes);
111 copy_slice_and_advance!(target, s.borrow().as_ref());
118 macro_rules! copy_slice_and_advance {
119 ($target:expr, $bytes:expr) => {
120 let len = $bytes.len();
121 let (head, tail) = {$target}.split_at_mut(len);
122 head.copy_from_slice($bytes);
127 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
128 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
129 // For this reason SliceConcatExt<T> is not specialized for T: Copy and SliceConcatExt<str> is the
130 // only user of this function. It is left in place for the time when that is fixed.
132 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
133 // [T] and str both impl AsRef<[T]> for some T
134 // => s.borrow().as_ref() and we always have slices
135 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
138 B: AsRef<[T]> + ?Sized,
141 let sep_len = sep.len();
142 let mut iter = slice.iter();
144 // the first slice is the only one without a separator preceding it
145 let first = match iter.next() {
146 Some(first) => first,
147 None => return vec![],
150 // compute the exact total length of the joined Vec
151 // if the `len` calculation overflows, we'll panic
152 // we would have run out of memory anyway and the rest of the function requires
153 // the entire Vec pre-allocated for safety
154 let len = sep_len.checked_mul(iter.len()).and_then(|n| {
156 .map(|s| s.borrow().as_ref().len())
157 .try_fold(n, usize::checked_add)
158 }).expect("attempt to join into collection with len > usize::MAX");
160 // crucial for safety
161 let mut result = Vec::with_capacity(len);
162 assert!(result.capacity() >= len);
164 result.extend_from_slice(first.borrow().as_ref());
168 let pos = result.len();
169 let target = result.get_unchecked_mut(pos..len);
171 // copy separator and slices over without bounds checks
172 // generate loops with hardcoded offsets for small separators
173 // massive improvements possible (~ x2)
174 spezialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl Borrow<str> for String {
184 fn borrow(&self) -> &str {
189 #[stable(feature = "string_borrow_mut", since = "1.36.0")]
190 impl BorrowMut<str> for String {
192 fn borrow_mut(&mut self) -> &mut str {
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl ToOwned for str {
201 fn to_owned(&self) -> String {
202 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
205 fn clone_into(&self, target: &mut String) {
206 let mut b = mem::take(target).into_bytes();
207 self.as_bytes().clone_into(&mut b);
208 *target = unsafe { String::from_utf8_unchecked(b) }
212 /// Methods for string slices.
213 #[lang = "str_alloc"]
216 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
223 /// let s = "this is a string";
224 /// let boxed_str = s.to_owned().into_boxed_str();
225 /// let boxed_bytes = boxed_str.into_boxed_bytes();
226 /// assert_eq!(*boxed_bytes, *s.as_bytes());
228 #[stable(feature = "str_box_extras", since = "1.20.0")]
230 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
234 /// Replaces all matches of a pattern with another string.
236 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
237 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
238 /// replaces them with the replacement string slice.
240 /// [`String`]: string/struct.String.html
247 /// let s = "this is old";
249 /// assert_eq!("this is new", s.replace("old", "new"));
252 /// When the pattern doesn't match:
255 /// let s = "this is old";
256 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
258 #[must_use = "this returns the replaced string as a new allocation, \
259 without modifying the original"]
260 #[stable(feature = "rust1", since = "1.0.0")]
262 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
263 let mut result = String::new();
264 let mut last_end = 0;
265 for (start, part) in self.match_indices(from) {
266 result.push_str(unsafe { self.get_unchecked(last_end..start) });
268 last_end = start + part.len();
270 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
274 /// Replaces first N matches of a pattern with another string.
276 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
277 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
278 /// replaces them with the replacement string slice at most `count` times.
280 /// [`String`]: string/struct.String.html
287 /// let s = "foo foo 123 foo";
288 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
289 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
290 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
293 /// When the pattern doesn't match:
296 /// let s = "this is old";
297 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
299 #[must_use = "this returns the replaced string as a new allocation, \
300 without modifying the original"]
301 #[stable(feature = "str_replacen", since = "1.16.0")]
302 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
303 // Hope to reduce the times of re-allocation
304 let mut result = String::with_capacity(32);
305 let mut last_end = 0;
306 for (start, part) in self.match_indices(pat).take(count) {
307 result.push_str(unsafe { self.get_unchecked(last_end..start) });
309 last_end = start + part.len();
311 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
315 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
317 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
320 /// Since some characters can expand into multiple characters when changing
321 /// the case, this function returns a [`String`] instead of modifying the
322 /// parameter in-place.
324 /// [`String`]: string/struct.String.html
333 /// assert_eq!("hello", s.to_lowercase());
336 /// A tricky example, with sigma:
341 /// assert_eq!("σ", sigma.to_lowercase());
343 /// // but at the end of a word, it's ς, not σ:
344 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
346 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
349 /// Languages without case are not changed:
352 /// let new_year = "农历新年";
354 /// assert_eq!(new_year, new_year.to_lowercase());
356 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
357 pub fn to_lowercase(&self) -> String {
358 let mut s = String::with_capacity(self.len());
359 for (i, c) in self[..].char_indices() {
361 // Σ maps to σ, except at the end of a word where it maps to ς.
362 // This is the only conditional (contextual) but language-independent mapping
363 // in `SpecialCasing.txt`,
364 // so hard-code it rather than have a generic "condition" mechanism.
365 // See https://github.com/rust-lang/rust/issues/26035
366 map_uppercase_sigma(self, i, &mut s)
368 match conversions::to_lower(c) {
369 [a, '\0', _] => s.push(a),
384 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
385 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
386 // for the definition of `Final_Sigma`.
387 debug_assert!('Σ'.len_utf8() == 2);
388 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
389 !case_ignoreable_then_cased(from[i + 2..].chars());
390 to.push_str(if is_word_final { "ς" } else { "σ" });
393 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
394 use core::unicode::derived_property::{Cased, Case_Ignorable};
395 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
402 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
404 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
407 /// Since some characters can expand into multiple characters when changing
408 /// the case, this function returns a [`String`] instead of modifying the
409 /// parameter in-place.
411 /// [`String`]: string/struct.String.html
420 /// assert_eq!("HELLO", s.to_uppercase());
423 /// Scripts without case are not changed:
426 /// let new_year = "农历新年";
428 /// assert_eq!(new_year, new_year.to_uppercase());
431 /// One character can become multiple:
433 /// let s = "tschüß";
435 /// assert_eq!("TSCHÜSS", s.to_uppercase());
437 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
438 pub fn to_uppercase(&self) -> String {
439 let mut s = String::with_capacity(self.len());
440 for c in self[..].chars() {
441 match conversions::to_upper(c) {
442 [a, '\0', _] => s.push(a),
457 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
459 /// [`String`]: string/struct.String.html
460 /// [`Box<str>`]: boxed/struct.Box.html
467 /// let string = String::from("birthday gift");
468 /// let boxed_str = string.clone().into_boxed_str();
470 /// assert_eq!(boxed_str.into_string(), string);
472 #[stable(feature = "box_str", since = "1.4.0")]
474 pub fn into_string(self: Box<str>) -> String {
475 let slice = Box::<[u8]>::from(self);
476 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
479 /// Creates a new [`String`] by repeating a string `n` times.
483 /// This function will panic if the capacity would overflow.
485 /// [`String`]: string/struct.String.html
492 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
495 /// A panic upon overflow:
499 /// // this will panic at runtime
500 /// "0123456789abcdef".repeat(usize::max_value());
503 #[stable(feature = "repeat_str", since = "1.16.0")]
504 pub fn repeat(&self, n: usize) -> String {
505 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
508 /// Returns a copy of this string where each character is mapped to its
509 /// ASCII upper case equivalent.
511 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
512 /// but non-ASCII letters are unchanged.
514 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
516 /// To uppercase ASCII characters in addition to non-ASCII characters, use
517 /// [`to_uppercase`].
522 /// let s = "Grüße, Jürgen ❤";
524 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
527 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
528 /// [`to_uppercase`]: #method.to_uppercase
529 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
531 pub fn to_ascii_uppercase(&self) -> String {
532 let mut bytes = self.as_bytes().to_vec();
533 bytes.make_ascii_uppercase();
534 // make_ascii_uppercase() preserves the UTF-8 invariant.
535 unsafe { String::from_utf8_unchecked(bytes) }
538 /// Returns a copy of this string where each character is mapped to its
539 /// ASCII lower case equivalent.
541 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
542 /// but non-ASCII letters are unchanged.
544 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
546 /// To lowercase ASCII characters in addition to non-ASCII characters, use
547 /// [`to_lowercase`].
552 /// let s = "Grüße, Jürgen ❤";
554 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
557 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
558 /// [`to_lowercase`]: #method.to_lowercase
559 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
561 pub fn to_ascii_lowercase(&self) -> String {
562 let mut bytes = self.as_bytes().to_vec();
563 bytes.make_ascii_lowercase();
564 // make_ascii_lowercase() preserves the UTF-8 invariant.
565 unsafe { String::from_utf8_unchecked(bytes) }
569 /// Converts a boxed slice of bytes to a boxed string slice without checking
570 /// that the string contains valid UTF-8.
577 /// let smile_utf8 = Box::new([226, 152, 186]);
578 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
580 /// assert_eq!("☺", &*smile);
582 #[stable(feature = "str_box_extras", since = "1.20.0")]
584 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
585 Box::from_raw(Box::into_raw(v) as *mut str)