alloc/str.rs
1//! Utilities for the `str` primitive type.
2//!
3//! *[See also the `str` primitive type](str).*
4
5#![stable(feature = "rust1", since = "1.0.0")]
6// Many of the usings in this module are only used in the test configuration.
7// It's cleaner to just turn off the unused_imports warning than to fix them.
8#![allow(unused_imports)]
9
10use core::borrow::{Borrow, BorrowMut};
11use core::iter::FusedIterator;
12use core::mem::MaybeUninit;
13#[stable(feature = "encode_utf16", since = "1.8.0")]
14pub use core::str::EncodeUtf16;
15#[stable(feature = "split_ascii_whitespace", since = "1.34.0")]
16pub use core::str::SplitAsciiWhitespace;
17#[stable(feature = "split_inclusive", since = "1.51.0")]
18pub use core::str::SplitInclusive;
19#[stable(feature = "rust1", since = "1.0.0")]
20pub use core::str::SplitWhitespace;
21#[stable(feature = "rust1", since = "1.0.0")]
22pub use core::str::pattern;
23use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher, Utf8Pattern};
24#[stable(feature = "rust1", since = "1.0.0")]
25pub use core::str::{Bytes, CharIndices, Chars, from_utf8, from_utf8_mut};
26#[stable(feature = "str_escape", since = "1.34.0")]
27pub use core::str::{EscapeDebug, EscapeDefault, EscapeUnicode};
28#[stable(feature = "rust1", since = "1.0.0")]
29pub use core::str::{FromStr, Utf8Error};
30#[allow(deprecated)]
31#[stable(feature = "rust1", since = "1.0.0")]
32pub use core::str::{Lines, LinesAny};
33#[stable(feature = "rust1", since = "1.0.0")]
34pub use core::str::{MatchIndices, RMatchIndices};
35#[stable(feature = "rust1", since = "1.0.0")]
36pub use core::str::{Matches, RMatches};
37#[stable(feature = "rust1", since = "1.0.0")]
38pub use core::str::{ParseBoolError, from_utf8_unchecked, from_utf8_unchecked_mut};
39#[stable(feature = "rust1", since = "1.0.0")]
40pub use core::str::{RSplit, Split};
41#[stable(feature = "rust1", since = "1.0.0")]
42pub use core::str::{RSplitN, SplitN};
43#[stable(feature = "rust1", since = "1.0.0")]
44pub use core::str::{RSplitTerminator, SplitTerminator};
45#[stable(feature = "utf8_chunks", since = "1.79.0")]
46pub use core::str::{Utf8Chunk, Utf8Chunks};
47#[unstable(feature = "str_from_raw_parts", issue = "119206")]
48pub use core::str::{from_raw_parts, from_raw_parts_mut};
49use core::unicode::conversions;
50use core::{mem, ptr};
51
52use crate::borrow::ToOwned;
53use crate::boxed::Box;
54use crate::slice::{Concat, Join, SliceIndex};
55use crate::string::String;
56use crate::vec::Vec;
57
58/// Note: `str` in `Concat<str>` is not meaningful here.
59/// This type parameter of the trait only exists to enable another impl.
60#[cfg(not(no_global_oom_handling))]
61#[unstable(feature = "slice_concat_ext", issue = "27747")]
62impl<S: Borrow<str>> Concat<str> for [S] {
63 type Output = String;
64
65 fn concat(slice: &Self) -> String {
66 Join::join(slice, "")
67 }
68}
69
70#[cfg(not(no_global_oom_handling))]
71#[unstable(feature = "slice_concat_ext", issue = "27747")]
72impl<S: Borrow<str>> Join<&str> for [S] {
73 type Output = String;
74
75 fn join(slice: &Self, sep: &str) -> String {
76 unsafe { String::from_utf8_unchecked(join_generic_copy(slice, sep.as_bytes())) }
77 }
78}
79
80#[cfg(not(no_global_oom_handling))]
81macro_rules! specialize_for_lengths {
82 ($separator:expr, $target:expr, $iter:expr; $($num:expr),*) => {{
83 let mut target = $target;
84 let iter = $iter;
85 let sep_bytes = $separator;
86 match $separator.len() {
87 $(
88 // loops with hardcoded sizes run much faster
89 // specialize the cases with small separator lengths
90 $num => {
91 for s in iter {
92 copy_slice_and_advance!(target, sep_bytes);
93 let content_bytes = s.borrow().as_ref();
94 copy_slice_and_advance!(target, content_bytes);
95 }
96 },
97 )*
98 _ => {
99 // arbitrary non-zero size fallback
100 for s in iter {
101 copy_slice_and_advance!(target, sep_bytes);
102 let content_bytes = s.borrow().as_ref();
103 copy_slice_and_advance!(target, content_bytes);
104 }
105 }
106 }
107 target
108 }}
109}
110
111#[cfg(not(no_global_oom_handling))]
112macro_rules! copy_slice_and_advance {
113 ($target:expr, $bytes:expr) => {
114 let len = $bytes.len();
115 let (head, tail) = { $target }.split_at_mut(len);
116 head.copy_from_slice($bytes);
117 $target = tail;
118 };
119}
120
121// Optimized join implementation that works for both Vec<T> (T: Copy) and String's inner vec
122// Currently (2018-05-13) there is a bug with type inference and specialization (see issue #36262)
123// For this reason SliceConcat<T> is not specialized for T: Copy and SliceConcat<str> is the
124// only user of this function. It is left in place for the time when that is fixed.
125//
126// the bounds for String-join are S: Borrow<str> and for Vec-join Borrow<[T]>
127// [T] and str both impl AsRef<[T]> for some T
128// => s.borrow().as_ref() and we always have slices
129#[cfg(not(no_global_oom_handling))]
130fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
131where
132 T: Copy,
133 B: AsRef<[T]> + ?Sized,
134 S: Borrow<B>,
135{
136 let sep_len = sep.len();
137 let mut iter = slice.iter();
138
139 // the first slice is the only one without a separator preceding it
140 let first = match iter.next() {
141 Some(first) => first,
142 None => return vec![],
143 };
144
145 // compute the exact total length of the joined Vec
146 // if the `len` calculation overflows, we'll panic
147 // we would have run out of memory anyway and the rest of the function requires
148 // the entire Vec pre-allocated for safety
149 let reserved_len = sep_len
150 .checked_mul(iter.len())
151 .and_then(|n| {
152 slice.iter().map(|s| s.borrow().as_ref().len()).try_fold(n, usize::checked_add)
153 })
154 .expect("attempt to join into collection with len > usize::MAX");
155
156 // prepare an uninitialized buffer
157 let mut result = Vec::with_capacity(reserved_len);
158 debug_assert!(result.capacity() >= reserved_len);
159
160 result.extend_from_slice(first.borrow().as_ref());
161
162 unsafe {
163 let pos = result.len();
164 let target = result.spare_capacity_mut().get_unchecked_mut(..reserved_len - pos);
165
166 // Convert the separator and slices to slices of MaybeUninit
167 // to simplify implementation in specialize_for_lengths
168 let sep_uninit = core::slice::from_raw_parts(sep.as_ptr().cast(), sep.len());
169 let iter_uninit = iter.map(|it| {
170 let it = it.borrow().as_ref();
171 core::slice::from_raw_parts(it.as_ptr().cast(), it.len())
172 });
173
174 // copy separator and slices over without bounds checks
175 // generate loops with hardcoded offsets for small separators
176 // massive improvements possible (~ x2)
177 let remain = specialize_for_lengths!(sep_uninit, target, iter_uninit; 0, 1, 2, 3, 4);
178
179 // A weird borrow implementation may return different
180 // slices for the length calculation and the actual copy.
181 // Make sure we don't expose uninitialized bytes to the caller.
182 let result_len = reserved_len - remain.len();
183 result.set_len(result_len);
184 }
185 result
186}
187
188#[stable(feature = "rust1", since = "1.0.0")]
189impl Borrow<str> for String {
190 #[inline]
191 fn borrow(&self) -> &str {
192 &self[..]
193 }
194}
195
196#[stable(feature = "string_borrow_mut", since = "1.36.0")]
197impl BorrowMut<str> for String {
198 #[inline]
199 fn borrow_mut(&mut self) -> &mut str {
200 &mut self[..]
201 }
202}
203
204#[cfg(not(no_global_oom_handling))]
205#[stable(feature = "rust1", since = "1.0.0")]
206impl ToOwned for str {
207 type Owned = String;
208
209 #[inline]
210 fn to_owned(&self) -> String {
211 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
212 }
213
214 #[inline]
215 fn clone_into(&self, target: &mut String) {
216 target.clear();
217 target.push_str(self);
218 }
219}
220
221/// Methods for string slices.
222#[cfg(not(test))]
223impl str {
224 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
225 ///
226 /// # Examples
227 ///
228 /// ```
229 /// let s = "this is a string";
230 /// let boxed_str = s.to_owned().into_boxed_str();
231 /// let boxed_bytes = boxed_str.into_boxed_bytes();
232 /// assert_eq!(*boxed_bytes, *s.as_bytes());
233 /// ```
234 #[rustc_allow_incoherent_impl]
235 #[stable(feature = "str_box_extras", since = "1.20.0")]
236 #[must_use = "`self` will be dropped if the result is not used"]
237 #[inline]
238 pub fn into_boxed_bytes(self: Box<str>) -> Box<[u8]> {
239 self.into()
240 }
241
242 /// Replaces all matches of a pattern with another string.
243 ///
244 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
245 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
246 /// replaces them with the replacement string slice.
247 ///
248 /// # Examples
249 ///
250 /// Basic usage:
251 ///
252 /// ```
253 /// let s = "this is old";
254 ///
255 /// assert_eq!("this is new", s.replace("old", "new"));
256 /// assert_eq!("than an old", s.replace("is", "an"));
257 /// ```
258 ///
259 /// When the pattern doesn't match, it returns this string slice as [`String`]:
260 ///
261 /// ```
262 /// let s = "this is old";
263 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
264 /// ```
265 #[cfg(not(no_global_oom_handling))]
266 #[rustc_allow_incoherent_impl]
267 #[must_use = "this returns the replaced string as a new allocation, \
268 without modifying the original"]
269 #[stable(feature = "rust1", since = "1.0.0")]
270 #[inline]
271 pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String {
272 // Fast path for replacing a single ASCII character with another.
273 if let Some(from_byte) = match from.as_utf8_pattern() {
274 Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte),
275 Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()),
276 _ => None,
277 } {
278 if let [to_byte] = to.as_bytes() {
279 return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };
280 }
281 }
282 // Set result capacity to self.len() when from.len() <= to.len()
283 let default_capacity = match from.as_utf8_pattern() {
284 Some(Utf8Pattern::StringPattern(s)) if s.len() <= to.len() => self.len(),
285 Some(Utf8Pattern::CharPattern(c)) if c.len_utf8() <= to.len() => self.len(),
286 _ => 0,
287 };
288 let mut result = String::with_capacity(default_capacity);
289 let mut last_end = 0;
290 for (start, part) in self.match_indices(from) {
291 result.push_str(unsafe { self.get_unchecked(last_end..start) });
292 result.push_str(to);
293 last_end = start + part.len();
294 }
295 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
296 result
297 }
298
299 /// Replaces first N matches of a pattern with another string.
300 ///
301 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
302 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
303 /// replaces them with the replacement string slice at most `count` times.
304 ///
305 /// # Examples
306 ///
307 /// Basic usage:
308 ///
309 /// ```
310 /// let s = "foo foo 123 foo";
311 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
312 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
313 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
314 /// ```
315 ///
316 /// When the pattern doesn't match, it returns this string slice as [`String`]:
317 ///
318 /// ```
319 /// let s = "this is old";
320 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
321 /// ```
322 #[cfg(not(no_global_oom_handling))]
323 #[rustc_allow_incoherent_impl]
324 #[must_use = "this returns the replaced string as a new allocation, \
325 without modifying the original"]
326 #[stable(feature = "str_replacen", since = "1.16.0")]
327 pub fn replacen<P: Pattern>(&self, pat: P, to: &str, count: usize) -> String {
328 // Hope to reduce the times of re-allocation
329 let mut result = String::with_capacity(32);
330 let mut last_end = 0;
331 for (start, part) in self.match_indices(pat).take(count) {
332 result.push_str(unsafe { self.get_unchecked(last_end..start) });
333 result.push_str(to);
334 last_end = start + part.len();
335 }
336 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
337 result
338 }
339
340 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
341 ///
342 /// 'Lowercase' is defined according to the terms of the Unicode Derived Core Property
343 /// `Lowercase`.
344 ///
345 /// Since some characters can expand into multiple characters when changing
346 /// the case, this function returns a [`String`] instead of modifying the
347 /// parameter in-place.
348 ///
349 /// # Examples
350 ///
351 /// Basic usage:
352 ///
353 /// ```
354 /// let s = "HELLO";
355 ///
356 /// assert_eq!("hello", s.to_lowercase());
357 /// ```
358 ///
359 /// A tricky example, with sigma:
360 ///
361 /// ```
362 /// let sigma = "Σ";
363 ///
364 /// assert_eq!("σ", sigma.to_lowercase());
365 ///
366 /// // but at the end of a word, it's ς, not σ:
367 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
368 ///
369 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
370 /// ```
371 ///
372 /// Languages without case are not changed:
373 ///
374 /// ```
375 /// let new_year = "农历新年";
376 ///
377 /// assert_eq!(new_year, new_year.to_lowercase());
378 /// ```
379 #[cfg(not(no_global_oom_handling))]
380 #[rustc_allow_incoherent_impl]
381 #[must_use = "this returns the lowercase string as a new String, \
382 without modifying the original"]
383 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
384 pub fn to_lowercase(&self) -> String {
385 let (mut s, rest) = convert_while_ascii(self, u8::to_ascii_lowercase);
386
387 let prefix_len = s.len();
388
389 for (i, c) in rest.char_indices() {
390 if c == 'Σ' {
391 // Σ maps to σ, except at the end of a word where it maps to ς.
392 // This is the only conditional (contextual) but language-independent mapping
393 // in `SpecialCasing.txt`,
394 // so hard-code it rather than have a generic "condition" mechanism.
395 // See https://github.com/rust-lang/rust/issues/26035
396 let sigma_lowercase = map_uppercase_sigma(self, prefix_len + i);
397 s.push(sigma_lowercase);
398 } else {
399 match conversions::to_lower(c) {
400 [a, '\0', _] => s.push(a),
401 [a, b, '\0'] => {
402 s.push(a);
403 s.push(b);
404 }
405 [a, b, c] => {
406 s.push(a);
407 s.push(b);
408 s.push(c);
409 }
410 }
411 }
412 }
413 return s;
414
415 fn map_uppercase_sigma(from: &str, i: usize) -> char {
416 // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
417 // for the definition of `Final_Sigma`.
418 debug_assert!('Σ'.len_utf8() == 2);
419 let is_word_final = case_ignorable_then_cased(from[..i].chars().rev())
420 && !case_ignorable_then_cased(from[i + 2..].chars());
421 if is_word_final { 'ς' } else { 'σ' }
422 }
423
424 fn case_ignorable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
425 use core::unicode::{Case_Ignorable, Cased};
426 match iter.skip_while(|&c| Case_Ignorable(c)).next() {
427 Some(c) => Cased(c),
428 None => false,
429 }
430 }
431 }
432
433 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
434 ///
435 /// 'Uppercase' is defined according to the terms of the Unicode Derived Core Property
436 /// `Uppercase`.
437 ///
438 /// Since some characters can expand into multiple characters when changing
439 /// the case, this function returns a [`String`] instead of modifying the
440 /// parameter in-place.
441 ///
442 /// # Examples
443 ///
444 /// Basic usage:
445 ///
446 /// ```
447 /// let s = "hello";
448 ///
449 /// assert_eq!("HELLO", s.to_uppercase());
450 /// ```
451 ///
452 /// Scripts without case are not changed:
453 ///
454 /// ```
455 /// let new_year = "农历新年";
456 ///
457 /// assert_eq!(new_year, new_year.to_uppercase());
458 /// ```
459 ///
460 /// One character can become multiple:
461 /// ```
462 /// let s = "tschüß";
463 ///
464 /// assert_eq!("TSCHÜSS", s.to_uppercase());
465 /// ```
466 #[cfg(not(no_global_oom_handling))]
467 #[rustc_allow_incoherent_impl]
468 #[must_use = "this returns the uppercase string as a new String, \
469 without modifying the original"]
470 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
471 pub fn to_uppercase(&self) -> String {
472 let (mut s, rest) = convert_while_ascii(self, u8::to_ascii_uppercase);
473
474 for c in rest.chars() {
475 match conversions::to_upper(c) {
476 [a, '\0', _] => s.push(a),
477 [a, b, '\0'] => {
478 s.push(a);
479 s.push(b);
480 }
481 [a, b, c] => {
482 s.push(a);
483 s.push(b);
484 s.push(c);
485 }
486 }
487 }
488 s
489 }
490
491 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// let string = String::from("birthday gift");
497 /// let boxed_str = string.clone().into_boxed_str();
498 ///
499 /// assert_eq!(boxed_str.into_string(), string);
500 /// ```
501 #[stable(feature = "box_str", since = "1.4.0")]
502 #[rustc_allow_incoherent_impl]
503 #[must_use = "`self` will be dropped if the result is not used"]
504 #[inline]
505 pub fn into_string(self: Box<str>) -> String {
506 let slice = Box::<[u8]>::from(self);
507 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
508 }
509
510 /// Creates a new [`String`] by repeating a string `n` times.
511 ///
512 /// # Panics
513 ///
514 /// This function will panic if the capacity would overflow.
515 ///
516 /// # Examples
517 ///
518 /// Basic usage:
519 ///
520 /// ```
521 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
522 /// ```
523 ///
524 /// A panic upon overflow:
525 ///
526 /// ```should_panic
527 /// // this will panic at runtime
528 /// let huge = "0123456789abcdef".repeat(usize::MAX);
529 /// ```
530 #[cfg(not(no_global_oom_handling))]
531 #[rustc_allow_incoherent_impl]
532 #[must_use]
533 #[stable(feature = "repeat_str", since = "1.16.0")]
534 #[inline]
535 pub fn repeat(&self, n: usize) -> String {
536 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
537 }
538
539 /// Returns a copy of this string where each character is mapped to its
540 /// ASCII upper case equivalent.
541 ///
542 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
543 /// but non-ASCII letters are unchanged.
544 ///
545 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
546 ///
547 /// To uppercase ASCII characters in addition to non-ASCII characters, use
548 /// [`to_uppercase`].
549 ///
550 /// # Examples
551 ///
552 /// ```
553 /// let s = "Grüße, Jürgen ❤";
554 ///
555 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
556 /// ```
557 ///
558 /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
559 /// [`to_uppercase`]: #method.to_uppercase
560 #[cfg(not(no_global_oom_handling))]
561 #[rustc_allow_incoherent_impl]
562 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
563 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
564 #[inline]
565 pub fn to_ascii_uppercase(&self) -> String {
566 let mut s = self.to_owned();
567 s.make_ascii_uppercase();
568 s
569 }
570
571 /// Returns a copy of this string where each character is mapped to its
572 /// ASCII lower case equivalent.
573 ///
574 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
575 /// but non-ASCII letters are unchanged.
576 ///
577 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
578 ///
579 /// To lowercase ASCII characters in addition to non-ASCII characters, use
580 /// [`to_lowercase`].
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// let s = "Grüße, Jürgen ❤";
586 ///
587 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
588 /// ```
589 ///
590 /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
591 /// [`to_lowercase`]: #method.to_lowercase
592 #[cfg(not(no_global_oom_handling))]
593 #[rustc_allow_incoherent_impl]
594 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
595 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
596 #[inline]
597 pub fn to_ascii_lowercase(&self) -> String {
598 let mut s = self.to_owned();
599 s.make_ascii_lowercase();
600 s
601 }
602}
603
604/// Converts a boxed slice of bytes to a boxed string slice without checking
605/// that the string contains valid UTF-8.
606///
607/// # Examples
608///
609/// ```
610/// let smile_utf8 = Box::new([226, 152, 186]);
611/// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
612///
613/// assert_eq!("☺", &*smile);
614/// ```
615#[stable(feature = "str_box_extras", since = "1.20.0")]
616#[must_use]
617#[inline]
618pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
619 unsafe { Box::from_raw(Box::into_raw(v) as *mut str) }
620}
621
622/// Converts leading ascii bytes in `s` by calling the `convert` function.
623///
624/// For better average performance, this happens in chunks of `2*size_of::<usize>()`.
625///
626/// Returns a tuple of the converted prefix and the remainder starting from
627/// the first non-ascii character.
628///
629/// This function is only public so that it can be verified in a codegen test,
630/// see `issue-123712-str-to-lower-autovectorization.rs`.
631#[unstable(feature = "str_internals", issue = "none")]
632#[doc(hidden)]
633#[inline]
634#[cfg(not(test))]
635#[cfg(not(no_global_oom_handling))]
636pub fn convert_while_ascii(s: &str, convert: fn(&u8) -> u8) -> (String, &str) {
637 // Process the input in chunks of 16 bytes to enable auto-vectorization.
638 // Previously the chunk size depended on the size of `usize`,
639 // but on 32-bit platforms with sse or neon is also the better choice.
640 // The only downside on other platforms would be a bit more loop-unrolling.
641 const N: usize = 16;
642
643 let mut slice = s.as_bytes();
644 let mut out = Vec::with_capacity(slice.len());
645 let mut out_slice = out.spare_capacity_mut();
646
647 let mut ascii_prefix_len = 0_usize;
648 let mut is_ascii = [false; N];
649
650 while slice.len() >= N {
651 // SAFETY: checked in loop condition
652 let chunk = unsafe { slice.get_unchecked(..N) };
653 // SAFETY: out_slice has at least same length as input slice and gets sliced with the same offsets
654 let out_chunk = unsafe { out_slice.get_unchecked_mut(..N) };
655
656 for j in 0..N {
657 is_ascii[j] = chunk[j] <= 127;
658 }
659
660 // Auto-vectorization for this check is a bit fragile, sum and comparing against the chunk
661 // size gives the best result, specifically a pmovmsk instruction on x86.
662 // See https://github.com/llvm/llvm-project/issues/96395 for why llvm currently does not
663 // currently recognize other similar idioms.
664 if is_ascii.iter().map(|x| *x as u8).sum::<u8>() as usize != N {
665 break;
666 }
667
668 for j in 0..N {
669 out_chunk[j] = MaybeUninit::new(convert(&chunk[j]));
670 }
671
672 ascii_prefix_len += N;
673 slice = unsafe { slice.get_unchecked(N..) };
674 out_slice = unsafe { out_slice.get_unchecked_mut(N..) };
675 }
676
677 // handle the remainder as individual bytes
678 while slice.len() > 0 {
679 let byte = slice[0];
680 if byte > 127 {
681 break;
682 }
683 // SAFETY: out_slice has at least same length as input slice
684 unsafe {
685 *out_slice.get_unchecked_mut(0) = MaybeUninit::new(convert(&byte));
686 }
687 ascii_prefix_len += 1;
688 slice = unsafe { slice.get_unchecked(1..) };
689 out_slice = unsafe { out_slice.get_unchecked_mut(1..) };
690 }
691
692 unsafe {
693 // SAFETY: ascii_prefix_len bytes have been initialized above
694 out.set_len(ascii_prefix_len);
695
696 // SAFETY: We have written only valid ascii to the output vec
697 let ascii_string = String::from_utf8_unchecked(out);
698
699 // SAFETY: we know this is a valid char boundary
700 // since we only skipped over leading ascii bytes
701 let rest = core::str::from_utf8_unchecked(slice);
702
703 (ascii_string, rest)
704 }
705}
706#[inline]
707#[cfg(not(test))]
708#[cfg(not(no_global_oom_handling))]
709#[allow(dead_code)]
710/// Faster implementation of string replacement for ASCII to ASCII cases.
711/// Should produce fast vectorized code.
712unsafe fn replace_ascii(utf8_bytes: &[u8], from: u8, to: u8) -> String {
713 let result: Vec<u8> = utf8_bytes.iter().map(|b| if *b == from { to } else { *b }).collect();
714 // SAFETY: We replaced ascii with ascii on valid utf8 strings.
715 unsafe { String::from_utf8_unchecked(result) }
716}