pub unsafe trait PlainOldData: Copy + Sized {
const BYTE_SIZE: usize = core::mem::size_of::<Self>();
#[inline]
fn zeroed() -> Self {
unsafe { core::mem::zeroed() }
}
#[inline]
fn as_bytes_mut(&mut self) -> &mut [u8] {
unsafe {
core::slice::from_raw_parts_mut(
core::ptr::from_mut(self) as *mut u8,
core::mem::size_of::<Self>(),
)
}
}
#[inline]
fn as_bytes(&self) -> &[u8] {
unsafe {
core::slice::from_raw_parts(
core::ptr::from_ref(self) as *const u8,
core::mem::size_of::<Self>(),
)
}
}
}
unsafe impl<T: PlainOldData, const N: usize> PlainOldData for [T; N] {}
pub unsafe trait ByteArray: Copy {
const BYTE_SIZE: usize;
}
unsafe impl<const N: usize> ByteArray for [u8; N] {
const BYTE_SIZE: usize = N;
}
pub trait ToByteArray: Sized {
type ByteArray: ByteArray;
const BYTE_SIZE: usize = Self::ByteArray::BYTE_SIZE;
#[allow(clippy::wrong_self_convention)]
fn to_byte_array(&self) -> Self::ByteArray;
}
pub trait FromByteArray: ToByteArray {
fn from_byte_array(byte_array: Self::ByteArray) -> Self;
}
pub trait TryFromByteArray: ToByteArray {
fn try_from_byte_array(byte_array: Self::ByteArray) -> Result<Self, DecodeError>;
}
impl<T: FromByteArray> TryFromByteArray for T {
fn try_from_byte_array(byte_array: Self::ByteArray) -> Result<Self, DecodeError> {
Ok(Self::from_byte_array(byte_array))
}
}
macro_rules! unsafe_impl_plain_old_data {
($($ty:ty),+) => {
$(
unsafe impl PlainOldData for $ty {}
)+
};
}
macro_rules! impl_byte_array {
($($ty:ty),+) => {
$(
impl ToByteArray for $ty
where $ty : PlainOldData
{
type ByteArray = [u8; ::core::mem::size_of::<Self>()];
fn to_byte_array(&self) -> Self::ByteArray {
#[allow(unnecessary_transmutes)]
unsafe { ::core::mem::transmute(*self) }
}
}
impl FromByteArray for $ty
where $ty : PlainOldData
{
fn from_byte_array(byte_array: Self::ByteArray) -> Self {
#[allow(unnecessary_transmutes)]
unsafe { ::core::mem::transmute(byte_array) }
}
}
)+
};
}
pub(crate) use impl_byte_array;
unsafe_impl_plain_old_data!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, f32, f64);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum DecodeError {
InvalidDiscriminant { raw: u64, type_name: &'static str },
InvalidBool(u8),
InvalidChar(u32),
InvalidTag { raw: u8, type_name: &'static str },
InvalidUtf8,
InvalidCString,
InvalidZero,
InvalidNaN,
CapacityExceeded {
len: u64,
capacity: usize,
type_name: &'static str,
},
}
impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
DecodeError::InvalidDiscriminant { raw, type_name } => {
write!(f, "invalid discriminant {raw} for type {type_name}")
}
DecodeError::InvalidBool(v) => write!(f, "invalid value {v} for bool"),
DecodeError::InvalidChar(v) => write!(f, "invalid value {v} for char"),
DecodeError::InvalidTag { raw, type_name } => {
write!(f, "invalid tag {raw} for {type_name}")
}
DecodeError::InvalidUtf8 => write!(f, "invalid UTF-8"),
DecodeError::InvalidCString => write!(f, "invalid CString: interior null byte"),
DecodeError::InvalidZero => write!(f, "invalid value: zero not allowed"),
DecodeError::InvalidNaN => write!(f, "invalid value: NaN not allowed"),
DecodeError::CapacityExceeded {
len,
capacity,
type_name,
} => write!(
f,
"capacity exceeded for {type_name}: got {len} elements, capacity is {capacity}"
),
}
}
}
impl core::error::Error for DecodeError {}
#[diagnostic::on_unimplemented(
message = "`{Self}` has no fixed-size wire representation",
label = "`{Self}` can't be used in a fixed-size #[derive(Byteable)] struct",
note = "if `{Self}` is variable-length (String, Vec<T>, HashMap<K, V>, ...), add \
`#[byteable(io_only)]` to the struct that uses it",
note = "if `{Self}` is a type you control and should be fixed-size, derive `Byteable` for it"
)]
pub trait RawRepr: Sized {
type Raw: PlainOldData;
fn to_raw(&self) -> Self::Raw;
}
impl<T: RawRepr, const N: usize> RawRepr for [T; N] {
type Raw = [T::Raw; N];
fn to_raw(&self) -> Self::Raw {
self.each_ref().map(|e| e.to_raw())
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` has no fixed-size wire representation",
label = "`{Self}` can't be used in a fixed-size #[derive(Byteable)] struct",
note = "if `{Self}` is variable-length (String, Vec<T>, HashMap<K, V>, ...), add \
`#[byteable(io_only)]` to the struct that uses it",
note = "if `{Self}` is a type you control and should be fixed-size, derive `Byteable` for it"
)]
pub trait FromRawRepr: RawRepr {
fn from_raw(raw: Self::Raw) -> Self;
}
impl<T: FromRawRepr, const N: usize> FromRawRepr for [T; N] {
fn from_raw(raw: Self::Raw) -> Self {
raw.map(|el| T::from_raw(el))
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` has no fixed-size wire representation",
label = "`{Self}` can't be used in a fixed-size #[derive(Byteable)] struct",
note = "if `{Self}` is variable-length (String, Vec<T>, HashMap<K, V>, ...), add \
`#[byteable(io_only)]` to the struct that uses it",
note = "if `{Self}` is a type you control and should be fixed-size, derive `Byteable` for it"
)]
pub trait TryFromRawRepr: RawRepr {
fn try_from_raw(raw: Self::Raw) -> Result<Self, DecodeError>;
}
impl<T: TryFromRawRepr, const N: usize> TryFromRawRepr for [T; N] {
fn try_from_raw(raw: Self::Raw) -> Result<Self, DecodeError> {
use core::mem::MaybeUninit;
let mut out: [MaybeUninit<T>; N] = [const { MaybeUninit::uninit() }; N];
let mut initialized = 0usize;
for (slot, el) in out.iter_mut().zip(raw) {
match T::try_from_raw(el) {
Ok(v) => {
slot.write(v);
initialized += 1;
}
Err(e) => {
for s in &mut out[..initialized] {
unsafe { s.assume_init_drop() };
}
return Err(e);
}
}
}
Ok(out.map(|e| unsafe { e.assume_init() }))
}
}
pub unsafe trait EndianConvert: PlainOldData {
fn from_le(value: Self) -> Self;
fn from_be(value: Self) -> Self;
fn to_le(self) -> Self;
fn to_be(self) -> Self;
}
macro_rules! impl_endian_convert {
($($type:ty),+) => {
$(
unsafe impl EndianConvert for $type {
#[inline]
fn from_le(value: Self) -> Self {
<$type>::from_le(value)
}
#[inline]
fn from_be(value: Self) -> Self {
<$type>::from_be(value)
}
#[inline]
fn to_le(self) -> Self {
<$type>::to_le(self)
}
#[inline]
fn to_be(self) -> Self {
<$type>::to_be(self)
}
}
)+
};
}
impl_endian_convert!(u16, u32, u64, u128, i16, i32, i64, i128);
macro_rules! impl_endian_convert_float {
($($type:ty => $base:ty),+) => {
$(
unsafe impl EndianConvert for $type {
#[inline]
fn from_le(value: Self) -> Self {
Self::from_bits(<$base>::from_le(value.to_bits()))
}
#[inline]
fn from_be(value: Self) -> Self {
Self::from_bits(<$base>::from_be(value.to_bits()))
}
#[inline]
fn to_le(self) -> Self {
Self::from_bits(self.to_bits().to_le())
}
#[inline]
fn to_be(self) -> Self {
Self::from_bits(self.to_bits().to_be())
}
}
)+
};
}
impl_endian_convert_float!(f32 => u32, f64 => u64);
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct BigEndian<T: EndianConvert>(T);
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct LittleEndian<T: EndianConvert>(T);
macro_rules! impl_endian_wrapper {
($name:ident, $to_fn:ident, $from_fn:ident) => {
impl<T: EndianConvert> $name<T> {
#[inline]
pub fn new(value: T) -> Self {
Self(value.$to_fn())
}
#[inline]
pub fn get(self) -> T {
T::$from_fn(self.0)
}
}
impl<T: core::fmt::Debug + EndianConvert> core::fmt::Debug for $name<T> {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple(stringify!($name)).field(&self.get()).finish()
}
}
#[cfg(feature = "defmt")]
impl<T: defmt::Format + EndianConvert> defmt::Format for $name<T> {
#[inline]
fn format(&self, fmt: defmt::Formatter) {
defmt::write!(fmt, "{}({})", stringify!($name), self.get())
}
}
impl<T: PartialEq + EndianConvert> PartialEq for $name<T> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.get() == other.get()
}
}
impl<T: Eq + EndianConvert> Eq for $name<T> {}
impl<T: PartialOrd + EndianConvert> PartialOrd for $name<T> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
self.get().partial_cmp(&other.get())
}
}
impl<T: Ord + EndianConvert> Ord for $name<T> {
#[inline]
fn cmp(&self, other: &Self) -> core::cmp::Ordering {
self.get().cmp(&other.get())
}
}
impl<T: core::hash::Hash + EndianConvert> core::hash::Hash for $name<T> {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.get().hash(state);
}
}
impl<T: EndianConvert + Default> Default for $name<T> {
#[inline]
fn default() -> Self {
Self::new(T::default())
}
}
impl<T: EndianConvert> From<T> for $name<T> {
fn from(value: T) -> Self {
Self::new(value)
}
}
impl<T: EndianConvert> RawRepr for $name<T> {
type Raw = Self;
fn to_raw(&self) -> Self::Raw {
*self
}
}
impl<T: EndianConvert> FromRawRepr for $name<T> {
fn from_raw(raw: Self::Raw) -> Self {
raw
}
}
impl<T: EndianConvert> TryFromRawRepr for $name<T> {
fn try_from_raw(raw: Self::Raw) -> Result<Self, DecodeError> {
Ok(Self::from_raw(raw))
}
}
};
}
impl_endian_wrapper!(BigEndian, to_be, from_be);
impl_endian_wrapper!(LittleEndian, to_le, from_le);
macro_rules! impl_from_endian_for_primitive {
($($ty:ty),+) => {
$(
impl From<BigEndian<$ty>> for $ty {
#[inline]
fn from(v: BigEndian<$ty>) -> $ty { v.get() }
}
impl From<LittleEndian<$ty>> for $ty {
#[inline]
fn from(v: LittleEndian<$ty>) -> $ty { v.get() }
}
)+
};
}
unsafe impl<T: EndianConvert + PlainOldData> PlainOldData for BigEndian<T> {}
unsafe impl<T: EndianConvert + PlainOldData> PlainOldData for LittleEndian<T> {}
macro_rules! impl_byte_array_endian {
($($type:ty),+) => {
$(
impl_byte_array!(LittleEndian<$type>, BigEndian<$type>);
)+
};
}
impl_byte_array_endian!(u16, u32, u64, u128, i16, i32, i64, i128, f32, f64);
impl_from_endian_for_primitive!(u16, u32, u64, u128, i16, i32, i64, i128, f32, f64);
macro_rules! impl_fingerprint_endian_int {
($signedness:expr, $($type:ty),+ $(,)?) => {
$(
impl crate::WireFingerprint for LittleEndian<$type> {
const WIRE_FINGERPRINT: u64 = <$type as crate::WireFingerprint>::WIRE_FINGERPRINT;
}
impl crate::WireFingerprint for BigEndian<$type> {
const WIRE_FINGERPRINT: u64 = crate::FingerprintBuilder::new()
.tag(crate::FingerprintTag::FixedInt)
.width(<$type as crate::ToByteArray>::BYTE_SIZE as u8)
.signedness($signedness)
.endianness(crate::Endianness::Big)
.finish();
}
)+
};
}
impl_fingerprint_endian_int!(crate::Signedness::Unsigned, u16, u32, u64, u128);
impl_fingerprint_endian_int!(crate::Signedness::Signed, i16, i32, i64, i128);
macro_rules! impl_fingerprint_endian_float {
($($type:ty),+ $(,)?) => {
$(
impl crate::WireFingerprint for LittleEndian<$type> {
const WIRE_FINGERPRINT: u64 = <$type as crate::WireFingerprint>::WIRE_FINGERPRINT;
}
impl crate::WireFingerprint for BigEndian<$type> {
const WIRE_FINGERPRINT: u64 = crate::FingerprintBuilder::new()
.tag(crate::FingerprintTag::Float)
.width(<$type as crate::ToByteArray>::BYTE_SIZE as u8)
.endianness(crate::Endianness::Big)
.finish();
}
)+
};
}
impl_fingerprint_endian_float!(f32, f64);
pub trait HasEndianRepr: Sized {
type LE: PlainOldData;
type BE: PlainOldData;
fn to_little_endian(self) -> Self::LE;
fn to_big_endian(self) -> Self::BE;
}
pub trait FromEndianRepr: HasEndianRepr {
fn from_little_endian(le: Self::LE) -> Self;
fn from_big_endian(be: Self::BE) -> Self;
}
pub trait TryFromEndianRepr: HasEndianRepr {
fn try_from_little_endian(le: Self::LE) -> Result<Self, DecodeError>;
fn try_from_big_endian(be: Self::BE) -> Result<Self, DecodeError>;
}
impl<T: FromEndianRepr> TryFromEndianRepr for T {
fn try_from_little_endian(le: Self::LE) -> Result<Self, DecodeError> {
Ok(Self::from_little_endian(le))
}
fn try_from_big_endian(be: Self::BE) -> Result<Self, DecodeError> {
Ok(Self::from_big_endian(be))
}
}
impl<T: EndianConvert> HasEndianRepr for T {
type LE = LittleEndian<T>;
type BE = BigEndian<T>;
fn to_little_endian(self) -> Self::LE {
LittleEndian::new(self)
}
fn to_big_endian(self) -> Self::BE {
BigEndian::new(self)
}
}
impl<T: EndianConvert> FromEndianRepr for T {
fn from_little_endian(le: Self::LE) -> Self {
le.get()
}
fn from_big_endian(be: Self::BE) -> Self {
be.get()
}
}
impl<T: crate::WireFingerprint, const N: usize> crate::WireFingerprint for [T; N] {
const WIRE_FINGERPRINT: u64 = {
let mut b = crate::FingerprintBuilder::new().tag(crate::FingerprintTag::Struct);
let mut i = 0;
while i < N {
b = b.nested::<T>();
i += 1;
}
b.finish()
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn little_endian_matches_plain_type_big_endian_differs() {
use crate::WireFingerprint;
assert_eq!(
<LittleEndian<u32> as WireFingerprint>::WIRE_FINGERPRINT,
u32::WIRE_FINGERPRINT
);
assert_ne!(
<BigEndian<u32> as WireFingerprint>::WIRE_FINGERPRINT,
u32::WIRE_FINGERPRINT
);
assert_ne!(
<BigEndian<u32> as WireFingerprint>::WIRE_FINGERPRINT,
<LittleEndian<u32> as WireFingerprint>::WIRE_FINGERPRINT
);
}
#[test]
fn endian_wrapper_widths_still_differ() {
use crate::WireFingerprint;
assert_ne!(
<BigEndian<u32> as WireFingerprint>::WIRE_FINGERPRINT,
<BigEndian<u64> as WireFingerprint>::WIRE_FINGERPRINT
);
}
#[test]
fn array_fingerprint_depends_on_length() {
use crate::WireFingerprint;
assert_ne!(
<[u32; 3] as WireFingerprint>::WIRE_FINGERPRINT,
<[u32; 7] as WireFingerprint>::WIRE_FINGERPRINT
);
}
}