You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.2 KiB

4 years ago
  1. use super::constants;
  2. use super::utils;
  3. pub struct TreeNode {
  4. pub child_l: [u8; 32],
  5. pub child_r: [u8; 32],
  6. }
  7. impl TreeNode {
  8. pub fn bytes(&self) -> Vec<u8> {
  9. concatenate_arrays(&self.child_l, &self.child_r)
  10. }
  11. pub fn ht(&self) -> [u8; 32] {
  12. utils::hash_vec(self.bytes())
  13. }
  14. }
  15. fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
  16. let mut concat = x.to_vec();
  17. concat.extend_from_slice(y);
  18. concat
  19. }
  20. pub fn parse_node_bytes(b: Vec<u8>) -> TreeNode {
  21. if b == constants::EMPTYNODEVALUE {
  22. let n = TreeNode {
  23. child_l: constants::EMPTYNODEVALUE,
  24. child_r: constants::EMPTYNODEVALUE,
  25. };
  26. return n;
  27. }
  28. let child_l = &b[0..32];
  29. let child_r = &b[32..];
  30. TreeNode {
  31. child_l: *array_ref!(child_l, 0, 32),
  32. child_r: *array_ref!(child_r, 0, 32),
  33. }
  34. }
  35. #[cfg(test)]
  36. mod tests {
  37. use super::*;
  38. use rustc_hex::ToHex;
  39. #[test]
  40. fn test_hash_vec() {
  41. let n = TreeNode {
  42. child_l: constants::EMPTYNODEVALUE,
  43. child_r: constants::EMPTYNODEVALUE,
  44. };
  45. assert_eq!(
  46. "ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5",
  47. n.ht().to_hex()
  48. )
  49. }
  50. }