1#![allow(unsafe_code)]
2
3use crate::sealed::Sealed;
4
5#[derive(Debug, thiserror::Error)]
6#[error("invalid ascii str")]
7pub struct AsciiError {}
8
9#[derive(Debug, thiserror::Error)]
10#[error("invalid utf8 str")]
11pub struct Utf8Error {}
12
13pub trait StrExt: Sealed {
14 fn from_ascii_simd(bytes: &[u8]) -> Result<&str, AsciiError>;
15
16 fn from_utf8_simd(bytes: &[u8]) -> Result<&str, Utf8Error>;
17}
18
19impl Sealed for str {}
20
21impl StrExt for str {
22 fn from_ascii_simd(bytes: &[u8]) -> Result<&str, AsciiError> {
23 if bytes.is_ascii() {
25 Ok(unsafe { core::str::from_utf8_unchecked(bytes) })
26 } else {
27 Err(AsciiError {})
28 }
29 }
30
31 fn from_utf8_simd(bytes: &[u8]) -> Result<&str, Utf8Error> {
32 simdutf8::basic::from_utf8(bytes).map_err(|_| Utf8Error {})
33 }
34}