Skip to main content

plexor_codec_serde_json/
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 serde::{Deserialize, Serialize};
9use serde_json::{from_slice, to_vec};
10
11#[derive(Debug, Clone)]
12pub struct SerdeJsonCodec;
13
14impl SerdeJsonCodec {}
15
16impl CodecName for SerdeJsonCodec {
17    fn name() -> &'static str {
18        "json"
19    }
20}
21
22impl<T> Codec<T> for SerdeJsonCodec
23where
24    T: Serialize + for<'de> Deserialize<'de> + Send + Sync + 'static,
25{
26    fn encode(value: &T) -> Result<Vec<u8>, CodecError> {
27        to_vec(value).map_err(|e| CodecError::Encode(format!("Failed to serialize to JSON: {e}")))
28    }
29
30    fn decode(bytes: &[u8]) -> Result<T, CodecError> {
31        from_slice(bytes)
32            .map_err(|e| CodecError::Decode(format!("Failed to deserialize from JSON: {e}")))
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn it_works() {
42        assert_eq!("json", SerdeJsonCodec::name());
43    }
44}