use crate::ule::{EncodeAsVarULE, UleError, VarULE};
#[cfg(feature = "alloc")]
use alloc::boxed::Box;
use core::fmt;
use core::marker::PhantomData;
#[cfg(feature = "alloc")]
use core::mem::ManuallyDrop;
use core::ops::Deref;
use core::ptr::NonNull;
use zerofrom::ZeroFrom;
pub struct VarZeroCow<'a, V: ?Sized> {
raw: RawVarZeroCow,
marker1: PhantomData<&'a V>,
#[cfg(feature = "alloc")]
marker2: PhantomData<Box<V>>,
}
struct RawVarZeroCow {
buf: NonNull<[u8]>,
#[cfg(feature = "alloc")]
owned: bool,
}
#[cfg(feature = "alloc")]
impl Drop for RawVarZeroCow {
fn drop(&mut self) {
if self.owned {
unsafe {
let _ = Box::<[u8]>::from_raw(self.buf.as_ptr());
}
}
}
}
unsafe impl Send for RawVarZeroCow {}
unsafe impl Sync for RawVarZeroCow {}
impl Clone for RawVarZeroCow {
fn clone(&self) -> Self {
#[cfg(feature = "alloc")]
if self.is_owned() {
let b: Box<[u8]> = self.as_bytes().into();
let b = ManuallyDrop::new(b);
let buf: NonNull<[u8]> = (&**b).into();
return Self {
buf,
owned: true,
};
}
Self {
buf: self.buf,
#[cfg(feature = "alloc")]
owned: false,
}
}
}
impl<'a, V: ?Sized> Clone for VarZeroCow<'a, V> {
fn clone(&self) -> Self {
let raw = self.raw.clone();
unsafe { Self::from_raw(raw) }
}
}
impl<'a, V: VarULE + ?Sized> VarZeroCow<'a, V> {
pub fn parse_bytes(bytes: &'a [u8]) -> Result<Self, UleError> {
let val = V::parse_bytes(bytes)?;
Ok(Self::new_borrowed(val))
}
#[cfg(feature = "alloc")]
pub fn parse_owned_bytes(bytes: Box<[u8]>) -> Result<Self, UleError> {
V::validate_bytes(&bytes)?;
let bytes = ManuallyDrop::new(bytes);
let buf: NonNull<[u8]> = (&**bytes).into();
let raw = RawVarZeroCow {
buf,
owned: true,
};
Ok(Self {
raw,
marker1: PhantomData,
#[cfg(feature = "alloc")]
marker2: PhantomData,
})
}
pub const unsafe fn from_bytes_unchecked(bytes: &'a [u8]) -> Self {
unsafe {
let buf: NonNull<[u8]> = NonNull::new_unchecked(bytes as *const [u8] as *mut [u8]);
let raw = RawVarZeroCow {
buf,
#[cfg(feature = "alloc")]
owned: false,
};
Self::from_raw(raw)
}
}
#[cfg(feature = "alloc")]
pub fn from_encodeable<E: EncodeAsVarULE<V>>(encodeable: &E) -> Self {
let b = crate::ule::encode_varule_to_box(encodeable);
Self::new_owned(b)
}
pub fn new_borrowed(val: &'a V) -> Self {
unsafe {
Self::from_bytes_unchecked(val.as_bytes())
}
}
#[cfg(feature = "alloc")]
pub fn new_owned(val: Box<V>) -> Self {
let val = ManuallyDrop::new(val);
let buf: NonNull<[u8]> = val.as_bytes().into();
let raw = RawVarZeroCow {
buf,
#[cfg(feature = "alloc")]
owned: true,
};
unsafe { Self::from_raw(raw) }
}
}
impl<'a, V: ?Sized> VarZeroCow<'a, V> {
pub fn is_owned(&self) -> bool {
self.raw.is_owned()
}
pub fn as_bytes(&self) -> &[u8] {
self.raw.as_bytes()
}
const unsafe fn from_raw(raw: RawVarZeroCow) -> Self {
Self {
raw,
marker1: PhantomData,
#[cfg(feature = "alloc")]
marker2: PhantomData,
}
}
}
impl RawVarZeroCow {
#[inline]
pub fn is_owned(&self) -> bool {
#[cfg(feature = "alloc")]
return self.owned;
#[cfg(not(feature = "alloc"))]
return false;
}
#[inline]
pub fn as_bytes(&self) -> &[u8] {
unsafe { self.buf.as_ref() }
}
}
impl<'a, V: VarULE + ?Sized> Deref for VarZeroCow<'a, V> {
type Target = V;
fn deref(&self) -> &V {
unsafe { V::from_bytes_unchecked(self.as_bytes()) }
}
}
impl<'a, V: VarULE + ?Sized> From<&'a V> for VarZeroCow<'a, V> {
fn from(other: &'a V) -> Self {
Self::new_borrowed(other)
}
}
#[cfg(feature = "alloc")]
impl<'a, V: VarULE + ?Sized> From<Box<V>> for VarZeroCow<'a, V> {
fn from(other: Box<V>) -> Self {
Self::new_owned(other)
}
}
impl<'a, V: VarULE + ?Sized + fmt::Debug> fmt::Debug for VarZeroCow<'a, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
self.deref().fmt(f)
}
}
impl<'a, V: VarULE + ?Sized + PartialEq> PartialEq for VarZeroCow<'a, V> {
fn eq(&self, other: &Self) -> bool {
self.deref().eq(other.deref())
}
}
impl<'a, V: VarULE + ?Sized + Eq> Eq for VarZeroCow<'a, V> {}
impl<'a, V: VarULE + ?Sized + PartialOrd> PartialOrd for VarZeroCow<'a, V> {
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
self.deref().partial_cmp(other.deref())
}
}
impl<'a, V: VarULE + ?Sized + Ord> Ord for VarZeroCow<'a, V> {
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.deref().cmp(other.deref())
}
}
unsafe impl<'a, V: VarULE + ?Sized> EncodeAsVarULE<V> for VarZeroCow<'a, V> {
fn encode_var_ule_as_slices<R>(&self, _: impl FnOnce(&[&[u8]]) -> R) -> R {
unreachable!()
}
#[inline]
fn encode_var_ule_len(&self) -> usize {
self.as_bytes().len()
}
#[inline]
fn encode_var_ule_write(&self, dst: &mut [u8]) {
dst.copy_from_slice(self.as_bytes())
}
}
#[cfg(feature = "serde")]
impl<'a, V: VarULE + ?Sized + serde::Serialize> serde::Serialize for VarZeroCow<'a, V> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if serializer.is_human_readable() {
<V as serde::Serialize>::serialize(self.deref(), serializer)
} else {
serializer.serialize_bytes(self.as_bytes())
}
}
}
#[cfg(all(feature = "serde", feature = "alloc"))]
impl<'a, 'de: 'a, V: VarULE + ?Sized> serde::Deserialize<'de> for VarZeroCow<'a, V>
where
Box<V>: serde::Deserialize<'de>,
{
fn deserialize<Des>(deserializer: Des) -> Result<Self, Des::Error>
where
Des: serde::Deserializer<'de>,
{
if deserializer.is_human_readable() {
let b = Box::<V>::deserialize(deserializer)?;
Ok(Self::new_owned(b))
} else {
let bytes = <&[u8]>::deserialize(deserializer)?;
Self::parse_bytes(bytes).map_err(serde::de::Error::custom)
}
}
}
#[cfg(feature = "databake")]
impl<'a, V: VarULE + ?Sized> databake::Bake for VarZeroCow<'a, V> {
fn bake(&self, env: &databake::CrateEnv) -> databake::TokenStream {
env.insert("zerovec");
let bytes = self.as_bytes().bake(env);
databake::quote! {
unsafe {
zerovec::VarZeroCow::from_bytes_unchecked(#bytes)
}
}
}
}
#[cfg(feature = "databake")]
impl<'a, V: VarULE + ?Sized> databake::BakeSize for VarZeroCow<'a, V> {
fn borrows_size(&self) -> usize {
self.as_bytes().len()
}
}
impl<'a, V: VarULE + ?Sized> ZeroFrom<'a, V> for VarZeroCow<'a, V> {
#[inline]
fn zero_from(other: &'a V) -> Self {
Self::new_borrowed(other)
}
}
impl<'a, 'b, V: VarULE + ?Sized> ZeroFrom<'a, VarZeroCow<'b, V>> for VarZeroCow<'a, V> {
#[inline]
fn zero_from(other: &'a VarZeroCow<'b, V>) -> Self {
Self::new_borrowed(other)
}
}
#[cfg(test)]
mod tests {
use super::VarZeroCow;
use crate::ule::tuplevar::Tuple3VarULE;
use crate::vecs::VarZeroSlice;
#[test]
fn test_cow_roundtrip() {
type Messy = Tuple3VarULE<str, [u8], VarZeroSlice<str>>;
let vec = vec!["one", "two", "three"];
let messy: VarZeroCow<Messy> =
VarZeroCow::from_encodeable(&("hello", &b"g\xFF\xFFdbye"[..], vec));
assert_eq!(messy.a(), "hello");
assert_eq!(messy.b(), b"g\xFF\xFFdbye");
assert_eq!(&messy.c()[1], "two");
#[cfg(feature = "serde")]
{
let bincode = bincode::serialize(&messy).unwrap();
let deserialized: VarZeroCow<Messy> = bincode::deserialize(&bincode).unwrap();
assert_eq!(
messy, deserialized,
"Single element roundtrips with bincode"
);
assert!(!deserialized.is_owned());
let json = serde_json::to_string(&messy).unwrap();
let deserialized: VarZeroCow<Messy> = serde_json::from_str(&json).unwrap();
assert_eq!(messy, deserialized, "Single element roundtrips with serde");
}
}
struct TwoCows<'a> {
cow1: VarZeroCow<'a, str>,
cow2: VarZeroCow<'a, str>,
}
#[test]
fn test_eyepatch_works() {
let mut two = TwoCows {
cow1: VarZeroCow::new_borrowed("hello"),
cow2: VarZeroCow::new_owned("world".into()),
};
let three = VarZeroCow::new_borrowed(&*two.cow2);
two.cow1 = three;
}
}