1use crate::enums::KzgError;
2use crate::kzg_proof::safe_scalar_affine_from_bytes;
3use crate::{BYTES_PER_BLOB, BYTES_PER_FIELD_ELEMENT};
4
5use alloc::{string::ToString, vec::Vec};
6use bls12_381::Scalar;
7
8macro_rules! define_bytes_type {
9 ($name:ident, $size:expr) => {
10 #[derive(Debug, Clone)]
11 pub struct $name([u8; $size]);
12
13 impl $name {
14 pub fn from_slice(slice: &[u8]) -> Result<Self, KzgError> {
15 if slice.len() != $size {
16 return Err(KzgError::InvalidBytesLength(
17 "Invalid slice length".to_string(),
18 ));
19 }
20 let mut bytes = [0u8; $size];
21 bytes.copy_from_slice(slice);
22 Ok($name(bytes))
23 }
24
25 pub fn as_slice(&self) -> &[u8] {
26 &self.0
27 }
28 }
29
30 impl From<$name> for [u8; $size] {
31 fn from(value: $name) -> [u8; $size] {
32 value.0
33 }
34 }
35 };
36}
37
38define_bytes_type!(Bytes32, 32);
39define_bytes_type!(Bytes48, 48);
40define_bytes_type!(Blob, BYTES_PER_BLOB);
41
42impl Blob {
43 pub fn as_polynomial(&self) -> Result<Vec<Scalar>, KzgError> {
44 self.0
45 .chunks(BYTES_PER_FIELD_ELEMENT)
46 .map(|slice| {
47 Bytes32::from_slice(slice).and_then(|bytes| safe_scalar_affine_from_bytes(&bytes))
48 })
49 .collect()
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 #[test]
56 fn test_bytes32() {
57 let bytes = crate::dtypes::Bytes32::from_slice(&[0u8; 32]).unwrap();
58 assert_eq!(bytes.0.len(), 32);
59 }
60
61 #[test]
62 fn test_bytes48() {
63 let bytes = crate::dtypes::Bytes48::from_slice(&[0u8; 48]).unwrap();
64 assert_eq!(bytes.0.len(), 48);
65 }
66}