diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/checksum/mod.rs | 58 | ||||
-rw-r--r-- | src/deserialise/d_stream/mod.rs | 53 | ||||
-rw-r--r-- | src/deserialise/deserialise/mod.rs | 133 | ||||
-rw-r--r-- | src/deserialise/mod.rs | 8 | ||||
-rw-r--r-- | src/deserialise/test.rs | 65 | ||||
-rw-r--r-- | src/error/mod.rs | 95 | ||||
-rw-r--r-- | src/fixed_string/fixed_string/mod.rs | 180 | ||||
-rw-r--r-- | src/fixed_string/iter/mod.rs | 23 | ||||
-rw-r--r-- | src/fixed_string/mod.rs | 5 | ||||
-rw-r--r-- | src/lib.rs | 16 | ||||
-rw-r--r-- | src/packet/mod.rs | 59 | ||||
-rw-r--r-- | src/serialise/mod.rs | 8 | ||||
-rw-r--r-- | src/serialise/s_stream/mod.rs | 54 | ||||
-rw-r--r-- | src/serialise/serialise/mod.rs | 111 | ||||
-rw-r--r-- | src/serialise/test.rs | 53 |
15 files changed, 921 insertions, 0 deletions
diff --git a/src/checksum/mod.rs b/src/checksum/mod.rs new file mode 100644 index 0000000..1dbf62c --- /dev/null +++ b/src/checksum/mod.rs @@ -0,0 +1,58 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::deserialise::{Deserialise, DStream}; +use crate::serialise::{SStream, Serialise}; + +use sha2::{Digest, Sha256}; +use std::fmt::{Debug, Display, Formatter}; + +#[derive(Clone, Eq, PartialEq)] +#[repr(transparent)] +pub struct Checksum(pub(in super) [u8; 0x20]); + +impl Checksum { + #[must_use] + pub fn new<T: Serialise>(data: &T) -> Self { + let data = SStream::from(data); + + let mut hasher = Sha256::new(); + hasher.update(data); + + Self(hasher.finalize().into()) + } +} + +impl Debug for Checksum { + #[inline(always)] + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { Display::fmt(self, f) } +} + +impl Deserialise for Checksum { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn std::error::Error>> { + let data = Deserialise::deserialise(stream)?; + + Ok(Self(data)) + } +} + +impl Display for Checksum { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + write!(f, + "{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}{:x}", + self.0[0x1F], self.0[0x1E], self.0[0x1D], self.0[0x1C], + self.0[0x1B], self.0[0x1A], self.0[0x19], self.0[0x18], + self.0[0x17], self.0[0x16], self.0[0x15], self.0[0x14], + self.0[0x13], self.0[0x12], self.0[0x11], self.0[0x10], + self.0[0x0F], self.0[0x0E], self.0[0x0D], self.0[0x0C], + self.0[0x0B], self.0[0x0A], self.0[0x09], self.0[0x08], + self.0[0x07], self.0[0x06], self.0[0x05], self.0[0x04], + self.0[0x03], self.0[0x02], self.0[0x01], self.0[0x00], + ) + } +} + +impl Serialise for Checksum { + fn serialise(&self, stream: &mut SStream) { + self.0.serialise(stream); + } +} diff --git a/src/deserialise/d_stream/mod.rs b/src/deserialise/d_stream/mod.rs new file mode 100644 index 0000000..05ed6a2 --- /dev/null +++ b/src/deserialise/d_stream/mod.rs @@ -0,0 +1,53 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::error::{Error, Result}; + +use std::fmt::{Debug, Formatter}; + +#[derive(Clone)] +pub struct DStream<'a> { + data: &'a [u8], + len: usize, +} + +impl DStream<'_> { + pub fn take(&mut self, len: usize) -> Result<&[u8]> { + if self.len < len { return Err(Error::EndOfDStream { len: self.len, ok_len: len } ) } + + let start = self.data.len() - self.len; + let stop = start + len; + + self.len -= len; + + Ok(&self.data[start..stop]) + } +} + +impl Debug for DStream<'_> { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + let stop = self.data.len(); + let start = self.data.len() - self.len; + + write!(f, "[")?; + + for v in &self.data[start..stop] { write!(f, "{v:#02X},")? }; + + write!(f, "]")?; + + Ok(()) + } +} + +impl<'a> From<&'a [u8]> for DStream<'a> { + fn from(value: &'a [u8]) -> Self { Self { + data: value, + len: value.len(), + } } +} + +impl<'a, const N: usize> From<&'a [u8; N]> for DStream<'a> { + fn from(value: &'a [u8; N]) -> Self { Self { + data: value, + len: N, + } } +} diff --git a/src/deserialise/deserialise/mod.rs b/src/deserialise/deserialise/mod.rs new file mode 100644 index 0000000..a51ec18 --- /dev/null +++ b/src/deserialise/deserialise/mod.rs @@ -0,0 +1,133 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::deserialise::DStream; +use crate::error::Error; + +use std::convert::Infallible; +use std::error::Error as StdError; +use std::mem::size_of; +use std::num::NonZero; + +pub trait Deserialise: Sized { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>>; +} + +macro_rules! impl_float { + ($type:ty) => { + impl Deserialise for $type { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let data = stream + .take(size_of::<Self>())? + .try_into() + .unwrap(); + + Ok(Self::from_be_bytes(data)) + } + } + }; +} + +macro_rules! impl_int { + ($type:ty) => { + impl Deserialise for $type { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let data = stream + .take(size_of::<Self>())? + .try_into() + .unwrap(); + + Ok(Self::from_be_bytes(data)) + } + } + + impl Deserialise for NonZero<$type> { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + Ok(Option::<Self>::deserialise(stream)? + .ok_or(Error::NullInteger)?) + } + } + }; +} + +impl<T: Deserialise, const N: usize> Deserialise for [T; N] { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let len = usize::try_from(u64::deserialise(stream)?).unwrap(); + if len != N { return Err(Box::new(Error::ArrayLengthMismatch { len, ok_len: N })) }; + + let mut buf = Vec::with_capacity(len); + for _ in 0x0..len { buf.push(Deserialise::deserialise(stream)?); } + + // If we had used the checked unwrap, we would also + // have to require `T: Debug`. + Ok(unsafe { buf.try_into().unwrap_unchecked() }) + } +} + +impl Deserialise for () { + fn deserialise(_stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { Ok(()) } +} + +impl Deserialise for bool { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let value = u8::deserialise(stream)?; + + match value { + 0x00 => Ok(false), + 0x01 => Ok(true), + _ => Err(Box::new(Error::InvalidBoolean { value })) + } + } +} + +impl Deserialise for char { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let value = u32::deserialise(stream)?; + + Self::from_u32(value) + .ok_or(Box::new(Error::InvalidCodePoint { value })) + } +} + +impl Deserialise for Infallible { + fn deserialise(_stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { unreachable!() } +} + +impl<T: Deserialise> Deserialise for Option<T> { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let sign = bool::deserialise(stream)?; + + if sign { + Ok(Some(T::deserialise(stream)?)) + } else { + Ok(None) + } + } +} + +impl<T: Deserialise, E: Deserialise> Deserialise for Result<T, E> { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn StdError>> { + let sign = bool::deserialise(stream)?; + + let value = if sign { + Err(E::deserialise(stream)?) + } else { + Ok(T::deserialise(stream)?) + }; + + Ok(value) + } +} + +impl_float!(f32); +impl_float!(f64); + +impl_int!(i128); +impl_int!(i16); +impl_int!(i32); +impl_int!(i64); +impl_int!(i8); +impl_int!(u128); +impl_int!(u16); +impl_int!(u32); +impl_int!(u64); +impl_int!(u8); diff --git a/src/deserialise/mod.rs b/src/deserialise/mod.rs new file mode 100644 index 0000000..17b102c --- /dev/null +++ b/src/deserialise/mod.rs @@ -0,0 +1,8 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::use_mod; +use_mod!(pub d_stream); +use_mod!(pub deserialise); + +#[cfg(test)] +mod test; diff --git a/src/deserialise/test.rs b/src/deserialise/test.rs new file mode 100644 index 0000000..38ad694 --- /dev/null +++ b/src/deserialise/test.rs @@ -0,0 +1,65 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::deserialise::{Deserialise, DStream}; +use crate::fixed_string::FixedString; + +#[test] +fn test_serialise() { + let data = [ + 0x00, 0xFF, 0xFF, 0x0F, 0xEF, 0x1F, 0xDF, 0x2F, + 0xCF, 0x3F, 0xBF, 0x4F, 0xAF, 0x5F, 0x9F, 0x6F, + 0x8F, 0x7F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x09, 0x6D, 0xC3, 0xA1, 0x6E, 0x61, 0xC3, + 0xB0, 0x75, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x05, 0x00, 0x00, 0x03, 0xBB, 0x00, + 0x00, 0x03, 0x91, 0x00, 0x00, 0x03, 0xBC, 0x00, + 0x00, 0x03, 0x94, 0x00, 0x00, 0x03, 0xB1, 0x01, + 0x00, 0x00, 0x01, 0x80, + ]; + + let mut stream = DStream::from(&data); + + assert_eq!( + u8::deserialise(&mut stream).unwrap(), + 0x00, + ); + assert_eq!( + u8::deserialise(&mut stream).unwrap(), + 0xFF, + ); + + assert_eq!( + u128::deserialise(&mut stream).unwrap(), + 0xFF_0F_EF_1F_DF_2F_CF_3F_BF_4F_AF_5F_9F_6F_8F_7F, + ); + + assert_eq!( + FixedString::<0x10>::deserialise(&mut stream).unwrap(), + "m\u{00E1}na\u{00F0}ur", + ); + + assert_eq!( + <[char; 0x5]>::deserialise(&mut stream).unwrap(), + ['\u{03BB}', '\u{0391}', '\u{03BC}', '\u{0394}', '\u{03B1}'], + ); + + assert_eq!( + Option::<()>::deserialise(&mut stream).unwrap(), + Some(()), + ); + + assert_eq!( + Option::<()>::deserialise(&mut stream).unwrap(), + None, + ); + + assert_eq!( + Result::<(), i8>::deserialise(&mut stream).unwrap(), + Ok(()), + ); + + assert_eq!( + Result::<(), i8>::deserialise(&mut stream).unwrap(), + Err(i8::MIN), + ); +} diff --git a/src/error/mod.rs b/src/error/mod.rs new file mode 100644 index 0000000..4582394 --- /dev/null +++ b/src/error/mod.rs @@ -0,0 +1,95 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::checksum::Checksum; + +use std::error::Error as StdError; +use std::fmt::{Display, Formatter}; +use std::process::{ExitCode, Termination}; + +pub type Result<T> = std::result::Result<T, Error>; + +#[derive(Debug)] +pub enum Error { + ArrayLengthMismatch { len: usize, ok_len: usize }, + + DeserialiseFailure { source: Box<dyn StdError> }, + + EndOfDStream { len: usize, ok_len: usize }, + + InvalidBoolean { value: u8 }, + + InvalidCodePoint { value: u32 }, + + FixedStringTooShort { len: usize, s: String }, + + InvalidPackageLength { len: usize, ok_len: usize }, + + NullInteger, + + PackageChecksumMismatch { sum: Checksum, ok_sum: Checksum }, +} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + use Error::*; + + match *self { + ArrayLengthMismatch { len, ok_len } => { + write!(f, "expected array of length ({ok_len}) but got ({len}) elements") + }, + + DeserialiseFailure { ref source } => { + write!(f, "unable to deserialise: \"{source}\"") + }, + + EndOfDStream { len, ok_len } => { + write!(f, "({ok_len}) byte(s) were requested but only ({len}) byte(s) were left") + }, + + FixedStringTooShort { len, ref s } => { + write!(f, "fixed string with `N = {len}` cannot hold {s:?}") + }, + + InvalidBoolean { value } => { + write!(f, "expected boolean but got {value:#02X}") + }, + + InvalidCodePoint { value } => { + write!(f, "code point U+{value:04X} is not valid") + } + + InvalidPackageLength { len, ok_len } => { + write!(f, "invalid packet length: expected at most ({ok_len}) byte(s) but got ({len}) byte(s)") + }, + + NullInteger => { + write!(f, "expected non-zero integer but got (0)") + }, + + PackageChecksumMismatch { ref sum, ref ok_sum } => { + write!(f, "expected packet checksum {ok_sum} but got {sum}") + }, + } + } +} + +impl StdError for Error { + fn source(&self) -> Option<&(dyn StdError + 'static)> { + use Error::*; + + match *self { + DeserialiseFailure { ref source } => Some(source.as_ref()), + + _ => None, + } + } +} + +impl From<Error> for i32 { + fn from(_: Error) -> Self { 0x1 } +} + +impl Termination for Error { + #[inline(always)] + fn report(self) -> ExitCode { ExitCode::FAILURE } +} diff --git a/src/fixed_string/fixed_string/mod.rs b/src/fixed_string/fixed_string/mod.rs new file mode 100644 index 0000000..dc347f3 --- /dev/null +++ b/src/fixed_string/fixed_string/mod.rs @@ -0,0 +1,180 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::deserialise::{Deserialise, DStream}; +use crate::error::Error; +use crate::fixed_string::Iter; +use crate::serialise::{SStream, Serialise}; + +use std::fmt::{Display, Debug, Formatter}; +use std::str::FromStr; + +#[derive(Clone)] +pub struct FixedString<const N: usize> { + pub(in super) buf: [char; N], + pub(in super) len: usize, +} + +impl<const N: usize> FixedString<N> { + pub fn new(s: &str) -> Result<Self, Error> { + let mut buf = ['\0'; N]; + let len = s.chars().count(); + + for (i, c) in s.chars().enumerate() { + if i >= N { return Err(Error::FixedStringTooShort { len: N, s: s.to_owned() }) } + + buf[i] = c; + } + + Ok(Self { buf, len }) + } + + #[inline(always)] + #[must_use] + pub const fn len(&self) -> usize { self.len } + + #[inline(always)] + #[must_use] + pub const fn is_empty(&self) -> bool { self.len == 0x0 } + + #[inline] + pub fn iter(&self) -> std::slice::Iter<'_, char> { self.buf[0x0..self.len].iter() } + + #[inline] + pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, char> { self.buf[0x0..self.len].iter_mut() } +} + +impl<const N: usize> Debug for FixedString<N> { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + write!(f, "\"")?; + + for c in self { + if c.is_ascii_graphic() { + write!(f, "{c}")?; + } else if *c == '\0' { + write!(f, "\\0")?; + } else { + write!(f, "{c}")?; + } + } + + write!(f, "\"")?; + + Ok(()) + } +} + +impl<const N: usize> Deserialise for FixedString<N> { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn std::error::Error>> { + let len = usize::try_from(u64::deserialise(stream)?).unwrap(); + + let data = stream.take(len)?; + let s = std::str::from_utf8(data)?; + + let len = s.chars().count(); + if len > N { + return Err(Box::new(Error::FixedStringTooShort { len, s: s.to_owned() })); + } + + let mut buf = ['\0'; N]; + for (i, c) in s.chars().enumerate() { + buf[i] = c; + } + + Ok(Self { buf, len }) + } +} + +impl<const N: usize> Default for FixedString<N> { + #[inline(always)] + fn default() -> Self { Self { + buf: ['\0'; N], + len: 0x0, + } } +} + +impl<const N: usize> Display for FixedString<N> { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + for c in self { write!(f, "{c}")? } + + Ok(()) + } +} + +impl<const N: usize> Eq for FixedString<N> { } + +impl<const N: usize> FromStr for FixedString<N> { + type Err = Error; + + fn from_str(s: &str) -> Result<Self, Error> { Self::new(s) } +} + +impl<const N: usize> IntoIterator for FixedString<N> { + type Item = char; + + type IntoIter = Iter<N>; + + fn into_iter(self) -> Self::IntoIter { + Iter { + buf: self.buf, + len: self.len, + + pos: Some(0x0), + } + } +} + +impl<'a, const N: usize> IntoIterator for &'a FixedString<N> { + type Item = &'a char; + + type IntoIter = std::slice::Iter<'a, char>; + + fn into_iter(self) -> Self::IntoIter { self.iter() } +} + +impl<'a, const N: usize> IntoIterator for &'a mut FixedString<N> { + type Item = &'a mut char; + + type IntoIter = std::slice::IterMut<'a, char>; + + fn into_iter(self) -> Self::IntoIter { self.iter_mut() } +} + +impl<const N: usize> PartialEq for FixedString<N> { + fn eq(&self, other: &Self) -> bool { + if self.len() != other.len() { return false }; + + for i in 0x0..self.len() { + if self.buf[i] != other.buf[i] { return false }; + } + + true + } +} + +impl<const N: usize> PartialEq<&str> for FixedString<N> { + fn eq(&self, other: &&str) -> bool { + for (i, c) in other.chars().enumerate() { + if self.buf.get(i) != Some(&c) { return false }; + } + + true + } +} + +impl<const N: usize> Serialise for FixedString<N> { + fn serialise(&self, stream: &mut SStream) { + let s: String = self.iter().collect(); + + let len = u64::try_from(s.len()).unwrap(); + + stream.append(&len.to_be_bytes()); + stream.append(&s.into_bytes()); + } +} + +impl<const N: usize> TryFrom<&str> for FixedString<N> { + type Error = Error; + + #[inline(always)] + fn try_from(value: &str) -> Result<Self, Self::Error> { Self::new(value) } +} diff --git a/src/fixed_string/iter/mod.rs b/src/fixed_string/iter/mod.rs new file mode 100644 index 0000000..12de225 --- /dev/null +++ b/src/fixed_string/iter/mod.rs @@ -0,0 +1,23 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +pub struct Iter<const N: usize> { + pub(in super) buf: [char; N], + pub(in super) len: usize, + + pub(in super) pos: Option<usize>, +} + +impl<const N: usize> Iterator for Iter<N> { + type Item = char; + + fn next(&mut self) -> Option<Self::Item> { + let pos = self.pos.as_mut()?; + + if *pos >= self.len { return None }; + + let item = self.buf[*pos]; + *pos += 0x1; + + Some(item) + } +} diff --git a/src/fixed_string/mod.rs b/src/fixed_string/mod.rs new file mode 100644 index 0000000..2ed072e --- /dev/null +++ b/src/fixed_string/mod.rs @@ -0,0 +1,5 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::use_mod; +use_mod!(pub fixed_string); +use_mod!(pub iter); diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..1120945 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,16 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +pub mod checksum; +pub mod deserialise; +pub mod error; +pub mod fixed_string; +pub mod packet; +pub mod serialise; + +macro_rules! use_mod { + ($vis:vis $name:ident) => { + mod $name; + $vis use $name::*; + }; +} +pub(in crate) use use_mod; diff --git a/src/packet/mod.rs b/src/packet/mod.rs new file mode 100644 index 0000000..b918dc2 --- /dev/null +++ b/src/packet/mod.rs @@ -0,0 +1,59 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::checksum::Checksum; +use crate::deserialise::{Deserialise, DStream}; +use crate::error::Error; +use crate::serialise::{SStream, Serialise}; + +use std::mem::size_of; + +#[derive(Clone, Debug)] +pub struct Packet<T: Deserialise + Serialise> { + message: T, + checksum: Checksum, +} + +impl<T: Deserialise + Serialise> Packet<T> { + #[must_use] + pub fn encode(message: T) -> Box<[u8]> { + let checksum = Checksum::new(&message); + let packet = Self { message, checksum }; + + SStream::from(&packet).into() + } + + pub fn decode(data: &[u8]) -> Result<T, Error> { + if data.len() > size_of::<Self>() { + return Err(Error::InvalidPackageLength { len: data.len(), ok_len: size_of::<Self>() }); + } + + let mut data = DStream::from(data); + + let packet = Self::deserialise(&mut data) + .map_err(|e| Error::DeserialiseFailure { source: e })?; + + let checksum = Checksum::new(&packet.message); + + if packet.checksum != checksum { + return Err(Error::PackageChecksumMismatch { sum: packet.checksum, ok_sum: checksum }); + } + + Ok(packet.message) + } +} + +impl<T: Deserialise + Serialise> Deserialise for Packet<T> { + fn deserialise(stream: &mut DStream) -> Result<Self, Box<dyn std::error::Error>> { + Ok(Self { + message: Deserialise::deserialise(stream)?, + checksum: Deserialise::deserialise(stream)?, + }) + } +} + +impl<T: Deserialise + Serialise> Serialise for Packet<T> { + fn serialise(&self, stream: &mut SStream) { + self.message.serialise(stream); + self.checksum.serialise(stream); + } +} diff --git a/src/serialise/mod.rs b/src/serialise/mod.rs new file mode 100644 index 0000000..9b87751 --- /dev/null +++ b/src/serialise/mod.rs @@ -0,0 +1,8 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::use_mod; +use_mod!(pub s_stream); +use_mod!(pub serialise); + +#[cfg(test)] +mod test; diff --git a/src/serialise/s_stream/mod.rs b/src/serialise/s_stream/mod.rs new file mode 100644 index 0000000..a1ae05c --- /dev/null +++ b/src/serialise/s_stream/mod.rs @@ -0,0 +1,54 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::serialise::Serialise; + +use std::fmt::{Debug, Formatter}; +use std::mem::size_of; + +#[derive(Clone, Eq, PartialEq)] +pub struct SStream(Vec<u8>); + +impl SStream { + #[must_use] + pub const fn new() -> Self { Self(Vec::new()) } + + pub fn append(&mut self, extra: &[u8]) { + self.0.extend(extra); + } +} + +impl AsRef<[u8]> for SStream { + #[inline(always)] + fn as_ref(&self) -> &[u8] { self.0.as_ref() } +} + +impl Debug for SStream { + fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { + write!(f, "[")?; + + for v in &self.0 { write!(f, "{v:#02X},")? }; + + write!(f, "]")?; + + Ok(()) + } +} + +impl Default for SStream { + #[inline(always)] + fn default() -> Self { Self::new() } +} + +impl<T: Serialise> From<&T> for SStream { + fn from(value: &T) -> Self { + let mut stream = Self(Vec::with_capacity(size_of::<T>())); + value.serialise(&mut stream); + + stream + } +} + +impl From<SStream> for Box<[u8]> { + #[inline(always)] + fn from(value: SStream) -> Self { value.0.into_boxed_slice() } +} diff --git a/src/serialise/serialise/mod.rs b/src/serialise/serialise/mod.rs new file mode 100644 index 0000000..febeee7 --- /dev/null +++ b/src/serialise/serialise/mod.rs @@ -0,0 +1,111 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::serialise::SStream; + +use std::convert::Infallible; +use std::mem::size_of; +use std::num::NonZero; + +pub trait Serialise: Sized { + fn serialise(&self, stream: &mut SStream); +} + +macro_rules! impl_float { + ($type:ty) => { + impl Serialise for $type { + fn serialise(&self, stream: &mut SStream) { + stream.append(&self.to_be_bytes()) + } + } + }; +} + +macro_rules! impl_int { + ($type:ty) => { + impl Serialise for $type { + fn serialise(&self, stream: &mut SStream) { + stream.append(&self.to_be_bytes()) + } + } + + impl Serialise for NonZero<$type> { + fn serialise(&self, stream: &mut SStream) { + self.get().serialise(stream) + } + } + }; +} + +impl<T: Serialise, const N: usize> Serialise for [T; N] { + fn serialise(&self, stream: &mut SStream) { + u64::try_from(self.len()).unwrap().serialise(stream); + + for v in self { v.serialise(stream) } + } +} + +impl Serialise for () { + fn serialise(&self, _stream: &mut SStream) { } +} + +impl Serialise for bool { + fn serialise(&self, stream: &mut SStream) { + u8::from(*self).serialise(stream) + } +} + +impl Serialise for char { + fn serialise(&self, stream: &mut SStream) { + u32::from(*self).serialise(stream) + } +} + +impl Serialise for Infallible { + fn serialise(&self, _stream: &mut SStream) { unreachable!() } +} + +impl<T: Serialise> Serialise for Option<T> { + fn serialise(&self, stream: &mut SStream) { + match *self { + None => { + stream.append(&[0x00]); + stream.append(&vec![0x00; size_of::<T>()]); + }, + + Some(ref v) => { + stream.append(&[0x01]); + v.serialise(stream); + }, + }; + } +} + +impl<T: Serialise, E: Serialise> Serialise for Result<T, E> { + fn serialise(&self, stream: &mut SStream) { + match *self { + Ok(ref v) => { + stream.append(&[0x00]); + v.serialise(stream); + }, + + Err(ref e) => { + stream.append(&[0x01]); + e.serialise(stream); + }, + }; + } +} + +impl_float!(f32); +impl_float!(f64); + +impl_int!(i128); +impl_int!(i16); +impl_int!(i32); +impl_int!(i64); +impl_int!(i8); +impl_int!(u128); +impl_int!(u16); +impl_int!(u32); +impl_int!(u64); +impl_int!(u8); diff --git a/src/serialise/test.rs b/src/serialise/test.rs new file mode 100644 index 0000000..5c224bc --- /dev/null +++ b/src/serialise/test.rs @@ -0,0 +1,53 @@ +// Copyright 2022-2024 Gabriel Bjørnager Jensen. + +use crate::serialise::{SStream, Serialise}; +use crate::fixed_string::FixedString; + +#[test] +fn test_serialise() { + let mut stream = SStream::new(); + + 0x00_u8.serialise(&mut stream); + 0xFF_u8.serialise(&mut stream); + 0x7F_u8.serialise(&mut stream); + + 0x0F_7E_u16.serialise(&mut stream); + + 0x00_2F_87_E7_u32.serialise(&mut stream); + + 0xF3_37_CF_8B_DB_03_2B_39_u64.serialise(&mut stream); + + 0x45_A0_15_6A_36_77_17_8A_83_2E_3C_2C_84_10_58_1A_u128.serialise(&mut stream); + + FixedString::<0x1>::new("A").unwrap().serialise(&mut stream); + FixedString::<0x8>::new("l\u{00F8}gma\u{00F0}ur").unwrap().serialise(&mut stream); + + ['\u{03B4}', '\u{0190}', '\u{03BB}', '\u{03A4}', '\u{03B1}'].serialise(&mut stream); + + Result::<u16, char>::Ok(0x45_45).serialise(&mut stream); + Result::<u16, char>::Err(char::REPLACEMENT_CHARACTER).serialise(&mut stream); + + Option::<()>::None.serialise(&mut stream); + Option::<()>::Some(()).serialise(&mut stream); + + let data: Box<[u8]> = stream.into(); + + assert_eq!( + data.as_ref(), + [ + 0x00, 0xFF, 0x7F, 0x0F, 0x7E, 0x00, 0x2F, 0x87, + 0xE7, 0xF3, 0x37, 0xCF, 0x8B, 0xDB, 0x03, 0x2B, + 0x39, 0x45, 0xA0, 0x15, 0x6A, 0x36, 0x77, 0x17, + 0x8A, 0x83, 0x2E, 0x3C, 0x2C, 0x84, 0x10, 0x58, + 0x1A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x01, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x0A, 0x6C, 0xC3, 0xB8, 0x67, 0x6D, 0x61, + 0xC3, 0xB0, 0x75, 0x72, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x03, 0xB4, + 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x03, 0xBB, + 0x00, 0x00, 0x03, 0xA4, 0x00, 0x00, 0x03, 0xB1, + 0x00, 0x45, 0x45, 0x01, 0x00, 0x00, 0xFF, 0xFD, + 0x00, 0x01, + ] + ); +} |