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//
130// # Safety notes
131//
132// `Borrow` is a safe trait, and implementations are not required
133// to be deterministic. An inconsistent `Borrow` implementation could return slices
134// of different lengths on consecutive calls (e.g. by using interior mutability).
135//
136// This implementation calls `borrow()` multiple times:
137// 1. To calculate `reserved_len`, all elements are borrowed once.
138// 2. The first element is borrowed again when copied via `extend_from_slice`.
139// 3. Subsequent elements are borrowed a second time when building the mapped iterator.
140//
141// Risks and Mitigations:
142// - If the first element GROWS on the second borrow, the length subtraction underflows.
143// We mitigate this by doing a `checked_sub` to panic rather than allowing an underflow
144// that fabricates a huge destination slice.
145// - If elements 2..N GROW on their second borrow, the target slice bounds set by `checked_sub`
146// means that `split_at_mut` inside `copy_slice_and_advance!` will correctly panic.
147// - If elements SHRINK on their second borrow, the spare space is never written, and the final
148// length set via `set_len` masks trailing uninitialized bytes.
149#[cfg(not(no_global_oom_handling))]
150fn join_generic_copy<B, T, S>(slice: &[S], sep: &[T]) -> Vec<T>
151where
152 T: Copy,
153 B: AsRef<[T]> + ?Sized,
154 S: Borrow<B>,
155{
156 let sep_len = sep.len();
157 let mut iter = slice.iter();
158
159 // the first slice is the only one without a separator preceding it
160 let first = match iter.next() {
161 Some(first) => first,
162 None => return vec![],
163 };
164
165 // compute the exact total length of the joined Vec
166 // if the `len` calculation overflows, we'll panic
167 // we would have run out of memory anyway and the rest of the function requires
168 // the entire Vec pre-allocated for safety
169 let reserved_len = sep_len
170 .checked_mul(iter.len())
171 .and_then(|n| {
172 slice.iter().map(|s| s.borrow().as_ref().len()).try_fold(n, usize::checked_add)
173 })
174 .expect("attempt to join into collection with len > usize::MAX");
175
176 // prepare an uninitialized buffer
177 let mut result = Vec::with_capacity(reserved_len);
178 debug_assert!(result.capacity() >= reserved_len);
179
180 result.extend_from_slice(first.borrow().as_ref());
181
182 unsafe {
183 let pos = result.len();
184 let target_len = reserved_len.checked_sub(pos).expect("inconsistent Borrow implementation");
185 let target = result.spare_capacity_mut().get_unchecked_mut(..target_len);
186
187 // Convert the separator and slices to slices of MaybeUninit
188 // to simplify implementation in specialize_for_lengths.
189 let sep_uninit = core::slice::from_raw_parts(sep.as_ptr().cast(), sep.len());
190 let iter_uninit = iter.map(|it| {
191 let it = it.borrow().as_ref();
192 core::slice::from_raw_parts(it.as_ptr().cast(), it.len())
193 });
194
195 // copy separator and slices over without bounds checks.
196 // `specialize_for_lengths!` internally calls `s.borrow()`, but because it uses
197 // the bounds-checked `split_at_mut` any misbehaving implementation
198 // will not write out of bounds.
199 let remain = specialize_for_lengths!(sep_uninit, target, iter_uninit; 0, 1, 2, 3, 4);
200
201 // A weird borrow implementation may return different
202 // slices for the length calculation and the actual copy.
203 // Make sure we don't expose uninitialized bytes to the caller.
204 let result_len = reserved_len - remain.len();
205 result.set_len(result_len);
206 }
207 result
208}
209
210#[stable(feature = "rust1", since = "1.0.0")]
211impl Borrow<str> for String {
212 #[inline]
213 fn borrow(&self) -> &str {
214 &self[..]
215 }
216}
217
218#[stable(feature = "string_borrow_mut", since = "1.36.0")]
219impl BorrowMut<str> for String {
220 #[inline]
221 fn borrow_mut(&mut self) -> &mut str {
222 &mut self[..]
223 }
224}
225
226#[cfg(not(no_global_oom_handling))]
227#[stable(feature = "rust1", since = "1.0.0")]
228impl ToOwned for str {
229 type Owned = String;
230
231 #[inline]
232 fn to_owned(&self) -> String {
233 unsafe { String::from_utf8_unchecked(self.as_bytes().to_owned()) }
234 }
235
236 #[inline]
237 fn clone_into(&self, target: &mut String) {
238 target.clear();
239 target.push_str(self);
240 }
241}
242
243/// Methods for string slices.
244impl str {
245 /// Converts a `Box<str>` into a `Box<[u8]>` without copying or allocating.
246 ///
247 /// # Examples
248 ///
249 /// ```
250 /// let s = "this is a string";
251 /// let boxed_str = s.to_owned().into_boxed_str();
252 /// let boxed_bytes = boxed_str.into_boxed_bytes();
253 /// assert_eq!(*boxed_bytes, *s.as_bytes());
254 /// ```
255 #[rustc_allow_incoherent_impl]
256 #[stable(feature = "str_box_extras", since = "1.20.0")]
257 #[must_use = "`self` will be dropped if the result is not used"]
258 #[inline]
259 pub fn into_boxed_bytes(self: Box<Self>) -> Box<[u8]> {
260 self.into()
261 }
262
263 /// Replaces all matches of a pattern with another string.
264 ///
265 /// `replace` creates a new [`String`], and copies the data from this string slice into it.
266 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
267 /// replaces them with the replacement string slice.
268 ///
269 /// # Examples
270 ///
271 /// ```
272 /// let s = "this is old";
273 ///
274 /// assert_eq!("this is new", s.replace("old", "new"));
275 /// assert_eq!("than an old", s.replace("is", "an"));
276 /// ```
277 ///
278 /// When the pattern doesn't match, it returns this string slice as [`String`]:
279 ///
280 /// ```
281 /// let s = "this is old";
282 /// assert_eq!(s, s.replace("cookie monster", "little lamb"));
283 /// ```
284 #[cfg(not(no_global_oom_handling))]
285 #[rustc_allow_incoherent_impl]
286 #[must_use = "this returns the replaced string as a new allocation, \
287 without modifying the original"]
288 #[stable(feature = "rust1", since = "1.0.0")]
289 #[inline]
290 pub fn replace<P: Pattern>(&self, from: P, to: &str) -> String {
291 // Fast path for replacing a single ASCII character with another.
292 if let Some(from_byte) = match from.as_utf8_pattern() {
293 Some(Utf8Pattern::StringPattern([from_byte])) => Some(*from_byte),
294 Some(Utf8Pattern::CharPattern(c)) => c.as_ascii().map(|ascii_char| ascii_char.to_u8()),
295 _ => None,
296 } {
297 if let [to_byte] = to.as_bytes() {
298 return unsafe { replace_ascii(self.as_bytes(), from_byte, *to_byte) };
299 }
300 }
301 // Set result capacity to self.len() when from.len() <= to.len()
302 let default_capacity = match from.as_utf8_pattern() {
303 Some(Utf8Pattern::StringPattern(s)) if s.len() <= to.len() => self.len(),
304 Some(Utf8Pattern::CharPattern(c)) if c.len_utf8() <= to.len() => self.len(),
305 _ => 0,
306 };
307 let mut result = String::with_capacity(default_capacity);
308 let mut last_end = 0;
309 for (start, part) in self.match_indices(from) {
310 result.push_str(unsafe { self.get_unchecked(last_end..start) });
311 result.push_str(to);
312 last_end = start + part.len();
313 }
314 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
315 result
316 }
317
318 /// Replaces first N matches of a pattern with another string.
319 ///
320 /// `replacen` creates a new [`String`], and copies the data from this string slice into it.
321 /// While doing so, it attempts to find matches of a pattern. If it finds any, it
322 /// replaces them with the replacement string slice at most `count` times.
323 ///
324 /// # Examples
325 ///
326 /// ```
327 /// let s = "foo foo 123 foo";
328 /// assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
329 /// assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
330 /// assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));
331 /// ```
332 ///
333 /// When the pattern doesn't match, it returns this string slice as [`String`]:
334 ///
335 /// ```
336 /// let s = "this is old";
337 /// assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
338 /// ```
339 #[cfg(not(no_global_oom_handling))]
340 #[rustc_allow_incoherent_impl]
341 #[doc(alias = "replace_first")]
342 #[must_use = "this returns the replaced string as a new allocation, \
343 without modifying the original"]
344 #[stable(feature = "str_replacen", since = "1.16.0")]
345 pub fn replacen<P: Pattern>(&self, pat: P, to: &str, count: usize) -> String {
346 // Hope to reduce the times of re-allocation
347 let mut result = String::with_capacity(32);
348 let mut last_end = 0;
349 for (start, part) in self.match_indices(pat).take(count) {
350 result.push_str(unsafe { self.get_unchecked(last_end..start) });
351 result.push_str(to);
352 last_end = start + part.len();
353 }
354 result.push_str(unsafe { self.get_unchecked(last_end..self.len()) });
355 result
356 }
357
358 /// Returns the lowercase equivalent of this string slice, as a new [`String`].
359 ///
360 /// 'Lowercase' is defined according to the terms of
361 /// [Chapter 3 (Conformance)](https://www.unicode.org/versions/latest/core-spec/chapter-3/#G34432)
362 /// of the Unicode standard.
363 ///
364 /// Since some characters can expand into multiple characters when changing
365 /// the case, this function returns a [`String`] instead of modifying the
366 /// parameter in-place.
367 ///
368 /// Unlike [`char::to_lowercase()`], this method fully handles the context-dependent
369 /// casing of Greek sigma. However, like that method, it does not handle locale-specific
370 /// casing, like Turkish and Azeri I/ı/İ/i. See that method's documentation
371 /// for more information.
372 ///
373 /// # Examples
374 ///
375 /// Basic usage:
376 ///
377 /// ```
378 /// let s = "HELLO";
379 ///
380 /// assert_eq!("hello", s.to_lowercase());
381 /// ```
382 ///
383 /// A tricky example, with sigma:
384 ///
385 /// ```
386 /// let sigma = "Σ";
387 ///
388 /// assert_eq!("σ", sigma.to_lowercase());
389 ///
390 /// // but at the end of a word, it's ς, not σ:
391 /// let odysseus = "ὈΔΥΣΣΕΎΣ";
392 ///
393 /// assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());
394 /// ```
395 ///
396 /// Languages without case are not changed:
397 ///
398 /// ```
399 /// let new_year = "农历新年";
400 ///
401 /// assert_eq!(new_year, new_year.to_lowercase());
402 /// ```
403 #[cfg(not(no_global_oom_handling))]
404 #[rustc_allow_incoherent_impl]
405 #[must_use = "this returns the lowercase string as a new String, \
406 without modifying the original"]
407 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
408 pub fn to_lowercase(&self) -> String {
409 // SAFETY: `to_ascii_lowercase` preserves ASCII bytes, so the converted
410 // prefix remains valid UTF-8.
411 let (mut s, rest) = unsafe { convert_while_ascii(self, u8::to_ascii_lowercase) };
412
413 let prefix_len = s.len();
414
415 for (i, c) in rest.char_indices() {
416 if c == 'Σ' {
417 // Σ maps to σ, except at the end of a word where it maps to ς.
418 // This is the only conditional (contextual) but language-independent mapping
419 // in `SpecialCasing.txt`,
420 // so hard-code it rather than have a generic "condition" mechanism.
421 // See https://github.com/rust-lang/rust/issues/26035
422 let sigma_lowercase = map_uppercase_sigma(self, prefix_len + i);
423 s.push(sigma_lowercase);
424 } else {
425 match conversions::to_lower(c) {
426 [a, '\0', _] => s.push(a),
427 [a, b, '\0'] => {
428 s.push(a);
429 s.push(b);
430 }
431 [a, b, c] => {
432 s.push(a);
433 s.push(b);
434 s.push(c);
435 }
436 }
437 }
438 }
439 return s;
440
441 fn map_uppercase_sigma(from: &str, i: usize) -> char {
442 // See https://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G33992
443 // for the definition of `Final_Sigma`.
444 let is_word_final = case_ignorable_then_cased(from[..i].chars().rev())
445 && !case_ignorable_then_cased(from[i + const { 'Σ'.len_utf8() }..].chars());
446 if is_word_final { 'ς' } else { 'σ' }
447 }
448
449 fn case_ignorable_then_cased<I: Iterator<Item = char>>(iter: I) -> bool {
450 match iter.skip_while(|&c| c.is_case_ignorable()).next() {
451 Some(c) => c.is_cased(),
452 None => false,
453 }
454 }
455 }
456
457 /// Returns the uppercase equivalent of this string slice, as a new [`String`].
458 ///
459 /// 'Uppercase' is defined according to the terms of
460 /// [Chapter 3 (Conformance)](https://www.unicode.org/versions/latest/core-spec/chapter-3/#G34431)
461 /// of the Unicode standard.
462 ///
463 /// Since some characters can expand into multiple characters when changing
464 /// the case, this function returns a [`String`] instead of modifying the
465 /// parameter in-place.
466 ///
467 /// Like [`char::to_uppercase()`] this method does not handle language-specific
468 /// casing, like Turkish and Azeri I/ı/İ/i. See that method's documentation
469 /// for more information.
470 ///
471 /// # Examples
472 ///
473 /// Basic usage:
474 ///
475 /// ```
476 /// let s = "hello";
477 ///
478 /// assert_eq!("HELLO", s.to_uppercase());
479 /// ```
480 ///
481 /// Scripts without case are not changed:
482 ///
483 /// ```
484 /// let new_year = "农历新年";
485 ///
486 /// assert_eq!(new_year, new_year.to_uppercase());
487 /// ```
488 ///
489 /// One character can become multiple:
490 /// ```
491 /// let s = "tschüß";
492 ///
493 /// assert_eq!("TSCHÜSS", s.to_uppercase());
494 /// ```
495 #[cfg(not(no_global_oom_handling))]
496 #[rustc_allow_incoherent_impl]
497 #[must_use = "this returns the uppercase string as a new String, \
498 without modifying the original"]
499 #[stable(feature = "unicode_case_mapping", since = "1.2.0")]
500 pub fn to_uppercase(&self) -> String {
501 // SAFETY: `to_ascii_uppercase` preserves ASCII bytes, so the converted
502 // prefix remains valid UTF-8.
503 let (mut s, rest) = unsafe { convert_while_ascii(self, u8::to_ascii_uppercase) };
504
505 for c in rest.chars() {
506 match conversions::to_upper(c) {
507 [a, '\0', _] => s.push(a),
508 [a, b, '\0'] => {
509 s.push(a);
510 s.push(b);
511 }
512 [a, b, c] => {
513 s.push(a);
514 s.push(b);
515 s.push(c);
516 }
517 }
518 }
519 s
520 }
521
522 /// Converts a [`Box<str>`] into a [`String`] without copying or allocating.
523 ///
524 /// # Examples
525 ///
526 /// ```
527 /// let string = String::from("birthday gift");
528 /// let boxed_str = string.clone().into_boxed_str();
529 ///
530 /// assert_eq!(boxed_str.into_string(), string);
531 /// ```
532 #[stable(feature = "box_str", since = "1.4.0")]
533 #[rustc_allow_incoherent_impl]
534 #[must_use = "`self` will be dropped if the result is not used"]
535 #[inline]
536 pub fn into_string(self: Box<Self>) -> String {
537 let slice = Box::<[u8]>::from(self);
538 unsafe { String::from_utf8_unchecked(slice.into_vec()) }
539 }
540
541 /// Creates a new [`String`] by repeating a string `n` times.
542 ///
543 /// # Panics
544 ///
545 /// This function will panic if the capacity would overflow.
546 ///
547 /// # Examples
548 ///
549 /// Basic usage:
550 ///
551 /// ```
552 /// assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));
553 /// ```
554 ///
555 /// A panic upon overflow:
556 ///
557 /// ```should_panic
558 /// // this will panic at runtime
559 /// let huge = "0123456789abcdef".repeat(usize::MAX);
560 /// ```
561 #[cfg(not(no_global_oom_handling))]
562 #[rustc_allow_incoherent_impl]
563 #[must_use]
564 #[stable(feature = "repeat_str", since = "1.16.0")]
565 #[inline]
566 pub fn repeat(&self, n: usize) -> String {
567 unsafe { String::from_utf8_unchecked(self.as_bytes().repeat(n)) }
568 }
569
570 /// Returns a copy of this string where each character is mapped to its
571 /// ASCII upper case equivalent.
572 ///
573 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
574 /// but non-ASCII letters are unchanged.
575 ///
576 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
577 ///
578 /// To uppercase ASCII characters in addition to non-ASCII characters, use
579 /// [`to_uppercase`].
580 ///
581 /// # Examples
582 ///
583 /// ```
584 /// let s = "Grüße, Jürgen ❤";
585 ///
586 /// assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
587 /// ```
588 ///
589 /// [`make_ascii_uppercase`]: str::make_ascii_uppercase
590 /// [`to_uppercase`]: #method.to_uppercase
591 #[cfg(not(no_global_oom_handling))]
592 #[rustc_allow_incoherent_impl]
593 #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
594 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
595 #[inline]
596 pub fn to_ascii_uppercase(&self) -> String {
597 let mut s = self.to_owned();
598 s.make_ascii_uppercase();
599 s
600 }
601
602 /// Returns a copy of this string where each character is mapped to its
603 /// ASCII lower case equivalent.
604 ///
605 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
606 /// but non-ASCII letters are unchanged.
607 ///
608 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
609 ///
610 /// To lowercase ASCII characters in addition to non-ASCII characters, use
611 /// [`to_lowercase`].
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// let s = "Grüße, Jürgen ❤";
617 ///
618 /// assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());
619 /// ```
620 ///
621 /// [`make_ascii_lowercase`]: str::make_ascii_lowercase
622 /// [`to_lowercase`]: #method.to_lowercase
623 #[cfg(not(no_global_oom_handling))]
624 #[rustc_allow_incoherent_impl]
625 #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
626 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
627 #[inline]
628 pub fn to_ascii_lowercase(&self) -> String {
629 let mut s = self.to_owned();
630 s.make_ascii_lowercase();
631 s
632 }
633}
634
635/// Converts a boxed slice of bytes to a boxed string slice without checking
636/// that the string contains valid UTF-8.
637///
638/// # Safety
639///
640/// * The provided bytes must contain a valid UTF-8 sequence.
641///
642/// # Examples
643///
644/// ```
645/// let smile_utf8 = Box::new([226, 152, 186]);
646/// let smile = unsafe { std::str::from_boxed_utf8_unchecked(smile_utf8) };
647///
648/// assert_eq!("☺", &*smile);
649/// ```
650#[stable(feature = "str_box_extras", since = "1.20.0")]
651#[must_use]
652#[inline]
653pub unsafe fn from_boxed_utf8_unchecked(v: Box<[u8]>) -> Box<str> {
654 unsafe { Box::from_raw(Box::into_raw(v) as *mut str) }
655}
656
657/// Converts leading ascii bytes in `s` by calling the `convert` function.
658///
659/// For better average performance, this happens in chunks of `2*size_of::<usize>()`.
660///
661/// Returns a tuple of the converted prefix and the remainder starting from
662/// the first non-ascii character.
663///
664/// This function is only public so that it can be verified in a codegen test,
665/// see `issue-123712-str-to-lower-autovectorization.rs`.
666///
667/// # Safety
668///
669/// `convert` must return an ASCII byte for every ASCII input byte.
670#[unstable(feature = "str_internals", issue = "none")]
671#[doc(hidden)]
672#[inline]
673#[cfg(not(no_global_oom_handling))]
674pub unsafe fn convert_while_ascii(s: &str, convert: fn(&u8) -> u8) -> (String, &str) {
675 // Process the input in chunks of 16 bytes to enable auto-vectorization.
676 // Previously the chunk size depended on the size of `usize`,
677 // but on 32-bit platforms with sse or neon is also the better choice.
678 // The only downside on other platforms would be a bit more loop-unrolling.
679 const N: usize = 16;
680
681 let mut slice = s.as_bytes();
682 let mut out = Vec::with_capacity(slice.len());
683 let mut out_slice = out.spare_capacity_mut();
684
685 let mut ascii_prefix_len = 0_usize;
686 let mut is_ascii = [false; N];
687
688 while slice.len() >= N {
689 // SAFETY: checked in loop condition
690 let chunk = unsafe { slice.get_unchecked(..N) };
691 // SAFETY: out_slice has at least same length as input slice and gets sliced with the same offsets
692 let out_chunk = unsafe { out_slice.get_unchecked_mut(..N) };
693
694 for j in 0..N {
695 is_ascii[j] = chunk[j] <= 127;
696 }
697
698 // Auto-vectorization for this check is a bit fragile, sum and comparing against the chunk
699 // size gives the best result, specifically a pmovmsk instruction on x86.
700 // See https://github.com/llvm/llvm-project/issues/96395 for why llvm currently does not
701 // currently recognize other similar idioms.
702 if is_ascii.iter().map(|x| *x as u8).sum::<u8>() as usize != N {
703 break;
704 }
705
706 for j in 0..N {
707 out_chunk[j] = MaybeUninit::new(convert(&chunk[j]));
708 }
709
710 ascii_prefix_len += N;
711 slice = unsafe { slice.get_unchecked(N..) };
712 out_slice = unsafe { out_slice.get_unchecked_mut(N..) };
713 }
714
715 // handle the remainder as individual bytes
716 while slice.len() > 0 {
717 let byte = slice[0];
718 if byte > 127 {
719 break;
720 }
721 // SAFETY: out_slice has at least same length as input slice
722 unsafe {
723 *out_slice.get_unchecked_mut(0) = MaybeUninit::new(convert(&byte));
724 }
725 ascii_prefix_len += 1;
726 slice = unsafe { slice.get_unchecked(1..) };
727 out_slice = unsafe { out_slice.get_unchecked_mut(1..) };
728 }
729
730 unsafe {
731 // SAFETY: ascii_prefix_len bytes have been initialized above
732 out.set_len(ascii_prefix_len);
733
734 // SAFETY: We have written only valid ascii to the output vec
735 let ascii_string = String::from_utf8_unchecked(out);
736
737 // SAFETY: we know this is a valid char boundary
738 // since we only skipped over leading ascii bytes
739 let rest = core::str::from_utf8_unchecked(slice);
740
741 (ascii_string, rest)
742 }
743}
744#[inline]
745#[cfg(not(no_global_oom_handling))]
746#[allow(dead_code)]
747/// Faster implementation of string replacement for ASCII to ASCII cases.
748/// Should produce fast vectorized code.
749unsafe fn replace_ascii(utf8_bytes: &[u8], from: u8, to: u8) -> String {
750 let result: Vec<u8> = utf8_bytes.iter().map(|b| if *b == from { to } else { *b }).collect();
751 // SAFETY: We replaced ascii with ascii on valid utf8 strings.
752 unsafe { String::from_utf8_unchecked(result) }
753}