use super::HeaplessBigInt;
use crate::MachineWord;
use crate::fixeduint::BytesHolder;
use const_num_traits::{FromBytes, Personality, ToBytes};
impl<T, const CAP: usize, P: Personality> HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
fn holder_be(&self) -> BytesHolder<T, CAP> {
crate::fixeduint::holder_be_from_limbs(&self.limbs)
}
fn holder_le(&self) -> BytesHolder<T, CAP> {
crate::fixeduint::holder_le_from_limbs(&self.limbs)
}
}
impl<T, const CAP: usize, P: Personality> ToBytes for HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
type Bytes = BytesHolder<T, CAP>;
fn to_be_bytes(self) -> Self::Bytes {
self.holder_be()
}
fn to_le_bytes(self) -> Self::Bytes {
self.holder_le()
}
}
impl<T, const CAP: usize, P: Personality> ToBytes for &HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
type Bytes = BytesHolder<T, CAP>;
fn to_be_bytes(self) -> Self::Bytes {
self.holder_be()
}
fn to_le_bytes(self) -> Self::Bytes {
self.holder_le()
}
}
impl<T, const CAP: usize, P: Personality> FromBytes for HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
type Bytes = BytesHolder<T, CAP>;
fn from_be_bytes(bytes: &Self::Bytes) -> Self {
Self::from_be_bytes(bytes.as_ref())
}
fn from_le_bytes(bytes: &Self::Bytes) -> Self {
Self::from_le_bytes(bytes.as_ref())
}
}
#[cfg(feature = "num-traits")]
impl<T, const CAP: usize, P: Personality> num_traits::ToBytes for HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
type Bytes = BytesHolder<T, CAP>;
fn to_be_bytes(&self) -> Self::Bytes {
self.holder_be()
}
fn to_le_bytes(&self) -> Self::Bytes {
self.holder_le()
}
}
#[cfg(feature = "num-traits")]
impl<T, const CAP: usize, P: Personality> num_traits::FromBytes for HeaplessBigInt<T, CAP, P>
where
T: MachineWord + core::fmt::Debug,
{
type Bytes = BytesHolder<T, CAP>;
fn from_be_bytes(bytes: &Self::Bytes) -> Self {
Self::from_be_bytes(bytes.as_ref())
}
fn from_le_bytes(bytes: &Self::Bytes) -> Self {
Self::from_le_bytes(bytes.as_ref())
}
}
#[cfg(all(test, feature = "num-traits"))]
mod num_traits_tests {
use super::HeaplessBigInt;
use num_traits::{FromBytes, ToBytes};
#[test]
fn round_trip_capacity_width() {
type H = HeaplessBigInt<u8, 4>;
let v = H::from(0x1234_5678u32);
let le = ToBytes::to_le_bytes(&v);
let be = ToBytes::to_be_bytes(&v);
let from_le = <H as FromBytes>::from_le_bytes(&le);
let from_be = <H as FromBytes>::from_be_bytes(&be);
assert_eq!(from_le, v);
assert_eq!(from_be, v);
assert_eq!(from_le.len(), 4); }
}