Skip to main content

switchback_codec_pb/
codec.rs

1//! [`ProtobufCodec`] — buffa wire encoding for the switchback artifact.
2
3use buffa::Message;
4use switchback_traits::{ReferenceManual, Result, SwitchbackCodec, SyncSwitchbackCodec};
5
6use crate::convert;
7use crate::pb;
8
9/// Default on-disk filename for a switchback binary file.
10pub const DEFAULT_SWITCHBACK_FILENAME: &str = "switchback.binpb";
11
12/// Reference protobuf codec using buffa-generated types from `canardleteer.switchback.v1alpha1`.
13///
14/// Implements [`SwitchbackCodec`] (async-primary) and [`SyncSwitchbackCodec`]
15/// per [ADR 0002](https://github.com/canardleteer/switchback-rs/blob/main/docs/adr/0002-async-first-traits-with-synchronous-secondary-apis-in-switchback-traits.md).
16/// Encode and decode are in-memory and synchronous; the async trait methods
17/// delegate to the same helpers without blocking on I/O.
18#[derive(Debug, Default, Clone, Copy)]
19pub struct ProtobufCodec;
20
21impl ProtobufCodec {
22    /// Serialize a [`ReferenceManual`] to protobuf wire bytes.
23    pub fn serialize_sync(&self, manual: &ReferenceManual) -> Result<Vec<u8>> {
24        let proto = convert::to_proto(manual)?;
25        Ok(proto.encode_to_vec())
26    }
27
28    /// Deserialize protobuf wire bytes into a [`ReferenceManual`].
29    pub fn deserialize_sync(&self, bytes: &[u8]) -> Result<ReferenceManual> {
30        let proto = pb::ReferenceManual::decode_from_slice(bytes)
31            .map_err(|err| switchback_traits::SwitchbackError::codec(err.to_string()))?;
32        convert::from_proto(proto)
33    }
34}
35
36impl SwitchbackCodec for ProtobufCodec {
37    async fn serialize(&self, manual: &ReferenceManual) -> Result<Vec<u8>> {
38        self.serialize_sync(manual)
39    }
40
41    async fn deserialize(&self, bytes: &[u8]) -> Result<ReferenceManual> {
42        self.deserialize_sync(bytes)
43    }
44}
45
46impl SyncSwitchbackCodec for ProtobufCodec {
47    fn serialize(&self, manual: &ReferenceManual) -> Result<Vec<u8>> {
48        self.serialize_sync(manual)
49    }
50
51    fn deserialize(&self, bytes: &[u8]) -> Result<ReferenceManual> {
52        self.deserialize_sync(bytes)
53    }
54}