]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/ascii.rs
remove exclamation mark
[rust.git] / library / core / src / slice / ascii.rs
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_attr(bootstrap, lang = "slice_u8")]
10 #[cfg(not(test))]
11 impl [u8] {
12     /// Checks if all bytes in this slice are within the ASCII range.
13     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
14     #[must_use]
15     #[inline]
16     pub fn is_ascii(&self) -> bool {
17         is_ascii(self)
18     }
19
20     /// Checks that two slices are an ASCII case-insensitive match.
21     ///
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")]
25     #[must_use]
26     #[inline]
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))
29     }
30
31     /// Converts this slice to its ASCII upper case equivalent in-place.
32     ///
33     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
34     /// but non-ASCII letters are unchanged.
35     ///
36     /// To return a new uppercased value without modifying the existing one, use
37     /// [`to_ascii_uppercase`].
38     ///
39     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
40     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
41     #[inline]
42     pub fn make_ascii_uppercase(&mut self) {
43         for byte in self {
44             byte.make_ascii_uppercase();
45         }
46     }
47
48     /// Converts this slice to its ASCII lower case equivalent in-place.
49     ///
50     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
51     /// but non-ASCII letters are unchanged.
52     ///
53     /// To return a new lowercased value without modifying the existing one, use
54     /// [`to_ascii_lowercase`].
55     ///
56     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
57     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
58     #[inline]
59     pub fn make_ascii_lowercase(&mut self) {
60         for byte in self {
61             byte.make_ascii_lowercase();
62         }
63     }
64
65     /// Returns an iterator that produces an escaped version of this slice,
66     /// treating it as an ASCII string.
67     ///
68     /// # Examples
69     ///
70     /// ```
71     ///
72     /// let s = b"0\t\r\n'\"\\\x9d";
73     /// let escaped = s.escape_ascii().to_string();
74     /// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
75     /// ```
76     #[must_use = "this returns the escaped bytes as an iterator, \
77                   without modifying the original"]
78     #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
79     pub fn escape_ascii(&self) -> EscapeAscii<'_> {
80         EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
81     }
82
83     /// Returns a byte slice with leading ASCII whitespace bytes removed.
84     ///
85     /// 'Whitespace' refers to the definition used by
86     /// `u8::is_ascii_whitespace`.
87     ///
88     /// # Examples
89     ///
90     /// ```
91     /// #![feature(byte_slice_trim_ascii)]
92     ///
93     /// assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
94     /// assert_eq!(b"  ".trim_ascii_start(), b"");
95     /// assert_eq!(b"".trim_ascii_start(), b"");
96     /// ```
97     #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
98     pub const fn trim_ascii_start(&self) -> &[u8] {
99         let mut bytes = self;
100         // Note: A pattern matching based approach (instead of indexing) allows
101         // making the function const.
102         while let [first, rest @ ..] = bytes {
103             if first.is_ascii_whitespace() {
104                 bytes = rest;
105             } else {
106                 break;
107             }
108         }
109         bytes
110     }
111
112     /// Returns a byte slice with trailing ASCII whitespace bytes removed.
113     ///
114     /// 'Whitespace' refers to the definition used by
115     /// `u8::is_ascii_whitespace`.
116     ///
117     /// # Examples
118     ///
119     /// ```
120     /// #![feature(byte_slice_trim_ascii)]
121     ///
122     /// assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
123     /// assert_eq!(b"  ".trim_ascii_end(), b"");
124     /// assert_eq!(b"".trim_ascii_end(), b"");
125     /// ```
126     #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
127     pub const fn trim_ascii_end(&self) -> &[u8] {
128         let mut bytes = self;
129         // Note: A pattern matching based approach (instead of indexing) allows
130         // making the function const.
131         while let [rest @ .., last] = bytes {
132             if last.is_ascii_whitespace() {
133                 bytes = rest;
134             } else {
135                 break;
136             }
137         }
138         bytes
139     }
140
141     /// Returns a byte slice with leading and trailing ASCII whitespace bytes
142     /// 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(), b"hello world");
153     /// assert_eq!(b"  ".trim_ascii(), b"");
154     /// assert_eq!(b"".trim_ascii(), b"");
155     /// ```
156     #[unstable(feature = "byte_slice_trim_ascii", issue = "94035")]
157     pub const fn trim_ascii(&self) -> &[u8] {
158         self.trim_ascii_start().trim_ascii_end()
159     }
160 }
161
162 impl_fn_for_zst! {
163     #[derive(Clone)]
164     struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
165         ascii::escape_default(*byte)
166     };
167 }
168
169 /// An iterator over the escaped version of a byte slice.
170 ///
171 /// This `struct` is created by the [`slice::escape_ascii`] method. See its
172 /// documentation for more information.
173 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
174 #[derive(Clone)]
175 #[must_use = "iterators are lazy and do nothing unless consumed"]
176 pub struct EscapeAscii<'a> {
177     inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
178 }
179
180 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
181 impl<'a> iter::Iterator for EscapeAscii<'a> {
182     type Item = u8;
183     #[inline]
184     fn next(&mut self) -> Option<u8> {
185         self.inner.next()
186     }
187     #[inline]
188     fn size_hint(&self) -> (usize, Option<usize>) {
189         self.inner.size_hint()
190     }
191     #[inline]
192     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
193     where
194         Fold: FnMut(Acc, Self::Item) -> R,
195         R: ops::Try<Output = Acc>,
196     {
197         self.inner.try_fold(init, fold)
198     }
199     #[inline]
200     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
201     where
202         Fold: FnMut(Acc, Self::Item) -> Acc,
203     {
204         self.inner.fold(init, fold)
205     }
206     #[inline]
207     fn last(mut self) -> Option<u8> {
208         self.next_back()
209     }
210 }
211
212 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
213 impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
214     fn next_back(&mut self) -> Option<u8> {
215         self.inner.next_back()
216     }
217 }
218 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
219 impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
220 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
221 impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
222 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
223 impl<'a> fmt::Display for EscapeAscii<'a> {
224     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225         self.clone().try_for_each(|b| f.write_char(b as char))
226     }
227 }
228 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
229 impl<'a> fmt::Debug for EscapeAscii<'a> {
230     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231         f.debug_struct("EscapeAscii").finish_non_exhaustive()
232     }
233 }
234
235 /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
236 /// from `../str/mod.rs`, which does something similar for utf8 validation.
237 #[inline]
238 fn contains_nonascii(v: usize) -> bool {
239     const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
240     (NONASCII_MASK & v) != 0
241 }
242
243 /// Optimized ASCII test that will use usize-at-a-time operations instead of
244 /// byte-at-a-time operations (when possible).
245 ///
246 /// The algorithm we use here is pretty simple. If `s` is too short, we just
247 /// check each byte and be done with it. Otherwise:
248 ///
249 /// - Read the first word with an unaligned load.
250 /// - Align the pointer, read subsequent words until end with aligned loads.
251 /// - Read the last `usize` from `s` with an unaligned load.
252 ///
253 /// If any of these loads produces something for which `contains_nonascii`
254 /// (above) returns true, then we know the answer is false.
255 #[inline]
256 fn is_ascii(s: &[u8]) -> bool {
257     const USIZE_SIZE: usize = mem::size_of::<usize>();
258
259     let len = s.len();
260     let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
261
262     // If we wouldn't gain anything from the word-at-a-time implementation, fall
263     // back to a scalar loop.
264     //
265     // We also do this for architectures where `size_of::<usize>()` isn't
266     // sufficient alignment for `usize`, because it's a weird edge case.
267     if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
268         return s.iter().all(|b| b.is_ascii());
269     }
270
271     // We always read the first word unaligned, which means `align_offset` is
272     // 0, we'd read the same value again for the aligned read.
273     let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
274
275     let start = s.as_ptr();
276     // SAFETY: We verify `len < USIZE_SIZE` above.
277     let first_word = unsafe { (start as *const usize).read_unaligned() };
278
279     if contains_nonascii(first_word) {
280         return false;
281     }
282     // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
283     // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
284     // above.
285     debug_assert!(offset_to_aligned <= len);
286
287     // SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
288     // middle chunk of the slice.
289     let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
290
291     // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
292     let mut byte_pos = offset_to_aligned;
293
294     // Paranoia check about alignment, since we're about to do a bunch of
295     // unaligned loads. In practice this should be impossible barring a bug in
296     // `align_offset` though.
297     debug_assert_eq!(word_ptr.addr() % mem::align_of::<usize>(), 0);
298
299     // Read subsequent words until the last aligned word, excluding the last
300     // aligned word by itself to be done in tail check later, to ensure that
301     // tail is always one `usize` at most to extra branch `byte_pos == len`.
302     while byte_pos < len - USIZE_SIZE {
303         debug_assert!(
304             // Sanity check that the read is in bounds
305             (word_ptr.addr() + USIZE_SIZE) <= start.addr().wrapping_add(len) &&
306             // And that our assumptions about `byte_pos` hold.
307             (word_ptr.addr() - start.addr()) == byte_pos
308         );
309
310         // SAFETY: We know `word_ptr` is properly aligned (because of
311         // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
312         let word = unsafe { word_ptr.read() };
313         if contains_nonascii(word) {
314             return false;
315         }
316
317         byte_pos += USIZE_SIZE;
318         // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
319         // after this `add`, `word_ptr` will be at most one-past-the-end.
320         word_ptr = unsafe { word_ptr.add(1) };
321     }
322
323     // Sanity check to ensure there really is only one `usize` left. This should
324     // be guaranteed by our loop condition.
325     debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
326
327     // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
328     let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
329
330     !contains_nonascii(last_word)
331 }