U256 to byts conversion
This commit is contained in:
parent
bb9163ac58
commit
668d735fa7
11
src/hash.rs
11
src/hash.rs
@ -9,6 +9,7 @@ use rand::Rng;
|
||||
use rand::os::OsRng;
|
||||
use bytes::BytesConvertable;
|
||||
use math::log2;
|
||||
use uint::U256;
|
||||
|
||||
/// types implementing FixedHash must be also BytesConvertable
|
||||
pub trait FixedHash: Sized + BytesConvertable {
|
||||
@ -307,6 +308,16 @@ macro_rules! impl_hash {
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> From<&'a U256> for H256 {
|
||||
fn from(value: &'a U256) -> H256 {
|
||||
unsafe {
|
||||
let mut ret: H256 = ::std::mem::uninitialized();
|
||||
value.to_bytes(&mut ret);
|
||||
ret
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl_hash!(H32, 4);
|
||||
impl_hash!(H64, 8);
|
||||
impl_hash!(H128, 16);
|
||||
|
19
src/uint.rs
19
src/uint.rs
@ -186,6 +186,15 @@ macro_rules! construct_uint {
|
||||
(arr[index / 8] >> ((index % 8)) * 8) as u8
|
||||
}
|
||||
|
||||
pub fn to_bytes(&self, bytes: &mut[u8]) {
|
||||
assert!($n_words * 8 == bytes.len());
|
||||
let &$name(ref arr) = self;
|
||||
for i in 0..bytes.len() {
|
||||
let rev = bytes.len() - 1 - i;
|
||||
let pos = rev / 8;
|
||||
bytes[i] = (arr[pos] >> ((rev % 8) * 8)) as u8;
|
||||
}
|
||||
}
|
||||
/// Multiplication by u32
|
||||
fn mul_u32(self, other: u32) -> $name {
|
||||
let $name(ref arr) = self;
|
||||
@ -514,6 +523,16 @@ mod tests {
|
||||
assert_eq!(U256([0x12f0, 1 , 0x0910203040506077, 0x8090a0b0c0d0e0f0]), U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn uint256_to() {
|
||||
let hex = "8090a0b0c0d0e0f00910203040506077583a2cf8264910e1436bda32571012f0";
|
||||
let uint = U256::from_str(hex).unwrap();
|
||||
let mut bytes = [0u8; 32];
|
||||
uint.to_bytes(&mut bytes);
|
||||
let uint2 = U256::from(&bytes[..]);
|
||||
assert_eq!(uint, uint2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn uint256_bits_test() {
|
||||
assert_eq!(U256::from(0u64).bits(), 0);
|
||||
|
Loading…
Reference in New Issue
Block a user