use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::coroutine::Value;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct LayerId(pub String);
impl From<&str> for LayerId {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
pub trait GuardLayer {
type Resource: Clone;
type Evidence: Clone;
fn open_(&mut self, layer: &LayerId) -> Result<(Self::Resource, Self::Evidence), String>;
fn close(&mut self, layer: &LayerId, evidence: Self::Evidence) -> Result<(), String>;
fn encode_evidence(evidence: &Self::Evidence) -> Result<Value, String>;
fn decode_evidence(value: &Value) -> Result<Self::Evidence, String>;
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct InMemoryGuardLayer {
pub resources: BTreeMap<LayerId, Value>,
}
impl GuardLayer for InMemoryGuardLayer {
type Resource = Value;
type Evidence = Value;
fn open_(&mut self, layer: &LayerId) -> Result<(Self::Resource, Self::Evidence), String> {
let resource = self
.resources
.get(layer)
.cloned()
.ok_or_else(|| format!("unknown guard layer {}", layer.0))?;
Ok((resource.clone(), resource))
}
fn close(&mut self, layer: &LayerId, evidence: Self::Evidence) -> Result<(), String> {
if !self.resources.contains_key(layer) {
return Err(format!("unknown guard layer {}", layer.0));
}
let _ = evidence;
Ok(())
}
fn encode_evidence(evidence: &Self::Evidence) -> Result<Value, String> {
Ok(evidence.clone())
}
fn decode_evidence(value: &Value) -> Result<Self::Evidence, String> {
Ok(value.clone())
}
}