From 6005491cd8adf569c0b7f88fc6b3af3f166963ea Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Thu, 27 Apr 2023 16:14:44 +0200 Subject: [PATCH] Use Cow<[u8]> for sort keys --- src/table/data.rs | 4 +--- src/table/schema.rs | 12 +++++++----- src/table/util.rs | 6 ++++-- 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/table/data.rs b/src/table/data.rs index 26cc3a5a..cfc67c18 100644 --- a/src/table/data.rs +++ b/src/table/data.rs @@ -347,9 +347,7 @@ impl TableData { // ---- Utility functions ---- pub fn tree_key(&self, p: &F::P, s: &F::S) -> Vec { - let mut ret = p.hash().to_vec(); - ret.extend(s.sort_key()); - ret + [p.hash().as_slice(), s.sort_key().as_ref()].concat() } pub fn decode_entry(&self, bytes: &[u8]) -> Result { diff --git a/src/table/schema.rs b/src/table/schema.rs index 5cbf6c95..44b10898 100644 --- a/src/table/schema.rs +++ b/src/table/schema.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use serde::{Deserialize, Serialize}; use garage_db as db; @@ -32,18 +34,18 @@ impl PartitionKey for FixedBytes32 { /// Trait for field used to sort data pub trait SortKey: Clone + Serialize + for<'de> Deserialize<'de> + Send + Sync + 'static { /// Get the key used to sort - fn sort_key(&self) -> &[u8]; + fn sort_key(&self) -> Cow<'_, [u8]>; } impl SortKey for String { - fn sort_key(&self) -> &[u8] { - self.as_bytes() + fn sort_key(&self) -> Cow<'_, [u8]> { + Cow::from(self.as_bytes()) } } impl SortKey for FixedBytes32 { - fn sort_key(&self) -> &[u8] { - self.as_slice() + fn sort_key(&self) -> Cow<'_, [u8]> { + Cow::from(self.as_slice()) } } diff --git a/src/table/util.rs b/src/table/util.rs index 0b10cf3f..39412c79 100644 --- a/src/table/util.rs +++ b/src/table/util.rs @@ -1,3 +1,5 @@ +use std::borrow::Cow; + use serde::{Deserialize, Serialize}; use garage_util::data::*; @@ -7,8 +9,8 @@ use crate::schema::*; #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct EmptyKey; impl SortKey for EmptyKey { - fn sort_key(&self) -> &[u8] { - &[] + fn sort_key(&self) -> Cow<'_, [u8]> { + Cow::from(&[][..]) } } impl PartitionKey for EmptyKey {