Skip to main content

core/slice/
ascii.rs

1//! Operations on ASCII `[u8]`.
2
3/// Ferrocene addition: Hidden module to test crate-internal functionality
4#[doc(hidden)]
5#[unstable(feature = "ferrocene_test", issue = "none")]
6pub(crate) mod ferrocene_test;
7
8use core::ascii::EscapeDefault;
9
10use crate::fmt::{self, Write};
11#[cfg(not(all(target_arch = "loongarch64", target_feature = "lsx")))]
12use crate::intrinsics::const_eval_select;
13use crate::{ascii, iter, ops};
14
15impl [u8] {
16    /// Checks if all bytes in this slice are within the ASCII range.
17    ///
18    /// An empty slice returns `true`.
19    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
20    #[rustc_const_stable(feature = "const_slice_is_ascii", since = "1.74.0")]
21    #[must_use]
22    #[inline]
23    #[ferrocene::prevalidated]
24    pub const fn is_ascii(&self) -> bool {
25        is_ascii(self)
26    }
27
28    /// If this slice [`is_ascii`](Self::is_ascii), returns it as a slice of
29    /// [ASCII characters](`ascii::Char`), otherwise returns `None`.
30    #[unstable(feature = "ascii_char", issue = "110998")]
31    #[must_use]
32    #[inline]
33    pub const fn as_ascii(&self) -> Option<&[ascii::Char]> {
34        if self.is_ascii() {
35            // SAFETY: Just checked that it's ASCII
36            Some(unsafe { self.as_ascii_unchecked() })
37        } else {
38            None
39        }
40    }
41
42    /// Converts this slice of bytes into a slice of ASCII characters,
43    /// without checking whether they're valid.
44    ///
45    /// # Safety
46    ///
47    /// Every byte in the slice must be in `0..=127`, or else this is UB.
48    #[unstable(feature = "ascii_char", issue = "110998")]
49    #[must_use]
50    #[inline]
51    pub const unsafe fn as_ascii_unchecked(&self) -> &[ascii::Char] {
52        let byte_ptr: *const [u8] = self;
53        let ascii_ptr = byte_ptr as *const [ascii::Char];
54        // SAFETY: The caller promised all the bytes are ASCII
55        unsafe { &*ascii_ptr }
56    }
57
58    /// Checks that two slices are an ASCII case-insensitive match.
59    ///
60    /// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
61    /// but without allocating and copying temporaries.
62    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
63    #[rustc_const_stable(feature = "const_eq_ignore_ascii_case", since = "1.89.0")]
64    #[must_use]
65    #[inline]
66    #[ferrocene::prevalidated]
67    pub const fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
68        if self.len() != other.len() {
69            return false;
70        }
71
72        #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
73        {
74            const CHUNK_SIZE: usize = 16;
75            // The following function has two invariants:
76            // 1. The slice lengths must be equal, which we checked above.
77            // 2. The slice lengths must greater than or equal to N, which this
78            //    if-statement is checking.
79            if self.len() >= CHUNK_SIZE {
80                return self.eq_ignore_ascii_case_chunks::<CHUNK_SIZE>(other);
81            }
82        }
83
84        self.eq_ignore_ascii_case_simple(other)
85    }
86
87    /// ASCII case-insensitive equality check without chunk-at-a-time
88    /// optimization.
89    #[inline]
90    #[ferrocene::prevalidated]
91    const fn eq_ignore_ascii_case_simple(&self, other: &[u8]) -> bool {
92        // FIXME(const-hack): This implementation can be reverted when
93        // `core::iter::zip` is allowed in const. The original implementation:
94        //  self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
95        let mut a = self;
96        let mut b = other;
97
98        while let ([first_a, rest_a @ ..], [first_b, rest_b @ ..]) = (a, b) {
99            if first_a.eq_ignore_ascii_case(&first_b) {
100                a = rest_a;
101                b = rest_b;
102            } else {
103                return false;
104            }
105        }
106
107        true
108    }
109
110    /// Optimized version of `eq_ignore_ascii_case` to process chunks at a time.
111    ///
112    /// Platforms that have SIMD instructions may benefit from this
113    /// implementation over `eq_ignore_ascii_case_simple`.
114    ///
115    /// # Invariants
116    ///
117    /// The caller must guarantee that the slices are equal in length, and the
118    /// slice lengths are greater than or equal to `N` bytes.
119    #[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
120    #[inline]
121    const fn eq_ignore_ascii_case_chunks<const N: usize>(&self, other: &[u8]) -> bool {
122        // FIXME(const-hack): The while-loops that follow should be replaced by
123        // for-loops when available in const.
124
125        let (self_chunks, self_rem) = self.as_chunks::<N>();
126        let (other_chunks, _) = other.as_chunks::<N>();
127
128        // Branchless check to encourage auto-vectorization
129        #[inline(always)]
130        const fn eq_ignore_ascii_inner<const L: usize>(lhs: &[u8; L], rhs: &[u8; L]) -> bool {
131            let mut equal_ascii = true;
132            let mut j = 0;
133            while j < L {
134                equal_ascii &= lhs[j].eq_ignore_ascii_case(&rhs[j]);
135                j += 1;
136            }
137
138            equal_ascii
139        }
140
141        // Process the chunks, returning early if an inequality is found
142        let mut i = 0;
143        while i < self_chunks.len() && i < other_chunks.len() {
144            if !eq_ignore_ascii_inner(&self_chunks[i], &other_chunks[i]) {
145                return false;
146            }
147            i += 1;
148        }
149
150        // Check the length invariant which is necessary for the tail-handling
151        // logic to be correct. This should have been upheld by the caller,
152        // otherwise lengths less than N will compare as true without any
153        // checking.
154        debug_assert!(self.len() >= N);
155
156        // If there are remaining tails, load the last N bytes in the slices to
157        // avoid falling back to per-byte checking.
158        if !self_rem.is_empty() {
159            if let (Some(a_rem), Some(b_rem)) = (self.last_chunk::<N>(), other.last_chunk::<N>()) {
160                if !eq_ignore_ascii_inner(a_rem, b_rem) {
161                    return false;
162                }
163            }
164        }
165
166        true
167    }
168
169    /// Converts this slice to its ASCII upper case equivalent in-place.
170    ///
171    /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
172    /// but non-ASCII letters are unchanged.
173    ///
174    /// To return a new uppercased value without modifying the existing one, use
175    /// [`to_ascii_uppercase`].
176    ///
177    /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
178    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
179    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
180    #[inline]
181    pub const fn make_ascii_uppercase(&mut self) {
182        // FIXME(const-hack): We would like to simply iterate using `for` loops but this isn't currently allowed in constant expressions.
183        let mut i = 0;
184        while i < self.len() {
185            let byte = &mut self[i];
186            byte.make_ascii_uppercase();
187            i += 1;
188        }
189    }
190
191    /// Converts this slice to its ASCII lower case equivalent in-place.
192    ///
193    /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
194    /// but non-ASCII letters are unchanged.
195    ///
196    /// To return a new lowercased value without modifying the existing one, use
197    /// [`to_ascii_lowercase`].
198    ///
199    /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
200    #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
201    #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
202    #[inline]
203    pub const fn make_ascii_lowercase(&mut self) {
204        // FIXME(const-hack): We would like to simply iterate using `for` loops but this isn't currently allowed in constant expressions.
205        let mut i = 0;
206        while i < self.len() {
207            let byte = &mut self[i];
208            byte.make_ascii_lowercase();
209            i += 1;
210        }
211    }
212
213    /// Returns an iterator that produces an escaped version of this slice,
214    /// treating it as an ASCII string.
215    ///
216    /// # Examples
217    ///
218    /// ```
219    /// let s = b"0\t\r\n'\"\\\x9d";
220    /// let escaped = s.escape_ascii().to_string();
221    /// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
222    /// ```
223    #[must_use = "this returns the escaped bytes as an iterator, \
224                  without modifying the original"]
225    #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
226    #[ferrocene::prevalidated]
227    pub fn escape_ascii(&self) -> EscapeAscii<'_> {
228        EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
229    }
230
231    /// Returns a byte slice with leading ASCII whitespace bytes removed.
232    ///
233    /// 'Whitespace' refers to the definition used by
234    /// [`u8::is_ascii_whitespace`].
235    ///
236    /// # Examples
237    ///
238    /// ```
239    /// assert_eq!(b" \t hello world\n".trim_ascii_start(), b"hello world\n");
240    /// assert_eq!(b"  ".trim_ascii_start(), b"");
241    /// assert_eq!(b"".trim_ascii_start(), b"");
242    /// ```
243    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
244    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
245    #[inline]
246    pub const fn trim_ascii_start(&self) -> &[u8] {
247        let mut bytes = self;
248        // Note: A pattern matching based approach (instead of indexing) allows
249        // making the function const.
250        while let [first, rest @ ..] = bytes {
251            if first.is_ascii_whitespace() {
252                bytes = rest;
253            } else {
254                break;
255            }
256        }
257        bytes
258    }
259
260    /// Returns a byte slice with trailing ASCII whitespace bytes removed.
261    ///
262    /// 'Whitespace' refers to the definition used by
263    /// [`u8::is_ascii_whitespace`].
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// assert_eq!(b"\r hello world\n ".trim_ascii_end(), b"\r hello world");
269    /// assert_eq!(b"  ".trim_ascii_end(), b"");
270    /// assert_eq!(b"".trim_ascii_end(), b"");
271    /// ```
272    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
273    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
274    #[inline]
275    pub const fn trim_ascii_end(&self) -> &[u8] {
276        let mut bytes = self;
277        // Note: A pattern matching based approach (instead of indexing) allows
278        // making the function const.
279        while let [rest @ .., last] = bytes {
280            if last.is_ascii_whitespace() {
281                bytes = rest;
282            } else {
283                break;
284            }
285        }
286        bytes
287    }
288
289    /// Returns a byte slice with leading and trailing ASCII whitespace bytes
290    /// removed.
291    ///
292    /// 'Whitespace' refers to the definition used by
293    /// [`u8::is_ascii_whitespace`].
294    ///
295    /// # Examples
296    ///
297    /// ```
298    /// assert_eq!(b"\r hello world\n ".trim_ascii(), b"hello world");
299    /// assert_eq!(b"  ".trim_ascii(), b"");
300    /// assert_eq!(b"".trim_ascii(), b"");
301    /// ```
302    #[stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
303    #[rustc_const_stable(feature = "byte_slice_trim_ascii", since = "1.80.0")]
304    #[inline]
305    pub const fn trim_ascii(&self) -> &[u8] {
306        self.trim_ascii_start().trim_ascii_end()
307    }
308}
309
310impl_fn_for_zst! {
311    #[derive(Clone)]
312    struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
313        ascii::escape_default(*byte)
314    };
315}
316
317/// An iterator over the escaped version of a byte slice.
318///
319/// This `struct` is created by the [`slice::escape_ascii`] method. See its
320/// documentation for more information.
321#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
322#[derive(Clone)]
323#[must_use = "iterators are lazy and do nothing unless consumed"]
324#[ferrocene::prevalidated]
325pub struct EscapeAscii<'a> {
326    inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
327}
328
329#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
330impl<'a> iter::Iterator for EscapeAscii<'a> {
331    type Item = u8;
332    #[inline]
333    fn next(&mut self) -> Option<u8> {
334        self.inner.next()
335    }
336    #[inline]
337    fn size_hint(&self) -> (usize, Option<usize>) {
338        self.inner.size_hint()
339    }
340    #[inline]
341    fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
342    where
343        Fold: FnMut(Acc, Self::Item) -> R,
344        R: ops::Try<Output = Acc>,
345    {
346        self.inner.try_fold(init, fold)
347    }
348    #[inline]
349    fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
350    where
351        Fold: FnMut(Acc, Self::Item) -> Acc,
352    {
353        self.inner.fold(init, fold)
354    }
355    #[inline]
356    fn last(mut self) -> Option<u8> {
357        self.next_back()
358    }
359}
360
361#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
362impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
363    fn next_back(&mut self) -> Option<u8> {
364        self.inner.next_back()
365    }
366}
367#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
368impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
369#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
370impl<'a> fmt::Display for EscapeAscii<'a> {
371    #[ferrocene::prevalidated]
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        // disassemble iterator, including front/back parts of flatmap in case it has been partially consumed
374        let (front, slice, back) = self.clone().inner.into_parts();
375        let front = front.unwrap_or(EscapeDefault::empty());
376        let mut bytes = slice.unwrap_or_default().as_slice();
377        let back = back.unwrap_or(EscapeDefault::empty());
378
379        // usually empty, so the formatter won't have to do any work
380        for byte in front {
381            f.write_char(byte as char)?;
382        }
383
384        #[ferrocene::prevalidated]
385        fn needs_escape(b: u8) -> bool {
386            b > 0x7E || b < 0x20 || b == b'\\' || b == b'\'' || b == b'"'
387        }
388
389        while bytes.len() > 0 {
390            // fast path for the printable, non-escaped subset of ascii
391            let prefix = bytes.iter().take_while(|&&b| !needs_escape(b)).count();
392            // SAFETY: prefix length was derived by counting bytes in the same splice, so it's in-bounds
393            let (prefix, remainder) = unsafe { bytes.split_at_unchecked(prefix) };
394            // SAFETY: prefix is a valid utf8 sequence, as it's a subset of ASCII
395            let prefix = unsafe { crate::str::from_utf8_unchecked(prefix) };
396
397            f.write_str(prefix)?; // the fast part
398
399            bytes = remainder;
400
401            if let Some(&b) = bytes.first() {
402                // guaranteed to be non-empty, better to write it as a str
403                fmt::Display::fmt(&ascii::escape_default(b), f)?;
404                bytes = &bytes[1..];
405            }
406        }
407
408        // also usually empty
409        for byte in back {
410            f.write_char(byte as char)?;
411        }
412        Ok(())
413    }
414}
415#[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
416impl<'a> fmt::Debug for EscapeAscii<'a> {
417    #[ferrocene::prevalidated]
418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
419        f.debug_struct("EscapeAscii").finish_non_exhaustive()
420    }
421}
422
423/// ASCII test *without* the chunk-at-a-time optimizations.
424///
425/// This is carefully structured to produce nice small code -- it's smaller in
426/// `-O` than what the "obvious" ways produces under `-C opt-level=s`.  If you
427/// touch it, be sure to run (and update if needed) the assembly test.
428#[unstable(feature = "str_internals", issue = "none")]
429#[doc(hidden)]
430#[inline]
431#[ferrocene::prevalidated]
432pub const fn is_ascii_simple(mut bytes: &[u8]) -> bool {
433    while let [rest @ .., last] = bytes {
434        if !last.is_ascii() {
435            break;
436        }
437        bytes = rest;
438    }
439    bytes.is_empty()
440}
441
442/// Optimized ASCII test that will use usize-at-a-time operations instead of
443/// byte-at-a-time operations (when possible).
444///
445/// The algorithm we use here is pretty simple. If `s` is too short, we just
446/// check each byte and be done with it. Otherwise:
447///
448/// - Read the first word with an unaligned load.
449/// - Align the pointer, read subsequent words until end with aligned loads.
450/// - Read the last `usize` from `s` with an unaligned load.
451///
452/// If any of these loads produces something for which `contains_nonascii`
453/// (above) returns true, then we know the answer is false.
454#[cfg(not(any(
455    all(target_arch = "x86_64", target_feature = "sse2"),
456    all(target_arch = "loongarch64", target_feature = "lsx")
457)))]
458#[inline]
459#[rustc_allow_const_fn_unstable(const_eval_select)] // fallback impl has same behavior
460#[ferrocene::prevalidated]
461const fn is_ascii(s: &[u8]) -> bool {
462    // The runtime version behaves the same as the compiletime version, it's
463    // just more optimized.
464    const_eval_select!(
465        @capture { s: &[u8] } -> bool:
466        if const {
467            is_ascii_simple(s)
468        } else {
469            /// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
470            /// from `../str/mod.rs`, which does something similar for utf8 validation.
471            #[ferrocene::prevalidated]
472            const fn contains_nonascii(v: usize) -> bool {
473                const NONASCII_MASK: usize = usize::repeat_u8(0x80);
474                (NONASCII_MASK & v) != 0
475            }
476
477            const USIZE_SIZE: usize = size_of::<usize>();
478
479            let len = s.len();
480            let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
481
482            // If we wouldn't gain anything from the word-at-a-time implementation, fall
483            // back to a scalar loop.
484            //
485            // We also do this for architectures where `size_of::<usize>()` isn't
486            // sufficient alignment for `usize`, because it's a weird edge case.
487            if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < align_of::<usize>() {
488                return is_ascii_simple(s);
489            }
490
491            // We always read the first word unaligned, which means `align_offset` is
492            // 0, we'd read the same value again for the aligned read.
493            let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
494
495            let start = s.as_ptr();
496            // SAFETY: We verify `len < USIZE_SIZE` above.
497            let first_word = unsafe { (start as *const usize).read_unaligned() };
498
499            if contains_nonascii(first_word) {
500                return false;
501            }
502            // We checked this above, somewhat implicitly. Note that `offset_to_aligned`
503            // is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
504            // above.
505            debug_assert!(offset_to_aligned <= len);
506
507            // SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
508            // middle chunk of the slice.
509            let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
510
511            // `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
512            let mut byte_pos = offset_to_aligned;
513
514            // Paranoia check about alignment, since we're about to do a bunch of
515            // unaligned loads. In practice this should be impossible barring a bug in
516            // `align_offset` though.
517            // While this method is allowed to spuriously fail in CTFE, if it doesn't
518            // have alignment information it should have given a `usize::MAX` for
519            // `align_offset` earlier, sending things through the scalar path instead of
520            // this one, so this check should pass if it's reachable.
521            debug_assert!(word_ptr.is_aligned_to(align_of::<usize>()));
522
523            // Read subsequent words until the last aligned word, excluding the last
524            // aligned word by itself to be done in tail check later, to ensure that
525            // tail is always one `usize` at most to extra branch `byte_pos == len`.
526            while byte_pos < len - USIZE_SIZE {
527                // Sanity check that the read is in bounds
528                debug_assert!(byte_pos + USIZE_SIZE <= len);
529                // And that our assumptions about `byte_pos` hold.
530                debug_assert!(word_ptr.cast::<u8>() == start.wrapping_add(byte_pos));
531
532                // SAFETY: We know `word_ptr` is properly aligned (because of
533                // `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
534                let word = unsafe { word_ptr.read() };
535                if contains_nonascii(word) {
536                    return false;
537                }
538
539                byte_pos += USIZE_SIZE;
540                // SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
541                // after this `add`, `word_ptr` will be at most one-past-the-end.
542                word_ptr = unsafe { word_ptr.add(1) };
543            }
544
545            // Sanity check to ensure there really is only one `usize` left. This should
546            // be guaranteed by our loop condition.
547            debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
548
549            // SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
550            let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
551
552            !contains_nonascii(last_word)
553        }
554    )
555}
556
557/// Chunk size for SSE2 vectorized ASCII checking (4x 16-byte loads).
558#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
559const SSE2_CHUNK_SIZE: usize = 64;
560
561#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
562#[inline]
563fn is_ascii_sse2(bytes: &[u8]) -> bool {
564    use crate::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_movemask_epi8, _mm_or_si128};
565
566    let (chunks, rest) = bytes.as_chunks::<SSE2_CHUNK_SIZE>();
567
568    for chunk in chunks {
569        let ptr = chunk.as_ptr();
570        // SAFETY: chunk is 64 bytes. SSE2 is baseline on x86_64.
571        let mask = unsafe {
572            let a1 = _mm_loadu_si128(ptr as *const __m128i);
573            let a2 = _mm_loadu_si128(ptr.add(16) as *const __m128i);
574            let b1 = _mm_loadu_si128(ptr.add(32) as *const __m128i);
575            let b2 = _mm_loadu_si128(ptr.add(48) as *const __m128i);
576            // OR all chunks - if any byte has high bit set, combined will too.
577            let combined = _mm_or_si128(_mm_or_si128(a1, a2), _mm_or_si128(b1, b2));
578            // Create a mask from the MSBs of each byte.
579            // If any byte is >= 128, its MSB is 1, so the mask will be non-zero.
580            _mm_movemask_epi8(combined)
581        };
582        if mask != 0 {
583            return false;
584        }
585    }
586
587    // Handle remaining bytes
588    rest.iter().all(|b| b.is_ascii())
589}
590
591/// ASCII test optimized to use the `pmovmskb` instruction on `x86-64`.
592///
593/// Uses explicit SSE2 intrinsics to prevent LLVM from auto-vectorizing with
594/// broken AVX-512 code that extracts mask bits one-by-one.
595#[cfg(all(target_arch = "x86_64", target_feature = "sse2"))]
596#[inline]
597#[rustc_allow_const_fn_unstable(const_eval_select)]
598const fn is_ascii(bytes: &[u8]) -> bool {
599    const USIZE_SIZE: usize = size_of::<usize>();
600    const NONASCII_MASK: usize = usize::MAX / 255 * 0x80;
601
602    const_eval_select!(
603        @capture { bytes: &[u8] } -> bool:
604        if const {
605            is_ascii_simple(bytes)
606        } else {
607            // For small inputs, use usize-at-a-time processing to avoid SSE2 call overhead.
608            if bytes.len() < SSE2_CHUNK_SIZE {
609                let chunks = bytes.chunks_exact(USIZE_SIZE);
610                let remainder = chunks.remainder();
611                for chunk in chunks {
612                    let word = usize::from_ne_bytes(chunk.try_into().unwrap());
613                    if (word & NONASCII_MASK) != 0 {
614                        return false;
615                    }
616                }
617                return remainder.iter().all(|b| b.is_ascii());
618            }
619
620            // Bug in the lint: is_ascii isn't validated, only the expansion of `is_ascii::runtime`
621            #[allow(ferrocene::unvalidated)]
622            is_ascii_sse2(bytes)
623        }
624    )
625}
626
627/// ASCII test optimized to use the `vmskltz.b` instruction on `loongarch64`.
628///
629/// Other platforms are not likely to benefit from this code structure, so they
630/// use SWAR techniques to test for ASCII in `usize`-sized chunks.
631#[cfg(all(target_arch = "loongarch64", target_feature = "lsx"))]
632#[inline]
633const fn is_ascii(bytes: &[u8]) -> bool {
634    // Process chunks of 32 bytes at a time in the fast path to enable
635    // auto-vectorization and use of `vmskltz.b`. Two 128-bit vector registers
636    // can be OR'd together and then the resulting vector can be tested for
637    // non-ASCII bytes.
638    const CHUNK_SIZE: usize = 32;
639
640    let mut i = 0;
641
642    while i + CHUNK_SIZE <= bytes.len() {
643        let chunk_end = i + CHUNK_SIZE;
644
645        // Get LLVM to produce a `vmskltz.b` instruction on loongarch64 which
646        // creates a mask from the most significant bit of each byte.
647        // ASCII bytes are less than 128 (0x80), so their most significant
648        // bit is unset.
649        let mut count = 0;
650        while i < chunk_end {
651            count += bytes[i].is_ascii() as u8;
652            i += 1;
653        }
654
655        // All bytes should be <= 127 so count is equal to chunk size.
656        if count != CHUNK_SIZE as u8 {
657            return false;
658        }
659    }
660
661    // Process the remaining `bytes.len() % N` bytes.
662    let mut is_ascii = true;
663    while i < bytes.len() {
664        is_ascii &= bytes[i].is_ascii();
665        i += 1;
666    }
667
668    is_ascii
669}