| // 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. | |
| //! Non-generic owned UTF-8 [`String`] (`24 B`, backed by [`RawVec`] and | |
| //! [`vx_core::str`] RFC-3629 UTF-8 validation; zero duplicate UTF-8 code). | |
| use core::borrow::Borrow; | |
| use core::mem::{ManuallyDrop, align_of, size_of}; | |
| use core::ops::Deref; | |
| use core::{fmt, slice}; | |
| use vx_core::str::{Utf8Error, from_utf8_unchecked, is_valid_utf8}; | |
| use crate::alloc::AllocError; | |
| use crate::raw_vec::{RawVec, raw_vec_extend_bytes, raw_vec_free, raw_vec_try_grow}; | |
| use crate::vec::Vec; | |
| /// Error returned by fallible UTF-8 string construction or append operations. | |
| /// | |
| /// Uses non-zero `#[repr(u8)]` discriminants so `Result<(), TryFromUtf8Error>` | |
| /// occupies 1 byte in a single register (zero `SRET(x8)`). | |
| #[repr(u8)] | |
| #[derive(Copy, Clone, PartialEq, Eq)] | |
| pub enum TryFromUtf8Error { | |
| InvalidUtf8 = 1, | |
| AllocError = 2, | |
| } | |
| const _: () = assert!(size_of::<TryFromUtf8Error>() == 1); | |
| const _: () = assert!(size_of::<Result<(), TryFromUtf8Error>>() == 1); | |
| impl fmt::Debug for TryFromUtf8Error { | |
| #[inline(always)] | |
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| match self { | |
| Self::InvalidUtf8 => f.write_str("TryFromUtf8Error::InvalidUtf8"), | |
| Self::AllocError => f.write_str("TryFromUtf8Error::AllocError"), | |
| } | |
| } | |
| } | |
| impl From<Utf8Error> for TryFromUtf8Error { | |
| #[inline(always)] | |
| fn from(_: Utf8Error) -> Self { | |
| Self::InvalidUtf8 | |
| } | |
| } | |
| impl From<AllocError> for TryFromUtf8Error { | |
| #[inline(always)] | |
| fn from(_: AllocError) -> Self { | |
| Self::AllocError | |
| } | |
| } | |
| /// Non-generic owned, UTF-8-validated heap string (`alloc::string::String` analog). | |
| /// | |
| /// Layout (`#[repr(C)]`, 24 bytes, 8-byte aligned): | |
| /// - `+0`: `raw: RawVec` (`ptr: NonNull<u8>`, `cap: usize`) | |
| /// - `+16`: `len: usize` (`0 <= len <= raw.cap`, UTF-8 invariant on `0..len`) | |
| #[repr(C)] | |
| pub struct String { | |
| raw: RawVec, | |
| len: usize, | |
| } | |
| const _: () = assert!(size_of::<String>() == 24); | |
| const _: () = assert!(align_of::<String>() == 8); | |
| const _: () = assert!(size_of::<Option<String>>() == 24); | |
| const _: () = assert!(size_of::<Result<String, AllocError>>() == 24); | |
| const _: () = assert!(core::mem::offset_of!(String, raw) == 0); | |
| const _: () = assert!(core::mem::offset_of!(String, len) == 16); | |
| impl String { | |
| /// Construct an empty [`String`] without allocating. | |
| #[inline(always)] | |
| pub const fn new() -> Self { | |
| Self { raw: RawVec::new_for_align(1), len: 0 } | |
| } | |
| /// Construct an empty [`String`] with capacity reserved for at least `cap` bytes. | |
| #[inline(always)] | |
| pub fn try_with_capacity(cap: usize) -> Result<Self, AllocError> { | |
| let mut s = Self::new(); | |
| if cap > 0 { | |
| s.try_reserve(cap)?; | |
| } | |
| Ok(s) | |
| } | |
| /// Construct an owned [`String`] by copying a valid `&str`. | |
| #[inline(always)] | |
| pub fn try_from_str(s: &str) -> Result<Self, AllocError> { | |
| let mut out = Self::new(); | |
| out.try_push_str(s)?; | |
| Ok(out) | |
| } | |
| /// Validate `bytes` as strict RFC-3629 UTF-8 (via [`vx_core::str::is_valid_utf8`]) | |
| /// and copy them into a new owned [`String`]. | |
| #[inline(always)] | |
| pub fn try_from_utf8(bytes: &[u8]) -> Result<Self, TryFromUtf8Error> { | |
| let mut out = Self::new(); | |
| out.try_push_utf8(bytes)?; | |
| Ok(out) | |
| } | |
| /// Validate an owned [`Vec<u8>`] as RFC-3629 UTF-8 and convert it into a | |
| /// [`String`] with zero reallocation. | |
| #[inline(always)] | |
| pub fn from_utf8(vec: Vec<u8>) -> Result<Self, Utf8Error> { | |
| if !is_valid_utf8(vec.as_slice()) { | |
| return Err(Utf8Error); | |
| } | |
| let md = ManuallyDrop::new(vec); | |
| let raw = RawVec { ptr: md.raw.ptr, cap: md.raw.cap }; | |
| let len = md.len; | |
| Ok(Self { raw, len }) | |
| } | |
| /// Reserve capacity for at least `additional` more UTF-8 bytes. | |
| #[curry::verified] | |
| pub fn try_reserve(&mut self, additional: usize) -> Result<(), AllocError> { | |
| // SAFETY: `self.raw` upholds the byte `RawVec` invariant (`1, 1`). | |
| unsafe { raw_vec_try_grow(&mut self.raw, self.len, additional, 1, 1) } | |
| } | |
| /// Append a valid `&str` onto `self`. | |
| /// | |
| /// On `Err(AllocError)`, `self` remains completely unchanged. | |
| #[curry::verified] | |
| pub fn try_push_str(&mut self, s: &str) -> Result<(), AllocError> { | |
| // SAFETY: `self.raw` is a byte `RawVec` and `&str` is disjoint from `self.raw.ptr`. | |
| unsafe { raw_vec_extend_bytes(&mut self.raw, &mut self.len, s.as_ptr(), s.len()) } | |
| } | |
| /// Validate `bytes` as strict RFC-3629 UTF-8 and append them onto `self`. | |
| /// | |
| /// Returns `Err(TryFromUtf8Error::InvalidUtf8)` without allocating if `bytes` | |
| /// is invalid UTF-8, or `Err(TryFromUtf8Error::AllocError)` leaving `self` | |
| /// intact on OOM. | |
| #[curry::verified] | |
| pub fn try_push_utf8(&mut self, bytes: &[u8]) -> Result<(), TryFromUtf8Error> { | |
| if !is_valid_utf8(bytes) { | |
| return Err(TryFromUtf8Error::InvalidUtf8); | |
| } | |
| // SAFETY: `bytes` is valid UTF-8 and disjoint from `self.raw.ptr`. | |
| match unsafe { | |
| raw_vec_extend_bytes(&mut self.raw, &mut self.len, bytes.as_ptr(), bytes.len()) | |
| } { | |
| Ok(()) => Ok(()), | |
| Err(AllocError) => Err(TryFromUtf8Error::AllocError), | |
| } | |
| } | |
| /// Borrow the string's UTF-8 byte slice. | |
| #[curry::verified] | |
| pub fn as_bytes(&self) -> &[u8] { | |
| // SAFETY: `self.raw.ptr` is non-null (aligned to 1) and `self.len` bytes | |
| // are initialized whenever `self.len > 0`. | |
| unsafe { slice::from_raw_parts(self.raw.ptr.as_ptr(), self.len) } | |
| } | |
| /// Borrow the string as a `&str`. | |
| #[curry::verified] | |
| pub fn as_str(&self) -> &str { | |
| let bytes = self.as_bytes(); | |
| // SAFETY: Every constructor and mutator preserves the RFC-3629 UTF-8 invariant. | |
| unsafe { from_utf8_unchecked(bytes) } | |
| } | |
| /// Reset the string length to `0` while retaining its allocated capacity. | |
| #[curry::verified] | |
| pub fn clear(&mut self) { | |
| self.len = 0; | |
| } | |
| /// Consume `self` and return the underlying [`Vec<u8>`] without reallocating. | |
| #[inline(always)] | |
| pub fn into_bytes(self) -> Vec<u8> { | |
| let md = ManuallyDrop::new(self); | |
| Vec::from_raw(RawVec { ptr: md.raw.ptr, cap: md.raw.cap }, md.len) | |
| } | |
| /// Return the length in UTF-8 bytes. | |
| #[inline(always)] | |
| pub const fn len(&self) -> usize { | |
| self.len | |
| } | |
| /// Return the current allocated capacity in bytes. | |
| #[inline(always)] | |
| pub const fn capacity(&self) -> usize { | |
| self.raw.cap | |
| } | |
| /// Return `true` if the string has length 0. | |
| #[inline(always)] | |
| pub const fn is_empty(&self) -> bool { | |
| self.len == 0 | |
| } | |
| } | |
| impl Default for String { | |
| #[inline(always)] | |
| fn default() -> Self { | |
| Self::new() | |
| } | |
| } | |
| impl Deref for String { | |
| type Target = str; | |
| #[inline(always)] | |
| fn deref(&self) -> &str { | |
| self.as_str() | |
| } | |
| } | |
| impl AsRef<str> for String { | |
| #[inline(always)] | |
| fn as_ref(&self) -> &str { | |
| self.as_str() | |
| } | |
| } | |
| impl AsRef<[u8]> for String { | |
| #[inline(always)] | |
| fn as_ref(&self) -> &[u8] { | |
| self.as_bytes() | |
| } | |
| } | |
| impl Borrow<str> for String { | |
| #[inline(always)] | |
| fn borrow(&self) -> &str { | |
| self.as_str() | |
| } | |
| } | |
| impl PartialEq for String { | |
| #[inline(always)] | |
| fn eq(&self, other: &Self) -> bool { | |
| self.as_bytes() == other.as_bytes() | |
| } | |
| } | |
| impl Eq for String {} | |
| impl PartialEq<str> for String { | |
| #[inline(always)] | |
| fn eq(&self, other: &str) -> bool { | |
| self.as_bytes() == other.as_bytes() | |
| } | |
| } | |
| impl PartialEq<&str> for String { | |
| #[inline(always)] | |
| fn eq(&self, other: &&str) -> bool { | |
| self.as_bytes() == other.as_bytes() | |
| } | |
| } | |
| impl Drop for String { | |
| #[curry::verified] | |
| fn drop(&mut self) { | |
| // SAFETY: `self.raw` is a byte `RawVec` (`elem_size = 1, elem_align = 1`). | |
| unsafe { | |
| raw_vec_free(&mut self.raw, 1, 1); | |
| } | |
| } | |
| } |