use crate::hash_path::path::Component;
use crate::hash_path::path::Path;
use holochain_integrity_types::prelude::GetStrategy;
use holochain_serialized_bytes::prelude::SerializedBytes;
pub const ROOT: &[u8; 2] = &[0x00, 0x00];
#[derive(PartialEq, SerializedBytes, serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct Anchor {
pub anchor_type: String,
pub anchor_text: Option<String>,
#[serde(default)]
pub strategy: GetStrategy,
}
impl Anchor {
pub fn new(anchor_type: String, anchor_text: Option<String>) -> Self {
Self {
anchor_type,
anchor_text,
strategy: GetStrategy::default(),
}
}
pub fn with_strategy(mut self, strategy: GetStrategy) -> Self {
self.strategy = strategy;
self
}
}
impl From<&Anchor> for Path {
fn from(anchor: &Anchor) -> Self {
let mut components = vec![
Component::new(ROOT.to_vec()),
Component::from(anchor.anchor_type.as_bytes().to_vec()),
];
if let Some(text) = anchor.anchor_text.as_ref() {
components.push(Component::from(text.as_bytes().to_vec()));
}
components.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_path_root() {
assert_eq!(ROOT, &[0_u8, 0]);
}
#[test]
fn hash_path_anchor_path() {
let examples = [
(
"foo",
None,
Path::from(vec![
Component::from(vec![0, 0]),
Component::from(vec![102, 111, 111]),
]),
),
(
"foo",
Some("bar".to_string()),
Path::from(vec![
Component::from(vec![0, 0]),
Component::from(vec![102, 111, 111]),
Component::from(vec![98, 97, 114]),
]),
),
];
for (atype, text, path) in examples {
assert_eq!(path, (&Anchor::new(atype.to_string(), text)).into(),);
}
}
#[test]
fn test_anchor_with_strategy() {
use crate::prelude::GetStrategy;
let anchor = Anchor::new("test_type".to_string(), Some("test_text".to_string()));
assert_eq!(anchor.strategy, GetStrategy::Network);
let anchor_local = anchor.clone().with_strategy(GetStrategy::Local);
assert_eq!(anchor_local.strategy, GetStrategy::Local);
}
}