Add U512 type and a few conversions.

This commit is contained in:
Gav Wood 2016-01-12 17:40:55 +01:00
parent e2de777c30
commit 6b1eb943e2
3 changed files with 81 additions and 10 deletions

View File

@ -109,25 +109,25 @@ impl BytesConvertable for Vec<u8> {
}
macro_rules! impl_bytes_convertable_for_array {
($zero: expr) => ();
($len: expr, $($idx: expr),*) => {
impl BytesConvertable for [u8; $len] {
fn bytes(&self) -> &[u8] { self }
}
impl_bytes_convertable_for_array! { $($idx),* }
}
($zero: expr) => ();
($len: expr, $($idx: expr),*) => {
impl BytesConvertable for [u8; $len] {
fn bytes(&self) -> &[u8] { self }
}
impl_bytes_convertable_for_array! { $($idx),* }
}
}
// -1 at the end is not expanded
impl_bytes_convertable_for_array! {
32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1
32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16,
15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1
}
#[test]
fn bytes_convertable() {
assert_eq!(vec![0x12u8, 0x34].bytes(), &[0x12u8, 0x34]);
assert_eq!([0u8; 0].bytes(), &[]);
assert_eq!([0u8; 0].bytes(), &[]);
}
/// Converts given type to its shortest representation in bytes

View File

@ -1,4 +1,6 @@
use hash::*;
use bytes::*;
use uint::*;
use secp256k1::{key, Secp256k1};
use rand::os::OsRng;
@ -19,6 +21,11 @@ impl Signature {
ret[64] = v;
ret
}
/// Convert transaction to R, S and V components.
pub fn to_rsv(&self) -> (U256, U256, u8) {
(U256::from(&self.as_slice()[0..32]), U256::from(&self.as_slice()[32..64]), self[64])
}
}
#[derive(Debug)]

View File

@ -462,9 +462,73 @@ macro_rules! construct_uint {
);
}
construct_uint!(U512, 8);
construct_uint!(U256, 4);
construct_uint!(U128, 2);
impl From<U256> for U512 {
fn from(value: U256) -> U512 {
let U256(ref arr) = value;
let mut ret = [0; 8];
ret[0] = arr[0];
ret[1] = arr[1];
ret[2] = arr[2];
ret[3] = arr[3];
U512(ret)
}
}
impl From<U512> for U256 {
fn from(value: U512) -> U256 {
let U512(ref arr) = value;
if arr[4] | arr[5] | arr[6] | arr[7] != 0 {
panic!("Overflow");
}
let mut ret = [0; 4];
ret[0] = arr[0];
ret[1] = arr[1];
ret[2] = arr[2];
ret[3] = arr[3];
U256(ret)
}
}
impl From<U256> for U128 {
fn from(value: U256) -> U128 {
let U256(ref arr) = value;
if arr[2] | arr[3] != 0 {
panic!("Overflow");
}
let mut ret = [0; 2];
ret[0] = arr[0];
ret[1] = arr[1];
U128(ret)
}
}
impl From<U512> for U128 {
fn from(value: U512) -> U128 {
let U512(ref arr) = value;
if arr[2] | arr[3] | arr[4] | arr[5] | arr[6] | arr[7] != 0 {
panic!("Overflow");
}
let mut ret = [0; 2];
ret[0] = arr[0];
ret[1] = arr[1];
U128(ret)
}
}
impl From<U128> for U512 {
fn from(value: U128) -> U512 {
let U128(ref arr) = value;
let mut ret = [0; 8];
ret[0] = arr[0];
ret[1] = arr[1];
U512(ret)
}
}
impl From<U128> for U256 {
fn from(value: U128) -> U256 {
let U128(ref arr) = value;