]> git.lizzy.rs Git - rust.git/blob - library/core/src/slice/ascii.rs
RustWrapper: simplify removing attributes
[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 #[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     /// #![feature(inherent_ascii_escape)]
72     ///
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");
76     /// ```
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) }
82     }
83 }
84
85 impl_fn_for_zst! {
86     #[derive(Clone)]
87     struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
88         ascii::escape_default(*byte)
89     };
90 }
91
92 /// An iterator over the escaped version of a byte slice.
93 ///
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")]
97 #[derive(Clone)]
98 pub struct EscapeAscii<'a> {
99     inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
100 }
101
102 #[unstable(feature = "inherent_ascii_escape", issue = "77174")]
103 impl<'a> iter::Iterator for EscapeAscii<'a> {
104     type Item = u8;
105     #[inline]
106     fn next(&mut self) -> Option<u8> {
107         self.inner.next()
108     }
109     #[inline]
110     fn size_hint(&self) -> (usize, Option<usize>) {
111         self.inner.size_hint()
112     }
113     #[inline]
114     fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
115     where
116         Fold: FnMut(Acc, Self::Item) -> R,
117         R: ops::Try<Output = Acc>,
118     {
119         self.inner.try_fold(init, fold)
120     }
121     #[inline]
122     fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
123     where
124         Fold: FnMut(Acc, Self::Item) -> Acc,
125     {
126         self.inner.fold(init, fold)
127     }
128     #[inline]
129     fn last(mut self) -> Option<u8> {
130         self.next_back()
131     }
132 }
133
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()
138     }
139 }
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))
148     }
149 }
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()
154     }
155 }
156
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.
159 #[inline]
160 fn contains_nonascii(v: usize) -> bool {
161     const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
162     (NONASCII_MASK & v) != 0
163 }
164
165 /// Optimized ASCII test that will use usize-at-a-time operations instead of
166 /// byte-at-a-time operations (when possible).
167 ///
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:
170 ///
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.
174 ///
175 /// If any of these loads produces something for which `contains_nonascii`
176 /// (above) returns true, then we know the answer is false.
177 #[inline]
178 fn is_ascii(s: &[u8]) -> bool {
179     const USIZE_SIZE: usize = mem::size_of::<usize>();
180
181     let len = s.len();
182     let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
183
184     // If we wouldn't gain anything from the word-at-a-time implementation, fall
185     // back to a scalar loop.
186     //
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());
191     }
192
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 };
196
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() };
200
201     if contains_nonascii(first_word) {
202         return false;
203     }
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
206     // above.
207     debug_assert!(offset_to_aligned <= len);
208
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 };
212
213     // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
214     let mut byte_pos = offset_to_aligned;
215
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);
220
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 {
225         debug_assert!(
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
230         );
231
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) {
236             return false;
237         }
238
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) };
243     }
244
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);
248
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() };
251
252     !contains_nonascii(last_word)
253 }