use std::cmp::Ordering;
use std::ops::Index;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Slice<'a> {
data: &'a [u8],
}
impl<'a> Slice<'a> {
pub fn new(data: &'a [u8]) -> Self {
Self { data }
}
pub fn data(&self) -> &'a [u8] {
self.data
}
pub fn size(&self) -> usize {
self.data.len()
}
pub fn empty(&self) -> bool {
self.data.is_empty()
}
pub fn starts_with(&self, prefix: Slice<'_>) -> bool {
self.data.starts_with(prefix.data)
}
pub fn compare(&self, other: Slice<'_>) -> Ordering {
self.data.cmp(other.data)
}
pub fn to_vec(&self) -> Vec<u8> {
self.data.to_vec()
}
pub fn remove_prefix(&mut self, n: usize) {
assert!(n <= self.data.len(), "Slice::remove_prefix: out of bounds");
self.data = &self.data[n..];
}
pub fn clear(&mut self) {
self.data = &[];
}
}
impl<'a> From<&'a [u8]> for Slice<'a> {
fn from(data: &'a [u8]) -> Self {
Self::new(data)
}
}
impl<'a> From<&'a Vec<u8>> for Slice<'a> {
fn from(data: &'a Vec<u8>) -> Self {
Self::new(data.as_slice())
}
}
impl<'a> From<&'a str> for Slice<'a> {
fn from(data: &'a str) -> Self {
Self::new(data.as_bytes())
}
}
impl<'a> Index<usize> for Slice<'a> {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.data[index]
}
}
impl<'a> AsRef<[u8]> for Slice<'a> {
fn as_ref(&self) -> &[u8] {
self.data
}
}