1 //! Operations on ASCII `[u8]`.
2
3 use crate::ascii;
4 use crate::fmt::{self, Write};
5 use crate::iter;
6 use crate::mem;
7 use crate::ops;
8
9 #[cfg(not(test))]
10 impl [u8] {
11 /// Checks if all bytes in this slice are within the ASCII range.
12 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
13 #[rustc_const_unstable(feature = "const_slice_is_ascii", issue = "111090")]
14 #[must_use]
15 #[inline]
is_ascii(&self) -> bool16 pub const fn is_ascii(&self) -> bool {
17 is_ascii(self)
18 }
19
20 /// If this slice [`is_ascii`](Self::is_ascii), returns it as a slice of
21 /// [ASCII characters](`ascii::Char`), otherwise returns `None`.
22 #[unstable(feature = "ascii_char", issue = "110998")]
23 #[must_use]
24 #[inline]
as_ascii(&self) -> Option<&[ascii::Char]>25 pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
26 if self.is_ascii() {
27 // SAFETY: Just checked that it's ASCII
28 Some(unsafe { self.as_ascii_unchecked() })
29 } else {
30 None
31 }
32 }
33
34 /// Converts this slice of bytes into a slice of ASCII characters,
35 /// without checking whether they're valid.
36 ///
37 /// # Safety
38 ///
39 /// Every byte in the slice must be in `0..=127`, or else this is UB.
40 #[unstable(feature = "ascii_char", issue = "110998")]
41 #[must_use]
42 #[inline]
as_ascii_unchecked(&self) -> &[ascii::Char]43 pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
44 let byte_ptr: *const [u8] = self;
45 let ascii_ptr = byte_ptr as *const [ascii::Char];
46 // SAFETY: The caller promised all the bytes are ASCII
47 unsafe { &*ascii_ptr }
48 }
49
50 /// Checks that two slices are an ASCII case-insensitive match.
51 ///
52 /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
53 /// but without allocating and copying temporaries.
54 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
55 #[must_use]
56 #[inline]
eq_ignore_ascii_case(&self, other: &[u8]) -> bool57 pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
58 self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
59 }
60
61 /// Converts this slice to its ASCII upper case equivalent in-place.
62 ///
63 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
64 /// but non-ASCII letters are unchanged.
65 ///
66 /// To return a new uppercased value without modifying the existing one, use
67 /// [`to_ascii_uppercase`].
68 ///
69 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
70 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
71 #[inline]
make_ascii_uppercase(&mut self)72 pub fn make_ascii_uppercase(&mut self) {
73 for byte in self {
74 byte.make_ascii_uppercase();
75 }
76 }
77
78 /// Converts this slice to its ASCII lower case equivalent in-place.
79 ///
80 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
81 /// but non-ASCII letters are unchanged.
82 ///
83 /// To return a new lowercased value without modifying the existing one, use
84 /// [`to_ascii_lowercase`].
85 ///
86 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
87 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
88 #[inline]
make_ascii_lowercase(&mut self)89 pub fn make_ascii_lowercase(&mut self) {
90 for byte in self {
91 byte.make_ascii_lowercase();
92 }
93 }
94
95 /// Returns an iterator that produces an escaped version of this slice,
96 /// treating it as an ASCII string.
97 ///
98 /// # Examples
99 ///
100 /// ```
101 ///
102 /// let s = b"0\t\r\n'\"\\\x9d";
103 /// let escaped = s.escape_ascii().to_string();
104 /// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
105 /// ```
106 #[must_use = "this returns the escaped bytes as an iterator, \
107 without modifying the original"]
108 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
escape_ascii(&self) -> EscapeAscii<'_>109 pub fn escape_ascii(&self) -> EscapeAscii<'_> {
110 EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
111 }
112
113 /// Returns a byte slice with leading ASCII whitespace bytes removed.
114 ///
115 /// 'Whitespace' refers to the definition used by
116 /// `u8::is_ascii_whitespace`.
117 ///
118 /// # Examples
119 ///
120 /// ```
121 /// #![feature(byte_slice_trim_ascii)]
122 ///
123 /// assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
124 /// assert_eq!(b" ".trim_ascii_start(), b"");
125 /// assert_eq!(b"".trim_ascii_start(), b"");
126 /// ```
127 #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
trim_ascii_start(&self) -> &[u8]128 pub const fn trim_ascii_start(&self) -> &[u8] {
129 let mut bytes = self;
130 // Note: A pattern matching based approach (instead of indexing) allows
131 // making the function const.
132 while let [first, rest @ ..] = bytes {
133 if first.is_ascii_whitespace() {
134 bytes = rest;
135 } else {
136 break;
137 }
138 }
139 bytes
140 }
141
142 /// Returns a byte slice with trailing ASCII whitespace bytes removed.
143 ///
144 /// 'Whitespace' refers to the definition used by
145 /// `u8::is_ascii_whitespace`.
146 ///
147 /// # Examples
148 ///
149 /// ```
150 /// #![feature(byte_slice_trim_ascii)]
151 ///
152 /// assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
153 /// assert_eq!(b" ".trim_ascii_end(), b"");
154 /// assert_eq!(b"".trim_ascii_end(), b"");
155 /// ```
156 #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
trim_ascii_end(&self) -> &[u8]157 pub const fn trim_ascii_end(&self) -> &[u8] {
158 let mut bytes = self;
159 // Note: A pattern matching based approach (instead of indexing) allows
160 // making the function const.
161 while let [rest @ .., last] = bytes {
162 if last.is_ascii_whitespace() {
163 bytes = rest;
164 } else {
165 break;
166 }
167 }
168 bytes
169 }
170
171 /// Returns a byte slice with leading and trailing ASCII whitespace bytes
172 /// removed.
173 ///
174 /// 'Whitespace' refers to the definition used by
175 /// `u8::is_ascii_whitespace`.
176 ///
177 /// # Examples
178 ///
179 /// ```
180 /// #![feature(byte_slice_trim_ascii)]
181 ///
182 /// assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
183 /// assert_eq!(b" ".trim_ascii(), b"");
184 /// assert_eq!(b"".trim_ascii(), b"");
185 /// ```
186 #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
trim_ascii(&self) -> &[u8]187 pub const fn trim_ascii(&self) -> &[u8] {
188 self.trim_ascii_start().trim_ascii_end()
189 }
190 }
191
192 impl_fn_for_zst! {
193 #[derive(Clone)]
194 struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
195 ascii::escape_default(*byte)
196 };
197 }
198
199 /// An iterator over the escaped version of a byte slice.
200 ///
201 /// This `struct` is created by the [`slice::escape_ascii`] method. See its
202 /// documentation for more information.
203 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
204 #[derive(Clone)]
205 #[must_use = "iterators are lazy and do nothing unless consumed"]
206 pub struct EscapeAscii<'a> {
207 inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
208 }
209
210 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
211 impl<'a> iter::Iterator for EscapeAscii<'a> {
212 type Item = u8;
213 #[inline]
next(&mut self) -> Option<u8>214 fn next(&mut self) -> Option<u8> {
215 self.inner.next()
216 }
217 #[inline]
size_hint(&self) -> (usize, Option<usize>)218 fn size_hint(&self) -> (usize, Option<usize>) {
219 self.inner.size_hint()
220 }
221 #[inline]
try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R where Fold: FnMut(Acc, Self::Item) -> R, R: ops::Try<Output = Acc>,222 fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
223 where
224 Fold: FnMut(Acc, Self::Item) -> R,
225 R: ops::Try<Output = Acc>,
226 {
227 self.inner.try_fold(init, fold)
228 }
229 #[inline]
fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc where Fold: FnMut(Acc, Self::Item) -> Acc,230 fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
231 where
232 Fold: FnMut(Acc, Self::Item) -> Acc,
233 {
234 self.inner.fold(init, fold)
235 }
236 #[inline]
last(mut self) -> Option<u8>237 fn last(mut self) -> Option<u8> {
238 self.next_back()
239 }
240 }
241
242 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
243 impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
next_back(&mut self) -> Option<u8>244 fn next_back(&mut self) -> Option<u8> {
245 self.inner.next_back()
246 }
247 }
248 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
249 impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
250 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
251 impl<'a> fmt::Display for EscapeAscii<'a> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 self.clone().try_for_each(|b| f.write_char(b as char))
254 }
255 }
256 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
257 impl<'a> fmt::Debug for EscapeAscii<'a> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result258 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259 f.debug_struct("EscapeAscii").finish_non_exhaustive()
260 }
261 }
262
263 /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
264 /// from `../str/mod.rs`, which does something similar for utf8 validation.
265 #[inline]
contains_nonascii(v: usize) -> bool266 const fn contains_nonascii(v: usize) -> bool {
267 const NONASCII_MASK: usize = usize::repeat_u8(0x80);
268 (NONASCII_MASK & v) != 0
269 }
270
271 /// ASCII test *without* the chunk-at-a-time optimizations.
272 ///
273 /// This is carefully structured to produce nice small code -- it's smaller in
274 /// `-O` than what the "obvious" ways produces under `-C opt-level=s`. If you
275 /// touch it, be sure to run (and update if needed) the assembly test.
276 #[unstable(feature = "str_internals", issue = "none")]
277 #[doc(hidden)]
278 #[inline]
is_ascii_simple(mut bytes: &[u8]) -> bool279 pub const fn is_ascii_simple(mut bytes: &[u8]) -> bool {
280 while let [rest @ .., last] = bytes {
281 if !last.is_ascii() {
282 break;
283 }
284 bytes = rest;
285 }
286 bytes.is_empty()
287 }
288
289 /// Optimized ASCII test that will use usize-at-a-time operations instead of
290 /// byte-at-a-time operations (when possible).
291 ///
292 /// The algorithm we use here is pretty simple. If `s` is too short, we just
293 /// check each byte and be done with it. Otherwise:
294 ///
295 /// - Read the first word with an unaligned load.
296 /// - Align the pointer, read subsequent words until end with aligned loads.
297 /// - Read the last `usize` from `s` with an unaligned load.
298 ///
299 /// If any of these loads produces something for which `contains_nonascii`
300 /// (above) returns true, then we know the answer is false.
301 #[inline]
is_ascii(s: &[u8]) -> bool302 const fn is_ascii(s: &[u8]) -> bool {
303 const USIZE_SIZE: usize = mem::size_of::<usize>();
304
305 let len = s.len();
306 let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
307
308 // If we wouldn't gain anything from the word-at-a-time implementation, fall
309 // back to a scalar loop.
310 //
311 // We also do this for architectures where `size_of::<usize>()` isn't
312 // sufficient alignment for `usize`, because it's a weird edge case.
313 if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
314 return is_ascii_simple(s);
315 }
316
317 // We always read the first word unaligned, which means `align_offset` is
318 // 0, we'd read the same value again for the aligned read.
319 let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
320
321 let start = s.as_ptr();
322 // SAFETY: We verify `len < USIZE_SIZE` above.
323 let first_word = unsafe { (start as *const usize).read_unaligned() };
324
325 if contains_nonascii(first_word) {
326 return false;
327 }
328 // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
329 // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
330 // above.
331 debug_assert!(offset_to_aligned <= len);
332
333 // SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
334 // middle chunk of the slice.
335 let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
336
337 // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
338 let mut byte_pos = offset_to_aligned;
339
340 // Paranoia check about alignment, since we're about to do a bunch of
341 // unaligned loads. In practice this should be impossible barring a bug in
342 // `align_offset` though.
343 // While this method is allowed to spuriously fail in CTFE, if it doesn't
344 // have alignment information it should have given a `usize::MAX` for
345 // `align_offset` earlier, sending things through the scalar path instead of
346 // this one, so this check should pass if it's reachable.
347 debug_assert!(word_ptr.is_aligned_to(mem::align_of::<usize>()));
348
349 // Read subsequent words until the last aligned word, excluding the last
350 // aligned word by itself to be done in tail check later, to ensure that
351 // tail is always one `usize` at most to extra branch `byte_pos == len`.
352 while byte_pos < len - USIZE_SIZE {
353 // Sanity check that the read is in bounds
354 debug_assert!(byte_pos + USIZE_SIZE <= len);
355 // And that our assumptions about `byte_pos` hold.
356 debug_assert!(matches!(
357 word_ptr.cast::<u8>().guaranteed_eq(start.wrapping_add(byte_pos)),
358 // These are from the same allocation, so will hopefully always be
359 // known to match even in CTFE, but if it refuses to compare them
360 // that's ok since it's just a debug check anyway.
361 None | Some(true),
362 ));
363
364 // SAFETY: We know `word_ptr` is properly aligned (because of
365 // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
366 let word = unsafe { word_ptr.read() };
367 if contains_nonascii(word) {
368 return false;
369 }
370
371 byte_pos += USIZE_SIZE;
372 // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
373 // after this `add`, `word_ptr` will be at most one-past-the-end.
374 word_ptr = unsafe { word_ptr.add(1) };
375 }
376
377 // Sanity check to ensure there really is only one `usize` left. This should
378 // be guaranteed by our loop condition.
379 debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
380
381 // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
382 let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
383
384 !contains_nonascii(last_word)
385 }
386