]> git.lizzy.rs Git - rust.git/blob - src/liballoc/str.rs
Convert more usages over
[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, BorrowMut};
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 #[stable(feature = "str_escape", since = "1.34.0")]
72 pub use core::str::{EscapeDebug, EscapeDefault, EscapeUnicode};
73
74 #[unstable(feature = "slice_concat_ext",
75            reason = "trait should not have to exist",
76            issue = "27747")]
77 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
78     type Output = String;
79
80     fn concat(&self) -> String {
81         self.join("")
82     }
83
84     fn join(&self, sep: &str) -> String {
85         unsafe {
86             String::from_utf8_unchecked( join_generic_copy(self, sep.as_bytes()) )
87         }
88     }
89 }
90
91 macro_rules! spezialize_for_lengths {
92     ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {
93         let mut target = $target;
94         let iter = $iter;
95         let sep_bytes = $separator;
96         match $separator.len() {
97             $(
98                 // loops with hardcoded sizes run much faster
99                 // specialize the cases with small separator lengths
100                 $num => {
101                     for s in iter {
102                         copy_slice_and_advance!(target, sep_bytes);
103                         copy_slice_and_advance!(target, s.borrow().as_ref());
104                     }
105                 },
106             )*
107             _ => {
108                 // arbitrary non-zero size fallback
109                 for s in iter {
110                     copy_slice_and_advance!(target, sep_bytes);
111                     copy_slice_and_advance!(target, s.borrow().as_ref());
112                 }
113             }
114         }
115     };
116 }
117
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);
123         $target = tail;
124     }
125 }
126
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.
131 //
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>
136 where
137     T: Copy,
138     B: AsRef<[T]> + ?Sized,
139     S: Borrow<B>,
140 {
141     let sep_len = sep.len();
142     let mut iter = slice.iter();
143
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![],
148     };
149
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| {
155             slice.iter()
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");
159
160     // crucial for safety
161     let mut result = Vec::with_capacity(len);
162     assert!(result.capacity() >= len);
163
164     result.extend_from_slice(first.borrow().as_ref());
165
166     unsafe {
167         {
168             let pos = result.len();
169             let target = result.get_unchecked_mut(pos..len);
170
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);
175         }
176         result.set_len(len);
177     }
178     result
179 }
180
181 #[stable(feature = "rust1", since = "1.0.0")]
182 impl Borrow<str> for String {
183     #[inline]
184     fn borrow(&self) -> &str {
185         &self[..]
186     }
187 }
188
189 #[stable(feature = "string_borrow_mut", since = "1.36.0")]
190 impl BorrowMut<str> for String {
191     #[inline]
192     fn borrow_mut(&mut self) -> &mut str {
193         &mut self[..]
194     }
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl ToOwned for str {
199     type Owned = String;
200     #[inline]
201     fn to_owned(&self) -> String {
202         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
203     }
204
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) }
209     }
210 }
211
212 /// Methods for string slices.
213 #[lang = "str_alloc"]
214 #[cfg(not(test))]
215 impl str {
216     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
217     ///
218     /// # Examples
219     ///
220     /// Basic usage:
221     ///
222     /// ```
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());
227     /// ```
228     #[stable(feature = "str_box_extras", since = "1.20.0")]
229     #[inline]
230     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
231         self.into()
232     }
233
234     /// Replaces all matches of a pattern with another string.
235     ///
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.
239     ///
240     /// [`String`]: string/struct.String.html
241     ///
242     /// # Examples
243     ///
244     /// Basic usage:
245     ///
246     /// ```
247     /// let s = "this is old";
248     ///
249     /// assert_eq!("this is new", s.replace("old", "new"));
250     /// ```
251     ///
252     /// When the pattern doesn't match:
253     ///
254     /// ```
255     /// let s = "this is old";
256     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
257     /// ```
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")]
261     #[inline]
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) });
267             result.push_str(to);
268             last_end = start + part.len();
269         }
270         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
271         result
272     }
273
274     /// Replaces first N matches of a pattern with another string.
275     ///
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.
279     ///
280     /// [`String`]: string/struct.String.html
281     ///
282     /// # Examples
283     ///
284     /// Basic usage:
285     ///
286     /// ```
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));
291     /// ```
292     ///
293     /// When the pattern doesn't match:
294     ///
295     /// ```
296     /// let s = "this is old";
297     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
298     /// ```
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) });
308             result.push_str(to);
309             last_end = start + part.len();
310         }
311         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
312         result
313     }
314
315     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
316     ///
317     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
318     /// `Lowercase`.
319     ///
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.
323     ///
324     /// [`String`]: string/struct.String.html
325     ///
326     /// # Examples
327     ///
328     /// Basic usage:
329     ///
330     /// ```
331     /// let s = "HELLO";
332     ///
333     /// assert_eq!("hello", s.to_lowercase());
334     /// ```
335     ///
336     /// A tricky example, with sigma:
337     ///
338     /// ```
339     /// let sigma = "Σ";
340     ///
341     /// assert_eq!("σ", sigma.to_lowercase());
342     ///
343     /// // but at the end of a word, it's ς, not σ:
344     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
345     ///
346     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
347     /// ```
348     ///
349     /// Languages without case are not changed:
350     ///
351     /// ```
352     /// let new_year = "农历新年";
353     ///
354     /// assert_eq!(new_year, new_year.to_lowercase());
355     /// ```
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() {
360             if c == 'Σ' {
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)
367             } else {
368                 match conversions::to_lower(c) {
369                     [a, '\0', _] => s.push(a),
370                     [a, b, '\0'] => {
371                         s.push(a);
372                         s.push(b);
373                     }
374                     [a, b, c] => {
375                         s.push(a);
376                         s.push(b);
377                         s.push(c);
378                     }
379                 }
380             }
381         }
382         return s;
383
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 { "σ" });
391         }
392
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() {
396                 Some(c) => Cased(c),
397                 None => false,
398             }
399         }
400     }
401
402     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
403     ///
404     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
405     /// `Uppercase`.
406     ///
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.
410     ///
411     /// [`String`]: string/struct.String.html
412     ///
413     /// # Examples
414     ///
415     /// Basic usage:
416     ///
417     /// ```
418     /// let s = "hello";
419     ///
420     /// assert_eq!("HELLO", s.to_uppercase());
421     /// ```
422     ///
423     /// Scripts without case are not changed:
424     ///
425     /// ```
426     /// let new_year = "农历新年";
427     ///
428     /// assert_eq!(new_year, new_year.to_uppercase());
429     /// ```
430     ///
431     /// One character can become multiple:
432     /// ```
433     /// let s = "tschüß";
434     ///
435     /// assert_eq!("TSCHÜSS", s.to_uppercase());
436     /// ```
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),
443                 [a, b, '\0'] => {
444                     s.push(a);
445                     s.push(b);
446                 }
447                 [a, b, c] => {
448                     s.push(a);
449                     s.push(b);
450                     s.push(c);
451                 }
452             }
453         }
454         return s;
455     }
456
457     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
458     ///
459     /// [`String`]: string/struct.String.html
460     /// [`Box<str>`]: boxed/struct.Box.html
461     ///
462     /// # Examples
463     ///
464     /// Basic usage:
465     ///
466     /// ```
467     /// let string = String::from("birthday gift");
468     /// let boxed_str = string.clone().into_boxed_str();
469     ///
470     /// assert_eq!(boxed_str.into_string(), string);
471     /// ```
472     #[stable(feature = "box_str", since = "1.4.0")]
473     #[inline]
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()) }
477     }
478
479     /// Creates a new [`String`] by repeating a string `n` times.
480     ///
481     /// # Panics
482     ///
483     /// This function will panic if the capacity would overflow.
484     ///
485     /// [`String`]: string/struct.String.html
486     ///
487     /// # Examples
488     ///
489     /// Basic usage:
490     ///
491     /// ```
492     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
493     /// ```
494     ///
495     /// A panic upon overflow:
496     ///
497     /// ```should_panic
498     /// fn main() {
499     ///     // this will panic at runtime
500     ///     "0123456789abcdef".repeat(usize::max_value());
501     /// }
502     /// ```
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)) }
506     }
507
508     /// Returns a copy of this string where each character is mapped to its
509     /// ASCII upper case equivalent.
510     ///
511     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
512     /// but non-ASCII letters are unchanged.
513     ///
514     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
515     ///
516     /// To uppercase ASCII characters in addition to non-ASCII characters, use
517     /// [`to_uppercase`].
518     ///
519     /// # Examples
520     ///
521     /// ```
522     /// let s = "Grüße, Jürgen ❤";
523     ///
524     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
525     /// ```
526     ///
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")]
530     #[inline]
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) }
536     }
537
538     /// Returns a copy of this string where each character is mapped to its
539     /// ASCII lower case equivalent.
540     ///
541     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
542     /// but non-ASCII letters are unchanged.
543     ///
544     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
545     ///
546     /// To lowercase ASCII characters in addition to non-ASCII characters, use
547     /// [`to_lowercase`].
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// let s = "Grüße, Jürgen ❤";
553     ///
554     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
555     /// ```
556     ///
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")]
560     #[inline]
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) }
566     }
567 }
568
569 /// Converts a boxed slice of bytes to a boxed string slice without checking
570 /// that the string contains valid UTF-8.
571 ///
572 /// # Examples
573 ///
574 /// Basic usage:
575 ///
576 /// ```
577 /// let smile_utf8 = Box::new([226, 152, 186]);
578 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
579 ///
580 /// assert_eq!("☺", &*smile);
581 /// ```
582 #[stable(feature = "str_box_extras", since = "1.20.0")]
583 #[inline]
584 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
585     Box::from_raw(Box::into_raw(v) as *mut str)
586 }