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