use std::borrow::Cow;
use crate::Value;
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct ByteString<'a>(Cow<'a, [u8]>);
impl<'a> ByteString<'a> {
pub const fn new() -> Self {
Self(Cow::Borrowed(&[]))
}
pub fn as_bytes(&self) -> &[u8] {
self.0.as_ref()
}
pub fn as_bytes_mut(&mut self) -> &mut Vec<u8> {
self.0.to_mut()
}
pub fn into_owned<'b>(self) -> ByteString<'b> {
match self.0 {
Cow::Borrowed(bytes) => ByteString(bytes.to_vec().into()),
Cow::Owned(bytes) => ByteString(bytes.into()),
}
}
}
impl<'a, T> From<&'a T> for ByteString<'a>
where
T: AsRef<[u8]> + ?Sized,
{
fn from(value: &'a T) -> Self {
Self(value.as_ref().into())
}
}
impl<'a> From<Vec<u8>> for ByteString<'a> {
fn from(value: Vec<u8>) -> Self {
Self(value.into())
}
}
impl<'a, const N: usize> From<[u8; N]> for ByteString<'a> {
fn from(value: [u8; N]) -> Self {
Self(value.to_vec().into())
}
}
impl<'a> From<Cow<'a, [u8]>> for ByteString<'a> {
fn from(value: Cow<'a, [u8]>) -> Self {
Self(value)
}
}
impl<'a> From<ByteString<'a>> for Value<'a> {
fn from(value: ByteString<'a>) -> Self {
Value::ByteString(value.0)
}
}