]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/str.rs
Rollup merge of #91746 - ssomers:btree_tests, r=Mark-Simulacrum
[rust.git] / library / alloc / src / str.rs
1 //! Unicode string slices.
2 //!
3 //! *[See also the `str` primitive type](str).*
4 //!
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.
7 //!
8 //! # Basic Usage
9 //!
10 //! A basic string declaration of `&str` type:
11 //!
12 //! ```
13 //! let hello_world = "Hello, World!";
14 //! ```
15 //!
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:
20 //!
21 //! ```
22 //! let hello_world: &'static str = "Hello, world!";
23 //! ```
24
25 #![stable(feature = "rust1", since = "1.0.0")]
26 // Many of the usings in this module are only used in the test configuration.
27 // It's cleaner to just turn off the unused_imports warning than to fix them.
28 #![allow(unused_imports)]
29
30 use core::borrow::{Borrow, BorrowMut};
31 use core::iter::FusedIterator;
32 use core::mem;
33 use core::ptr;
34 use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher};
35 use core::unicode::conversions;
36
37 use crate::borrow::ToOwned;
38 use crate::boxed::Box;
39 use crate::slice::{Concat, Join, SliceIndex};
40 use crate::string::String;
41 use crate::vec::Vec;
42
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub use core::str::pattern;
45 #[stable(feature = "encode_utf16", since = "1.8.0")]
46 pub use core::str::EncodeUtf16;
47 #[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
48 pub use core::str::SplitAsciiWhitespace;
49 #[stable(feature = "split_inclusive", since = "1.51.0")]
50 pub use core::str::SplitInclusive;
51 #[stable(feature = "rust1", since = "1.0.0")]
52 pub use core::str::SplitWhitespace;
53 #[stable(feature = "rust1", since = "1.0.0")]
54 pub use core::str::{from_utf8, from_utf8_mut, Bytes, CharIndices, Chars};
55 #[stable(feature = "rust1", since = "1.0.0")]
56 pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError};
57 #[stable(feature = "str_escape", since = "1.34.0")]
58 pub use core::str::{EscapeDebug, EscapeDefault, EscapeUnicode};
59 #[stable(feature = "rust1", since = "1.0.0")]
60 pub use core::str::{FromStr, Utf8Error};
61 #[allow(deprecated)]
62 #[stable(feature = "rust1", since = "1.0.0")]
63 pub use core::str::{Lines, LinesAny};
64 #[stable(feature = "rust1", since = "1.0.0")]
65 pub use core::str::{MatchIndices, RMatchIndices};
66 #[stable(feature = "rust1", since = "1.0.0")]
67 pub use core::str::{Matches, RMatches};
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub use core::str::{RSplit, Split};
70 #[stable(feature = "rust1", since = "1.0.0")]
71 pub use core::str::{RSplitN, SplitN};
72 #[stable(feature = "rust1", since = "1.0.0")]
73 pub use core::str::{RSplitTerminator, SplitTerminator};
74
75 /// Note: `str` in `Concat<str>` is not meaningful here.
76 /// This type parameter of the trait only exists to enable another impl.
77 #[cfg(not(no_global_oom_handling))]
78 #[unstable(feature = "slice_concat_ext", issue = "27747")]
79 impl<S: Borrow<str>> Concat<str> for [S] {
80     type Output = String;
81
82     fn concat(slice: &Self) -> String {
83         Join::join(slice, "")
84     }
85 }
86
87 #[cfg(not(no_global_oom_handling))]
88 #[unstable(feature = "slice_concat_ext", issue = "27747")]
89 impl<S: Borrow<str>> Join<&str> for [S] {
90     type Output = String;
91
92     fn join(slice: &Self, sep: &str) -> String {
93         unsafe { String::from_utf8_unchecked(join_generic_copy(slice, sep.as_bytes())) }
94     }
95 }
96
97 #[cfg(not(no_global_oom_handling))]
98 macro_rules! specialize_for_lengths {
99     ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {{
100         let mut target = $target;
101         let iter = $iter;
102         let sep_bytes = $separator;
103         match $separator.len() {
104             $(
105                 // loops with hardcoded sizes run much faster
106                 // specialize the cases with small separator lengths
107                 $num => {
108                     for s in iter {
109                         copy_slice_and_advance!(target, sep_bytes);
110                         let content_bytes = s.borrow().as_ref();
111                         copy_slice_and_advance!(target, content_bytes);
112                     }
113                 },
114             )*
115             _ => {
116                 // arbitrary non-zero size fallback
117                 for s in iter {
118                     copy_slice_and_advance!(target, sep_bytes);
119                     let content_bytes = s.borrow().as_ref();
120                     copy_slice_and_advance!(target, content_bytes);
121                 }
122             }
123         }
124         target
125     }}
126 }
127
128 #[cfg(not(no_global_oom_handling))]
129 macro_rules! copy_slice_and_advance {
130     ($target:expr, $bytes:expr) => {
131         let len = $bytes.len();
132         let (head, tail) = { $target }.split_at_mut(len);
133         head.copy_from_slice($bytes);
134         $target = tail;
135     };
136 }
137
138 // Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
139 // Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
140 // For this reason SliceConcat<T> is not specialized for T: Copy and SliceConcat<str> is the
141 // only user of this function. It is left in place for the time when that is fixed.
142 //
143 // the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
144 // [T] and str both impl AsRef<[T]> for some T
145 // => s.borrow().as_ref() and we always have slices
146 #[cfg(not(no_global_oom_handling))]
147 fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
148 where
149     T: Copy,
150     B: AsRef<[T]> + ?Sized,
151     S: Borrow<B>,
152 {
153     let sep_len = sep.len();
154     let mut iter = slice.iter();
155
156     // the first slice is the only one without a separator preceding it
157     let first = match iter.next() {
158         Some(first) => first,
159         None => return vec![],
160     };
161
162     // compute the exact total length of the joined Vec
163     // if the `len` calculation overflows, we'll panic
164     // we would have run out of memory anyway and the rest of the function requires
165     // the entire Vec pre-allocated for safety
166     let reserved_len = sep_len
167         .checked_mul(iter.len())
168         .and_then(|n| {
169             slice.iter().map(|s| s.borrow().as_ref().len()).try_fold(n, usize::checked_add)
170         })
171         .expect("attempt to join into collection with len > usize::MAX");
172
173     // prepare an uninitialized buffer
174     let mut result = Vec::with_capacity(reserved_len);
175     debug_assert!(result.capacity() >= reserved_len);
176
177     result.extend_from_slice(first.borrow().as_ref());
178
179     unsafe {
180         let pos = result.len();
181         let target = result.get_unchecked_mut(pos..reserved_len);
182
183         // copy separator and slices over without bounds checks
184         // generate loops with hardcoded offsets for small separators
185         // massive improvements possible (~ x2)
186         let remain = specialize_for_lengths!(sep, target, iter; 0, 1, 2, 3, 4);
187
188         // A weird borrow implementation may return different
189         // slices for the length calculation and the actual copy.
190         // Make sure we don't expose uninitialized bytes to the caller.
191         let result_len = reserved_len - remain.len();
192         result.set_len(result_len);
193     }
194     result
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl Borrow<str> for String {
199     #[inline]
200     fn borrow(&self) -> &str {
201         &self[..]
202     }
203 }
204
205 #[stable(feature = "string_borrow_mut", since = "1.36.0")]
206 impl BorrowMut<str> for String {
207     #[inline]
208     fn borrow_mut(&mut self) -> &mut str {
209         &mut self[..]
210     }
211 }
212
213 #[cfg(not(no_global_oom_handling))]
214 #[stable(feature = "rust1", since = "1.0.0")]
215 impl ToOwned for str {
216     type Owned = String;
217     #[inline]
218     fn to_owned(&self) -> String {
219         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
220     }
221
222     fn clone_into(&self, target: &mut String) {
223         let mut b = mem::take(target).into_bytes();
224         self.as_bytes().clone_into(&mut b);
225         *target = unsafe { String::from_utf8_unchecked(b) }
226     }
227 }
228
229 /// Methods for string slices.
230 #[lang = "str_alloc"]
231 #[cfg(not(test))]
232 impl str {
233     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
234     ///
235     /// # Examples
236     ///
237     /// Basic usage:
238     ///
239     /// ```
240     /// let s = "this is a string";
241     /// let boxed_str = s.to_owned().into_boxed_str();
242     /// let boxed_bytes = boxed_str.into_boxed_bytes();
243     /// assert_eq!(*boxed_bytes, *s.as_bytes());
244     /// ```
245     #[stable(feature = "str_box_extras", since = "1.20.0")]
246     #[must_use = "`self` will be dropped if the result is not used"]
247     #[inline]
248     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
249         self.into()
250     }
251
252     /// Replaces all matches of a pattern with another string.
253     ///
254     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
255     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
256     /// replaces them with the replacement string slice.
257     ///
258     /// # Examples
259     ///
260     /// Basic usage:
261     ///
262     /// ```
263     /// let s = "this is old";
264     ///
265     /// assert_eq!("this is new", s.replace("old", "new"));
266     /// ```
267     ///
268     /// When the pattern doesn't match:
269     ///
270     /// ```
271     /// let s = "this is old";
272     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
273     /// ```
274     #[cfg(not(no_global_oom_handling))]
275     #[must_use = "this returns the replaced string as a new allocation, \
276                   without modifying the original"]
277     #[stable(feature = "rust1", since = "1.0.0")]
278     #[inline]
279     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
280         let mut result = String::new();
281         let mut last_end = 0;
282         for (start, part) in self.match_indices(from) {
283             result.push_str(unsafe { self.get_unchecked(last_end..start) });
284             result.push_str(to);
285             last_end = start + part.len();
286         }
287         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
288         result
289     }
290
291     /// Replaces first N matches of a pattern with another string.
292     ///
293     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
294     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
295     /// replaces them with the replacement string slice at most `count` times.
296     ///
297     /// # Examples
298     ///
299     /// Basic usage:
300     ///
301     /// ```
302     /// let s = "foo foo 123 foo";
303     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
304     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
305     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
306     /// ```
307     ///
308     /// When the pattern doesn't match:
309     ///
310     /// ```
311     /// let s = "this is old";
312     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
313     /// ```
314     #[cfg(not(no_global_oom_handling))]
315     #[must_use = "this returns the replaced string as a new allocation, \
316                   without modifying the original"]
317     #[stable(feature = "str_replacen", since = "1.16.0")]
318     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
319         // Hope to reduce the times of re-allocation
320         let mut result = String::with_capacity(32);
321         let mut last_end = 0;
322         for (start, part) in self.match_indices(pat).take(count) {
323             result.push_str(unsafe { self.get_unchecked(last_end..start) });
324             result.push_str(to);
325             last_end = start + part.len();
326         }
327         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
328         result
329     }
330
331     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
332     ///
333     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
334     /// `Lowercase`.
335     ///
336     /// Since some characters can expand into multiple characters when changing
337     /// the case, this function returns a [`String`] instead of modifying the
338     /// parameter in-place.
339     ///
340     /// # Examples
341     ///
342     /// Basic usage:
343     ///
344     /// ```
345     /// let s = "HELLO";
346     ///
347     /// assert_eq!("hello", s.to_lowercase());
348     /// ```
349     ///
350     /// A tricky example, with sigma:
351     ///
352     /// ```
353     /// let sigma = "Σ";
354     ///
355     /// assert_eq!("σ", sigma.to_lowercase());
356     ///
357     /// // but at the end of a word, it's ς, not σ:
358     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
359     ///
360     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
361     /// ```
362     ///
363     /// Languages without case are not changed:
364     ///
365     /// ```
366     /// let new_year = "农历新年";
367     ///
368     /// assert_eq!(new_year, new_year.to_lowercase());
369     /// ```
370     #[cfg(not(no_global_oom_handling))]
371     #[must_use = "this returns the lowercase string as a new String, \
372                   without modifying the original"]
373     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
374     pub fn to_lowercase(&self) -> String {
375         let mut s = String::with_capacity(self.len());
376         for (i, c) in self[..].char_indices() {
377             if c == 'Σ' {
378                 // Σ maps to σ, except at the end of a word where it maps to ς.
379                 // This is the only conditional (contextual) but language-independent mapping
380                 // in `SpecialCasing.txt`,
381                 // so hard-code it rather than have a generic "condition" mechanism.
382                 // See https://github.com/rust-lang/rust/issues/26035
383                 map_uppercase_sigma(self, i, &mut s)
384             } else {
385                 match conversions::to_lower(c) {
386                     [a, '\0', _] => s.push(a),
387                     [a, b, '\0'] => {
388                         s.push(a);
389                         s.push(b);
390                     }
391                     [a, b, c] => {
392                         s.push(a);
393                         s.push(b);
394                         s.push(c);
395                     }
396                 }
397             }
398         }
399         return s;
400
401         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
402             // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
403             // for the definition of `Final_Sigma`.
404             debug_assert!('Σ'.len_utf8() == 2);
405             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev())
406                 && !case_ignoreable_then_cased(from[i + 2..].chars());
407             to.push_str(if is_word_final { "ς" } else { "σ" });
408         }
409
410         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
411             use core::unicode::{Case_Ignorable, Cased};
412             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
413                 Some(c) => Cased(c),
414                 None => false,
415             }
416         }
417     }
418
419     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
420     ///
421     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
422     /// `Uppercase`.
423     ///
424     /// Since some characters can expand into multiple characters when changing
425     /// the case, this function returns a [`String`] instead of modifying the
426     /// parameter in-place.
427     ///
428     /// # Examples
429     ///
430     /// Basic usage:
431     ///
432     /// ```
433     /// let s = "hello";
434     ///
435     /// assert_eq!("HELLO", s.to_uppercase());
436     /// ```
437     ///
438     /// Scripts without case are not changed:
439     ///
440     /// ```
441     /// let new_year = "农历新年";
442     ///
443     /// assert_eq!(new_year, new_year.to_uppercase());
444     /// ```
445     ///
446     /// One character can become multiple:
447     /// ```
448     /// let s = "tschüß";
449     ///
450     /// assert_eq!("TSCHÜSS", s.to_uppercase());
451     /// ```
452     #[cfg(not(no_global_oom_handling))]
453     #[must_use = "this returns the uppercase string as a new String, \
454                   without modifying the original"]
455     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
456     pub fn to_uppercase(&self) -> String {
457         let mut s = String::with_capacity(self.len());
458         for c in self[..].chars() {
459             match conversions::to_upper(c) {
460                 [a, '\0', _] => s.push(a),
461                 [a, b, '\0'] => {
462                     s.push(a);
463                     s.push(b);
464                 }
465                 [a, b, c] => {
466                     s.push(a);
467                     s.push(b);
468                     s.push(c);
469                 }
470             }
471         }
472         s
473     }
474
475     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
476     ///
477     /// # Examples
478     ///
479     /// Basic usage:
480     ///
481     /// ```
482     /// let string = String::from("birthday gift");
483     /// let boxed_str = string.clone().into_boxed_str();
484     ///
485     /// assert_eq!(boxed_str.into_string(), string);
486     /// ```
487     #[stable(feature = "box_str", since = "1.4.0")]
488     #[must_use = "`self` will be dropped if the result is not used"]
489     #[inline]
490     pub fn into_string(self: Box<str>) -> String {
491         let slice = Box::<[u8]>::from(self);
492         unsafe { String::from_utf8_unchecked(slice.into_vec()) }
493     }
494
495     /// Creates a new [`String`] by repeating a string `n` times.
496     ///
497     /// # Panics
498     ///
499     /// This function will panic if the capacity would overflow.
500     ///
501     /// # Examples
502     ///
503     /// Basic usage:
504     ///
505     /// ```
506     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
507     /// ```
508     ///
509     /// A panic upon overflow:
510     ///
511     /// ```should_panic
512     /// // this will panic at runtime
513     /// let huge = "0123456789abcdef".repeat(usize::MAX);
514     /// ```
515     #[cfg(not(no_global_oom_handling))]
516     #[must_use]
517     #[stable(feature = "repeat_str", since = "1.16.0")]
518     pub fn repeat(&self, n: usize) -> String {
519         unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
520     }
521
522     /// Returns a copy of this string where each character is mapped to its
523     /// ASCII upper case equivalent.
524     ///
525     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
526     /// but non-ASCII letters are unchanged.
527     ///
528     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
529     ///
530     /// To uppercase ASCII characters in addition to non-ASCII characters, use
531     /// [`to_uppercase`].
532     ///
533     /// # Examples
534     ///
535     /// ```
536     /// let s = "Grüße, Jürgen ❤";
537     ///
538     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
539     /// ```
540     ///
541     /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
542     /// [`to_uppercase`]: #method.to_uppercase
543     #[cfg(not(no_global_oom_handling))]
544     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
545     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
546     #[inline]
547     pub fn to_ascii_uppercase(&self) -> String {
548         let mut bytes = self.as_bytes().to_vec();
549         bytes.make_ascii_uppercase();
550         // make_ascii_uppercase() preserves the UTF-8 invariant.
551         unsafe { String::from_utf8_unchecked(bytes) }
552     }
553
554     /// Returns a copy of this string where each character is mapped to its
555     /// ASCII lower case equivalent.
556     ///
557     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
558     /// but non-ASCII letters are unchanged.
559     ///
560     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
561     ///
562     /// To lowercase ASCII characters in addition to non-ASCII characters, use
563     /// [`to_lowercase`].
564     ///
565     /// # Examples
566     ///
567     /// ```
568     /// let s = "Grüße, Jürgen ❤";
569     ///
570     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
571     /// ```
572     ///
573     /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
574     /// [`to_lowercase`]: #method.to_lowercase
575     #[cfg(not(no_global_oom_handling))]
576     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
577     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
578     #[inline]
579     pub fn to_ascii_lowercase(&self) -> String {
580         let mut bytes = self.as_bytes().to_vec();
581         bytes.make_ascii_lowercase();
582         // make_ascii_lowercase() preserves the UTF-8 invariant.
583         unsafe { String::from_utf8_unchecked(bytes) }
584     }
585 }
586
587 /// Converts a boxed slice of bytes to a boxed string slice without checking
588 /// that the string contains valid UTF-8.
589 ///
590 /// # Examples
591 ///
592 /// Basic usage:
593 ///
594 /// ```
595 /// let smile_utf8 = Box::new([226, 152, 186]);
596 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
597 ///
598 /// assert_eq!("☺", &*smile);
599 /// ```
600 #[stable(feature = "str_box_extras", since = "1.20.0")]
601 #[must_use]
602 #[inline]
603 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
604     unsafe { Box::from_raw(Box::into_raw(v) as *mut str) }
605 }