Skip to main content

plexor_core/
codec.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 thiserror::Error;
8
9#[derive(Debug, Clone, PartialEq, Error)]
10pub enum CodecError {
11    #[error("Encode error: {0}")]
12    Encode(String),
13    #[error("Decode error: {0}")]
14    Decode(String),
15}
16
17pub trait Codec<T> {
18    fn encode(d: &T) -> Result<Vec<u8>, CodecError>;
19    fn decode(e: &[u8]) -> Result<T, CodecError>;
20}
21
22pub trait CodecName {
23    fn name() -> &'static str;
24}
25
26/// A codec that does nothing.
27/// Useful for in-process communication where serialization is not needed.
28/// Attempts to encode/decode will return an error.
29pub struct PassthroughCodec;
30
31impl CodecName for PassthroughCodec {
32    fn name() -> &'static str {
33        "native"
34    }
35}
36
37impl<T: Send + Sync + 'static> Codec<T> for PassthroughCodec {
38    fn encode(_: &T) -> Result<Vec<u8>, CodecError> {
39        Err(CodecError::Encode("PassthroughCodec cannot encode".into()))
40    }
41    fn decode(_: &[u8]) -> Result<T, CodecError> {
42        Err(CodecError::Decode("PassthroughCodec cannot decode".into()))
43    }
44}
45
46/// A codec for plain text (UTF-8).
47/// Maps `String` <-> `Vec<u8>`.
48#[derive(Debug, Clone)]
49pub struct TextCodec;
50
51impl CodecName for TextCodec {
52    fn name() -> &'static str {
53        "text"
54    }
55}
56
57impl Codec<String> for TextCodec {
58    fn encode(d: &String) -> Result<Vec<u8>, CodecError> {
59        Ok(d.as_bytes().to_vec())
60    }
61    fn decode(e: &[u8]) -> Result<String, CodecError> {
62        String::from_utf8(e.to_vec()).map_err(|e| CodecError::Decode(e.to_string()))
63    }
64}