Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs
This commit is contained in:
Vendored
+231
@@ -0,0 +1,231 @@
|
||||
# `simd_cesu8`   [![Build Status]][simd-cesu8] [![Crates.io Version]][crates-io] ![Crates.io MSRV]
|
||||
|
||||
[Build Status]: https://img.shields.io/github/actions/workflow/status/seancroach/simd_cesu8/ci.yml
|
||||
|
||||
[simd-cesu8]: https://github.com/seancroach/simd_cesu8
|
||||
|
||||
[Crates.io Version]: https://img.shields.io/crates/v/simd_cesu8
|
||||
|
||||
[crates-io]: https://crates.io/crates/simd_cesu8
|
||||
|
||||
[Crates.io MSRV]: https://img.shields.io/crates/msrv/simd_cesu8
|
||||
|
||||
An extremely fast, SIMD-accelerated, encoding and decoding library
|
||||
for [CESU-8](https://en.wikipedia.org/wiki/UTF-8#CESU-8) and [Modified
|
||||
UTF-8](https://en.wikipedia.org/wiki/UTF-8#Modified_UTF-8).
|
||||
|
||||
## Features
|
||||
|
||||
- Extremely fast encoding and decoding of CESU-8 and Modified UTF-8.
|
||||
- Only allocates memory when absolutely necessary. Zero reallocations.
|
||||
- Supports lossy decoding of CESU-8 and MUTF-8.
|
||||
- Supports strict decoding of CESU-8 and MUTF-8.
|
||||
- Up to 25 times faster than known alternatives when encoding.
|
||||
- Up to 14 times faster than known alternatives when decoding.
|
||||
- Supports AVX 2 and SSE 4.2 implementations on x86 and x86-64.
|
||||
- ARM64 (aarch64) SIMD is supported.
|
||||
- WASM (wasm32) SIMD is supported.
|
||||
- PowerPC (powerpc) SIMD is (partially) supported.
|
||||
- Falls back to word-at-a-time implementations instead of byte-at-a-time.
|
||||
- No-std support.
|
||||
|
||||
## Usage
|
||||
|
||||
Add this to your `Cargo.toml` file:
|
||||
|
||||
```toml
|
||||
[dependencies.simd_cesu8]
|
||||
version = "1"
|
||||
features = ["nightly"]
|
||||
```
|
||||
|
||||
It is extremely recommended to use the nightly feature, as it enables the
|
||||
fastest implementations of the library. If you don't want to use nightly, you
|
||||
can remove the feature and the library will still work, but will be slower.
|
||||
|
||||
## Documentation
|
||||
|
||||
The documentation can be found on [docs.rs](https://docs.rs/simd_cesu8).
|
||||
|
||||
## MSRV
|
||||
|
||||
The minimum supported Rust version is 1.85.0.
|
||||
|
||||
## Benchmarks
|
||||
|
||||
These benchmarks were run with an AMD Ryzen 9 7950X3D on WSL2 with Rust
|
||||
1.81.0-nightly. Each of the operations were measured with an input exactly equal
|
||||
to 16,380 bytes. Data sets were randomly generated with the same seed for each
|
||||
operation. Each set contained 1,000 values, that were endlessly repeated as
|
||||
input. The benchmarks were run with the [`criterion`] crate. The tables got
|
||||
created via [`critcmp`]. The source code for the benchmarks can be found in the
|
||||
`benches` directory. Any call to `simd_cesu8` was replaced with the `cesu8`
|
||||
equivalent when collecting the data for the `cesu8` benchmarks. The data
|
||||
collected can also be found in the `benches` directory.
|
||||
|
||||
We compare `simd_cesu8` to the [`cesu8`] library, as it's the most popular
|
||||
library for CESU-8 and MUTF-8 encoding and decoding in Rust. I originally
|
||||
started this project, however, because there's a few minor semantic errors in
|
||||
the `cesu8` library that I wanted to fix myself.
|
||||
|
||||
[`criterion`]: https://github.com/bheisler/criterion.rs
|
||||
|
||||
[`critcmp`]: https://github.com/BurntSushi/critcmp
|
||||
|
||||
### Encoding
|
||||
|
||||
To understand the benchmarks, it's first a good idea to familiarize yourself
|
||||
with the datasets used to benchmark the encoding operations:
|
||||
|
||||
- `ascii_non_null_strings` are strings exactly 16,380 bytes long with only ASCII
|
||||
characters and no null bytes.
|
||||
- `ascii_null_alternating_strings` are strings exactly 16,380 bytes long with
|
||||
only ASCII characters and null bytes alternating, where every odd byte is
|
||||
non-null and every even byte is null.
|
||||
- `interspersed_strings` are strings exactly 16,380 bytes long with every 20
|
||||
bytes in the following pattern:
|
||||
- A non-null ASCII character (1 byte)
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character
|
||||
- A null byte
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character
|
||||
- `null_strings` are strings exactly 16,380 bytes long with only null bytes.
|
||||
- `utf8_clamped_width_2_strings` are strings exactly 16,380 bytes long with only
|
||||
2-byte UTF-8 characters.
|
||||
- `utf8_clamped_width_3_strings` are strings exactly 16,380 bytes long with only
|
||||
3-byte UTF-8 characters.
|
||||
- `utf8_clamped_width_4_strings` are strings exactly 16,380 bytes long with only
|
||||
4-byte UTF-8 characters.
|
||||
|
||||
#### `simd_cesu8::encode`
|
||||
|
||||

|
||||
|
||||
`simd_cesu8::encode` is around %2,500 faster than `cesu8::to_cesu8` in optimal
|
||||
conditions. In suboptimal conditions, `simd_cesu8::encode` is around %50 faster
|
||||
than `cesu8::to_cesu8`. The main reason for the speedup, beyond SIMD, is
|
||||
that `simd_cesu8` doesn't quickly check for just ASCII characters, but instead,
|
||||
it checks for the start of 4-byte characters. This is a significant speedup over
|
||||
the traditional ASCII hot paths. Other speedups come in the form of cumulative,
|
||||
tiny optimizations that add up to a significant speedup.
|
||||
|
||||
#### `simd_cesu8::mutf8::encode`
|
||||
|
||||

|
||||
|
||||
Similar to `simd_cesu8::encode`, `simd_cesu8::mutf8::encode` is around %1800
|
||||
faster than `cesu8::to_java_cesu8` in optimal conditions. In suboptimal
|
||||
conditions, `simd_cesu8::mutf8::encode` is around %50 faster than
|
||||
`cesu8::to_java_cesu8`. The same reason for the speedup applies here, but
|
||||
instead of checking for the start of 4-byte characters, we're also checking for
|
||||
any null bytes with SIMD. Other speedups come in the form of cumulative, tiny
|
||||
optimizations that add up to a significant speedup.
|
||||
|
||||
### Decoding
|
||||
|
||||
To understand the benchmarks, it's first a good idea to familiarize yourself
|
||||
with the datasets used to benchmark the decoding operations:
|
||||
|
||||
- `ascii_non_null_bytes` is a set of UTF-8 strings exactly 16,380 bytes long
|
||||
with only ASCII characters and no null bytes.
|
||||
- `ascii_null_alternating_bytes` is a set of UTF-8 strings exactly 16,380 bytes
|
||||
long with only ASCII characters and null bytes alternating, where every odd
|
||||
byte is non-null and every even byte is null.
|
||||
- `interspersed_bytes` is a set of UTF-8 strings exactly 16,380 bytes long with
|
||||
every 20 bytes in the following pattern:
|
||||
- A non-null ASCII character (1 byte)
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character
|
||||
- A null byte
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character
|
||||
- `interspersed_cesu8_bytes` is a set of CESU-8 strings exactly 16,380 bytes
|
||||
long with every 12 bytes in the following pattern:
|
||||
- An ASCII character (1 byte)
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character encoded as a surrogate pair (6 bytes)
|
||||
- `interspersed_mutf8_bytes` is a set of MUTF-8 strings exactly 16,380 bytes
|
||||
long with every 26 bytes in the following pattern:
|
||||
- A non-null ASCII character (1 byte)
|
||||
- A non-null ASCII character (1 byte)
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character encoded as a surrogate pair (6 bytes)
|
||||
- A null byte encoded as a 2-byte sequence
|
||||
- A 2-byte UTF-8 character
|
||||
- A 3-byte UTF-8 character
|
||||
- A 4-byte UTF-8 character encoded as a surrogate pair (6 bytes)
|
||||
- `mutf8_null_bytes` is a set of MUTF-8 strings exactly 16,380 bytes long with
|
||||
only null encoded as a 2-byte sequence.
|
||||
- `null_bytes` is a set of UTF-8 strings exactly 16,380 bytes long with only
|
||||
null bytes.
|
||||
- `surrogate_pairs_bytes` is a set of CESU-8 strings exactly 16,380 bytes long
|
||||
with only 6-byte surrogate pairs.
|
||||
- `utf8_clamped_width_2_bytes` is a set of UTF-8 strings exactly 16,380 bytes
|
||||
long with only 2-byte UTF-8 characters.
|
||||
- `utf8_clamped_width_3_bytes` is a set of UTF-8 strings exactly 16,380 bytes
|
||||
long with only 3-byte UTF-8 characters.
|
||||
- `utf8_clamped_width_4_bytes` is a set of UTF-8 strings exactly 16,380 bytes
|
||||
long with only 4-byte UTF-8 characters.
|
||||
|
||||
#### `simd_cesu8::decode`
|
||||
|
||||

|
||||
|
||||
In optimal conditions, `simd_cesu8::decode` can be around %1,400 faster than
|
||||
`cesu8::to_cesu8`. However, `simd_cesu8::decode` is slower
|
||||
than `cesu8::to_cesu8` when decoding surrogate pairs. The main reason is
|
||||
that `simd_cesu8` supports lossy decoding, but the internals of that seems to
|
||||
introduce a decent amount of overhead. `simd_cesu8` is faster in all ways
|
||||
that `cesu8` **when LTO is enabled**. However, I didn't run the benchmarks with
|
||||
LTO enabled because it seems disingenuous to do so as LTO shouldn't be a
|
||||
requirement for a library to be fast.
|
||||
|
||||
#### `simd_cesu8::mutf8::decode`
|
||||
|
||||

|
||||
|
||||
Much like `simd_cesu8::decode`, `simd_cesu8::mutf8::decode` can be around %1,400
|
||||
faster than `cesu8::to_java_cesu8`. But, the pitfalls are equally the same, as
|
||||
`simd_cesu8::mutf8::decode` is slower than `cesu8::to_java_cesu8` when decoding
|
||||
surrogate pairs. The other catch is that we're slightly slower than `cesu8` when
|
||||
decoding null bytes. The same reasoning applies here, as the overhead is higher.
|
||||
|
||||
## Thanks
|
||||
|
||||
- To the authors of the [`cesu8`] library. It's a genuinely good library that
|
||||
helped me years ago learn some more complex Rust concepts.
|
||||
- To the authors of [`simdutf8`] for arguably one of the biggest improvements to
|
||||
the borrow paths in this library.
|
||||
- To the authors of [`simdnbt`] for the inspiration of using `portable_simd`.
|
||||
|
||||
[`cesu8`]: https://github.com/emk/cesu8-rs/
|
||||
|
||||
[`simdutf8`]: https://github.com/rusticstuff/simdutf8
|
||||
|
||||
[`simdnbt`]: https://github.com/azalea-rs/simdnbt
|
||||
|
||||
## License
|
||||
|
||||
Licensed under either of
|
||||
|
||||
- Apache License, Version 2.0
|
||||
([LICENSE-APACHE](https://github.com/seancroach/simd_cesu8/blob/main/LICENSE-APACHE)
|
||||
or <http://www.apache.org/licenses/LICENSE-2.0>)
|
||||
- MIT license
|
||||
([LICENSE-MIT](https://github.com/seancroach/simd_cesu8/blob/main/LICENSE-MIT)
|
||||
or <http://opensource.org/licenses/MIT>)
|
||||
|
||||
at your option.
|
||||
|
||||
## Contribution
|
||||
|
||||
Unless you explicitly state otherwise, any contribution intentionally submitted
|
||||
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
|
||||
dual licensed as above, without any additional terms or conditions.
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
use core::{error, fmt};
|
||||
|
||||
/// A zero-sized type that represents an error that occurred while decoding.
|
||||
///
|
||||
/// No information is provided where the error occurred or what the error was,
|
||||
/// only that an error *did* occur.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
#[allow(clippy::module_name_repetitions)]
|
||||
pub struct DecodingError(pub(crate) ());
|
||||
|
||||
impl fmt::Debug for DecodingError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("DecodingError")
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DecodingError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("invalid input")
|
||||
}
|
||||
}
|
||||
|
||||
impl error::Error for DecodingError {}
|
||||
@@ -0,0 +1,22 @@
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_null_or_utf8_4_byte_char_header(bytes: &[u8]) -> bool {
|
||||
for &byte in bytes {
|
||||
if byte == 0x00 || byte & 0b1111_1000 == 0b1111_0000 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_utf8_4_byte_char_header(bytes: &[u8]) -> bool {
|
||||
for &byte in bytes {
|
||||
if byte & 0b1111_1000 == 0b1111_0000 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
//! This module contains certain implementation details that are used for
|
||||
//! optimization purposes.
|
||||
//!
|
||||
//! THIS MODULE IS NOT PART OF THE PUBLIC API AND IS SEMVER EXEMPT.
|
||||
|
||||
pub mod fallback;
|
||||
#[cfg(feature = "nightly")]
|
||||
pub mod simd;
|
||||
#[cfg(any(feature = "bench", not(feature = "nightly")))]
|
||||
pub mod word;
|
||||
|
||||
#[cfg(feature = "nightly")]
|
||||
pub use self::simd as active;
|
||||
#[cfg(not(feature = "nightly"))]
|
||||
pub use self::word as active;
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
use core::simd::prelude::*;
|
||||
use core::slice;
|
||||
|
||||
use super::fallback;
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_null_or_utf8_4_byte_char_header(value: &[u8]) -> bool {
|
||||
let mut remainder = value;
|
||||
|
||||
macro_rules! process {
|
||||
($simd:ty) => {
|
||||
let (array_chunks, array_remainder) = as_chunks_simd::<{ <$simd>::LEN }>(remainder);
|
||||
remainder = array_remainder;
|
||||
|
||||
let zero = <$simd>::splat(0x00);
|
||||
let mask = <$simd>::splat(0b1111_1000);
|
||||
let header = <$simd>::splat(0b1111_0000);
|
||||
|
||||
for &array in array_chunks {
|
||||
let simd = <$simd>::from_array(array);
|
||||
|
||||
if simd.simd_eq(zero).any() || (simd & mask).simd_eq(header).any() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
process!(u8x64);
|
||||
process!(u8x32);
|
||||
process!(u8x16);
|
||||
process!(u8x8);
|
||||
process!(u8x4);
|
||||
process!(u8x2);
|
||||
|
||||
fallback::contains_null_or_utf8_4_byte_char_header(remainder)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_utf8_4_byte_char_header(value: &[u8]) -> bool {
|
||||
let mut remainder = value;
|
||||
|
||||
macro_rules! process {
|
||||
($simd:ty) => {
|
||||
let (array_chunks, array_remainder) = as_chunks_simd::<{ <$simd>::LEN }>(remainder);
|
||||
remainder = array_remainder;
|
||||
|
||||
let mask = <$simd>::splat(0b1111_1000);
|
||||
let header = <$simd>::splat(0b1111_0000);
|
||||
|
||||
for &array in array_chunks {
|
||||
let simd = <$simd>::from_array(array);
|
||||
|
||||
if (simd & mask).simd_eq(header).any() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
process!(u8x64);
|
||||
process!(u8x32);
|
||||
process!(u8x16);
|
||||
process!(u8x8);
|
||||
process!(u8x4);
|
||||
process!(u8x2);
|
||||
|
||||
fallback::contains_utf8_4_byte_char_header(remainder)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn as_chunks_simd<const N: usize>(slice: &[u8]) -> (&[[u8; N]], &[u8]) {
|
||||
debug_assert_ne!(N, 0, "N must be greater than 0");
|
||||
let len_rounded_down = slice.len() / N * N;
|
||||
// SAFETY: The rounded-down value is always the same or smaller than the
|
||||
// original length, and thus must be in-bounds of the slice.
|
||||
let (multiple_of_n, remainder) = unsafe { slice.split_at_unchecked(len_rounded_down) };
|
||||
// SAFETY: multiple_of_n has a length that is a multiple of N.
|
||||
(unsafe { as_arrays::<N>(multiple_of_n) }, remainder)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
///
|
||||
/// `slice` must have a length that is a multiple of `N`.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
unsafe fn as_arrays<const N: usize>(slice: &[u8]) -> &[[u8; N]] {
|
||||
debug_assert_ne!(N, 0, "N must be greater than 0");
|
||||
debug_assert_eq!(slice.len() % N, 0, "slice length must be a multiple of N");
|
||||
let len = slice.len() / N;
|
||||
// SAFETY: This is effectively a cast from &[u8] to &[[u8; N]].
|
||||
unsafe { slice::from_raw_parts(slice.as_ptr().cast::<[u8; N]>(), len) }
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
use core::mem;
|
||||
|
||||
use super::fallback;
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_null_or_utf8_4_byte_char_header(value: &[u8]) -> bool {
|
||||
test_word_any(
|
||||
value,
|
||||
fallback::contains_null_or_utf8_4_byte_char_header,
|
||||
word_contains_null_or_utf8_4_byte_char_header,
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn word_contains_null_or_utf8_4_byte_char_header(word: usize) -> bool {
|
||||
word_contains_null_byte(word) || word_contains_utf8_4_byte_char_header(word)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn contains_utf8_4_byte_char_header(value: &[u8]) -> bool {
|
||||
test_word_any(
|
||||
value,
|
||||
fallback::contains_utf8_4_byte_char_header,
|
||||
word_contains_utf8_4_byte_char_header,
|
||||
)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn word_contains_utf8_4_byte_char_header(word: usize) -> bool {
|
||||
const MASK: usize = usize_repeat_u8(0b1111_1000);
|
||||
const HEADER: usize = usize_repeat_u8(0b1111_0000);
|
||||
|
||||
word_contains_null_byte((word & MASK) ^ HEADER)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn word_contains_null_byte(word: usize) -> bool {
|
||||
const LOW_MASK: usize = usize_repeat_u8(0x01);
|
||||
const HIGH_MASK: usize = usize_repeat_u8(0x80);
|
||||
|
||||
(word.wrapping_sub(LOW_MASK) & !word & HIGH_MASK) != 0
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
const fn usize_repeat_u8(byte: u8) -> usize {
|
||||
usize::from_ne_bytes([byte; USIZE_SIZE])
|
||||
}
|
||||
|
||||
/// This is an optimized test that will use usize-at-a-time operations instead
|
||||
/// of byte-at-a-time operations (when possible). It is imperative to understand
|
||||
/// that some bytes might be read multiple times, so this function should only
|
||||
/// be used to test for the presence of a specific byte.
|
||||
///
|
||||
/// `fallback` is a function that will be called if the slice is too small for
|
||||
/// usize-at-a-time operations or if the platform wouldn't benefit from it.
|
||||
///
|
||||
/// `test` is a function that will be called with the usize value read from the
|
||||
/// slice. If it returns `true`, the function will return `true` immediately.
|
||||
///
|
||||
/// The algorithm works as follows:
|
||||
///
|
||||
/// - Read the first word from the slice as an unaligned value.
|
||||
/// - Align the pointer, read subsequent words until the last aligned word.
|
||||
/// - Read the last word from the slice as an unaligned value.
|
||||
///
|
||||
/// If any of the words satisfy the test, the function will immediately return
|
||||
/// `true`. Otherwise, it will return `false`.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn test_word_any<F, T>(value: &[u8], fallback: F, test: T) -> bool
|
||||
where
|
||||
F: Fn(&[u8]) -> bool,
|
||||
T: Fn(usize) -> bool,
|
||||
{
|
||||
let len = value.len();
|
||||
let start_ptr = value.as_ptr();
|
||||
|
||||
let align_offset = start_ptr.align_offset(USIZE_SIZE);
|
||||
|
||||
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
|
||||
return fallback(value);
|
||||
}
|
||||
|
||||
let offset_to_aligned = if align_offset == 0 {
|
||||
USIZE_SIZE
|
||||
} else {
|
||||
align_offset
|
||||
};
|
||||
|
||||
// SAFETY: We have already checked that `len` is less than `USIZE_SIZE`
|
||||
// above.
|
||||
let first_word = unsafe { start_ptr.cast::<usize>().read_unaligned() };
|
||||
|
||||
if test(first_word) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_ptr_alignment)]
|
||||
// SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
|
||||
// middle chunk of the slice.
|
||||
let mut word_ptr = unsafe { start_ptr.add(offset_to_aligned).cast::<usize>() };
|
||||
|
||||
// NOTE: `byte_position` is the byte index of `word_ptr`, used for loop end
|
||||
// checks.
|
||||
let mut byte_position = offset_to_aligned;
|
||||
|
||||
while byte_position < len - USIZE_SIZE {
|
||||
// SAFETY: We know `word_ptr` is properly aligned from the previous
|
||||
// offset, and said pointer points to a valid usize because of the loop
|
||||
// condition.
|
||||
let word = unsafe { word_ptr.read() };
|
||||
|
||||
if test(word) {
|
||||
return true;
|
||||
}
|
||||
|
||||
byte_position += USIZE_SIZE;
|
||||
|
||||
// SAFETY: We know that `byte_position` is less than or equal to
|
||||
// `len - USIZE_SIZE`. At most, `word_ptr` will be one past the end
|
||||
// at most (in which it won't be used because this will be the last
|
||||
// iteration).
|
||||
word_ptr = unsafe { word_ptr.add(1) };
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_ptr_alignment)]
|
||||
// SAFETY: We know that `len` is greater than or equal to `USIZE_SIZE`, so
|
||||
// this should take us to USIZE_SIZE bytes before the end of the slice.
|
||||
let last_word_ptr = unsafe { start_ptr.add(len - USIZE_SIZE).cast::<usize>() };
|
||||
// SAFETY: We know there's exactly one usize left in the slice.
|
||||
let last_word = unsafe { last_word_ptr.read_unaligned() };
|
||||
|
||||
test(last_word)
|
||||
}
|
||||
|
||||
const USIZE_SIZE: usize = mem::size_of::<usize>();
|
||||
Vendored
+312
@@ -0,0 +1,312 @@
|
||||
use alloc::string::String;
|
||||
use alloc::vec::Vec;
|
||||
use core::hint;
|
||||
|
||||
use simdutf8::basic::from_utf8;
|
||||
|
||||
use crate::error::DecodingError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Flavor {
|
||||
Cesu8,
|
||||
Mutf8,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn decode(bytes: &[u8], options: DecodeOptions) -> Result<String, DecodingError> {
|
||||
let capacity = if options.lossy {
|
||||
// NOTE: This is the worst-case scenario where *every* byte is invalid,
|
||||
// and we have to replace it with the "U+FFFD REPLACEMENT CHARACTER".
|
||||
bytes.len().checked_mul(3).unwrap_or(ISIZE_MAX_USIZE)
|
||||
} else {
|
||||
// NOTE: Valid CESU-8 and MUTF-8 strings will always be longer than
|
||||
// their UTF-8 counterparts, so we can use the length of the input
|
||||
// bytes as a speculative capacity.
|
||||
bytes.len()
|
||||
};
|
||||
|
||||
let mut decoded = Vec::<u8>::with_capacity(capacity);
|
||||
let mut index = 0;
|
||||
let mut processed = 0;
|
||||
|
||||
macro_rules! err {
|
||||
() => {{
|
||||
if options.lossy {
|
||||
// NOTE: This is the "U+FFFD REPLACEMENT CHARACTER" in UTF-8.
|
||||
// Because CESU-8 and MUTF-8 only differ in how they encode
|
||||
// 4-byte characters, and null, this UTF-8 is valid as-is in
|
||||
// both encodings.
|
||||
decoded.extend_from_slice(&[0xef, 0xbf, 0xbd]);
|
||||
// SAFETY: We know that `processed` will only ever be less than
|
||||
// or equal to `bytes.len()`, so this is safe. We increment
|
||||
// `processed` here to ensure that we don't get stuck in an
|
||||
// infinite loop.
|
||||
processed = unsafe { processed.unchecked_add(1) };
|
||||
// NOTE: We unwind `index` to the new start.
|
||||
index = processed;
|
||||
continue;
|
||||
}
|
||||
|
||||
return Err(DecodingError(()));
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! next {
|
||||
() => {{
|
||||
if index >= bytes.len() {
|
||||
err!();
|
||||
}
|
||||
|
||||
// SAFETY: We know that `index` is less than `bytes.len()`.
|
||||
let byte = unsafe { *bytes.get_unchecked(index) };
|
||||
// SAFETY: We know that `index` is less than `bytes.len()`, so at
|
||||
// most, `index + 1` will be equal to `isize::MAX + 1`, which will
|
||||
// never overflow a `usize`.
|
||||
index = unsafe { index.unchecked_add(1) };
|
||||
byte
|
||||
}};
|
||||
}
|
||||
|
||||
macro_rules! next_continue {
|
||||
() => {{
|
||||
let byte = next!();
|
||||
|
||||
if byte & 0b1100_0000 != 0b1000_0000 {
|
||||
err!();
|
||||
}
|
||||
|
||||
byte
|
||||
}};
|
||||
}
|
||||
|
||||
while processed < bytes.len() {
|
||||
// NOTE: `processed` should be equal to `index` at the start of each
|
||||
// iteration.
|
||||
debug_assert_eq!(index, processed);
|
||||
// SAFETY: We know that `index` is less than `bytes.len()` due to the
|
||||
// loop condition.
|
||||
let first = unsafe { *bytes.get_unchecked(processed) };
|
||||
// SAFETY: We know that `index` is less than `bytes.len()`, so at most,
|
||||
// `index + 1` will be equal to `isize::MAX + 1`, which will never
|
||||
// overflow a `usize`.
|
||||
index = unsafe { index.unchecked_add(1) };
|
||||
|
||||
match first {
|
||||
0x00 if options.flavor == Flavor::Mutf8 => err!(),
|
||||
0x00..=0x7f => {
|
||||
decoded.push(first);
|
||||
}
|
||||
0xc0 if options.flavor == Flavor::Mutf8 => {
|
||||
if next!() != 0x80 {
|
||||
err!();
|
||||
}
|
||||
|
||||
decoded.push(0x00);
|
||||
}
|
||||
0xc2..=0xdf => {
|
||||
let second = next_continue!();
|
||||
decoded.extend_from_slice(&[first, second]);
|
||||
}
|
||||
0xe0..=0xef => {
|
||||
let second = next!();
|
||||
|
||||
match (first, second) {
|
||||
(0xe0, 0xa0..=0xbf)
|
||||
| (0xe1..=0xec | 0xee..=0xef, 0x80..=0xbf)
|
||||
| (0xed, 0x80..=0x9f) => {
|
||||
let third = next_continue!();
|
||||
decoded.extend_from_slice(&[first, second, third]);
|
||||
}
|
||||
(0xed, 0xa0..=0xaf) => {
|
||||
if index + 4 > bytes.len() {
|
||||
err!();
|
||||
}
|
||||
|
||||
// SAFETY: We know that `index + 4` is less than or
|
||||
// equal to `bytes.len()`, so this is safe.
|
||||
let slice = unsafe { bytes.get_unchecked(index..index + 4) };
|
||||
|
||||
let &[third, fourth, fifth, sixth] = slice else {
|
||||
// SAFETY: We know that the slice is exactly four
|
||||
// bytes.
|
||||
unsafe { hint::unreachable_unchecked() };
|
||||
};
|
||||
|
||||
// PERF: There was a lot of branching here before, so
|
||||
// this is some magic. Basically, we're checking if the
|
||||
// first byte is a continuation byte, the second byte is
|
||||
// equal to 0xed, the third byte checks if the value is
|
||||
// in the range 0xb0..=0xbf, and the fourth byte is a
|
||||
// continuation byte.
|
||||
let value = u32::from_be_bytes([third, fourth, fifth, sixth]);
|
||||
let validation_mask = 0b1100_0000_1111_1111_1111_0000_1100_0000u32;
|
||||
let desired = 0b1000_0000_1110_1101_1011_0000_1000_0000u32;
|
||||
|
||||
if value & validation_mask != desired {
|
||||
err!();
|
||||
}
|
||||
|
||||
index += 4;
|
||||
let c = decode_surrogate_pair(second, third, fifth, sixth);
|
||||
decoded.extend_from_slice(&c);
|
||||
}
|
||||
_ => err!(),
|
||||
}
|
||||
}
|
||||
_ => err!(),
|
||||
}
|
||||
|
||||
processed = index;
|
||||
}
|
||||
|
||||
// NOTE: We do a sanity check that the decoded string is valid UTF-8. We
|
||||
// have to do this because `String::from_utf8_unchecked` doesn't have a
|
||||
// sanity check in debug mode.
|
||||
debug_assert!(from_utf8(&decoded).is_ok());
|
||||
// SAFETY: We know that `decoded` is a valid UTF-8 string because we only
|
||||
// ever push valid UTF-8 bytes to it.
|
||||
let decoded = unsafe { String::from_utf8_unchecked(decoded) };
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct DecodeOptions {
|
||||
pub(crate) flavor: Flavor,
|
||||
pub(crate) lossy: bool,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_surrogate_pair(second: u8, third: u8, fifth: u8, sixth: u8) -> [u8; 4] {
|
||||
let high = decode_surrogate(second, third);
|
||||
let low = decode_surrogate(fifth, sixth);
|
||||
let code_point = 0x10000 + ((high - 0xd800) << 10 | (low - 0xdc00));
|
||||
decode_code_point(code_point)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_surrogate(second: u8, third: u8) -> u32 {
|
||||
0xd000 | u32::from(second & 0b0011_1111) << 6 | u32::from(third & 0b0011_1111)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_code_point(code_point: u32) -> [u8; 4] {
|
||||
[
|
||||
0b1111_0000 | ((code_point & 0b1_1100_0000_0000_0000_0000) >> 18) as u8,
|
||||
0b1000_0000 | ((code_point & 0b0_0011_1111_0000_0000_0000) >> 12) as u8,
|
||||
0b1000_0000 | ((code_point & 0b0_0000_0000_1111_1100_0000) >> 6) as u8,
|
||||
0b1000_0000 | ((code_point & 0b0_0000_0000_0000_0011_1111) as u8),
|
||||
]
|
||||
}
|
||||
|
||||
/// Encodes a string into a new vector of bytes using the given flavor of
|
||||
/// encoding: CESU-8 or MUTF-8.
|
||||
///
|
||||
/// NOTE: This function is inlined. It is expected that the call site of this
|
||||
/// function is **not** inlined. This is to ensure that LLVM elides the flavor
|
||||
/// logic when the flavor is known at compile time.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If `value` is greater than <code>[isize::MAX] / 2</code> bytes long, this
|
||||
/// function might panic by trying to allocate a vector with a capacity greater
|
||||
/// than [`isize::MAX`] bytes.
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub(crate) fn encode(value: &str, flavor: Flavor) -> Vec<u8> {
|
||||
let mut buf = Vec::new();
|
||||
encode_into(value, flavor, &mut buf);
|
||||
buf
|
||||
}
|
||||
|
||||
/// Encodes a string into an existing vector of bytes using the given flavor of
|
||||
/// encoding: CESU-8 or MUTF-8.
|
||||
///
|
||||
/// NOTE: This function is inlined. It is expected that the call site of this
|
||||
/// function is **not** inlined. This is to ensure that LLVM elides the flavor
|
||||
/// logic when the flavor is known at compile time.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If `value` is greater than <code>[isize::MAX] / 2</code> bytes long, this
|
||||
/// function might panic by trying to allocate a vector with a capacity greater
|
||||
/// than [`isize::MAX`] bytes.
|
||||
#[inline]
|
||||
pub(crate) fn encode_into(value: &str, flavor: Flavor, buf: &mut Vec<u8>) {
|
||||
let capacity = value.len().checked_mul(2).unwrap_or(ISIZE_MAX_USIZE);
|
||||
buf.reserve(capacity);
|
||||
|
||||
let bytes = value.as_bytes();
|
||||
let mut index = 0;
|
||||
|
||||
while index < bytes.len() {
|
||||
// SAFETY: We know that `index` is less than `bytes.len()`. This is
|
||||
// surprisingly significantly faster than a while let loop.
|
||||
let first = unsafe { *bytes.get_unchecked(index) };
|
||||
|
||||
// PERF: While it's tempting to use a match statement here, converting
|
||||
// this logic to the if statement you see here (without merging 2 and 3)
|
||||
// improved performance by over 80%.
|
||||
if first <= 0x7f {
|
||||
if flavor == Flavor::Mutf8 && first == 0x00 {
|
||||
buf.extend_from_slice(&[0xc0, 0x80]);
|
||||
} else {
|
||||
buf.push(first);
|
||||
}
|
||||
|
||||
index += 1;
|
||||
} else if first <= 0xdf {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string, so the
|
||||
// slice is guaranteed to be valid.
|
||||
let slice = unsafe { bytes.get_unchecked(index..index + 2) };
|
||||
buf.extend_from_slice(slice);
|
||||
index += 2;
|
||||
} else if first <= 0xef {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string, so the
|
||||
// slice is guaranteed to be valid.
|
||||
let slice = unsafe { bytes.get_unchecked(index..index + 3) };
|
||||
buf.extend_from_slice(slice);
|
||||
index += 3;
|
||||
} else {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string, so the
|
||||
// slice is guaranteed to be valid.
|
||||
let slice = unsafe { bytes.get_unchecked(index..index + 4) };
|
||||
|
||||
let &[first, second, third, fourth] = slice else {
|
||||
// SAFETY: We know that the slice is exactly four bytes.
|
||||
unsafe { hint::unreachable_unchecked() };
|
||||
};
|
||||
|
||||
let code_point = (u32::from(first & 0b0000_0111) << 18)
|
||||
| (u32::from(second & 0b0011_1111) << 12)
|
||||
| (u32::from(third & 0b0011_1111) << 6)
|
||||
| u32::from(fourth & 0b0011_1111);
|
||||
|
||||
let [s1, s2] = to_surrogate_pair(code_point);
|
||||
buf.extend_from_slice(&encode_surrogate(s1));
|
||||
buf.extend_from_slice(&encode_surrogate(s2));
|
||||
index += 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn to_surrogate_pair(code_point: u32) -> [u16; 2] {
|
||||
let code_point = code_point - 0x10000;
|
||||
#[allow(clippy::cast_possible_truncation)]
|
||||
let high = ((code_point >> 10) as u16) | 0xd800;
|
||||
let low = ((code_point & 0x3ff) as u16) | 0xdc00;
|
||||
[high, low]
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
#[inline]
|
||||
fn encode_surrogate(surrogate: u16) -> [u8; 3] {
|
||||
[
|
||||
0b1110_0000 | ((surrogate & 0b1111_0000_0000_0000) >> 12) as u8,
|
||||
0b1000_0000 | ((surrogate & 0b0000_1111_1100_0000) >> 6) as u8,
|
||||
0b1000_0000 | ((surrogate & 0b0000_0000_0011_1111) as u8),
|
||||
]
|
||||
}
|
||||
|
||||
const ISIZE_MAX_USIZE: usize = isize::MAX as usize;
|
||||
Vendored
+546
@@ -0,0 +1,546 @@
|
||||
#![doc = include_str!("README.md")]
|
||||
#![cfg_attr(not(feature = "std"), no_std)]
|
||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
||||
#![cfg_attr(feature = "nightly", feature(portable_simd))]
|
||||
#![allow(stable_features)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
mod error;
|
||||
#[doc(hidden)]
|
||||
pub mod implementation;
|
||||
mod internal;
|
||||
pub mod mutf8;
|
||||
|
||||
use alloc::borrow::Cow;
|
||||
use alloc::vec::Vec;
|
||||
|
||||
use simdutf8::basic::from_utf8;
|
||||
|
||||
pub use self::error::DecodingError;
|
||||
use self::implementation::active::contains_utf8_4_byte_char_header;
|
||||
use self::internal::{DecodeOptions, Flavor};
|
||||
|
||||
/// Converts a slice of bytes to a string, including invalid characters.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid UTF-8, but also valid CESU-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but not valid UTF-8, the function will
|
||||
/// return <code>[Cow::Owned]\([String]\)</code>. This case has the potential
|
||||
/// to panic.
|
||||
/// - If the input is not valid CESU-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>, where the best attempt at decoding
|
||||
/// the input strictly as CESU-8 will be made, with any invalid bytes being
|
||||
/// replaced with the [U+FFFD REPLACEMENT CHARACTER] (�). This case has the
|
||||
/// potential to panic.
|
||||
///
|
||||
/// **NOTE:** This function is significantly slower than [`decode_lossy`], but
|
||||
/// is more "correct" in the sense that valid UTF-8 that is not valid CESU-8
|
||||
/// will be treated as invalid input and properly replaced with the [U+FFFD
|
||||
/// REPLACEMENT CHARACTER] (�). If you don't need this guarantee, and can
|
||||
/// tolerate valid UTF-8 that is not valid CESU-8, use [`decode_lossy`] instead.
|
||||
///
|
||||
/// [U+FFFD REPLACEMENT CHARACTER]: char::REPLACEMENT_CHARACTER
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid UTF-8, but also valid CESU-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = simd_cesu8::decode_lossy_strict(bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but not valid UTF-8, the function will return
|
||||
/// an owned Rust string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("💖")));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is not valid CESU-8, the function will return an owned Rust
|
||||
/// string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// // NOTE: This is an unpaired surrogate followed by a valid CESU-8 surrogate
|
||||
/// // pair.
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("���💖")));
|
||||
/// ```
|
||||
///
|
||||
/// Unlike [`decode_lossy`], this function will treat valid UTF-8 that is not
|
||||
/// valid CESU-8 as invalid input:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// // NOTE: This is a valid UTF-8 string, but not valid CESU-8.
|
||||
/// let bytes = [0xf0, 0x9f, 0x92, 0x96];
|
||||
/// assert_eq!(core::str::from_utf8(&bytes), Ok("💖"));
|
||||
/// let decoded = simd_cesu8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("����")));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn decode_lossy_strict(bytes: &[u8]) -> Cow<'_, str> {
|
||||
if contains_utf8_4_byte_char_header(bytes) || from_utf8(bytes).is_err() {
|
||||
let result = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Cesu8,
|
||||
lossy: true,
|
||||
});
|
||||
|
||||
// SAFETY: If `lossy` is `true`, the function will always return a valid
|
||||
// string.
|
||||
let string = unsafe { result.unwrap_unchecked() };
|
||||
|
||||
Cow::Owned(string)
|
||||
} else {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string.
|
||||
Cow::Borrowed(unsafe { core::str::from_utf8_unchecked(bytes) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string, including invalid characters.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid UTF-8, but invalid CESU-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but not valid UTF-8, the function will
|
||||
/// return <code>[Cow::Owned]\([String]\)</code>. This case has the potential
|
||||
/// to panic.
|
||||
/// - If the input is not valid CESU-8 or UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>, where the best attempt at decoding
|
||||
/// the input strictly as CESU-8 will be made, with any invalid bytes being
|
||||
/// replaced with the [U+FFFD REPLACEMENT CHARACTER] (�). This case has the
|
||||
/// potential to panic.
|
||||
///
|
||||
/// **NOTE:** The first case may be interpreted as an error, but it's actually
|
||||
/// a significant performance optimization. If you need to strictly enforce
|
||||
/// CESU-8 decoding, use [`decode_lossy_strict`] instead.
|
||||
///
|
||||
/// [U+FFFD REPLACEMENT CHARACTER]: char::REPLACEMENT_CHARACTER
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid UTF-8, but invalid CESU-8, the function will return a
|
||||
/// borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// // NOTE: This is a valid UTF-8 string, but not valid CESU-8.
|
||||
/// let bytes = [0xf0, 0x9f, 0x92, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("💖"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = simd_cesu8::decode_lossy(bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but not valid UTF-8, the function will return
|
||||
/// an owned Rust string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("💖")));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is not valid CESU-8 or UTF-8, the function will return an owned
|
||||
/// Rust string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// // NOTE: This is an unpaired surrogate followed by a valid CESU-8 surrogate
|
||||
/// // pair.
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("���💖")));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn decode_lossy(bytes: &[u8]) -> Cow<'_, str> {
|
||||
if let Ok(string) = from_utf8(bytes) {
|
||||
Cow::Borrowed(string)
|
||||
} else {
|
||||
let result = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Cesu8,
|
||||
lossy: true,
|
||||
});
|
||||
|
||||
// SAFETY: If `lossy` is `true`, the function will always return a valid
|
||||
// string.
|
||||
let string = unsafe { result.unwrap_unchecked() };
|
||||
|
||||
Cow::Owned(string)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid CESU-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but not valid UTF-8, the function will
|
||||
/// return <code>[Cow::Owned]\([String]\)</code>. This case has the potential
|
||||
/// to panic.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the input is not valid CESU-8, this function will return a
|
||||
/// [`DecodingError`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid CESU-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = simd_cesu8::decode_strict(bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but not valid UTF-8, the function will return
|
||||
/// an owned Rust string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode_strict(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("💖")));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Unlike [`decode`], this function will treat valid UTF-8 that is not valid
|
||||
/// CESU-8 as invalid input:
|
||||
///
|
||||
/// ```
|
||||
/// // NOTE: This is a valid UTF-8 string, but not valid CESU-8.
|
||||
/// let bytes = [0xf0, 0x9f, 0x92, 0x96];
|
||||
/// assert_eq!(core::str::from_utf8(&bytes), Ok("💖"));
|
||||
///
|
||||
/// let result = simd_cesu8::decode_strict(&bytes);
|
||||
/// assert!(result.is_err());
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn decode_strict(bytes: &[u8]) -> Result<Cow<'_, str>, DecodingError> {
|
||||
if contains_utf8_4_byte_char_header(bytes) || from_utf8(bytes).is_err() {
|
||||
let string = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Cesu8,
|
||||
lossy: false,
|
||||
})?;
|
||||
|
||||
Ok(Cow::Owned(string))
|
||||
} else {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string.
|
||||
let string = unsafe { core::str::from_utf8_unchecked(bytes) };
|
||||
Ok(Cow::Borrowed(string))
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid UTF-8, but invalid CESU-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid CESU-8, but not valid UTF-8, the function will
|
||||
/// return <code>[Cow::Owned]\([String]\)</code>. This case has the potential
|
||||
/// to panic.
|
||||
///
|
||||
/// **NOTE:** The first case may be interpreted as an error, but it's actually
|
||||
/// a significant performance optimization. If you need to strictly enforce
|
||||
/// CESU-8 decoding, use [`decode_strict`] instead.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the input is not valid CESU-8 or UTF-8, this function will return a
|
||||
/// [`DecodingError`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid UTF-8, but invalid CESU-8, the function will return a
|
||||
/// borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// // NOTE: This is a valid UTF-8 string, but not valid CESU-8.
|
||||
/// let bytes = [0xf0, 0x9f, 0x92, 0x96];
|
||||
/// let decoded = simd_cesu8::decode(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("💖"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = simd_cesu8::decode(bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid CESU-8, but not valid UTF-8, the function will return
|
||||
/// an owned Rust string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = [0xed, 0xa0, 0xbd, 0xed, 0xb2, 0x96];
|
||||
/// let decoded = simd_cesu8::decode(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("💖")));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, DecodingError> {
|
||||
if let Ok(string) = from_utf8(bytes) {
|
||||
Ok(Cow::Borrowed(string))
|
||||
} else {
|
||||
let string = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Cesu8,
|
||||
lossy: false,
|
||||
})?;
|
||||
|
||||
Ok(Cow::Owned(string))
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a string to CESU-8.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input, as UTF-8, is also valid CESU-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\([&\[u8\]][slice]\)</code>.
|
||||
/// - If the input, as UTF-8, is not valid CESU-8, the function will return
|
||||
/// <code>[Cow::Owned]\([Vec]<[u8]>\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to encode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// let single_byte = "\u{0045}";
|
||||
/// assert_eq!(single_byte, "E");
|
||||
/// assert_eq!(single_byte.len(), 1);
|
||||
/// assert_eq!(single_byte.as_bytes(), &[0x45]);
|
||||
/// assert_eq!(simd_cesu8::encode(single_byte), Cow::Borrowed(&[0x45]));
|
||||
///
|
||||
/// let two_bytes = "\u{0205}";
|
||||
/// assert_eq!(two_bytes, "ȅ");
|
||||
/// assert_eq!(two_bytes.len(), 2);
|
||||
/// assert_eq!(two_bytes.as_bytes(), &[0xc8, 0x85]);
|
||||
/// assert_eq!(simd_cesu8::encode(two_bytes), Cow::Borrowed(&[0xc8, 0x85]));
|
||||
///
|
||||
/// let three_bytes = "\u{20ac}";
|
||||
/// assert_eq!(three_bytes, "€");
|
||||
/// assert_eq!(three_bytes.len(), 3);
|
||||
/// assert_eq!(three_bytes.as_bytes(), &[0xe2, 0x82, 0xac]);
|
||||
/// assert_eq!(
|
||||
/// simd_cesu8::encode(three_bytes),
|
||||
/// Cow::Borrowed(&[0xe2, 0x82, 0xac])
|
||||
/// );
|
||||
///
|
||||
/// let four_bytes = "\u{10400}";
|
||||
/// assert_eq!(four_bytes, "𐐀");
|
||||
/// assert_eq!(four_bytes.len(), 4);
|
||||
/// assert_eq!(four_bytes.as_bytes(), &[0xf0, 0x90, 0x90, 0x80]);
|
||||
/// assert_eq!(
|
||||
/// simd_cesu8::encode(four_bytes),
|
||||
/// Cow::<[u8]>::Owned(vec![0xed, 0xa0, 0x81, 0xed, 0xb0, 0x80])
|
||||
/// );
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn encode(value: &str) -> Cow<'_, [u8]> {
|
||||
if needs_encoded(value) {
|
||||
Cow::Owned(internal::encode(value, Flavor::Cesu8))
|
||||
} else {
|
||||
Cow::Borrowed(value.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a string to CESU-8 into a provided vector of bytes.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input, as UTF-8, is also valid CESU-8, the function will copy the
|
||||
/// input into the buffer.
|
||||
/// - If the input, as UTF-8, is not valid CESU-8, the function will encode the
|
||||
/// input into the buffer. This case has the potential to panic.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the total buffer, including any existing bytes,
|
||||
/// required to encode the input exceeds [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// let mut buf = Vec::new();
|
||||
///
|
||||
/// let single_byte = "\u{0045}";
|
||||
/// assert_eq!(single_byte, "E");
|
||||
/// assert_eq!(single_byte.len(), 1);
|
||||
/// assert_eq!(single_byte.as_bytes(), &[0x45]);
|
||||
/// simd_cesu8::encode_into(single_byte, &mut buf);
|
||||
/// assert_eq!(&buf, &[0x45]);
|
||||
/// buf.clear();
|
||||
///
|
||||
/// let two_bytes = "\u{0205}";
|
||||
/// assert_eq!(two_bytes, "ȅ");
|
||||
/// assert_eq!(two_bytes.len(), 2);
|
||||
/// assert_eq!(two_bytes.as_bytes(), &[0xc8, 0x85]);
|
||||
/// simd_cesu8::encode_into(two_bytes, &mut buf);
|
||||
/// assert_eq!(&buf, &[0xc8, 0x85]);
|
||||
/// buf.clear();
|
||||
///
|
||||
/// let three_bytes = "\u{20ac}";
|
||||
/// assert_eq!(three_bytes, "€");
|
||||
/// assert_eq!(three_bytes.len(), 3);
|
||||
/// assert_eq!(three_bytes.as_bytes(), &[0xe2, 0x82, 0xac]);
|
||||
/// simd_cesu8::encode_into(three_bytes, &mut buf);
|
||||
/// assert_eq!(&buf, &[0xe2, 0x82, 0xac]);
|
||||
/// buf.clear();
|
||||
///
|
||||
/// let four_bytes = "\u{10400}";
|
||||
/// assert_eq!(four_bytes, "𐐀");
|
||||
/// assert_eq!(four_bytes.len(), 4);
|
||||
/// assert_eq!(four_bytes.as_bytes(), &[0xf0, 0x90, 0x90, 0x80]);
|
||||
/// simd_cesu8::encode_into(four_bytes, &mut buf);
|
||||
/// assert_eq!(&buf, &[0xed, 0xa0, 0x81, 0xed, 0xb0, 0x80]);
|
||||
/// buf.clear();
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn encode_into(value: &str, buf: &mut Vec<u8>) {
|
||||
if needs_encoded(value) {
|
||||
internal::encode_into(value, Flavor::Cesu8, buf);
|
||||
} else {
|
||||
buf.extend_from_slice(value.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the input string needs to be encoded to CESU-8.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// let one = "E";
|
||||
/// assert_eq!(one.len(), 1);
|
||||
/// assert!(!simd_cesu8::needs_encoded(one));
|
||||
///
|
||||
/// let two = "ȅ";
|
||||
/// assert_eq!(two.len(), 2);
|
||||
/// assert!(!simd_cesu8::needs_encoded(two));
|
||||
///
|
||||
/// let three = "€";
|
||||
/// assert_eq!(three.len(), 3);
|
||||
/// assert!(!simd_cesu8::needs_encoded(three));
|
||||
///
|
||||
/// let four = "𐐀";
|
||||
/// assert_eq!(four.len(), 4);
|
||||
/// assert!(simd_cesu8::needs_encoded(four));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn needs_encoded(value: &str) -> bool {
|
||||
implementation::active::contains_utf8_4_byte_char_header(value.as_bytes())
|
||||
}
|
||||
Vendored
+510
@@ -0,0 +1,510 @@
|
||||
//! A module for encoding and decoding Modified UTF-8 (MUTF-8), a variant of
|
||||
//! CESU-8 that encodes the null character (`0x00`) as two bytes: `0xc0` and
|
||||
//! `0x80`. In general, this module is nearly identical to the functions found
|
||||
//! in the root of this crate.
|
||||
|
||||
use alloc::borrow::Cow;
|
||||
|
||||
use simdutf8::basic::from_utf8;
|
||||
|
||||
use crate::error::DecodingError;
|
||||
use crate::implementation::active::contains_null_or_utf8_4_byte_char_header;
|
||||
use crate::internal;
|
||||
use crate::internal::{DecodeOptions, Flavor};
|
||||
|
||||
/// Converts a slice of bytes to a string, including invalid characters.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid MUTF-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid MUTF-8, but invalid UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
/// - If the input is not valid MUTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>, where the best attempt at decoding
|
||||
/// the input strictly as MUTF-8 will be made, with any invalid bytes being
|
||||
/// replaced with the [U+FFFD REPLACEMENT CHARACTER] (�). This case has the
|
||||
/// potential to panic.
|
||||
///
|
||||
/// **NOTE:** This function is significantly slower than [`decode_lossy`], but
|
||||
/// is more "correct" in the sense that valid UTF-8 that is not valid MUTF-8
|
||||
/// will be treated as invalid input and properly replaced with the [U+FFFD
|
||||
/// REPLACEMENT CHARACTER] (�). If you don't need this guarantee, and can
|
||||
/// tolerate valid UTF-8 that is not valid MUTF-8, use [`decode_lossy`] instead.
|
||||
///
|
||||
/// [U+FFFD REPLACEMENT CHARACTER]: char::REPLACEMENT_CHARACTER
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid MUTF-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = mutf8::decode_lossy_strict(bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but invalid UTF-8, the function will return an
|
||||
/// owned string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = [0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("\0")));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is not valid MUTF-8, the function will return an owned string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// // NOTE: This is the first half of MUTF-8's byte pair followed by a null
|
||||
/// // byte in MUTF-8.
|
||||
/// let bytes = [0xc0, 0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("�\0")));
|
||||
/// ```
|
||||
///
|
||||
/// Unlike [`decode_lossy`], this function will treat valid UTF-8 that is not
|
||||
/// valid MUTF-8 as an invalid input:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = [0x00, 0x00, 0x00];
|
||||
/// assert_eq!(core::str::from_utf8(&bytes), Ok("\0\0\0"));
|
||||
///
|
||||
/// let decoded = mutf8::decode_lossy_strict(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("���")));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn decode_lossy_strict(bytes: &[u8]) -> Cow<'_, str> {
|
||||
if contains_null_or_utf8_4_byte_char_header(bytes) || from_utf8(bytes).is_err() {
|
||||
let result = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Mutf8,
|
||||
lossy: true,
|
||||
});
|
||||
|
||||
// SAFETY: When `lossy` is `true`, the function will always return a
|
||||
// valid string.
|
||||
let string = unsafe { result.unwrap_unchecked() };
|
||||
|
||||
Cow::Owned(string)
|
||||
} else {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string.
|
||||
Cow::Borrowed(unsafe { core::str::from_utf8_unchecked(bytes) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string, including invalid characters.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid UTF-8, but invalid MUTF-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid MUTF-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid MUTF-8, but invalid UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
/// - If the input is not valid MUTF-8 or UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>, where the best attempt at decoding
|
||||
/// the input strictly as MUTF-8 will be made, with any invalid bytes being
|
||||
/// replaced with the [U+FFFD REPLACEMENT CHARACTER] (�). This case has the
|
||||
/// potential to panic.
|
||||
///
|
||||
/// **NOTE:** The first case may be interpreted as an error, but it's actually
|
||||
/// a significant performance optimization. If you need to strictly enforce
|
||||
/// MUTF-8 decoding, use [`decode_lossy_strict`] instead.
|
||||
///
|
||||
/// [U+FFFD REPLACEMENT CHARACTER]: char::REPLACEMENT_CHARACTER
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid UTF-8, but invalid MUTF-8, the function will return a
|
||||
/// borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// // NOTE: This is a valid UTF-8 string, but invalid MUTF-8.
|
||||
/// let bytes = [0x00];
|
||||
/// let decoded = mutf8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("\0"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = mutf8::decode_lossy(bytes);
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but invalid UTF-8, the function will return an
|
||||
/// owned string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = [0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("\0")));
|
||||
/// ```
|
||||
///
|
||||
/// If the input is not valid MUTF-8 or UTF-8, the function will return an owned
|
||||
/// string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// // NOTE: This is the first half of MUTF-8's byte pair followed by a null
|
||||
/// // byte in MUTF-8.
|
||||
/// let bytes = [0xc0, 0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode_lossy(&bytes);
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("�\0")));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn decode_lossy(bytes: &[u8]) -> Cow<'_, str> {
|
||||
if let Ok(string) = from_utf8(bytes) {
|
||||
Cow::Borrowed(string)
|
||||
} else {
|
||||
let result = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Mutf8,
|
||||
lossy: true,
|
||||
});
|
||||
|
||||
// SAFETY: When `lossy` is `true`, the function will always return a
|
||||
// valid string.
|
||||
let string = unsafe { result.unwrap_unchecked() };
|
||||
|
||||
Cow::Owned(string)
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid MUTF-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\(&[str]\)</code>.
|
||||
/// - If the input is valid MUTF-8, but invalid UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the input is not valid MUTF-8, the function will return a
|
||||
/// [`DecodingError`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid MUTF-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = mutf8::decode_strict(bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but invalid UTF-8, the function will return an
|
||||
/// owned string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = [0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode_strict(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("\0")));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// Unlike [`decode`], this function will treat valid UTF-8 that is not valid
|
||||
/// MUTF-8 as an invalid input:
|
||||
///
|
||||
/// ```
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let bytes = [0x00];
|
||||
/// assert_eq!(core::str::from_utf8(&bytes), Ok("\0"));
|
||||
///
|
||||
/// let result = mutf8::decode_strict(&bytes);
|
||||
/// assert!(result.is_err());
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn decode_strict(bytes: &[u8]) -> Result<Cow<'_, str>, DecodingError> {
|
||||
if contains_null_or_utf8_4_byte_char_header(bytes) || from_utf8(bytes).is_err() {
|
||||
let string = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Mutf8,
|
||||
lossy: false,
|
||||
})?;
|
||||
|
||||
Ok(Cow::Owned(string))
|
||||
} else {
|
||||
// SAFETY: We know that `bytes` is a valid UTF-8 string.
|
||||
let string = unsafe { core::str::from_utf8_unchecked(bytes) };
|
||||
Ok(Cow::Borrowed(string))
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a slice of bytes to a string.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input is valid UTF-8, but invalid MUTF-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\([&str\])</code>.
|
||||
/// - If the input is valid MUTF-8, but also valid UTF-8, the function will
|
||||
/// return <code>[Cow::Borrowed]\([&str\])</code>.
|
||||
/// - If the input is valid MUTF-8, but invalid UTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([String]\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
///
|
||||
/// **NOTE:** The first case might be interpreted as an error, but it's actually
|
||||
/// a significant performance optimization. If you need to strictly enforce
|
||||
/// MUTF-8 decoding, use [`decode_strict`] instead.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// If the input is not valid MUTF-8 or UTF-8, the function will return a
|
||||
/// [`DecodingError`].
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to decode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// If the input is valid UTF-8, but invalid MUTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// // NOTE: This is valid UTF-8, but invalid MUTF-8.
|
||||
/// let bytes = [0x00];
|
||||
/// let decoded = mutf8::decode(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("\0"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but also valid UTF-8, the function will return
|
||||
/// a borrowed string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = b"Hello, world!";
|
||||
/// let decoded = mutf8::decode(bytes)?;
|
||||
/// assert_eq!(decoded, Cow::Borrowed("Hello, world!"));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// If the input is valid MUTF-8, but invalid UTF-8, the function will return an
|
||||
/// owned string:
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
/// use alloc::string::String;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// # fn main() -> Result<(), simd_cesu8::DecodingError> {
|
||||
/// let bytes = [0xc0, 0x80];
|
||||
/// let decoded = mutf8::decode(&bytes)?;
|
||||
/// assert_eq!(decoded, Cow::<str>::Owned(String::from("\0")));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
#[inline]
|
||||
pub fn decode(bytes: &[u8]) -> Result<Cow<'_, str>, DecodingError> {
|
||||
if let Ok(value) = from_utf8(bytes) {
|
||||
Ok(Cow::Borrowed(value))
|
||||
} else {
|
||||
let string = internal::decode(bytes, DecodeOptions {
|
||||
flavor: Flavor::Mutf8,
|
||||
lossy: false,
|
||||
})?;
|
||||
|
||||
Ok(Cow::Owned(string))
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a string to MUTF-8.
|
||||
///
|
||||
/// The algorithm is as follows:
|
||||
///
|
||||
/// - If the input, as UTF-8, is also valid MUTF-8, the function will return
|
||||
/// <code>[Cow::Borrowed]\([&\[u8\]][slice]\)</code>.
|
||||
/// - If the input, as UTF-8, is not valid MUTF-8, the function will return
|
||||
/// <code>[Cow::Owned]\([Vec]<[u8]>\)</code>. This case has the potential to
|
||||
/// panic.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This function will panic if the buffer required to encode the input exceeds
|
||||
/// [`isize::MAX`] bytes.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// # extern crate alloc;
|
||||
/// use alloc::borrow::Cow;
|
||||
///
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let null = "\0";
|
||||
/// assert_eq!(null.len(), 1);
|
||||
/// assert_eq!(null.as_bytes(), &[0x00]);
|
||||
/// assert_eq!(mutf8::encode(null), Cow::<[u8]>::Owned(vec![0xc0, 0x80]));
|
||||
///
|
||||
/// let single_byte = "\u{0045}";
|
||||
/// assert_eq!(single_byte, "E");
|
||||
/// assert_eq!(single_byte.len(), 1);
|
||||
/// assert_eq!(single_byte.as_bytes(), &[0x45]);
|
||||
/// assert_eq!(mutf8::encode(single_byte), Cow::Borrowed(&[0x45]));
|
||||
///
|
||||
/// let two_bytes = "\u{0205}";
|
||||
/// assert_eq!(two_bytes, "ȅ");
|
||||
/// assert_eq!(two_bytes.len(), 2);
|
||||
/// assert_eq!(two_bytes.as_bytes(), &[0xc8, 0x85]);
|
||||
/// assert_eq!(mutf8::encode(two_bytes), Cow::Borrowed(&[0xc8, 0x85]));
|
||||
///
|
||||
/// let three_bytes = "\u{20ac}";
|
||||
/// assert_eq!(three_bytes, "€");
|
||||
/// assert_eq!(three_bytes.len(), 3);
|
||||
/// assert_eq!(three_bytes.as_bytes(), &[0xe2, 0x82, 0xac]);
|
||||
/// assert_eq!(
|
||||
/// mutf8::encode(three_bytes),
|
||||
/// Cow::Borrowed(&[0xe2, 0x82, 0xac])
|
||||
/// );
|
||||
///
|
||||
/// let four_bytes = "\u{10400}";
|
||||
/// assert_eq!(four_bytes, "𐐀");
|
||||
/// assert_eq!(four_bytes.len(), 4);
|
||||
/// assert_eq!(four_bytes.as_bytes(), &[0xf0, 0x90, 0x90, 0x80]);
|
||||
/// assert_eq!(
|
||||
/// mutf8::encode(four_bytes),
|
||||
/// Cow::<[u8]>::Owned(vec![0xed, 0xa0, 0x81, 0xed, 0xb0, 0x80])
|
||||
/// );
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn encode(value: &str) -> Cow<'_, [u8]> {
|
||||
if contains_null_or_utf8_4_byte_char_header(value.as_bytes()) {
|
||||
Cow::Owned(internal::encode(value, Flavor::Mutf8))
|
||||
} else {
|
||||
Cow::Borrowed(value.as_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if the input string needs to be encoded to MUTF-8.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use simd_cesu8::mutf8;
|
||||
///
|
||||
/// let null = "\0";
|
||||
/// assert_eq!(null.len(), 1);
|
||||
/// assert!(mutf8::needs_encoded(null));
|
||||
///
|
||||
/// let single_byte = "E";
|
||||
/// assert_eq!(single_byte.len(), 1);
|
||||
/// assert!(!mutf8::needs_encoded(single_byte));
|
||||
///
|
||||
/// let two_bytes = "ȅ";
|
||||
/// assert_eq!(two_bytes.len(), 2);
|
||||
/// assert!(!mutf8::needs_encoded(two_bytes));
|
||||
///
|
||||
/// let three_bytes = "€";
|
||||
/// assert_eq!(three_bytes.len(), 3);
|
||||
/// assert!(!mutf8::needs_encoded(three_bytes));
|
||||
///
|
||||
/// let four_bytes = "𐐀";
|
||||
/// assert_eq!(four_bytes.len(), 4);
|
||||
/// assert!(mutf8::needs_encoded(four_bytes));
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[inline]
|
||||
pub fn needs_encoded(value: &str) -> bool {
|
||||
contains_null_or_utf8_4_byte_char_header(value.as_bytes())
|
||||
}
|
||||
Reference in New Issue
Block a user