|
1 | 1 | //! Interop support for `hybrid-array` |
2 | 2 |
|
3 | | -use crate::{Encoding, Integer}; |
| 3 | +use crate::{EncodedUint, Encoding, Integer, Limb}; |
4 | 4 | use core::ops::Add; |
5 | | -use hybrid_array::{Array, ArraySize, typenum::Unsigned}; |
| 5 | +use hybrid_array::{Array, ArrayN, ArraySize, typenum::Unsigned}; |
6 | 6 |
|
7 | 7 | /// Alias for a byte array whose size is defined by [`ArrayEncoding::ByteSize`]. |
8 | 8 | pub type ByteArray<T> = Array<u8, <T as ArrayEncoding>::ByteSize>; |
@@ -36,3 +36,58 @@ pub trait ArrayDecoding { |
36 | 36 | /// Deserialize from a little-endian `Array`. |
37 | 37 | fn into_uint_le(self) -> Self::Output; |
38 | 38 | } |
| 39 | + |
| 40 | +macro_rules! from_impls_for_encoded_uint { |
| 41 | + ( $($nlimbs:expr),+ ) => { |
| 42 | + $( |
| 43 | + impl From<EncodedUint<$nlimbs>> for ArrayN<u8, { $nlimbs * Limb::BYTES }> { |
| 44 | + #[inline] |
| 45 | + fn from(input: EncodedUint<$nlimbs>) -> Self { |
| 46 | + let mut output = Self::default(); |
| 47 | + output.as_mut_slice().copy_from_slice(input.as_ref()); |
| 48 | + output |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + impl From<ArrayN<u8, { $nlimbs * Limb::BYTES }>> for EncodedUint<$nlimbs> { |
| 53 | + #[inline] |
| 54 | + fn from(input: ArrayN<u8, { $nlimbs * Limb::BYTES }>) -> Self { |
| 55 | + let mut output = Self::default(); |
| 56 | + output.as_mut().copy_from_slice(input.as_ref()); |
| 57 | + output |
| 58 | + } |
| 59 | + } |
| 60 | + )+ |
| 61 | + }; |
| 62 | +} |
| 63 | + |
| 64 | +// Support up to 16 limbs for now (chosen somewhat arbitrarily) |
| 65 | +from_impls_for_encoded_uint!(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); |
| 66 | + |
| 67 | +#[cfg(test)] |
| 68 | +mod tests { |
| 69 | + const LIMBS: usize = 4; |
| 70 | + const BYTES: usize = super::Limb::BYTES * LIMBS; |
| 71 | + |
| 72 | + type Array = super::ArrayN<u8, { BYTES }>; |
| 73 | + type EncodedUint = super::EncodedUint<LIMBS>; |
| 74 | + |
| 75 | + const ARRAY: Array = { |
| 76 | + let mut i = 0; |
| 77 | + let mut ret = [0u8; BYTES]; |
| 78 | + while i < BYTES { |
| 79 | + ret[i] = i as u8; |
| 80 | + i += 1; |
| 81 | + } |
| 82 | + hybrid_array::Array(ret) |
| 83 | + }; |
| 84 | + |
| 85 | + #[test] |
| 86 | + fn from_impls_for_encoded_uint() { |
| 87 | + let encoded_uint = EncodedUint::from(ARRAY); |
| 88 | + assert_eq!(encoded_uint.as_ref(), ARRAY.as_slice()); |
| 89 | + |
| 90 | + let array = Array::from(encoded_uint); |
| 91 | + assert_eq!(array, ARRAY); |
| 92 | + } |
| 93 | +} |
0 commit comments