use crate::contract::address::{hash, Addresser, AddresserError, ADDRESS_LENGTH};
pub struct KeyHashAddresser {
prefix: String,
}
impl KeyHashAddresser {
pub fn new(prefix: String) -> KeyHashAddresser {
KeyHashAddresser { prefix }
}
}
impl Addresser<String> for KeyHashAddresser {
fn compute(&self, key: &String) -> Result<String, AddresserError> {
let hash_length = ADDRESS_LENGTH - self.prefix.len();
Ok(String::from(&self.prefix) + &hash(hash_length, key))
}
fn normalize(&self, key: &String) -> String {
key.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_hash_addresser() {
let addresser = KeyHashAddresser::new("prefix".to_string());
let addr = addresser.compute(&"a".to_string()).unwrap();
assert_eq!(addr[..6], "prefix".to_string());
assert_eq!(addr.len(), ADDRESS_LENGTH);
let key_hash = hash(64, "a");
let remaining = ADDRESS_LENGTH - 6;
assert_eq!(addr[6..ADDRESS_LENGTH], key_hash[..remaining]);
let normalized = addresser.normalize(&"b".to_string());
assert_eq!(normalized, "b".to_string());
}
}