Updated everything and moved to hard tab indentation

This commit is contained in:
2025-01-08 19:20:34 +01:00
parent 7cdfe7e3c4
commit 52c8d1c95a
100 changed files with 5949 additions and 5998 deletions

View File

@@ -6,6 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
itertools = "0.13.0"
itertools = "0.14.0"
never = "0.1.0"
ordered-float = "4.2"
ordered-float = "4.6.0"

View File

@@ -13,36 +13,36 @@ use ordered_float::NotNan;
use crate::encode_enum;
pub trait Decode {
/// Decode an instance from the beginning of the buffer. Return the decoded
/// data and the remaining buffer.
fn decode<R: Read + ?Sized>(read: &mut R) -> Self;
/// Decode an instance from the beginning of the buffer. Return the decoded
/// data and the remaining buffer.
fn decode<R: Read + ?Sized>(read: &mut R) -> Self;
}
pub trait Encode {
/// Append an instance of the struct to the buffer
fn encode<W: Write + ?Sized>(&self, write: &mut W);
/// Append an instance of the struct to the buffer
fn encode<W: Write + ?Sized>(&self, write: &mut W);
}
pub trait Coding: Encode + Decode + Clone {
fn get_decoder<T>(map: impl Fn(Self) -> T + 'static) -> impl Fn(&mut dyn Read) -> T {
move |r| map(Self::decode(r))
}
fn get_decoder<T>(map: impl Fn(Self) -> T + 'static) -> impl Fn(&mut dyn Read) -> T {
move |r| map(Self::decode(r))
}
}
impl<T: Encode + Decode + Clone> Coding for T {}
macro_rules! num_impl {
($number:ty) => {
impl Decode for $number {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut bytes = [0u8; (<$number>::BITS / 8) as usize];
read.read_exact(&mut bytes).unwrap();
<$number>::from_be_bytes(bytes)
}
}
impl Encode for $number {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&self.to_be_bytes()).expect("Could not write number")
}
}
};
($number:ty) => {
impl Decode for $number {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut bytes = [0u8; (<$number>::BITS / 8) as usize];
read.read_exact(&mut bytes).unwrap();
<$number>::from_be_bytes(bytes)
}
}
impl Encode for $number {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&self.to_be_bytes()).expect("Could not write number")
}
}
};
}
num_impl!(u128);
num_impl!(u64);
@@ -56,14 +56,14 @@ num_impl!(i16);
num_impl!(i8);
macro_rules! nonzero_impl {
($name:ty) => {
impl Decode for $name {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { Self::new(Decode::decode(read)).unwrap() }
}
impl Encode for $name {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { self.get().encode(write) }
}
};
($name:ty) => {
impl Decode for $name {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { Self::new(Decode::decode(read)).unwrap() }
}
impl Encode for $name {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { self.get().encode(write) }
}
};
}
nonzero_impl!(std::num::NonZeroU8);
@@ -78,111 +78,111 @@ nonzero_impl!(std::num::NonZeroI64);
nonzero_impl!(std::num::NonZeroI128);
impl<T: Encode + ?Sized> Encode for &T {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
}
macro_rules! float_impl {
($t:ty, $size:expr) => {
impl Decode for NotNan<$t> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut bytes = [0u8; $size];
read.read_exact(&mut bytes).unwrap();
NotNan::new(<$t>::from_be_bytes(bytes)).expect("Float was NaN")
}
}
impl Encode for NotNan<$t> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&self.as_ref().to_be_bytes()).expect("Could not write number")
}
}
};
($t:ty, $size:expr) => {
impl Decode for NotNan<$t> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut bytes = [0u8; $size];
read.read_exact(&mut bytes).unwrap();
NotNan::new(<$t>::from_be_bytes(bytes)).expect("Float was NaN")
}
}
impl Encode for NotNan<$t> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&self.as_ref().to_be_bytes()).expect("Could not write number")
}
}
};
}
float_impl!(f64, 8);
float_impl!(f32, 4);
impl Decode for String {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
let mut data = vec![0u8; len];
read.read_exact(&mut data).unwrap();
std::str::from_utf8(&data).expect("String invalid UTF-8").to_owned()
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
let mut data = vec![0u8; len];
read.read_exact(&mut data).unwrap();
std::str::from_utf8(&data).expect("String invalid UTF-8").to_owned()
}
}
impl Encode for String {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
write.write_all(self.as_bytes()).unwrap()
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
write.write_all(self.as_bytes()).unwrap()
}
}
impl Encode for str {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
write.write_all(self.as_bytes()).unwrap()
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
write.write_all(self.as_bytes()).unwrap()
}
}
impl<T: Decode> Decode for Vec<T> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
iter::repeat_with(|| T::decode(read)).take(len).collect()
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
iter::repeat_with(|| T::decode(read)).take(len).collect()
}
}
impl<T: Encode> Encode for Vec<T> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|t| t.encode(write));
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|t| t.encode(write));
}
}
impl<T: Encode> Encode for [T] {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|t| t.encode(write));
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|t| t.encode(write));
}
}
impl<T: Decode> Decode for Option<T> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
match u8::decode(read) {
0 => None,
1 => Some(T::decode(read)),
x => panic!("{x} is not a valid option value"),
}
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
match u8::decode(read) {
0 => None,
1 => Some(T::decode(read)),
x => panic!("{x} is not a valid option value"),
}
}
}
impl<T: Encode> Encode for Option<T> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
let t = if let Some(t) = self { t } else { return 0u8.encode(write) };
1u8.encode(write);
t.encode(write);
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
let t = if let Some(t) = self { t } else { return 0u8.encode(write) };
1u8.encode(write);
t.encode(write);
}
}
impl<T: Decode, E: Decode> Decode for Result<T, E> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
match u8::decode(read) {
0 => Self::Ok(T::decode(read)),
1 => Self::Err(E::decode(read)),
x => panic!("Invalid Result tag {x}"),
}
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
match u8::decode(read) {
0 => Self::Ok(T::decode(read)),
1 => Self::Err(E::decode(read)),
x => panic!("Invalid Result tag {x}"),
}
}
}
impl<T: Encode, E: Encode> Encode for Result<T, E> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
match self {
Ok(t) => encode_enum(write, 0, |w| t.encode(w)),
Err(e) => encode_enum(write, 1, |w| e.encode(w)),
}
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
match self {
Ok(t) => encode_enum(write, 0, |w| t.encode(w)),
Err(e) => encode_enum(write, 1, |w| e.encode(w)),
}
}
}
impl<K: Decode + Eq + Hash, V: Decode> Decode for HashMap<K, V> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
iter::repeat_with(|| <(K, V)>::decode(read)).take(len).collect()
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let len = u64::decode(read).try_into().unwrap();
iter::repeat_with(|| <(K, V)>::decode(read)).take(len).collect()
}
}
impl<K: Encode + Eq + Hash, V: Encode> Encode for HashMap<K, V> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|pair| pair.encode(write));
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
u64::try_from(self.len()).unwrap().encode(write);
self.iter().for_each(|pair| pair.encode(write));
}
}
macro_rules! tuple {
(($($t:ident)*) ($($T:ident)*)) => {
@@ -216,40 +216,40 @@ tuple!((t u v x y z a b c d e f g h i) (T U V X Y Z A B C D E F G H I));
tuple!((t u v x y z a b c d e f g h i j) (T U V X Y Z A B C D E F G H I J)); // 16
impl Decode for () {
fn decode<R: Read + ?Sized>(_: &mut R) -> Self {}
fn decode<R: Read + ?Sized>(_: &mut R) -> Self {}
}
impl Encode for () {
fn encode<W: Write + ?Sized>(&self, _: &mut W) {}
fn encode<W: Write + ?Sized>(&self, _: &mut W) {}
}
impl Decode for Never {
fn decode<R: Read + ?Sized>(_: &mut R) -> Self {
unreachable!("A value of Never cannot exist so it can't have been serialized");
}
fn decode<R: Read + ?Sized>(_: &mut R) -> Self {
unreachable!("A value of Never cannot exist so it can't have been serialized");
}
}
impl Encode for Never {
fn encode<W: Write + ?Sized>(&self, _: &mut W) { match *self {} }
fn encode<W: Write + ?Sized>(&self, _: &mut W) { match *self {} }
}
impl Decode for bool {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut buf = [0];
read.read_exact(&mut buf).unwrap();
buf[0] != 0
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
let mut buf = [0];
read.read_exact(&mut buf).unwrap();
buf[0] != 0
}
}
impl Encode for bool {
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&[if *self { 0xff } else { 0 }]).unwrap()
}
fn encode<W: Write + ?Sized>(&self, write: &mut W) {
write.write_all(&[if *self { 0xff } else { 0 }]).unwrap()
}
}
impl<T: Decode, const N: usize> Decode for [T; N] {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
// TODO: figure out how to do this in safe rust on the stack
((0..N).map(|_| T::decode(read)).collect::<Vec<_>>().try_into())
.unwrap_or_else(|_| unreachable!("The length of this iterator is statically known"))
}
fn decode<R: Read + ?Sized>(read: &mut R) -> Self {
// TODO: figure out how to do this in safe rust on the stack
((0..N).map(|_| T::decode(read)).collect::<Vec<_>>().try_into())
.unwrap_or_else(|_| unreachable!("The length of this iterator is statically known"))
}
}
impl<T: Encode, const N: usize> Encode for [T; N] {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { self.iter().for_each(|t| t.encode(write)) }
fn encode<W: Write + ?Sized>(&self, write: &mut W) { self.iter().for_each(|t| t.encode(write)) }
}
macro_rules! two_end_range {
@@ -271,14 +271,14 @@ two_end_range!(x, Range, .., x.start, x.end);
two_end_range!(x, RangeInclusive, ..=, x.start(), x.end());
macro_rules! smart_ptr {
($name:tt) => {
impl<T: Decode> Decode for $name<T> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { $name::new(T::decode(read)) }
}
impl<T: Encode> Encode for $name<T> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
}
};
($name:tt) => {
impl<T: Decode> Decode for $name<T> {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { $name::new(T::decode(read)) }
}
impl<T: Encode> Encode for $name<T> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
}
};
}
smart_ptr!(Arc);
@@ -288,15 +288,15 @@ smart_ptr!(Box);
impl<T: ?Sized + ToOwned> Decode for Cow<'_, T>
where T::Owned: Decode
{
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { Cow::Owned(T::Owned::decode(read)) }
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { Cow::Owned(T::Owned::decode(read)) }
}
impl<T: ?Sized + Encode + ToOwned> Encode for Cow<'_, T> {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (**self).encode(write) }
}
impl Decode for char {
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { char::from_u32(u32::decode(read)).unwrap() }
fn decode<R: Read + ?Sized>(read: &mut R) -> Self { char::from_u32(u32::decode(read)).unwrap() }
}
impl Encode for char {
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (*self as u32).encode(write) }
fn encode<W: Write + ?Sized>(&self, write: &mut W) { (*self as u32).encode(write) }
}

View File

@@ -5,32 +5,32 @@ use itertools::{Chunk, Itertools};
use crate::Encode;
pub fn encode_enum<W: Write + ?Sized>(write: &mut W, id: u8, f: impl FnOnce(&mut W)) {
id.encode(write);
f(write)
id.encode(write);
f(write)
}
pub fn write_exact<W: Write + ?Sized>(write: &mut W, bytes: &'static [u8]) {
write.write_all(bytes).expect("Failed to write exact bytes")
write.write_all(bytes).expect("Failed to write exact bytes")
}
pub fn print_bytes(b: &[u8]) -> String {
(b.iter().map(|b| format!("{b:02x}")))
.chunks(4)
.into_iter()
.map(|mut c: Chunk<_>| c.join(" "))
.join(" ")
(b.iter().map(|b| format!("{b:02x}")))
.chunks(4)
.into_iter()
.map(|mut c: Chunk<_>| c.join(" "))
.join(" ")
}
pub fn read_exact<R: Read + ?Sized>(read: &mut R, bytes: &'static [u8]) {
let mut data = vec![0u8; bytes.len()];
read.read_exact(&mut data).expect("Failed to read bytes");
if data != bytes {
panic!("Wrong bytes!\nExpected: {}\nFound: {}", print_bytes(bytes), print_bytes(&data));
}
let mut data = vec![0u8; bytes.len()];
read.read_exact(&mut data).expect("Failed to read bytes");
if data != bytes {
panic!("Wrong bytes!\nExpected: {}\nFound: {}", print_bytes(bytes), print_bytes(&data));
}
}
pub fn enc_vec(enc: &impl Encode) -> Vec<u8> {
let mut vec = Vec::new();
enc.encode(&mut vec);
vec
let mut vec = Vec::new();
enc.encode(&mut vec);
vec
}

View File

@@ -11,54 +11,54 @@ impl TLBool for TLFalse {}
/// A type that implements [Hierarchy]. Used to select implementations of traits
/// on the hierarchy
pub trait InHierarchy: Clone {
/// Indicates that this hierarchy element is a leaf. Leaves can never have
/// children
type IsLeaf: TLBool;
/// Indicates that this hierarchy element is a root. Roots can never have
/// parents
type IsRoot: TLBool;
/// Indicates that this hierarchy element is a leaf. Leaves can never have
/// children
type IsLeaf: TLBool;
/// Indicates that this hierarchy element is a root. Roots can never have
/// parents
type IsRoot: TLBool;
}
/// A type that derives from a parent type.
pub trait Extends: InHierarchy<IsRoot = TLFalse> + Into<Self::Parent> {
/// Specify the immediate parent of this type. This guides the
type Parent: InHierarchy<IsLeaf = TLFalse>
+ TryInto<Self>
+ UnderRootImpl<<Self::Parent as InHierarchy>::IsRoot>;
/// Specify the immediate parent of this type. This guides the
type Parent: InHierarchy<IsLeaf = TLFalse>
+ TryInto<Self>
+ UnderRootImpl<<Self::Parent as InHierarchy>::IsRoot>;
}
pub trait UnderRootImpl<IsRoot: TLBool>: Sized {
type __Root: UnderRoot<IsRoot = TLTrue, Root = Self::__Root>;
fn __into_root(self) -> Self::__Root;
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root>;
type __Root: UnderRoot<IsRoot = TLTrue, Root = Self::__Root>;
fn __into_root(self) -> Self::__Root;
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root>;
}
pub trait UnderRoot: InHierarchy {
type Root: UnderRoot<IsRoot = TLTrue, Root = Self::Root>;
fn into_root(self) -> Self::Root;
fn try_from_root(root: Self::Root) -> Result<Self, Self::Root>;
type Root: UnderRoot<IsRoot = TLTrue, Root = Self::Root>;
fn into_root(self) -> Self::Root;
fn try_from_root(root: Self::Root) -> Result<Self, Self::Root>;
}
impl<T: InHierarchy + UnderRootImpl<T::IsRoot>> UnderRoot for T {
type Root = <Self as UnderRootImpl<<Self as InHierarchy>::IsRoot>>::__Root;
fn into_root(self) -> Self::Root { self.__into_root() }
fn try_from_root(root: Self::Root) -> Result<Self, Self::Root> { Self::__try_from_root(root) }
type Root = <Self as UnderRootImpl<<Self as InHierarchy>::IsRoot>>::__Root;
fn into_root(self) -> Self::Root { self.__into_root() }
fn try_from_root(root: Self::Root) -> Result<Self, Self::Root> { Self::__try_from_root(root) }
}
impl<T: InHierarchy<IsRoot = TLTrue>> UnderRootImpl<TLTrue> for T {
type __Root = Self;
fn __into_root(self) -> Self::__Root { self }
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root> { Ok(root) }
type __Root = Self;
fn __into_root(self) -> Self::__Root { self }
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root> { Ok(root) }
}
impl<T: InHierarchy<IsRoot = TLFalse> + Extends> UnderRootImpl<TLFalse> for T {
type __Root = <<Self as Extends>::Parent as UnderRootImpl<
<<Self as Extends>::Parent as InHierarchy>::IsRoot,
>>::__Root;
fn __into_root(self) -> Self::__Root {
<Self as Into<<Self as Extends>::Parent>>::into(self).into_root()
}
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root> {
let parent = <Self as Extends>::Parent::try_from_root(root)?;
parent.clone().try_into().map_err(|_| parent.into_root())
}
type __Root = <<Self as Extends>::Parent as UnderRootImpl<
<<Self as Extends>::Parent as InHierarchy>::IsRoot,
>>::__Root;
fn __into_root(self) -> Self::__Root {
<Self as Into<<Self as Extends>::Parent>>::into(self).into_root()
}
fn __try_from_root(root: Self::__Root) -> Result<Self, Self::__Root> {
let parent = <Self as Extends>::Parent::try_from_root(root)?;
parent.clone().try_into().map_err(|_| parent.into_root())
}
}

View File

@@ -2,20 +2,20 @@ use super::coding::Coding;
use crate::helpers::enc_vec;
pub trait Request: Coding + Sized + Send + 'static {
type Response: Coding + Send + 'static;
type Response: Coding + Send + 'static;
}
pub fn respond<R: Request>(_: &R, rep: R::Response) -> Vec<u8> { enc_vec(&rep) }
pub fn respond_with<R: Request>(r: &R, f: impl FnOnce(&R) -> R::Response) -> Vec<u8> {
respond(r, f(r))
respond(r, f(r))
}
pub trait Channel: 'static {
type Req: Coding + Sized + Send + 'static;
type Notif: Coding + Sized + Send + 'static;
type Req: Coding + Sized + Send + 'static;
type Notif: Coding + Sized + Send + 'static;
}
pub trait MsgSet: Send + Sync + 'static {
type In: Channel;
type Out: Channel;
type In: Channel;
type Out: Channel;
}