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