hpl_toolkit/compression/
default_impl.rsuse crate::compression::ToNode;
use anchor_lang::{prelude::*, solana_program::keccak};
use std::collections::HashMap;
macro_rules! impl_to_node_for_numbers {
($($t:ty)+) => {
$(
impl ToNode for $t {
fn to_node(&self) -> [u8; 32] {
let bytes = self.clone().to_le_bytes();
keccak::hashv(&[bytes.as_ref()][..]).to_bytes()
}
}
)+
};
}
impl_to_node_for_numbers!(u8 u16 u32 u64 i8 i16 i32 i64 f32 f64);
impl ToNode for String {
fn to_node(&self) -> [u8; 32] {
keccak::hashv(&[self.clone().as_bytes()][..]).to_bytes()
}
}
impl<T: ToNode> ToNode for Vec<T> {
fn to_node(&self) -> [u8; 32] {
let mut seeds: Vec<[u8; 32]> = vec![];
for item in self {
let node = item.to_node();
seeds.push(node);
}
let seeds_refs: Vec<&[u8]> = seeds.iter().map(|node| &node[..]).collect();
keccak::hashv(&seeds_refs[..]).to_bytes()
}
}
impl ToNode for Pubkey {
fn to_node(&self) -> [u8; 32] {
self.to_bytes()
}
}
impl ToNode for bool {
fn to_node(&self) -> [u8; 32] {
let bytes = self.clone().try_to_vec().unwrap();
keccak::hashv(&[bytes.as_ref()][..]).to_bytes()
}
}
impl<T: ToNode> ToNode for Option<T> {
fn to_node(&self) -> [u8; 32] {
match self {
Some(value) => value.to_node(),
None => keccak::hashv(&[&[0u8][..]][..]).to_bytes(),
}
}
}
impl<V: ToNode> ToNode for HashMap<String, V> {
fn to_node(&self) -> [u8; 32] {
let mut seeds: Vec<[u8; 32]> = vec![];
for (key, value) in self {
seeds.push(key.to_node());
seeds.push(value.to_node());
}
let seeds_refs: Vec<&[u8]> = seeds.iter().map(|node| &node[..]).collect();
keccak::hashv(&seeds_refs[..]).to_bytes()
}
}
impl ToNode for [u8; 32] {
fn to_node(&self) -> [u8; 32] {
*self
}
}
impl<A: ToNode, B: ToNode> ToNode for (A, B) {
fn to_node(&self) -> [u8; 32] {
let mut seeds: Vec<[u8; 32]> = vec![];
seeds.push(self.0.to_node());
seeds.push(self.1.to_node());
let seeds_refs: Vec<&[u8]> = seeds.iter().map(|node| &node[..]).collect();
keccak::hashv(&seeds_refs[..]).to_bytes()
}
}
impl<A: ToNode, B: ToNode, C: ToNode> ToNode for (A, B, C) {
fn to_node(&self) -> [u8; 32] {
let mut seeds: Vec<[u8; 32]> = vec![];
seeds.push(self.0.to_node());
seeds.push(self.1.to_node());
let seeds_refs: Vec<&[u8]> = seeds.iter().map(|node| &node[..]).collect();
keccak::hashv(&seeds_refs[..]).to_bytes()
}
}