Skip to main content

plexor_codec_serde_postcard/
lib.rs

1// Copyright 2025 Alecks Gates
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use plexor_core::codec::{Codec, CodecError, CodecName};
8use postcard::{from_bytes, to_allocvec};
9use serde::{Deserialize, Serialize};
10
11#[derive(Debug, Clone)]
12pub struct SerdePostcardCodec;
13
14impl SerdePostcardCodec {}
15
16impl CodecName for SerdePostcardCodec {
17    fn name() -> &'static str {
18        "postcard"
19    }
20}
21
22impl<T> Codec<T> for SerdePostcardCodec
23where
24    T: Serialize + for<'de> Deserialize<'de> + Send + Sync + 'static,
25{
26    fn encode(value: &T) -> Result<Vec<u8>, CodecError> {
27        to_allocvec(value)
28            .map_err(|e| CodecError::Encode(format!("Failed to serialize to Postcard: {e}")))
29    }
30
31    fn decode(bytes: &[u8]) -> Result<T, CodecError> {
32        from_bytes(bytes)
33            .map_err(|e| CodecError::Decode(format!("Failed to deserialize from Postcard: {e}")))
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn it_works() {
43        assert_eq!("postcard", SerdePostcardCodec::name());
44    }
45}