1 //! Operations on ASCII `[u8]`.
4 use crate::fmt::{self, Write};
12 /// Checks if all bytes in this slice are within the ASCII range.
13 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
16 pub fn is_ascii(&self) -> bool {
20 /// Checks that two slices are an ASCII case-insensitive match.
22 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
23 /// but without allocating and copying temporaries.
24 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
27 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
28 self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
31 /// Converts this slice to its ASCII upper case equivalent in-place.
33 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
34 /// but non-ASCII letters are unchanged.
36 /// To return a new uppercased value without modifying the existing one, use
37 /// [`to_ascii_uppercase`].
39 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
40 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
42 pub fn make_ascii_uppercase(&mut self) {
44 byte.make_ascii_uppercase();
48 /// Converts this slice to its ASCII lower case equivalent in-place.
50 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
51 /// but non-ASCII letters are unchanged.
53 /// To return a new lowercased value without modifying the existing one, use
54 /// [`to_ascii_lowercase`].
56 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
57 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
59 pub fn make_ascii_lowercase(&mut self) {
61 byte.make_ascii_lowercase();
65 /// Returns an iterator that produces an escaped version of this slice,
66 /// treating it as an ASCII string.
71 /// #![feature(inherent_ascii_escape)]
73 /// let s = b"0\t\r\n'\"\\\x9d";
74 /// let escaped = s.escape_ascii().to_string();
75 /// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
77 #[must_use = "this returns the escaped bytes as an iterator, \
78 without modifying the original"]
79 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
80 pub fn escape_ascii(&self) -> EscapeAscii<'_> {
81 EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
87 struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
88 ascii::escape_default(*byte)
92 /// An iterator over the escaped version of a byte slice.
94 /// This `struct` is created by the [`slice::escape_ascii`] method. See its
95 /// documentation for more information.
96 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
98 pub struct EscapeAscii<'a> {
99 inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
102 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
103 impl<'a> iter::Iterator for EscapeAscii<'a> {
106 fn next(&mut self) -> Option<u8> {
110 fn size_hint(&self) -> (usize, Option<usize>) {
111 self.inner.size_hint()
114 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
116 Fold: FnMut(Acc, Self::Item) -> R,
117 R: ops::Try<Output = Acc>,
119 self.inner.try_fold(init, fold)
122 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
124 Fold: FnMut(Acc, Self::Item) -> Acc,
126 self.inner.fold(init, fold)
129 fn last(mut self) -> Option<u8> {
134 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
135 impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
136 fn next_back(&mut self) -> Option<u8> {
137 self.inner.next_back()
140 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
141 impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
142 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
143 impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
144 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
145 impl<'a> fmt::Display for EscapeAscii<'a> {
146 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147 self.clone().try_for_each(|b| f.write_char(b as char))
150 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
151 impl<'a> fmt::Debug for EscapeAscii<'a> {
152 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153 f.debug_struct("EscapeAscii").finish_non_exhaustive()
157 /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
158 /// from `../str/mod.rs`, which does something similar for utf8 validation.
160 fn contains_nonascii(v: usize) -> bool {
161 const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
162 (NONASCII_MASK & v) != 0
165 /// Optimized ASCII test that will use usize-at-a-time operations instead of
166 /// byte-at-a-time operations (when possible).
168 /// The algorithm we use here is pretty simple. If `s` is too short, we just
169 /// check each byte and be done with it. Otherwise:
171 /// - Read the first word with an unaligned load.
172 /// - Align the pointer, read subsequent words until end with aligned loads.
173 /// - Read the last `usize` from `s` with an unaligned load.
175 /// If any of these loads produces something for which `contains_nonascii`
176 /// (above) returns true, then we know the answer is false.
178 fn is_ascii(s: &[u8]) -> bool {
179 const USIZE_SIZE: usize = mem::size_of::<usize>();
182 let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
184 // If we wouldn't gain anything from the word-at-a-time implementation, fall
185 // back to a scalar loop.
187 // We also do this for architectures where `size_of::<usize>()` isn't
188 // sufficient alignment for `usize`, because it's a weird edge case.
189 if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
190 return s.iter().all(|b| b.is_ascii());
193 // We always read the first word unaligned, which means `align_offset` is
194 // 0, we'd read the same value again for the aligned read.
195 let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
197 let start = s.as_ptr();
198 // SAFETY: We verify `len < USIZE_SIZE` above.
199 let first_word = unsafe { (start as *const usize).read_unaligned() };
201 if contains_nonascii(first_word) {
204 // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
205 // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
207 debug_assert!(offset_to_aligned <= len);
209 // SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
210 // middle chunk of the slice.
211 let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
213 // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
214 let mut byte_pos = offset_to_aligned;
216 // Paranoia check about alignment, since we're about to do a bunch of
217 // unaligned loads. In practice this should be impossible barring a bug in
218 // `align_offset` though.
219 debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
221 // Read subsequent words until the last aligned word, excluding the last
222 // aligned word by itself to be done in tail check later, to ensure that
223 // tail is always one `usize` at most to extra branch `byte_pos == len`.
224 while byte_pos < len - USIZE_SIZE {
226 // Sanity check that the read is in bounds
227 (word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
228 // And that our assumptions about `byte_pos` hold.
229 (word_ptr as usize) - (start as usize) == byte_pos
232 // SAFETY: We know `word_ptr` is properly aligned (because of
233 // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
234 let word = unsafe { word_ptr.read() };
235 if contains_nonascii(word) {
239 byte_pos += USIZE_SIZE;
240 // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
241 // after this `add`, `word_ptr` will be at most one-past-the-end.
242 word_ptr = unsafe { word_ptr.add(1) };
245 // Sanity check to ensure there really is only one `usize` left. This should
246 // be guaranteed by our loop condition.
247 debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
249 // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
250 let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
252 !contains_nonascii(last_word)