plexor-core 0.1.0-alpha.2

Core library for the rust implementation of the Plexo distributed system architecture, providing the fundamental Plexus, Neuron, Codec, and Axon abstractions.
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 thiserror::Error;

#[derive(Debug, Clone, PartialEq, Error)]
pub enum CodecError {
    #[error("Encode error: {0}")]
    Encode(String),
    #[error("Decode error: {0}")]
    Decode(String),
}

pub trait Codec<T> {
    fn encode(d: &T) -> Result<Vec<u8>, CodecError>;
    fn decode(e: &[u8]) -> Result<T, CodecError>;
}

pub trait CodecName {
    fn name() -> &'static str;
}

/// A codec that does nothing.
/// Useful for in-process communication where serialization is not needed.
/// Attempts to encode/decode will return an error.
pub struct PassthroughCodec;

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

impl<T: Send + Sync + 'static> Codec<T> for PassthroughCodec {
    fn encode(_: &T) -> Result<Vec<u8>, CodecError> {
        Err(CodecError::Encode("PassthroughCodec cannot encode".into()))
    }
    fn decode(_: &[u8]) -> Result<T, CodecError> {
        Err(CodecError::Decode("PassthroughCodec cannot decode".into()))
    }
}

/// A codec for plain text (UTF-8).
/// Maps `String` <-> `Vec<u8>`.
#[derive(Debug, Clone)]
pub struct TextCodec;

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

impl Codec<String> for TextCodec {
    fn encode(d: &String) -> Result<Vec<u8>, CodecError> {
        Ok(d.as_bytes().to_vec())
    }
    fn decode(e: &[u8]) -> Result<String, CodecError> {
        String::from_utf8(e.to_vec()).map_err(|e| CodecError::Decode(e.to_string()))
    }
}