1 // Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Unicode string slices.
13 //! *[See also the `str` primitive type](../../std/primitive.str.html).*
15 //! The `&str` type is one of the two main string types, the other being `String`.
16 //! Unlike its `String` counterpart, its contents are borrowed.
20 //! A basic string declaration of `&str` type:
23 //! let hello_world = "Hello, World!";
26 //! Here we have declared a string literal, also known as a string slice.
27 //! String literals have a static lifetime, which means the string `hello_world`
28 //! is guaranteed to be valid for the duration of the entire program.
29 //! We can explicitly specify `hello_world`'s lifetime as well:
32 //! let hello_world: &'static str = "Hello, world!";
35 #![stable(feature = "rust1", since = "1.0.0")]
37 // Many of the usings in this module are only used in the test configuration.
38 // It's cleaner to just turn off the unused_imports warning than to fix them.
39 #![allow(unused_imports)]
42 use core::str as core_str;
43 use core::str::pattern::Pattern;
44 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
47 use core::iter::FusedIterator;
48 use core::unicode::conversions;
50 use borrow::{Borrow, ToOwned};
52 use slice::{SliceConcatExt, SliceIndex};
56 #[stable(feature = "rust1", since = "1.0.0")]
57 pub use core::str::{FromStr, Utf8Error};
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use core::str::{Lines, LinesAny};
61 #[stable(feature = "rust1", since = "1.0.0")]
62 pub use core::str::{Split, RSplit};
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub use core::str::{SplitN, RSplitN};
65 #[stable(feature = "rust1", since = "1.0.0")]
66 pub use core::str::{SplitTerminator, RSplitTerminator};
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub use core::str::{Matches, RMatches};
69 #[stable(feature = "rust1", since = "1.0.0")]
70 pub use core::str::{MatchIndices, RMatchIndices};
71 #[stable(feature = "rust1", since = "1.0.0")]
72 pub use core::str::{from_utf8, from_utf8_mut, Chars, CharIndices, Bytes};
73 #[stable(feature = "rust1", since = "1.0.0")]
74 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
75 #[stable(feature = "rust1", since = "1.0.0")]
76 pub use core::str::SplitWhitespace;
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub use core::str::pattern;
79 #[stable(feature = "encode_utf16", since = "1.8.0")]
80 pub use core::str::EncodeUtf16;
81 #[unstable(feature = "split_ascii_whitespace", issue = "48656")]
82 pub use core::str::SplitAsciiWhitespace;
84 #[unstable(feature = "slice_concat_ext",
85 reason = "trait should not have to exist",
87 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
90 fn concat(&self) -> String {
94 fn join(&self, sep: &str) -> String {
96 String::from_utf8_unchecked( join_generic_copy(self, sep.as_bytes()) )
100 fn connect(&self, sep: &str) -> String {
105 macro_rules! spezialize_for_lengths {
106 ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
107 let mut target = $target;
109 let sep_bytes = $separator;
110 match $separator.len() {
112 // loops with hardcoded sizes run much faster
113 // specialize the cases with small separator lengths
116 copy_slice_and_advance!(target, sep_bytes);
117 copy_slice_and_advance!(target, s.borrow().as_ref());
122 // arbitrary non-zero size fallback
124 copy_slice_and_advance!(target, sep_bytes);
125 copy_slice_and_advance!(target, s.borrow().as_ref());
132 macro_rules! copy_slice_and_advance {
133 ($target:expr, $bytes:expr) => {
134 let len = $bytes.len();
135 let (head, tail) = {$target}.split_at_mut(len);
136 head.copy_from_slice($bytes);
141 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
142 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
143 // For this reason SliceConcatExt<T> is not specialized for T: Copy and SliceConcatExt<str> is the
144 // only user of this function. It is left in place for the time when that is fixed.
146 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
147 // [T] and str both impl AsRef<[T]> for some T
148 // => s.borrow().as_ref() and we always have slices
149 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
152 B: AsRef<[T]> + ?Sized,
155 let sep_len = sep.len();
156 let mut iter = slice.iter();
158 // the first slice is the only one without a separator preceding it
159 let first = match iter.next() {
160 Some(first) => first,
161 None => return vec![],
164 // compute the exact total length of the joined Vec
165 // if the `len` calculation overflows, we'll panic
166 // we would have run out of memory anyway and the rest of the function requires
167 // the entire Vec pre-allocated for safety
168 let len = sep_len.checked_mul(iter.len()).and_then(|n| {
170 .map(|s| s.borrow().as_ref().len())
171 .try_fold(n, usize::checked_add)
172 }).expect("attempt to join into collection with len > usize::MAX");
174 // crucial for safety
175 let mut result = Vec::with_capacity(len);
176 assert!(result.capacity() >= len);
178 result.extend_from_slice(first.borrow().as_ref());
182 let pos = result.len();
183 let target = result.get_unchecked_mut(pos..len);
185 // copy separator and slices over without bounds checks
186 // generate loops with hardcoded offsets for small separators
187 // massive improvements possible (~ x2)
188 spezialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
195 #[stable(feature = "rust1", since = "1.0.0")]
196 impl Borrow<str> for String {
198 fn borrow(&self) -> &str {
203 #[stable(feature = "rust1", since = "1.0.0")]
204 impl ToOwned for str {
207 fn to_owned(&self) -> String {
208 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
211 fn clone_into(&self, target: &mut String) {
212 let mut b = mem::replace(target, String::new()).into_bytes();
213 self.as_bytes().clone_into(&mut b);
214 *target = unsafe { String::from_utf8_unchecked(b) }
218 /// Methods for string slices.
219 #[lang = "str_alloc"]
222 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
229 /// let s = "this is a string";
230 /// let boxed_str = s.to_owned().into_boxed_str();
231 /// let boxed_bytes = boxed_str.into_boxed_bytes();
232 /// assert_eq!(*boxed_bytes, *s.as_bytes());
234 #[stable(feature = "str_box_extras", since = "1.20.0")]
236 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
240 /// Replaces all matches of a pattern with another string.
242 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
243 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
244 /// replaces them with the replacement string slice.
246 /// [`String`]: string/struct.String.html
253 /// let s = "this is old";
255 /// assert_eq!("this is new", s.replace("old", "new"));
258 /// When the pattern doesn't match:
261 /// let s = "this is old";
262 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
264 #[must_use = "this returns the replaced string as a new allocation, \
265 without modifying the original"]
266 #[stable(feature = "rust1", since = "1.0.0")]
268 pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
269 let mut result = String::new();
270 let mut last_end = 0;
271 for (start, part) in self.match_indices(from) {
272 result.push_str(unsafe { self.get_unchecked(last_end..start) });
274 last_end = start + part.len();
276 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
280 /// Replaces first N matches of a pattern with another string.
282 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
283 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
284 /// replaces them with the replacement string slice at most `count` times.
286 /// [`String`]: string/struct.String.html
293 /// let s = "foo foo 123 foo";
294 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
295 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
296 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
299 /// When the pattern doesn't match:
302 /// let s = "this is old";
303 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
305 #[must_use = "this returns the replaced string as a new allocation, \
306 without modifying the original"]
307 #[stable(feature = "str_replacen", since = "1.16.0")]
308 pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
309 // Hope to reduce the times of re-allocation
310 let mut result = String::with_capacity(32);
311 let mut last_end = 0;
312 for (start, part) in self.match_indices(pat).take(count) {
313 result.push_str(unsafe { self.get_unchecked(last_end..start) });
315 last_end = start + part.len();
317 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
321 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
323 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
326 /// Since some characters can expand into multiple characters when changing
327 /// the case, this function returns a [`String`] instead of modifying the
328 /// parameter in-place.
330 /// [`String`]: string/struct.String.html
339 /// assert_eq!("hello", s.to_lowercase());
342 /// A tricky example, with sigma:
347 /// assert_eq!("σ", sigma.to_lowercase());
349 /// // but at the end of a word, it's ς, not σ:
350 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
352 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
355 /// Languages without case are not changed:
358 /// let new_year = "农历新年";
360 /// assert_eq!(new_year, new_year.to_lowercase());
362 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
363 pub fn to_lowercase(&self) -> String {
364 let mut s = String::with_capacity(self.len());
365 for (i, c) in self[..].char_indices() {
367 // Σ maps to σ, except at the end of a word where it maps to ς.
368 // This is the only conditional (contextual) but language-independent mapping
369 // in `SpecialCasing.txt`,
370 // so hard-code it rather than have a generic "condition" mechanism.
371 // See https://github.com/rust-lang/rust/issues/26035
372 map_uppercase_sigma(self, i, &mut s)
374 match conversions::to_lower(c) {
375 [a, '\0', _] => s.push(a),
390 fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
391 // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
392 // for the definition of `Final_Sigma`.
393 debug_assert!('Σ'.len_utf8() == 2);
394 let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev()) &&
395 !case_ignoreable_then_cased(from[i + 2..].chars());
396 to.push_str(if is_word_final { "ς" } else { "σ" });
399 fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
400 use core::unicode::derived_property::{Cased, Case_Ignorable};
401 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
408 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
410 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
413 /// Since some characters can expand into multiple characters when changing
414 /// the case, this function returns a [`String`] instead of modifying the
415 /// parameter in-place.
417 /// [`String`]: string/struct.String.html
426 /// assert_eq!("HELLO", s.to_uppercase());
429 /// Scripts without case are not changed:
432 /// let new_year = "农历新年";
434 /// assert_eq!(new_year, new_year.to_uppercase());
436 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
437 pub fn to_uppercase(&self) -> String {
438 let mut s = String::with_capacity(self.len());
439 for c in self[..].chars() {
440 match conversions::to_upper(c) {
441 [a, '\0', _] => s.push(a),
456 /// Escapes each char in `s` with [`char::escape_debug`].
458 /// Note: only extended grapheme codepoints that begin the string will be
461 /// [`char::escape_debug`]: primitive.char.html#method.escape_debug
462 #[unstable(feature = "str_escape",
463 reason = "return type may change to be an iterator",
465 pub fn escape_debug(&self) -> String {
466 let mut string = String::with_capacity(self.len());
467 let mut chars = self.chars();
468 if let Some(first) = chars.next() {
469 string.extend(first.escape_debug_ext(true))
471 string.extend(chars.flat_map(|c| c.escape_debug_ext(false)));
475 /// Escapes each char in `s` with [`char::escape_default`].
477 /// [`char::escape_default`]: primitive.char.html#method.escape_default
478 #[unstable(feature = "str_escape",
479 reason = "return type may change to be an iterator",
481 pub fn escape_default(&self) -> String {
482 self.chars().flat_map(|c| c.escape_default()).collect()
485 /// Escapes each char in `s` with [`char::escape_unicode`].
487 /// [`char::escape_unicode`]: primitive.char.html#method.escape_unicode
488 #[unstable(feature = "str_escape",
489 reason = "return type may change to be an iterator",
491 pub fn escape_unicode(&self) -> String {
492 self.chars().flat_map(|c| c.escape_unicode()).collect()
495 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
497 /// [`String`]: string/struct.String.html
498 /// [`Box<str>`]: boxed/struct.Box.html
505 /// let string = String::from("birthday gift");
506 /// let boxed_str = string.clone().into_boxed_str();
508 /// assert_eq!(boxed_str.into_string(), string);
510 #[stable(feature = "box_str", since = "1.4.0")]
512 pub fn into_string(self: Box<str>) -> String {
513 let slice = Box::<[u8]>::from(self);
514 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
517 /// Creates a new [`String`] by repeating a string `n` times.
521 /// This function will panic if the capacity would overflow.
523 /// [`String`]: string/struct.String.html
530 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
533 /// A panic upon overflow:
537 /// // this will panic at runtime
538 /// "0123456789abcdef".repeat(usize::max_value());
541 #[stable(feature = "repeat_str", since = "1.16.0")]
542 pub fn repeat(&self, n: usize) -> String {
543 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
546 /// Returns a copy of this string where each character is mapped to its
547 /// ASCII upper case equivalent.
549 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
550 /// but non-ASCII letters are unchanged.
552 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
554 /// To uppercase ASCII characters in addition to non-ASCII characters, use
555 /// [`to_uppercase`].
560 /// let s = "Grüße, Jürgen ❤";
562 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
565 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
566 /// [`to_uppercase`]: #method.to_uppercase
567 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
569 pub fn to_ascii_uppercase(&self) -> String {
570 let mut bytes = self.as_bytes().to_vec();
571 bytes.make_ascii_uppercase();
572 // make_ascii_uppercase() preserves the UTF-8 invariant.
573 unsafe { String::from_utf8_unchecked(bytes) }
576 /// Returns a copy of this string where each character is mapped to its
577 /// ASCII lower case equivalent.
579 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
580 /// but non-ASCII letters are unchanged.
582 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
584 /// To lowercase ASCII characters in addition to non-ASCII characters, use
585 /// [`to_lowercase`].
590 /// let s = "Grüße, Jürgen ❤";
592 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
595 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
596 /// [`to_lowercase`]: #method.to_lowercase
597 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
599 pub fn to_ascii_lowercase(&self) -> String {
600 let mut bytes = self.as_bytes().to_vec();
601 bytes.make_ascii_lowercase();
602 // make_ascii_lowercase() preserves the UTF-8 invariant.
603 unsafe { String::from_utf8_unchecked(bytes) }
607 /// Converts a boxed slice of bytes to a boxed string slice without checking
608 /// that the string contains valid UTF-8.
615 /// let smile_utf8 = Box::new([226, 152, 186]);
616 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
618 /// assert_eq!("☺", &*smile);
620 #[stable(feature = "str_box_extras", since = "1.20.0")]
622 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
623 Box::from_raw(Box::into_raw(v) as *mut str)