lambdaworks_math/
traits.rs

1use crate::{
2    errors::DeserializationError,
3    field::{element::FieldElement, traits::IsField},
4};
5
6use crate::errors::ByteConversionError;
7/// A trait for converting an element to and from its byte representation and
8/// for getting an element from its byte representation in big-endian or
9/// little-endian order.
10pub trait ByteConversion {
11    /// Returns the byte representation of the element in big-endian order.}
12    #[cfg(feature = "alloc")]
13    fn to_bytes_be(&self) -> alloc::vec::Vec<u8>;
14
15    /// Returns the byte representation of the element in little-endian order.
16    #[cfg(feature = "alloc")]
17    fn to_bytes_le(&self) -> alloc::vec::Vec<u8>;
18
19    /// Returns the element from its byte representation in big-endian order.
20    fn from_bytes_be(bytes: &[u8]) -> Result<Self, ByteConversionError>
21    where
22        Self: Sized;
23
24    /// Returns the element from its byte representation in little-endian order.
25    fn from_bytes_le(bytes: &[u8]) -> Result<Self, ByteConversionError>
26    where
27        Self: Sized;
28}
29
30/// Serialize function without args
31/// Used for serialization when formatting options are not relevant
32#[cfg(feature = "alloc")]
33pub trait AsBytes {
34    /// Default serialize without args
35    fn as_bytes(&self) -> alloc::vec::Vec<u8>;
36}
37
38#[cfg(feature = "alloc")]
39impl AsBytes for u32 {
40    fn as_bytes(&self) -> alloc::vec::Vec<u8> {
41        self.to_le_bytes().to_vec()
42    }
43}
44
45#[cfg(feature = "alloc")]
46impl AsBytes for u64 {
47    fn as_bytes(&self) -> alloc::vec::Vec<u8> {
48        self.to_le_bytes().to_vec()
49    }
50}
51
52/// Deserialize function without args
53pub trait Deserializable {
54    fn deserialize(bytes: &[u8]) -> Result<Self, DeserializationError>
55    where
56        Self: Sized;
57}
58
59pub trait IsRandomFieldElementGenerator<F: IsField> {
60    fn generate(&self) -> FieldElement<F>;
61}