1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
//! Contains [EncodeMethod] and [DecodeMethod] to generically implement encoding and decoding over
//! different libraries.
//!
//! Module also contains already implemented codecs to be easily used.
use bytes::{Bytes, BytesMut};
use std::io;
#[cfg(feature = "serde")]
use serde::{de::DeserializeOwned, Serialize};
/// Trait for encoding a given item into bytes.
///
/// Generic parameter `T` is the data that will be encoded.
/// When implementing this trait, you can specify trait requirements for `T`, so that,
/// any types that implements that trait will be able to be encoded.
///
/// # Example
///
/// Below example will serialize any item that implements `serde::Serialize` into json.
///
/// ```no_run
/// use tsyncp::util::codec::EncodeMethod;
/// use bytes::Bytes;
///
/// pub struct MyCustomCodec;
///
/// impl<T: serde::Serialize> EncodeMethod<T> for MyCustomCodec {
/// type Error = serde_json::Error;
///
/// fn encode(data: &T) -> Result<Bytes, Self::Error> {
/// serde_json::to_vec(data).map(Into::into)
/// }
/// }
/// ```
pub trait EncodeMethod<T> {
/// Error returned by associated method `encode(_)`.
type Error: 'static + snafu::Error;
/// Encode given data.
fn encode(data: &T) -> Result<Bytes, Self::Error>;
}
/// Trait for decoding given bytes into an item.
///
/// Generic parameter `T` is the data that will be decoded.
/// When implementing this trait, you can specify trait requirements for `T`, so that,
/// any types that implements that trait will be able to be decoded.
///
/// # Example
///
/// Below example will deserialize any item that implements `serde::de::DeserializeOwned` from json bytes.
///
/// ```no_run
/// use tsyncp::util::codec::DecodeMethod;
/// use bytes::BytesMut;
///
/// pub struct MyCustomCodec;
///
/// impl<T: serde::de::DeserializeOwned> DecodeMethod<T> for MyCustomCodec {
/// type Error = serde_json::Error;
///
/// fn decode(bytes: BytesMut) -> Result<T, Self::Error> {
/// serde_json::from_slice(bytes.as_ref())
/// }
/// }
/// ```
pub trait DecodeMethod<T> {
/// Error returned by associated method `decode(_)`.
type Error: 'static + snafu::Error;
/// Decode given data.
fn decode(bytes: BytesMut) -> Result<T, Self::Error>;
}
/// Unit struct that encodes and decodes empty tuple. Used for sending empty payloads.
///
/// `EmptyCodec` only implements traits for empty tuple `()`, and is created mainly for [barrier](crate::barrier) primitives.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct EmptyCodec;
impl EncodeMethod<()> for EmptyCodec {
type Error = io::Error;
fn encode(_: &()) -> Result<Bytes, Self::Error> {
Ok(Bytes::from([0].as_ref()))
}
}
impl DecodeMethod<()> for EmptyCodec {
type Error = io::Error;
fn decode(bytes: BytesMut) -> Result<(), Self::Error> {
if bytes.len() == 1 {
if bytes[0] == 0 {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"[EmptyCodec] Received byte that is not 0u8",
))
}
} else {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"[EmptyCodec] Received bytes lenngth greater than 1",
))
}
}
}
#[cfg(feature = "json")]
pub use json::*;
#[cfg(feature = "json")]
mod json {
use super::*;
/// Unit struct that encodes and decodes data as json objects.
///
/// This implements serializing/deserializing as json using `serde` and `serde_json`.
/// Think of it as a light wrapper around `serde_json`.
///
/// You can use this codec in any of the primitives for any data structs that implements
/// `serde::Serialize` and `serde::Deserialize`.
///
/// All primitives already introduces type alias for this codec so you can just use that for simplicity:
///
/// ```no_run
/// use tsyncp::mpsc;
///
/// pub type JsonSender<T> = mpsc::Sender<T, tsyncp::util::codec::JsonCodec>;
///
/// pub type JsonReceiver<T, const N: usize = 0> = mpsc::Receiver<T, tsyncp::util::codec::JsonCodec, N>;
/// ```
///
/// ### Example
/// ```no_run
/// use serde::{Serialize, Deserialize};
/// use tsyncp::mpsc;
///
/// #[derive(Debug, Serialize, Deserialize)]
/// struct Dummy {
/// field1: String,
/// field2: u64,
/// field3: Vec<u8>,
/// }
///
/// #[tokio::main]
/// async fn main() -> color_eyre::Result<()> {
/// let rx: mpsc::JsonReceiver<Dummy> = mpsc::receiver_on("localhost:8000").await?;
/// let tx: mpsc::JsonSender<Dummy> = mpsc::sender_to("localhost:8000").await?;
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct JsonCodec;
impl<T: Serialize> EncodeMethod<T> for JsonCodec {
type Error = serde_json::Error;
fn encode(data: &T) -> Result<Bytes, Self::Error> {
serde_json::to_vec(data).map(Into::into)
}
}
impl<T: DeserializeOwned> DecodeMethod<T> for JsonCodec {
type Error = serde_json::Error;
fn decode(bytes: BytesMut) -> Result<T, Self::Error> {
serde_json::from_slice(bytes.as_ref())
}
}
}
#[cfg(feature = "bincode")]
pub use bincode_mod::*;
#[cfg(feature = "bincode")]
mod bincode_mod {
use super::*;
/// Unit struct that encodes and decodes data using bincode.
///
/// This implements encoding/decoding `bincode` crate.
/// Think of it as a light wrapper around `bincode`.
///
/// You can use this codec in any of the primitives for any data structs that implements
/// `serde::Serialize` and `serde::Deserialize`.
///
/// All primitives already introduces type alias for this codec so you can just use that for simplicity:
///
/// ```no_run
/// use tsyncp::mpsc;
///
/// pub type BincodeSender<T> = mpsc::Sender<T, tsyncp::util::codec::BincodeCodec>;
///
/// pub type BincodeReceiver<T, const N: usize = 0> = mpsc::Receiver<T, tsyncp::util::codec::BincodeCodec, N>;
/// ```
///
/// ### Example
/// ```no_run
/// use serde::{Serialize, Deserialize};
/// use tsyncp::mpsc;
///
/// #[derive(Debug, Serialize, Deserialize)]
/// struct Dummy {
/// field1: String,
/// field2: u64,
/// field3: Vec<u8>,
/// }
///
/// #[tokio::main]
/// async fn main() -> color_eyre::Result<()> {
/// let rx: mpsc::BincodeReceiver<Dummy> = mpsc::receiver_on("localhost:8000").await?;
/// let tx: mpsc::BincodeSender<Dummy> = mpsc::sender_to("localhost:8000").await?;
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct BincodeCodec;
impl<T: Serialize> EncodeMethod<T> for BincodeCodec {
type Error = bincode::Error;
fn encode(data: &T) -> Result<Bytes, Self::Error> {
bincode::serialize(data).map(Into::into)
}
}
impl<T: DeserializeOwned> DecodeMethod<T> for BincodeCodec {
type Error = bincode::Error;
fn decode(bytes: BytesMut) -> Result<T, Self::Error> {
bincode::deserialize(bytes.as_ref())
}
}
}
#[cfg(feature = "prost")]
pub use prost_mod::*;
#[cfg(feature = "prost")]
mod prost_mod {
use super::*;
/// Unit struct that encodes and decodes data as protobuf objects.
///
/// This implements serializing/deserializing as protobuf using `prost`.
/// Think of it as a light wrapper around `prost`.
///
/// You can use this codec in any of the primitives for any data structs that implements
/// `prost::Message`.
///
/// All primitives already introduces type alias for this codec so you can just use that for simplicity:
///
/// ```no_run
/// use tsyncp::mpsc;
///
/// pub type ProstSender<T> = mpsc::Sender<T, tsyncp::util::codec::ProstCodec>;
///
/// pub type ProstReceiver<T, const N: usize = 0> = mpsc::Receiver<T, tsyncp::util::codec::ProstCodec, N>;
/// ```
///
/// ### Example
/// ```no_run
/// use prost::Message;
/// use tsyncp::mpsc;
///
/// #[derive(Message)]
/// struct Dummy {
/// #[prost(string, tag = "1")]
/// field1: String,
/// #[prost(uint64, tag = "2")]
/// field2: u64,
/// }
///
/// #[tokio::main]
/// async fn main() -> color_eyre::Result<()> {
/// let rx: mpsc::ProstReceiver<Dummy> = mpsc::receiver_on("localhost:8000").await?;
/// let tx: mpsc::ProstSender<Dummy> = mpsc::sender_to("localhost:8000").await?;
/// Ok(())
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ProstCodec;
impl<T: prost::Message> EncodeMethod<T> for ProstCodec {
type Error = prost::EncodeError;
fn encode(data: &T) -> Result<Bytes, Self::Error> {
Ok(data.encode_to_vec().into())
}
}
impl<T: prost::Message + Default> DecodeMethod<T> for ProstCodec {
type Error = prost::DecodeError;
fn decode(mut bytes: BytesMut) -> Result<T, Self::Error> {
T::decode(&mut bytes)
}
}
}
// #[cfg(feature = "rkyv")]
// pub use rkyv_mod::*;
// #[cfg(feature = "rkyv")]
// mod rkyv_mod {
// use super::{DecodeMethod, EncodeMethod};
// use bytecheck::CheckBytes;
// use bytes::{Bytes, BytesMut};
// use rkyv::{
// ser::serializers::{
// AlignedSerializer, AllocScratch, AllocScratchError, CompositeSerializer,
// CompositeSerializerError, FallbackScratch, HeapScratch, SharedSerializeMap,
// SharedSerializeMapError,
// },
// AlignedVec,
// };
// #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
// pub struct RkyvCodec;
// impl<
// T: rkyv::Serialize<
// CompositeSerializer<
// AlignedSerializer<AlignedVec>,
// FallbackScratch<HeapScratch<256_usize>, AllocScratch>,
// SharedSerializeMap,
// >,
// >,
// > EncodeMethod<T> for RkyvCodec
// {
// // type Error = CompositeSerializerError<Infallible, AllocScratchError>;
// type Error = CompositeSerializerError<
// std::convert::Infallible,
// AllocScratchError,
// SharedSerializeMapError,
// >;
// fn encode(data: &T) -> Result<Bytes, Self::Error> {
// rkyv::to_bytes::<_, 256>(data).map(|bytes| Bytes::from(bytes.to_vec()))
// }
// }
// impl<T: rkyv::Archive + CheckBytes> DecodeMethod<T> for RkyvCodec {
// type Error = std::convert::Infallible;
// fn decode(bytes: BytesMut) -> Result<T, Self::Error> {
// let archived = rkyv::check_archived_root::<T>(&bytes[..]).unwrap();
// let t: T = archived.deserialize(&mut rkyv::Infallible).unwrap();
// // Ok(t)
// todo!();
// }
// }
// }