1use serde::{Deserialize, Serialize};
9
10use crate::backend::Backend;
11use crate::error::StoreError;
12
13const BLOB_PREFIX: &str = "blob/";
14
15#[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
18pub struct Hash([u8; 32]);
19
20impl Hash {
21 pub fn of(bytes: &[u8]) -> Self {
23 Self(*blake3::hash(bytes).as_bytes())
24 }
25
26 pub fn from_bytes(bytes: [u8; 32]) -> Self {
30 Self(bytes)
31 }
32
33 pub fn as_bytes(&self) -> &[u8; 32] {
35 &self.0
36 }
37
38 pub fn to_hex(&self) -> String {
40 blake3::Hash::from_bytes(self.0).to_hex().to_string()
41 }
42
43 pub fn from_hex(s: &str) -> Option<Self> {
45 blake3::Hash::from_hex(s).ok().map(|h| Self(*h.as_bytes()))
46 }
47}
48
49impl std::fmt::Debug for Hash {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 write!(f, "Hash({})", self.to_hex())
52 }
53}
54
55impl std::fmt::Display for Hash {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.write_str(&self.to_hex())
58 }
59}
60
61pub struct BlobStore<B> {
63 backend: B,
64}
65
66impl<B: Backend> BlobStore<B> {
67 pub fn new(backend: B) -> Self {
69 Self { backend }
70 }
71
72 pub fn backend(&self) -> &B {
74 &self.backend
75 }
76
77 pub async fn put(&self, bytes: &[u8]) -> Result<Hash, StoreError> {
80 let hash = Hash::of(bytes);
81 self.backend.put(&key(&hash), bytes).await?;
82 Ok(hash)
83 }
84
85 pub async fn get(&self, hash: &Hash) -> Result<Option<Vec<u8>>, StoreError> {
87 self.backend.get(&key(hash)).await
88 }
89
90 pub async fn has(&self, hash: &Hash) -> Result<bool, StoreError> {
92 Ok(self.backend.get(&key(hash)).await?.is_some())
93 }
94}
95
96fn key(hash: &Hash) -> String {
97 format!("{BLOB_PREFIX}{}", hash.to_hex())
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use crate::backend::MemoryBackend;
104
105 #[test]
106 fn hash_is_content_stable() {
107 assert_eq!(Hash::of(b"hello"), Hash::of(b"hello"));
108 assert_ne!(Hash::of(b"hello"), Hash::of(b"world"));
109 }
110
111 #[test]
112 fn hex_round_trips() {
113 let h = Hash::of(b"the quick brown fox");
114 assert_eq!(Hash::from_hex(&h.to_hex()), Some(h));
115 assert_eq!(h.to_hex().len(), 64);
116 }
117
118 #[test]
119 fn put_returns_content_hash_and_get_round_trips() {
120 pollster::block_on(async {
121 let store = BlobStore::new(MemoryBackend::new());
122 let h = store.put(b"media bytes").await.unwrap();
123 assert_eq!(h, Hash::of(b"media bytes"));
124 assert_eq!(store.get(&h).await.unwrap(), Some(b"media bytes".to_vec()));
125 assert!(store.has(&h).await.unwrap());
126 });
127 }
128
129 #[test]
130 fn identical_content_dedupes_to_one_key() {
131 pollster::block_on(async {
132 let backend = MemoryBackend::new();
133 let store = BlobStore::new(backend.clone());
134 let a = store.put(b"same").await.unwrap();
135 let b = store.put(b"same").await.unwrap();
136 assert_eq!(a, b);
137 assert_eq!(backend.len(), 1, "identical content stored once");
138 });
139 }
140
141 #[test]
142 fn missing_blob_is_none() {
143 pollster::block_on(async {
144 let store = BlobStore::new(MemoryBackend::new());
145 let h = Hash::of(b"never stored");
146 assert_eq!(store.get(&h).await.unwrap(), None);
147 assert!(!store.has(&h).await.unwrap());
148 });
149 }
150}