openethereum/src/triehash.rs

112 lines
2.7 KiB
Rust
Raw Normal View History

2015-11-29 12:22:35 +01:00
//! Generete trie root
//use std::collections::HashMap;
//use hash::*;
//use rlp;
/// Hex-prefix Notation. First nibble has flags: oddness = 2^0 & termination = 2^1.
///
/// The "termination marker" and "leaf-node" specifier are completely equivalent.
///
/// Input values are in range `[0, 0xf]`.
///
/// ```markdown
/// [0,0,1,2,3,4,5] 0x10012345 // 7 > 4
/// [0,1,2,3,4,5] 0x00012345 // 6 > 4
/// [1,2,3,4,5] 0x112345 // 5 > 3
/// [0,0,1,2,3,4] 0x00001234 // 6 > 3
/// [0,1,2,3,4] 0x101234 // 5 > 3
/// [1,2,3,4] 0x001234 // 4 > 3
/// [0,0,1,2,3,4,5,T] 0x30012345 // 7 > 4
/// [0,0,1,2,3,4,T] 0x20001234 // 6 > 4
/// [0,1,2,3,4,5,T] 0x20012345 // 6 > 4
/// [1,2,3,4,5,T] 0x312345 // 5 > 3
/// [1,2,3,4,T] 0x201234 // 4 > 3
/// ```
///
/// ```rust
/// extern crate ethcore_util as util;
/// use util::triehash::*;
///
/// fn main() {
/// let v = vec![0, 0, 1, 2, 3, 4, 5];
/// let e = vec![0x10, 0x01, 0x23, 0x45];
/// let h = hex_prefix_encode(&v, false);
/// assert_eq!(h, e);
///
/// let v = vec![0, 1, 2, 3, 4, 5];
/// let e = vec![0x00, 0x01, 0x23, 0x45];
/// let h = hex_prefix_encode(&v, false);
/// assert_eq!(h, e);
///
/// let v = vec![0, 1, 2, 3, 4, 5];
/// let e = vec![0x20, 0x01, 0x23, 0x45];
/// let h = hex_prefix_encode(&v, true);
/// assert_eq!(h, e);
///
/// let v = vec![1, 2, 3, 4, 5];
/// let e = vec![0x31, 0x23, 0x45];
/// let h = hex_prefix_encode(&v, true);
/// assert_eq!(h, e);
///
/// let v = vec![1, 2, 3, 4];
/// let e = vec![0x00, 0x12, 0x34];
/// let h = hex_prefix_encode(&v, false);
/// assert_eq!(h, e);
/// }
/// ```
///
2015-11-29 12:39:37 +01:00
pub fn hex_prefix_encode(nibbles: &[u8], leaf: bool) -> Vec<u8> {
let inlen = nibbles.len();
2015-11-29 12:22:35 +01:00
let oddness_factor = inlen % 2;
// next even number divided by two
let reslen = (inlen + 2) >> 1;
let mut res = vec![];
res.reserve(reslen);
let first_byte = {
let mut bits = ((inlen as u8 & 1) + (2 * leaf as u8)) << 4;
if oddness_factor == 1 {
2015-11-29 12:39:37 +01:00
bits += nibbles[0];
2015-11-29 12:22:35 +01:00
}
bits
};
res.push(first_byte);
let mut offset = oddness_factor;
while offset < inlen {
2015-11-29 12:39:37 +01:00
let byte = (nibbles[offset] << 4) + nibbles[offset + 1];
2015-11-29 12:22:35 +01:00
res.push(byte);
offset += 2;
}
res
}
2015-11-29 12:39:37 +01:00
/// Converts slice of bytes to nibbles.
///
/// ```rust
/// extern crate ethcore_util as util;
/// use util::triehash::*;
///
/// fn main () {
/// let v = vec![0x31, 0x23, 0x45];
/// let e = vec![3, 1, 2, 3, 4, 5];
/// assert_eq!(as_nibbles(&v), e);
/// }
/// ```
pub fn as_nibbles(bytes: &[u8]) -> Vec<u8> {
let mut res = vec![];
res.reserve(bytes.len() * 2);
for i in 0..bytes.len() {
res.push(bytes[i] >> 4);
res.push((bytes[i] << 4) >> 4);
}
res
}
2015-11-29 12:22:35 +01:00
#[cfg(test)]
mod tests {
}