From 7b92bd7c340d9f9c094ed2fa57912049317d9b20 Mon Sep 17 00:00:00 2001 From: Laurenz Date: Mon, 26 Jun 2023 13:57:21 +0200 Subject: Basic package management --- src/util/bytes.rs | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 src/util/bytes.rs (limited to 'src/util/bytes.rs') diff --git a/src/util/bytes.rs b/src/util/bytes.rs new file mode 100644 index 00000000..9165467b --- /dev/null +++ b/src/util/bytes.rs @@ -0,0 +1,59 @@ +use std::borrow::Cow; +use std::fmt::{self, Debug, Formatter}; +use std::ops::Deref; +use std::sync::Arc; + +use comemo::Prehashed; + +/// A shared byte buffer that is cheap to clone and hash. +#[derive(Clone, Hash, Eq, PartialEq)] +pub struct Bytes(Arc>>); + +impl Bytes { + /// Create a buffer from a static byte slice. + pub fn from_static(slice: &'static [u8]) -> Self { + Self(Arc::new(Prehashed::new(Cow::Borrowed(slice)))) + } + + /// Return a view into the buffer. + pub fn as_slice(&self) -> &[u8] { + self + } + + /// Return a copy of the buffer as a vector. + pub fn to_vec(&self) -> Vec { + self.0.to_vec() + } +} + +impl From<&[u8]> for Bytes { + fn from(slice: &[u8]) -> Self { + Self(Arc::new(Prehashed::new(slice.to_vec().into()))) + } +} + +impl From> for Bytes { + fn from(vec: Vec) -> Self { + Self(Arc::new(Prehashed::new(vec.into()))) + } +} + +impl Deref for Bytes { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl AsRef<[u8]> for Bytes { + fn as_ref(&self) -> &[u8] { + self + } +} + +impl Debug for Bytes { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + write!(f, "bytes({})", self.len()) + } +} -- cgit v1.2.3