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