use crate::compat::borrow::Cow;
use crate::compat::vec::Vec;
use core::ops::Deref;
use minicbor::{Decode, Encode};
use serde::{Deserialize, Serialize};
#[derive(
Debug, Clone, Encode, Decode, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[cbor(transparent)]
#[serde(transparent)]
pub struct CowBytes<'a>(
#[cbor(b(0), with = "minicbor::bytes")]
#[serde(borrow)]
pub Cow<'a, [u8]>,
);
impl CowBytes<'_> {
pub fn is_borrowed(&self) -> bool {
matches!(self.0, Cow::Borrowed(_))
}
pub fn to_owned<'r>(&self) -> CowBytes<'r> {
CowBytes(Cow::Owned(self.0.to_vec()))
}
pub fn into_owned(self) -> Vec<u8> {
self.0.into_owned()
}
}
impl<'a> From<&'a [u8]> for CowBytes<'a> {
fn from(s: &'a [u8]) -> Self {
CowBytes(Cow::Borrowed(s))
}
}
impl From<Vec<u8>> for CowBytes<'_> {
fn from(s: Vec<u8>) -> Self {
CowBytes(Cow::Owned(s))
}
}
impl<'a> From<CowBytes<'a>> for Cow<'a, [u8]> {
fn from(c: CowBytes<'a>) -> Self {
c.0
}
}
impl<'a> Deref for CowBytes<'a> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}