Skip to main content

cratestack_core/
codec.rs

1//! Pluggable codec + envelope traits used by the transport layer.
2
3use serde::{Deserialize, Serialize};
4
5use crate::context::CoolContext;
6use crate::error::CoolError;
7
8pub trait CoolCodec: Clone + Send + Sync + 'static {
9    const CONTENT_TYPE: &'static str;
10
11    fn encode<T: Serialize + ?Sized>(&self, value: &T) -> Result<Vec<u8>, CoolError>;
12
13    fn decode<T: for<'de> Deserialize<'de>>(&self, bytes: &[u8]) -> Result<T, CoolError>;
14}
15
16pub trait CoolEnvelope: Clone + Send + Sync + 'static {
17    fn request_content_type(&self) -> &'static str;
18
19    fn response_content_type(&self) -> &'static str;
20
21    fn open_request(&self, bytes: &[u8], _ctx: &mut CoolContext) -> Result<Vec<u8>, CoolError>;
22
23    fn seal_response(&self, bytes: &[u8], _ctx: &CoolContext) -> Result<Vec<u8>, CoolError>;
24}
25
26/// Pass-through envelope used when transport-layer signing is not
27/// required.
28#[derive(Debug, Clone, Default)]
29pub struct NoEnvelope;
30
31impl CoolEnvelope for NoEnvelope {
32    fn request_content_type(&self) -> &'static str {
33        "application/octet-stream"
34    }
35
36    fn response_content_type(&self) -> &'static str {
37        "application/octet-stream"
38    }
39
40    fn open_request(&self, bytes: &[u8], _ctx: &mut CoolContext) -> Result<Vec<u8>, CoolError> {
41        Ok(bytes.to_vec())
42    }
43
44    fn seal_response(&self, bytes: &[u8], _ctx: &CoolContext) -> Result<Vec<u8>, CoolError> {
45        Ok(bytes.to_vec())
46    }
47}