use std::{borrow::Borrow, ops::Deref};
use bytes::Bytes;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Component<'a, const MAX_COMPONENT_LENGTH: usize>(&'a [u8]);
impl<'a, const MAX_COMPONENT_LENGTH: usize> Component<'a, MAX_COMPONENT_LENGTH> {
pub fn new(slice: &'a [u8]) -> Option<Self> {
if slice.len() <= MAX_COMPONENT_LENGTH {
Some(unsafe { Self::new_unchecked(slice) }) } else {
None
}
}
pub unsafe fn new_unchecked(slice: &'a [u8]) -> Self {
Self(slice)
}
pub fn new_empty() -> Self {
Self(&[])
}
pub fn into_inner(self) -> &'a [u8] {
self.0
}
}
impl<const MAX_COMPONENT_LENGTH: usize> Deref for Component<'_, MAX_COMPONENT_LENGTH> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0
}
}
impl<const MAX_COMPONENT_LENGTH: usize> AsRef<[u8]> for Component<'_, MAX_COMPONENT_LENGTH> {
fn as_ref(&self) -> &[u8] {
self.0
}
}
impl<const MAX_COMPONENT_LENGTH: usize> Borrow<[u8]> for Component<'_, MAX_COMPONENT_LENGTH> {
fn borrow(&self) -> &[u8] {
self.0
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OwnedComponent<const MAX_COMPONENT_LENGTH: usize>(pub(crate) Bytes);
impl<const MAX_COMPONENT_LENGTH: usize> OwnedComponent<MAX_COMPONENT_LENGTH> {
pub fn new(data: &[u8]) -> Option<Self> {
if data.len() <= MAX_COMPONENT_LENGTH {
Some(unsafe { Self::new_unchecked(data) }) } else {
None
}
}
pub unsafe fn new_unchecked(data: &[u8]) -> Self {
Self(Bytes::copy_from_slice(data))
}
pub fn new_empty() -> Self {
Self(Bytes::new())
}
}
impl<const MAX_COMPONENT_LENGTH: usize> Deref for OwnedComponent<MAX_COMPONENT_LENGTH> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
impl<const MAX_COMPONENT_LENGTH: usize> AsRef<[u8]> for OwnedComponent<MAX_COMPONENT_LENGTH> {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl<const MAX_COMPONENT_LENGTH: usize> Borrow<[u8]> for OwnedComponent<MAX_COMPONENT_LENGTH> {
fn borrow(&self) -> &[u8] {
self.0.borrow()
}
}