initial commit

This commit is contained in:
2024-02-08 17:34:21 +01:00
commit 7a8554d313
8 changed files with 1129 additions and 0 deletions

143
src/ints.rs Normal file
View File

@@ -0,0 +1,143 @@
use bytemuck::{Pod, Zeroable};
use core::fmt::Debug;
use core::marker::PhantomData;
use serde::Serialize;
#[derive(Pod, Zeroable, Clone, Copy, Debug, Serialize)]
#[repr(C, packed)]
pub struct BigEndian;
#[derive(Pod, Zeroable, Clone, Copy, Debug, Serialize)]
#[repr(C, packed)]
pub struct LittleEndian;
pub trait Decode: Copy {
type Native: Debug + Copy;
fn to_native(self) -> Self::Native;
}
#[derive(Pod, Zeroable, Clone, Copy)]
#[repr(C, packed)]
pub struct U64<E> {
raw: [u8; 8],
_endian: PhantomData<E>,
}
#[derive(Pod, Zeroable, Clone, Copy)]
#[repr(C, packed)]
pub struct U32<E> {
raw: [u8; 4],
_endian: PhantomData<E>,
}
#[derive(Pod, Zeroable, Clone, Copy)]
#[repr(C, packed)]
pub struct U16<E> {
raw: [u8; 2],
_endian: PhantomData<E>,
}
impl Decode for U64<BigEndian> {
type Native = u64;
fn to_native(self) -> Self::Native {
u64::from_be_bytes(self.raw)
}
}
impl Decode for U64<LittleEndian> {
type Native = u64;
fn to_native(self) -> Self::Native {
u64::from_le_bytes(self.raw)
}
}
impl Decode for U32<BigEndian> {
type Native = u32;
fn to_native(self) -> Self::Native {
u32::from_be_bytes(self.raw)
}
}
impl Decode for U32<LittleEndian> {
type Native = u32;
fn to_native(self) -> Self::Native {
u32::from_le_bytes(self.raw)
}
}
impl Decode for U16<BigEndian> {
type Native = u16;
fn to_native(self) -> Self::Native {
u16::from_be_bytes(self.raw)
}
}
impl Decode for U16<LittleEndian> {
type Native = u16;
fn to_native(self) -> Self::Native {
u16::from_le_bytes(self.raw)
}
}
impl<E> Debug for U64<E>
where
Self: Decode,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.to_native(), f)
}
}
impl<E> Debug for U32<E>
where
Self: Decode,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.to_native(), f)
}
}
impl<E> Debug for U16<E>
where
Self: Decode,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.to_native(), f)
}
}
impl<E> Serialize for U64<E>
where
Self: Decode,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
format!("{:?}", self.to_native()).serialize(serializer)
}
}
impl<E> Serialize for U32<E>
where
Self: Decode,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
format!("{:?}", self.to_native()).serialize(serializer)
}
}
impl<E> Serialize for U16<E>
where
Self: Decode,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
format!("{:?}", self.to_native()).serialize(serializer)
}
}