arcium-primitives 0.8.1

Arcium primitives
Documentation
use derive_more::derive::{AsMut, AsRef, Deref, DerefMut, From};
use serde::{Deserialize, Serialize};

// TODO: Remove once v0.7.0 is released

#[cfg(not(target_pointer_width = "64"))]
compile_error!("this crate builds on 64-bit platforms only");

/// A wrapper around `crypto_bigint::BoxedUint` that implements `Serialize` and `Deserialize`.
#[derive(
    Debug, Clone, Deref, DerefMut, PartialEq, Eq, Hash, AsRef, AsMut, From, PartialOrd, Ord,
)]
#[as_ref(forward)]
#[from(forward)]
#[repr(transparent)]
pub struct BoxedUint(crypto_bigint::BoxedUint);

impl Serialize for BoxedUint {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let bytes = self.0.to_le_bytes();
        bytes.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for BoxedUint {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let bytes = Vec::<u8>::deserialize(deserializer)?;
        let bits_precision = bytes.len() * 8;
        let boxed_uint = crypto_bigint::BoxedUint::from_le_slice(&bytes, bits_precision as u32)
            .map_err(serde::de::Error::custom)?;
        Ok(BoxedUint(boxed_uint))
    }
}

#[cfg(test)]
mod tests {
    // Roundtrip test BoxedUint serialization
    use crypto_bigint::U256;

    use super::BoxedUint;
    use crate::utils::codec::bincode_io;
    #[test]
    fn test_boxed_uint_bincode() {
        let original = BoxedUint(crypto_bigint::BoxedUint::from(U256::from_u64(123456789)));
        let serialized = bincode_io::serialize(&original).expect("Serialization failed");
        let deserialized: BoxedUint =
            bincode_io::deserialize(&serialized).expect("Deserialization failed");
        assert_eq!(original, deserialized);
    }
}