#![no_std]
extern crate alloc;
#[cfg(feature = "serde")]
mod serde;
use alloc::{boxed::Box, string::String, vec::Vec};
use core::{borrow::Borrow, fmt, hash, ops, str};
use bytes::Bytes;
#[doc(alias = "BytesStr")]
#[doc(alias = "ByteStr")]
#[doc(alias = "Str")]
#[doc(alias = "String")]
#[doc(alias = "SharedString")]
#[doc(alias = "SharedStr")]
#[doc(alias = "ArcStr")]
#[doc(alias = "RcStr")]
#[doc(alias = "ImmutableString")]
#[doc(alias = "Utf8String")]
#[doc(alias = "Utf8Bytes")]
#[doc(alias = "UTF-8")]
#[doc(alias = "byte string")]
#[doc(alias = "shared string")]
#[doc(alias = "reference counted string")]
#[doc(alias = "immutable string")]
#[doc(alias = "read-only string")]
#[doc(alias = "zero-copy string")]
#[derive(Clone, Default, Eq, PartialOrd, Ord)]
pub struct ByteString(Bytes);
impl ByteString {
#[doc(alias = "empty")]
#[inline]
#[must_use]
pub const fn new() -> Self {
ByteString(Bytes::new())
}
#[doc(alias = "from_static_str")]
#[inline]
#[must_use]
pub const fn from_static(src: &'static str) -> ByteString {
Self(Bytes::from_static(src.as_bytes()))
}
#[must_use]
pub fn from_owner<T>(owner: T) -> Self
where
T: AsRef<str> + Send + 'static,
{
struct Owner<T>(T);
impl<T: AsRef<str>> AsRef<[u8]> for Owner<T> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref().as_bytes()
}
}
Self(Bytes::from_owner(Owner(owner)))
}
#[inline]
pub fn from_utf8(bytes: Bytes) -> Result<Self, FromUtf8Error> {
match validate_utf8(&bytes) {
Ok(()) => Ok(Self(bytes)),
Err(error) => Err(FromUtf8Error { bytes, error }),
}
}
#[doc(alias = "from_utf8_unchecked")]
#[inline]
#[must_use]
pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
Self(src)
}
#[inline]
#[must_use]
pub const fn len(&self) -> usize {
self.0.len()
}
#[inline]
#[must_use]
pub const fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[inline]
#[must_use]
pub fn as_str(&self) -> &str {
self
}
#[doc(alias = "as_inner")]
#[doc(alias = "as_ref")]
#[inline]
#[must_use]
pub const fn as_bytes(&self) -> &Bytes {
&self.0
}
#[must_use]
pub fn slice(&self, range: impl ops::RangeBounds<usize>) -> Self {
use ops::Bound;
let start = match range.start_bound() {
Bound::Included(&n) => n,
Bound::Excluded(&n) => n.checked_add(1).expect("range start overflow"),
Bound::Unbounded => 0,
};
let end = match range.end_bound() {
Bound::Included(&n) => n.checked_add(1).expect("range end overflow"),
Bound::Excluded(&n) => n,
Bound::Unbounded => self.len(),
};
self.slice_ref(&self[start..end])
}
#[doc(alias = "slice")]
#[doc(alias = "substring")]
#[doc(alias = "substr")]
#[doc(alias = "subslice")]
#[inline]
#[must_use]
pub fn slice_ref(&self, subset: &str) -> Self {
Self(self.0.slice_ref(subset.as_bytes()))
}
#[inline]
#[must_use = "use truncate if the suffix is not needed"]
pub fn split_off(&mut self, at: usize) -> Self {
assert!(self.is_char_boundary(at), "invalid split boundary");
Self(self.0.split_off(at))
}
#[inline]
#[must_use = "use advance if the prefix is not needed"]
pub fn split_to(&mut self, at: usize) -> Self {
assert!(self.is_char_boundary(at), "invalid split boundary");
Self(self.0.split_to(at))
}
#[doc(alias = "split")]
#[must_use]
pub fn split_at(&self, mid: usize) -> (ByteString, ByteString) {
let this: &str = self.as_ref();
let _valid_midpoint_check = this.split_at(mid);
let mut bytes = self.0.clone();
let first = bytes.split_to(mid);
let last = bytes;
unsafe {
(
ByteString::from_bytes_unchecked(first),
ByteString::from_bytes_unchecked(last),
)
}
}
#[inline]
pub fn truncate(&mut self, len: usize) {
assert!(
len >= self.len() || self.is_char_boundary(len),
"invalid truncate boundary"
);
self.0.truncate(len);
}
#[inline]
pub fn advance(&mut self, cnt: usize) {
assert!(self.is_char_boundary(cnt), "invalid advance boundary");
bytes::Buf::advance(&mut self.0, cnt);
}
#[doc(alias = "into_inner")]
#[doc(alias = "unwrap")]
#[inline]
#[must_use]
pub fn into_bytes(self) -> Bytes {
self.0
}
}
impl PartialEq<str> for ByteString {
#[inline]
fn eq(&self, other: &str) -> bool {
&self[..] == other
}
}
impl<T: AsRef<str>> PartialEq<T> for ByteString {
#[inline]
fn eq(&self, other: &T) -> bool {
&self[..] == other.as_ref()
}
}
impl AsRef<ByteString> for ByteString {
#[inline]
fn as_ref(&self) -> &ByteString {
self
}
}
impl AsRef<[u8]> for ByteString {
#[inline]
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsRef<str> for ByteString {
#[inline]
fn as_ref(&self) -> &str {
self
}
}
impl hash::Hash for ByteString {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl ops::Deref for ByteString {
type Target = str;
#[inline]
fn deref(&self) -> &str {
let bytes = self.0.as_ref();
unsafe { str::from_utf8_unchecked(bytes) }
}
}
impl Borrow<str> for ByteString {
#[inline]
fn borrow(&self) -> &str {
self
}
}
impl From<ByteString> for Bytes {
fn from(value: ByteString) -> Self {
value.into_bytes()
}
}
impl From<String> for ByteString {
#[inline]
fn from(value: String) -> Self {
Self(Bytes::from(value))
}
}
impl From<&str> for ByteString {
#[inline]
fn from(value: &str) -> Self {
Self(Bytes::copy_from_slice(value.as_ref()))
}
}
impl From<Box<str>> for ByteString {
#[inline]
fn from(value: Box<str>) -> Self {
Self(Bytes::from(value.into_boxed_bytes()))
}
}
impl From<ByteString> for String {
#[inline]
fn from(value: ByteString) -> Self {
unsafe { String::from_utf8_unchecked(value.0.into()) }
}
}
#[cfg(feature = "simd")]
fn validate_utf8(bytes: &[u8]) -> Result<(), str::Utf8Error> {
if bytes.len() < 64 {
if bytes.is_ascii() {
return Ok(());
}
return str::from_utf8(bytes).map(|_| ());
}
if simdutf8::compat::from_utf8(bytes).is_ok() {
return Ok(());
}
validate_utf8_err(bytes)
}
#[cfg(not(feature = "simd"))]
fn validate_utf8(bytes: &[u8]) -> Result<(), str::Utf8Error> {
const CHUNK_SIZE: usize = 64;
let (chunks, remainder) = bytes.as_chunks::<CHUNK_SIZE>();
let mut offset = 0;
for chunk in chunks {
if !chunk.is_ascii() {
let tail = &bytes[offset..];
return match str::from_utf8(tail) {
Ok(_) => Ok(()),
Err(err) if offset == 0 => Err(err),
Err(_) => validate_utf8_err(bytes),
};
}
offset += CHUNK_SIZE;
}
if remainder.is_ascii() {
return Ok(());
}
match str::from_utf8(remainder) {
Ok(_) => Ok(()),
Err(err) if offset == 0 => Err(err),
Err(_) => validate_utf8_err(bytes),
}
}
#[cold]
fn validate_utf8_err(bytes: &[u8]) -> Result<(), str::Utf8Error> {
str::from_utf8(bytes).map(|_| ())
}
impl TryFrom<&[u8]> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
validate_utf8(value)?;
Ok(ByteString(Bytes::copy_from_slice(value)))
}
}
impl TryFrom<Vec<u8>> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
validate_utf8(&value)?;
Ok(ByteString(Bytes::from(value)))
}
}
impl TryFrom<Bytes> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: Bytes) -> Result<Self, Self::Error> {
validate_utf8(&value)?;
Ok(ByteString(value))
}
}
impl TryFrom<bytes::BytesMut> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: bytes::BytesMut) -> Result<Self, Self::Error> {
validate_utf8(&value)?;
Ok(ByteString(value.freeze()))
}
}
macro_rules! array_impls {
($($len:expr)+) => {
$(
impl TryFrom<[u8; $len]> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: [u8; $len]) -> Result<Self, Self::Error> {
ByteString::try_from(&value[..])
}
}
impl TryFrom<&[u8; $len]> for ByteString {
type Error = str::Utf8Error;
#[inline]
fn try_from(value: &[u8; $len]) -> Result<Self, Self::Error> {
ByteString::try_from(&value[..])
}
}
)+
}
}
array_impls!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32);
impl fmt::Debug for ByteString {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, fmt)
}
}
impl fmt::Display for ByteString {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&**self, fmt)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FromUtf8Error {
bytes: Bytes,
error: str::Utf8Error,
}
impl FromUtf8Error {
#[inline]
#[must_use]
pub fn into_bytes(self) -> Bytes {
self.bytes
}
#[inline]
#[must_use]
pub const fn utf8_error(&self) -> str::Utf8Error {
self.error
}
}
impl fmt::Display for FromUtf8Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.error, f)
}
}
impl core::error::Error for FromUtf8Error {}
#[cfg(test)]
mod tests {
use core::panic::{RefUnwindSafe, UnwindSafe};
use static_assertions::assert_impl_all;
use super::*;
assert_impl_all!(ByteString: Send, Sync, Unpin, Sized);
assert_impl_all!(ByteString: Clone, Default, Eq, PartialOrd, Ord);
assert_impl_all!(ByteString: fmt::Debug, fmt::Display);
assert_impl_all!(ByteString: UnwindSafe, RefUnwindSafe);
}