use super::bytes::Bytes;
pub struct Slice<'a> {
inner: SliceInner<'a>,
}
enum SliceInner<'a> {
Borrowed(&'a [u8]),
Owned(Bytes),
}
impl<'a> From<&'a [u8]> for Slice<'a> {
fn from(data: &'a [u8]) -> Self {
Slice {
inner: SliceInner::Borrowed(data),
}
}
}
impl From<Bytes> for Slice<'static> {
fn from(bytes: Bytes) -> Self {
Slice {
inner: SliceInner::Owned(bytes),
}
}
}
impl<'a> std::fmt::Debug for Slice<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Slice({:?})", self.as_bytes())
}
}
impl<'a> PartialEq for Slice<'a> {
fn eq(&self, other: &Self) -> bool {
self.as_bytes() == other.as_bytes()
}
}
impl<'a> Eq for Slice<'a> {}
impl<'a> PartialOrd for Slice<'a> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<'a> Ord for Slice<'a> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_bytes().cmp(other.as_bytes())
}
}
impl<'a> Slice<'a> {
pub fn as_bytes(&self) -> &[u8] {
match &self.inner {
SliceInner::Borrowed(data) => data,
SliceInner::Owned(bytes) => bytes.as_ref(),
}
}
}
impl<'a> PartialEq<Vec<u8>> for Slice<'a> {
fn eq(&self, other: &Vec<u8>) -> bool {
self.as_bytes() == other.as_slice()
}
}
impl<'a> PartialEq<&[u8]> for Slice<'a> {
fn eq(&self, other: &&[u8]) -> bool {
self.as_bytes() == *other
}
}
impl<'a> PartialEq<Slice<'a>> for Vec<u8> {
fn eq(&self, other: &Slice<'a>) -> bool {
self.as_slice() == other.as_bytes()
}
}
impl<'a> PartialEq<Slice<'a>> for &[u8] {
fn eq(&self, other: &Slice<'a>) -> bool {
*self == other.as_bytes()
}
}
impl<const N: usize> PartialEq<[u8; N]> for Slice<'_> {
fn eq(&self, other: &[u8; N]) -> bool {
self.as_bytes() == other.as_slice()
}
}
impl<const N: usize> PartialEq<Slice<'_>> for [u8; N] {
fn eq(&self, other: &Slice<'_>) -> bool {
self.as_slice() == other.as_bytes()
}
}