]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/str.rs
Auto merge of #98558 - nnethercote:smallvec-1.8.1, r=lqd
[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.spare_capacity_mut().get_unchecked_mut(..reserved_len - pos);
182
183         // Convert the separator and slices to slices of MaybeUninit
184         // to simplify implementation in specialize_for_lengths
185         let sep_uninit = core::slice::from_raw_parts(sep.as_ptr().cast(), sep.len());
186         let iter_uninit = iter.map(|it| {
187             let it = it.borrow().as_ref();
188             core::slice::from_raw_parts(it.as_ptr().cast(), it.len())
189         });
190
191         // copy separator and slices over without bounds checks
192         // generate loops with hardcoded offsets for small separators
193         // massive improvements possible (~ x2)
194         let remain = specialize_for_lengths!(sep_uninit, target, iter_uninit; 0, 1, 2, 3, 4);
195
196         // A weird borrow implementation may return different
197         // slices for the length calculation and the actual copy.
198         // Make sure we don't expose uninitialized bytes to the caller.
199         let result_len = reserved_len - remain.len();
200         result.set_len(result_len);
201     }
202     result
203 }
204
205 #[stable(feature = "rust1", since = "1.0.0")]
206 impl Borrow<str> for String {
207     #[inline]
208     fn borrow(&self) -> &str {
209         &self[..]
210     }
211 }
212
213 #[stable(feature = "string_borrow_mut", since = "1.36.0")]
214 impl BorrowMut<str> for String {
215     #[inline]
216     fn borrow_mut(&mut self) -> &mut str {
217         &mut self[..]
218     }
219 }
220
221 #[cfg(not(no_global_oom_handling))]
222 #[stable(feature = "rust1", since = "1.0.0")]
223 impl ToOwned for str {
224     type Owned = String;
225     #[inline]
226     fn to_owned(&self) -> String {
227         unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
228     }
229
230     fn clone_into(&self, target: &mut String) {
231         let mut b = mem::take(target).into_bytes();
232         self.as_bytes().clone_into(&mut b);
233         *target = unsafe { String::from_utf8_unchecked(b) }
234     }
235 }
236
237 /// Methods for string slices.
238 #[cfg(not(test))]
239 impl str {
240     /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
241     ///
242     /// # Examples
243     ///
244     /// Basic usage:
245     ///
246     /// ```
247     /// let s = "this is a string";
248     /// let boxed_str = s.to_owned().into_boxed_str();
249     /// let boxed_bytes = boxed_str.into_boxed_bytes();
250     /// assert_eq!(*boxed_bytes, *s.as_bytes());
251     /// ```
252     #[rustc_allow_incoherent_impl]
253     #[stable(feature = "str_box_extras", since = "1.20.0")]
254     #[must_use = "`self` will be dropped if the result is not used"]
255     #[inline]
256     pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
257         self.into()
258     }
259
260     /// Replaces all matches of a pattern with another string.
261     ///
262     /// `replace` creates a new [`String`], and copies the data from this string slice into it.
263     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
264     /// replaces them with the replacement string slice.
265     ///
266     /// # Examples
267     ///
268     /// Basic usage:
269     ///
270     /// ```
271     /// let s = "this is old";
272     ///
273     /// assert_eq!("this is new", s.replace("old", "new"));
274     /// assert_eq!("than an old", s.replace("is", "an"));
275     /// ```
276     ///
277     /// When the pattern doesn't match:
278     ///
279     /// ```
280     /// let s = "this is old";
281     /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
282     /// ```
283     #[cfg(not(no_global_oom_handling))]
284     #[rustc_allow_incoherent_impl]
285     #[must_use = "this returns the replaced string as a new allocation, \
286                   without modifying the original"]
287     #[stable(feature = "rust1", since = "1.0.0")]
288     #[inline]
289     pub fn replace<'a, P: Pattern<'a>>(&'a self, from: P, to: &str) -> String {
290         let mut result = String::new();
291         let mut last_end = 0;
292         for (start, part) in self.match_indices(from) {
293             result.push_str(unsafe { self.get_unchecked(last_end..start) });
294             result.push_str(to);
295             last_end = start + part.len();
296         }
297         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
298         result
299     }
300
301     /// Replaces first N matches of a pattern with another string.
302     ///
303     /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
304     /// While doing so, it attempts to find matches of a pattern. If it finds any, it
305     /// replaces them with the replacement string slice at most `count` times.
306     ///
307     /// # Examples
308     ///
309     /// Basic usage:
310     ///
311     /// ```
312     /// let s = "foo foo 123 foo";
313     /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
314     /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
315     /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
316     /// ```
317     ///
318     /// When the pattern doesn't match:
319     ///
320     /// ```
321     /// let s = "this is old";
322     /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
323     /// ```
324     #[cfg(not(no_global_oom_handling))]
325     #[rustc_allow_incoherent_impl]
326     #[must_use = "this returns the replaced string as a new allocation, \
327                   without modifying the original"]
328     #[stable(feature = "str_replacen", since = "1.16.0")]
329     pub fn replacen<'a, P: Pattern<'a>>(&'a self, pat: P, to: &str, count: usize) -> String {
330         // Hope to reduce the times of re-allocation
331         let mut result = String::with_capacity(32);
332         let mut last_end = 0;
333         for (start, part) in self.match_indices(pat).take(count) {
334             result.push_str(unsafe { self.get_unchecked(last_end..start) });
335             result.push_str(to);
336             last_end = start + part.len();
337         }
338         result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
339         result
340     }
341
342     /// Returns the lowercase equivalent of this string slice, as a new [`String`].
343     ///
344     /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
345     /// `Lowercase`.
346     ///
347     /// Since some characters can expand into multiple characters when changing
348     /// the case, this function returns a [`String`] instead of modifying the
349     /// parameter in-place.
350     ///
351     /// # Examples
352     ///
353     /// Basic usage:
354     ///
355     /// ```
356     /// let s = "HELLO";
357     ///
358     /// assert_eq!("hello", s.to_lowercase());
359     /// ```
360     ///
361     /// A tricky example, with sigma:
362     ///
363     /// ```
364     /// let sigma = "Σ";
365     ///
366     /// assert_eq!("σ", sigma.to_lowercase());
367     ///
368     /// // but at the end of a word, it's ς, not σ:
369     /// let odysseus = "ὈΔΥΣΣΕΎΣ";
370     ///
371     /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
372     /// ```
373     ///
374     /// Languages without case are not changed:
375     ///
376     /// ```
377     /// let new_year = "农历新年";
378     ///
379     /// assert_eq!(new_year, new_year.to_lowercase());
380     /// ```
381     #[cfg(not(no_global_oom_handling))]
382     #[rustc_allow_incoherent_impl]
383     #[must_use = "this returns the lowercase string as a new String, \
384                   without modifying the original"]
385     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
386     pub fn to_lowercase(&self) -> String {
387         let out = convert_while_ascii(self.as_bytes(), u8::to_ascii_lowercase);
388
389         // Safety: we know this is a valid char boundary since
390         // out.len() is only progressed if ascii bytes are found
391         let rest = unsafe { self.get_unchecked(out.len()..) };
392
393         // Safety: We have written only valid ASCII to our vec
394         let mut s = unsafe { String::from_utf8_unchecked(out) };
395
396         for (i, c) in rest[..].char_indices() {
397             if c == 'Σ' {
398                 // Σ maps to σ, except at the end of a word where it maps to ς.
399                 // This is the only conditional (contextual) but language-independent mapping
400                 // in `SpecialCasing.txt`,
401                 // so hard-code it rather than have a generic "condition" mechanism.
402                 // See https://github.com/rust-lang/rust/issues/26035
403                 map_uppercase_sigma(rest, i, &mut s)
404             } else {
405                 match conversions::to_lower(c) {
406                     [a, '\0', _] => s.push(a),
407                     [a, b, '\0'] => {
408                         s.push(a);
409                         s.push(b);
410                     }
411                     [a, b, c] => {
412                         s.push(a);
413                         s.push(b);
414                         s.push(c);
415                     }
416                 }
417             }
418         }
419         return s;
420
421         fn map_uppercase_sigma(from: &str, i: usize, to: &mut String) {
422             // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
423             // for the definition of `Final_Sigma`.
424             debug_assert!('Σ'.len_utf8() == 2);
425             let is_word_final = case_ignoreable_then_cased(from[..i].chars().rev())
426                 && !case_ignoreable_then_cased(from[i + 2..].chars());
427             to.push_str(if is_word_final { "ς" } else { "σ" });
428         }
429
430         fn case_ignoreable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
431             use core::unicode::{Case_Ignorable, Cased};
432             match iter.skip_while(|&c| Case_Ignorable(c)).next() {
433                 Some(c) => Cased(c),
434                 None => false,
435             }
436         }
437     }
438
439     /// Returns the uppercase equivalent of this string slice, as a new [`String`].
440     ///
441     /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
442     /// `Uppercase`.
443     ///
444     /// Since some characters can expand into multiple characters when changing
445     /// the case, this function returns a [`String`] instead of modifying the
446     /// parameter in-place.
447     ///
448     /// # Examples
449     ///
450     /// Basic usage:
451     ///
452     /// ```
453     /// let s = "hello";
454     ///
455     /// assert_eq!("HELLO", s.to_uppercase());
456     /// ```
457     ///
458     /// Scripts without case are not changed:
459     ///
460     /// ```
461     /// let new_year = "农历新年";
462     ///
463     /// assert_eq!(new_year, new_year.to_uppercase());
464     /// ```
465     ///
466     /// One character can become multiple:
467     /// ```
468     /// let s = "tschüß";
469     ///
470     /// assert_eq!("TSCHÜSS", s.to_uppercase());
471     /// ```
472     #[cfg(not(no_global_oom_handling))]
473     #[rustc_allow_incoherent_impl]
474     #[must_use = "this returns the uppercase string as a new String, \
475                   without modifying the original"]
476     #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
477     pub fn to_uppercase(&self) -> String {
478         let out = convert_while_ascii(self.as_bytes(), u8::to_ascii_uppercase);
479
480         // Safety: we know this is a valid char boundary since
481         // out.len() is only progressed if ascii bytes are found
482         let rest = unsafe { self.get_unchecked(out.len()..) };
483
484         // Safety: We have written only valid ASCII to our vec
485         let mut s = unsafe { String::from_utf8_unchecked(out) };
486
487         for c in rest.chars() {
488             match conversions::to_upper(c) {
489                 [a, '\0', _] => s.push(a),
490                 [a, b, '\0'] => {
491                     s.push(a);
492                     s.push(b);
493                 }
494                 [a, b, c] => {
495                     s.push(a);
496                     s.push(b);
497                     s.push(c);
498                 }
499             }
500         }
501         s
502     }
503
504     /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
505     ///
506     /// # Examples
507     ///
508     /// Basic usage:
509     ///
510     /// ```
511     /// let string = String::from("birthday gift");
512     /// let boxed_str = string.clone().into_boxed_str();
513     ///
514     /// assert_eq!(boxed_str.into_string(), string);
515     /// ```
516     #[stable(feature = "box_str", since = "1.4.0")]
517     #[rustc_allow_incoherent_impl]
518     #[must_use = "`self` will be dropped if the result is not used"]
519     #[inline]
520     pub fn into_string(self: Box<str>) -> String {
521         let slice = Box::<[u8]>::from(self);
522         unsafe { String::from_utf8_unchecked(slice.into_vec()) }
523     }
524
525     /// Creates a new [`String`] by repeating a string `n` times.
526     ///
527     /// # Panics
528     ///
529     /// This function will panic if the capacity would overflow.
530     ///
531     /// # Examples
532     ///
533     /// Basic usage:
534     ///
535     /// ```
536     /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
537     /// ```
538     ///
539     /// A panic upon overflow:
540     ///
541     /// ```should_panic
542     /// // this will panic at runtime
543     /// let huge = "0123456789abcdef".repeat(usize::MAX);
544     /// ```
545     #[cfg(not(no_global_oom_handling))]
546     #[rustc_allow_incoherent_impl]
547     #[must_use]
548     #[stable(feature = "repeat_str", since = "1.16.0")]
549     pub fn repeat(&self, n: usize) -> String {
550         unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
551     }
552
553     /// Returns a copy of this string where each character is mapped to its
554     /// ASCII upper case equivalent.
555     ///
556     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
557     /// but non-ASCII letters are unchanged.
558     ///
559     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
560     ///
561     /// To uppercase ASCII characters in addition to non-ASCII characters, use
562     /// [`to_uppercase`].
563     ///
564     /// # Examples
565     ///
566     /// ```
567     /// let s = "Grüße, Jürgen ❤";
568     ///
569     /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
570     /// ```
571     ///
572     /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
573     /// [`to_uppercase`]: #method.to_uppercase
574     #[cfg(not(no_global_oom_handling))]
575     #[rustc_allow_incoherent_impl]
576     #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
577     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
578     #[inline]
579     pub fn to_ascii_uppercase(&self) -> String {
580         let mut bytes = self.as_bytes().to_vec();
581         bytes.make_ascii_uppercase();
582         // make_ascii_uppercase() preserves the UTF-8 invariant.
583         unsafe { String::from_utf8_unchecked(bytes) }
584     }
585
586     /// Returns a copy of this string where each character is mapped to its
587     /// ASCII lower case equivalent.
588     ///
589     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
590     /// but non-ASCII letters are unchanged.
591     ///
592     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
593     ///
594     /// To lowercase ASCII characters in addition to non-ASCII characters, use
595     /// [`to_lowercase`].
596     ///
597     /// # Examples
598     ///
599     /// ```
600     /// let s = "Grüße, Jürgen ❤";
601     ///
602     /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
603     /// ```
604     ///
605     /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
606     /// [`to_lowercase`]: #method.to_lowercase
607     #[cfg(not(no_global_oom_handling))]
608     #[rustc_allow_incoherent_impl]
609     #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
610     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
611     #[inline]
612     pub fn to_ascii_lowercase(&self) -> String {
613         let mut bytes = self.as_bytes().to_vec();
614         bytes.make_ascii_lowercase();
615         // make_ascii_lowercase() preserves the UTF-8 invariant.
616         unsafe { String::from_utf8_unchecked(bytes) }
617     }
618 }
619
620 /// Converts a boxed slice of bytes to a boxed string slice without checking
621 /// that the string contains valid UTF-8.
622 ///
623 /// # Examples
624 ///
625 /// Basic usage:
626 ///
627 /// ```
628 /// let smile_utf8 = Box::new([226, 152, 186]);
629 /// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
630 ///
631 /// assert_eq!("☺", &*smile);
632 /// ```
633 #[stable(feature = "str_box_extras", since = "1.20.0")]
634 #[must_use]
635 #[inline]
636 pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
637     unsafe { Box::from_raw(Box::into_raw(v) as *mut str) }
638 }
639
640 /// Converts the bytes while the bytes are still ascii.
641 /// For better average performance, this is happens in chunks of `2*size_of::<usize>()`.
642 /// Returns a vec with the converted bytes.
643 #[inline]
644 #[cfg(not(test))]
645 #[cfg(not(no_global_oom_handling))]
646 fn convert_while_ascii(b: &[u8], convert: fn(&u8) -> u8) -> Vec<u8> {
647     let mut out = Vec::with_capacity(b.len());
648
649     const USIZE_SIZE: usize = mem::size_of::<usize>();
650     const MAGIC_UNROLL: usize = 2;
651     const N: usize = USIZE_SIZE * MAGIC_UNROLL;
652     const NONASCII_MASK: usize = usize::from_ne_bytes([0x80; USIZE_SIZE]);
653
654     let mut i = 0;
655     unsafe {
656         while i + N <= b.len() {
657             // Safety: we have checks the sizes `b` and `out` to know that our
658             let in_chunk = b.get_unchecked(i..i + N);
659             let out_chunk = out.spare_capacity_mut().get_unchecked_mut(i..i + N);
660
661             let mut bits = 0;
662             for j in 0..MAGIC_UNROLL {
663                 // read the bytes 1 usize at a time (unaligned since we haven't checked the alignment)
664                 // safety: in_chunk is valid bytes in the range
665                 bits |= in_chunk.as_ptr().cast::<usize>().add(j).read_unaligned();
666             }
667             // if our chunks aren't ascii, then return only the prior bytes as init
668             if bits & NONASCII_MASK != 0 {
669                 break;
670             }
671
672             // perform the case conversions on N bytes (gets heavily autovec'd)
673             for j in 0..N {
674                 // safety: in_chunk and out_chunk is valid bytes in the range
675                 let out = out_chunk.get_unchecked_mut(j);
676                 out.write(convert(in_chunk.get_unchecked(j)));
677             }
678
679             // mark these bytes as initialised
680             i += N;
681         }
682         out.set_len(i);
683     }
684
685     out
686 }