blob: 7121577a1ab62fb414217d279a6c795a2ff11b3b [file]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Verified RFC-3629 UTF-8 validation and `&str` conversion (`vx_core::str`).
//!
//! Uses a 0-byte ZST [`Utf8Error`] so `Result<&str, Utf8Error>` leverages
//! `&str`'s non-null pointer niche (`16 B` returned in `x0, x1`, zero `SRET(x8)`),
//! avoiding `libcore`'s out-of-line `core::str::converts::from_utf8`.
pub use ::core::str::from_utf8_unchecked;
/// Error returned when a byte slice is not valid RFC-3629 UTF-8.
///
/// Zero-sized so `Result<&str, Utf8Error>` has size 16 (returned in `x0, x1`
/// with zero `SRET(x8)`).
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Utf8Error;
const _: () = assert!(::core::mem::size_of::<Utf8Error>() == 0);
const _: () = assert!(::core::mem::size_of::<Result<&str, Utf8Error>>() == 16);
// Implemented manually with `#[inline(always)]` rather than `#[derive(Debug)]`
// so `vx_core.o` does not emit an out-of-line `Debug::fmt` referencing
// unlinked `core::fmt::Formatter::write_str`.
impl ::core::fmt::Debug for Utf8Error {
#[inline(always)]
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str("Utf8Error")
}
}
/// Return `true` iff `b` is a UTF-8 continuation byte (`0x80..=0xBF`).
#[inline(always)]
const fn is_cont(b: u8) -> bool {
(b & 0xC0) == 0x80
}
/// Validate one RFC-3629 4-byte UTF-8 sequence starting at `bytes[0]`
/// (`0xF0..=0xF4`), returning `4` if valid or `0` if invalid or truncated.
#[curry::verified]
fn utf8_4byte_len(bytes: &[u8]) -> usize {
let [b0, b1, b2, b3, ..] = *bytes else {
return 0;
};
if !is_cont(b2) || !is_cont(b3) {
return 0;
}
let b1_ok = if b0 == 0xF0 {
(0x90..=0xBF).contains(&b1)
} else if b0 == 0xF4 {
(0x80..=0x8F).contains(&b1)
} else {
is_cont(b1)
};
if b1_ok { 4 } else { 0 }
}
/// Validate one RFC-3629 multi-byte UTF-8 sequence starting at `bytes[0]`
/// (`b0 >= 0x80`), returning its byte length (`2`, `3`, or `4`) if valid,
/// or `0` if malformed, overlong, surrogate, out-of-range, or truncated.
#[curry::verified]
fn utf8_multibyte_len(bytes: &[u8]) -> usize {
let [b0, ..] = *bytes else {
return 0;
};
if (0xC2..=0xDF).contains(&b0) {
let [_, b1, ..] = *bytes else {
return 0;
};
return if is_cont(b1) { 2 } else { 0 };
}
if (0xE0..=0xEF).contains(&b0) {
let [_, b1, b2, ..] = *bytes else {
return 0;
};
if !is_cont(b2) {
return 0;
}
let b1_ok = if b0 == 0xE0 {
(0xA0..=0xBF).contains(&b1)
} else if b0 == 0xED {
(0x80..=0x9F).contains(&b1)
} else {
is_cont(b1)
};
return if b1_ok { 3 } else { 0 };
}
if (0xF0..=0xF4).contains(&b0) {
return utf8_4byte_len(bytes);
}
0
}
/// Strict RFC-3629 UTF-8 validator over `bytes` (zero panics, zero `unsafe`).
#[curry::verified]
pub fn is_valid_utf8(bytes: &[u8]) -> bool {
let mut i: usize = 0;
while let Some(rest) = bytes.get(i..) {
let [b0, ..] = *rest else {
return true;
};
if b0 <= 0x7F {
i += 1;
} else {
let step = utf8_multibyte_len(rest);
if step == 0 {
return false;
}
i += step;
}
}
true
}
/// Validate `bytes` as strict RFC-3629 UTF-8 and convert it to `&str`.
///
/// Returns `Ok(&str)` or `Err(Utf8Error)` in registers `x0, x1` (`16 B`,
/// zero `SRET(x8)`, zero dependency on `libcore`).
#[curry::verified]
pub fn from_utf8(bytes: &[u8]) -> Result<&str, Utf8Error> {
if is_valid_utf8(bytes) {
// SAFETY: `is_valid_utf8(bytes)` just verified that `bytes` is valid RFC-3629 UTF-8.
Ok(unsafe { ::core::str::from_utf8_unchecked(bytes) })
} else {
Err(Utf8Error)
}
}