This commit is contained in:
Gav Wood 2015-11-27 17:54:33 +01:00
parent c08292663f
commit 006fe20287
5 changed files with 165 additions and 107 deletions

View File

@ -13,5 +13,5 @@ rustc-serialize = "0.3"
arrayvec = "0.3"
mio = "0.*"
rand = "0.*"
tiny-keccak = "0.2"
tiny-keccak = "0.3"
rocksdb = "0.2.1"

View File

@ -10,6 +10,23 @@ use std::fmt;
use std::error::Error as StdError;
use uint::{U128, U256};
pub trait BytesConvertable {
fn bytes(&self) -> &[u8];
}
impl<'a> BytesConvertable for &'a [u8] {
fn bytes(&self) -> &[u8] { self }
}
impl BytesConvertable for Vec<u8> {
fn bytes(&self) -> &[u8] { self }
}
#[test]
fn bytes_convertable() {
assert_eq!(vec![0x12u8, 0x34].bytes(), &[0x12u8, 0x34]);
}
/// TODO: optimise some conversations
pub trait ToBytes {
fn to_bytes(&self) -> Vec<u8>;

View File

@ -6,6 +6,7 @@ use rustc_serialize::hex::*;
use error::EthcoreError;
use rand::Rng;
use rand::os::OsRng;
use bytes::BytesConvertable;
macro_rules! impl_hash {
($from: ident, $size: expr) => {
@ -25,6 +26,16 @@ macro_rules! impl_hash {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
pub fn mut_bytes(&mut self) -> &mut [u8; $size] {
&mut self.0
}
}
impl BytesConvertable for $from {
fn bytes(&self) -> &[u8] {
&self.0
}
}
impl FromStr for $from {

View File

@ -15,6 +15,7 @@ pub mod bytes;
pub mod rlp;
pub mod vector;
pub mod db;
pub mod sha3;
//pub mod network;

29
src/sha3.rs Normal file
View File

@ -0,0 +1,29 @@
use std::mem::uninitialized;
use tiny_keccak::keccak_256;
use bytes::BytesConvertable;
use hash::H256;
trait Hashable {
fn sha3(&self) -> H256;
}
impl<T> Hashable for T where T: BytesConvertable {
fn sha3(&self) -> H256 {
unsafe {
let mut ret: H256 = uninitialized();
keccak_256(self.bytes(), ret.mut_bytes());
ret
}
}
}
#[test]
fn sha3_empty() {
use std::str::FromStr;
assert_eq!((&[0u8; 0][..]).sha3(), H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
}
#[test]
fn sha3_as() {
use std::str::FromStr;
assert_eq!((&[0x41u8; 32][..]).sha3(), H256::from_str("59cad5948673622c1d64e2322488bf01619f7ff45789741b15a9f782ce9290a8").unwrap());
}