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