to big endian for elments

This commit is contained in:
NikVolf
2017-03-22 13:56:28 +03:00
parent 78cf02fd7b
commit e749d4577a
3 changed files with 36 additions and 1 deletions
+25
View File
@@ -195,6 +195,16 @@ impl U256 {
Ok(U256(n))
}
pub fn to_big_endian(&self, s: &mut [u8]) -> Result<(), Error> {
if s.len() != 32 { return Err(Error::InvalidLength { expected: 32, actual: s.len() }); }
for (l, i) in (0..4).rev().zip((0..4).map(|i| i * 8)) {
BigEndian::write_u64(&mut s[i..], self.0[l]);
}
Ok(())
}
#[inline]
pub fn zero() -> U256 {
U256([0, 0, 0, 0])
@@ -540,6 +550,21 @@ fn from_slice() {
assert_eq!(num, tst);
}
#[test]
fn to_big_endian() {
let num = U256::one();
let mut s = [0u8; 32];
num.to_big_endian(&mut s).expect("U256 should convert to bytes ok in `to_big_endian` test");
assert_eq!(
s,
[
0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8,
]
);
}
#[test]
fn testing_divrem() {
let rng = &mut ::rand::thread_rng();
+4
View File
@@ -79,6 +79,10 @@ macro_rules! field_impl {
pub fn modulus() -> U256 {
U256($modulus)
}
pub fn raw(&self) -> &U256 {
&self.0
}
}
impl FieldElement for $name {
+7 -1
View File
@@ -32,7 +32,10 @@ impl Fr {
.map_err(|_| FieldError::InvalidSliceLength) // todo: maybe more sensful error handling
.and_then(|x| fields::Fr::new(x).ok_or(FieldError::NotMember))
.map(|x| Fr(x))
}
}
pub fn to_big_endian(&self, slice: &mut [u8]) -> Result<(), FieldError> {
self.0.raw().to_big_endian(slice).map_err(|_| FieldError::InvalidSliceLength)
}
}
impl Add<Fr> for Fr {
@@ -86,6 +89,9 @@ impl Fq {
.and_then(|x| fields::Fq::new(x).ok_or(FieldError::NotMember))
.map(|x| Fq(x))
}
pub fn to_big_endian(&self, slice: &mut [u8]) -> Result<(), FieldError> {
self.0.raw().to_big_endian(slice).map_err(|_| FieldError::InvalidSliceLength)
}
}
impl Add<Fq> for Fq {