plexor-codec-serde-postcard 0.1.0-alpha.2

Postcard codec implementation for the Plexo distributed system architecture using Serde.
Documentation
// Copyright 2025 Alecks Gates
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use plexor_core::codec::{Codec, CodecError, CodecName};
use postcard::{from_bytes, to_allocvec};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone)]
pub struct SerdePostcardCodec;

impl SerdePostcardCodec {}

impl CodecName for SerdePostcardCodec {
    fn name() -> &'static str {
        "postcard"
    }
}

impl<T> Codec<T> for SerdePostcardCodec
where
    T: Serialize + for<'de> Deserialize<'de> + Send + Sync + 'static,
{
    fn encode(value: &T) -> Result<Vec<u8>, CodecError> {
        to_allocvec(value)
            .map_err(|e| CodecError::Encode(format!("Failed to serialize to Postcard: {e}")))
    }

    fn decode(bytes: &[u8]) -> Result<T, CodecError> {
        from_bytes(bytes)
            .map_err(|e| CodecError::Decode(format!("Failed to deserialize from Postcard: {e}")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!("postcard", SerdePostcardCodec::name());
    }
}