Skip to content

Commit 1ebbd8b

Browse files
authored
Add From impls between ByteArray and EncodedUint (#1064)
One thing lost from #1016 is the ability to convert from `Uint::Repr` and `hybrid_array::Array<u8, _>`. Arguably these cases should use the dedicated `ArrayEncoding`/`ArrayDecoding` traits for this purpose instead, but for the sake of retrofitting the changes from #1016 this adds back the ability to do these conversions for `EncodedUint` up to 16 limbs.
1 parent 21cef5b commit 1ebbd8b

File tree

1 file changed

+57
-2
lines changed

1 file changed

+57
-2
lines changed

src/array.rs

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
//! Interop support for `hybrid-array`
22
3-
use crate::{Encoding, Integer};
3+
use crate::{EncodedUint, Encoding, Integer, Limb};
44
use core::ops::Add;
5-
use hybrid_array::{Array, ArraySize, typenum::Unsigned};
5+
use hybrid_array::{Array, ArrayN, ArraySize, typenum::Unsigned};
66

77
/// Alias for a byte array whose size is defined by [`ArrayEncoding::ByteSize`].
88
pub type ByteArray<T> = Array<u8, <T as ArrayEncoding>::ByteSize>;
@@ -36,3 +36,58 @@ pub trait ArrayDecoding {
3636
/// Deserialize from a little-endian `Array`.
3737
fn into_uint_le(self) -> Self::Output;
3838
}
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

Comments
 (0)