1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// SPDX-License-Identifier: Apache-2.0 OR MIT
//! Codec plugin trait — interface stub for slice 1.
//!
//! Sits between the engine and `Storage`. Encodes / decodes blobs at-rest.
//! Slice 1 ships an implicit identity codec (the engine writes plaintext);
//! the trait + the future `Builder::codec(impl Codec)` hook exist so a
//! future encryption / compression / content-defined-chunking codec lands
//! without changing the on-disk shape or breaking SemVer.
//!
//! See spec § 12.10.
use async_trait::async_trait;
use bytes::Bytes;
use crate::error::Result;
/// Encode/decode pre-storage.
#[async_trait]
pub trait Codec: Send + Sync + std::fmt::Debug + 'static {
/// Stable identifier (e.g. `"identity:v1"`, `"aes-gcm:v1"`).
fn id(&self) -> &str;
/// Encode a plaintext blob into its at-rest form.
async fn encode(&self, plain: Bytes) -> Result<Bytes>;
/// Decode an at-rest blob back to plaintext.
async fn decode(&self, encoded: Bytes) -> Result<Bytes>;
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct IdentityCodec;
#[async_trait]
impl Codec for IdentityCodec {
fn id(&self) -> &str {
"test:identity:v1"
}
async fn encode(&self, plain: Bytes) -> Result<Bytes> {
Ok(plain)
}
async fn decode(&self, encoded: Bytes) -> Result<Bytes> {
Ok(encoded)
}
}
#[tokio::test]
async fn object_safe_round_trip() {
let boxed: Box<dyn Codec> = Box::new(IdentityCodec);
let plain = Bytes::from_static(b"hello world");
let enc = boxed.encode(plain.clone()).await.unwrap();
let dec = boxed.decode(enc).await.unwrap();
assert_eq!(dec, plain);
assert_eq!(boxed.id(), "test:identity:v1");
}
}