feat(tvix/store/digests): use bytes::Bytes instead of Vec<u8>

This will save us some copies, because a clone will simply create an
additional pointer to the same data.

Change-Id: I017a5d6b4c85a861b5541ebad2858ad4fbf8e8fa
Reviewed-on: https://cl.tvl.fyi/c/depot/+/8978
Reviewed-by: raitobezarius <tvl@lahfa.xyz>
Autosubmit: flokli <flokli@flokli.de>
Tested-by: BuildkiteCI
This commit is contained in:
Florian Klink 2023-07-20 13:37:29 +03:00 committed by clbot
parent 72e82ffcb1
commit a6580748aa
14 changed files with 99 additions and 68 deletions

View file

@ -1,10 +1,9 @@
use bytes::Bytes;
use data_encoding::BASE64;
use thiserror::Error;
// FUTUREWORK: make generic
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct B3Digest(Vec<u8>);
pub struct B3Digest(Bytes);
// TODO: allow converting these errors to crate::Error
#[derive(Error, Debug)]
@ -14,25 +13,49 @@ pub enum Error {
}
impl B3Digest {
// constructs a [B3Digest] from a [Vec<u8>].
// Returns an error if the digest has the wrong length.
pub fn from_vec(value: Vec<u8>) -> Result<Self, Error> {
if value.len() != 32 {
Err(Error::InvalidDigestLen(value.len()))
} else {
Ok(Self(value))
}
}
// returns a copy of the inner [Vec<u8>].
pub fn to_vec(&self) -> Vec<u8> {
self.0.to_vec()
}
}
impl From<B3Digest> for bytes::Bytes {
fn from(val: B3Digest) -> Self {
val.0
}
}
impl TryFrom<Vec<u8>> for B3Digest {
type Error = Error;
// constructs a [B3Digest] from a [Vec<u8>].
// Returns an error if the digest has the wrong length.
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
if value.len() != 32 {
Err(Error::InvalidDigestLen(value.len()))
} else {
Ok(Self(value.into()))
}
}
}
impl TryFrom<bytes::Bytes> for B3Digest {
type Error = Error;
// constructs a [B3Digest] from a [bytes::Bytes].
// Returns an error if the digest has the wrong length.
fn try_from(value: bytes::Bytes) -> Result<Self, Self::Error> {
if value.len() != 32 {
Err(Error::InvalidDigestLen(value.len()))
} else {
Ok(Self(value))
}
}
}
impl From<&[u8; 32]> for B3Digest {
fn from(value: &[u8; 32]) -> Self {
Self(value.to_vec())
Self(value.to_vec().into())
}
}
@ -44,6 +67,6 @@ impl Clone for B3Digest {
impl std::fmt::Display for B3Digest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "b3:{}", BASE64.encode(self.0.as_slice()))
write!(f, "b3:{}", BASE64.encode(&self.0))
}
}