use std::{
any::{Any, TypeId, type_name},
cell::RefCell,
collections::HashMap,
};
#[derive(Debug, Clone, Default)]
pub struct AccessSpec {
reads: HashMap<TypeId, &'static str>,
writes: HashMap<TypeId, &'static str>,
consumes: HashMap<TypeId, &'static str>,
}
impl AccessSpec {
pub fn new() -> Self {
Self::default()
}
pub fn reads<T: 'static>(mut self) -> Self {
self.reads.insert(TypeId::of::<T>(), type_name::<T>());
self
}
pub fn writes<T: 'static>(mut self) -> Self {
self.writes.insert(TypeId::of::<T>(), type_name::<T>());
self
}
pub fn reads_writes<T: 'static>(self) -> Self {
self.reads::<T>().writes::<T>()
}
pub fn consumes<T: 'static>(mut self) -> Self {
self.consumes.insert(TypeId::of::<T>(), type_name::<T>());
self.reads::<T>().writes::<T>()
}
pub fn can_read(&self, id: TypeId) -> bool {
self.reads.contains_key(&id)
}
pub fn can_write(&self, id: TypeId) -> bool {
self.writes.contains_key(&id)
}
pub fn can_consume(&self, id: TypeId) -> bool {
self.consumes.contains_key(&id)
}
pub fn read_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
self.reads.iter().map(|(id, name)| (*id, *name))
}
pub fn write_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
self.writes.iter().map(|(id, name)| (*id, *name))
}
pub fn consume_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
self.consumes.iter().map(|(id, name)| (*id, *name))
}
pub(crate) fn extend_reads(
&mut self,
entries: impl IntoIterator<Item = (TypeId, &'static str)>,
) {
self.reads.extend(entries);
}
pub(crate) fn extend_writes(
&mut self,
entries: impl IntoIterator<Item = (TypeId, &'static str)>,
) {
self.writes.extend(entries);
}
pub(crate) fn extend_consumes(
&mut self,
entries: impl IntoIterator<Item = (TypeId, &'static str)>,
) {
self.consumes.extend(entries);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessKind {
Read,
Write,
Consume,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessViolation {
pub step: String,
pub entry: &'static str,
pub kind: AccessKind,
}
impl AccessViolation {
pub(crate) fn verb(&self) -> &'static str {
match self.kind {
AccessKind::Read => "read",
AccessKind::Write => "wrote",
AccessKind::Consume => "consumed",
}
}
}
#[derive(Debug, Default)]
pub struct Context {
entries: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
active: Option<(String, AccessSpec)>,
violation: RefCell<Option<AccessViolation>>,
}
impl Context {
pub fn new() -> Self {
Self::default()
}
pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Read) {
return None;
}
self.entries
.get(&TypeId::of::<T>())
.and_then(|v| v.downcast_ref())
}
pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
if !self.check_read_and_write(TypeId::of::<T>(), type_name::<T>()) {
return None;
}
self.entries
.get_mut(&TypeId::of::<T>())
.and_then(|v| v.downcast_mut())
}
pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Write) {
return None;
}
let previous = self
.entries
.insert(TypeId::of::<T>(), Box::new(value))
.and_then(|v| v.downcast().ok())
.map(|v| *v);
if self.can_read_active(TypeId::of::<T>()) {
previous
} else {
None
}
}
pub fn take<T: Send + Sync + 'static>(&mut self) -> Option<T> {
let id = TypeId::of::<T>();
let entry = type_name::<T>();
if !self.check_read_and_write(id, entry) {
return None;
}
if !self.check(id, entry, AccessKind::Consume) {
return None;
}
self.entries
.remove(&TypeId::of::<T>())
.and_then(|v| v.downcast().ok())
.map(|v| *v)
}
pub fn contains<T: Send + Sync + 'static>(&mut self) -> bool {
if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Read) {
return false;
}
self.entries.contains_key(&TypeId::of::<T>())
}
fn can_read_active(&self, id: TypeId) -> bool {
match &self.active {
Some((_, spec)) => spec.can_read(id),
None => true,
}
}
fn check_read_and_write(&self, id: TypeId, entry: &'static str) -> bool {
self.check(id, entry, AccessKind::Read) && self.check(id, entry, AccessKind::Write)
}
fn check(&self, id: TypeId, entry: &'static str, kind: AccessKind) -> bool {
let Some((step, spec)) = &self.active else {
return true;
};
let allowed = match kind {
AccessKind::Read => spec.can_read(id),
AccessKind::Write => spec.can_write(id),
AccessKind::Consume => spec.can_consume(id),
};
if !allowed {
let mut violation = self.violation.borrow_mut();
if violation.is_none() {
*violation = Some(AccessViolation {
step: step.clone(),
entry,
kind,
});
}
}
allowed
}
pub(crate) fn set_active(&mut self, step: String, spec: AccessSpec) {
self.active = Some((step, spec));
}
pub(crate) fn clear_active(&mut self) {
self.active = None;
}
pub(crate) fn take_violation(&mut self) -> Option<AccessViolation> {
self.violation.borrow_mut().take()
}
}
#[cfg(test)]
mod test {
use super::*;
struct Alpha(i32);
struct Beta(&'static str);
#[test]
fn new_creates_spec_with_no_access() {
let spec = AccessSpec::new();
assert!(!spec.can_read(TypeId::of::<Alpha>()));
assert!(!spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn default_creates_spec_with_no_access() {
let spec = AccessSpec::default();
assert!(!spec.can_read(TypeId::of::<Alpha>()));
assert!(!spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn reads_grants_read_access_for_type() {
let spec = AccessSpec::new().reads::<Alpha>();
assert!(spec.can_read(TypeId::of::<Alpha>()));
}
#[test]
fn reads_does_not_grant_write_access() {
let spec = AccessSpec::new().reads::<Alpha>();
assert!(!spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn writes_grants_write_access_for_type() {
let spec = AccessSpec::new().writes::<Alpha>();
assert!(spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn writes_does_not_grant_read_access() {
let spec = AccessSpec::new().writes::<Alpha>();
assert!(!spec.can_read(TypeId::of::<Alpha>()));
}
#[test]
fn reads_writes_grants_both_read_and_write_access() {
let spec = AccessSpec::new().reads_writes::<Alpha>();
assert!(spec.can_read(TypeId::of::<Alpha>()));
assert!(spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn consumes_grants_both_read_and_write_access() {
let spec = AccessSpec::new().consumes::<Alpha>();
assert!(spec.can_read(TypeId::of::<Alpha>()));
assert!(spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn consume_entries_yields_typeid_and_type_name() {
let spec = AccessSpec::new().consumes::<Alpha>();
let entries: Vec<_> = spec.consume_entries().collect();
assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
}
#[test]
fn consume_entries_is_empty_for_new_spec() {
assert_eq!(AccessSpec::new().consume_entries().count(), 0);
}
#[test]
fn reads_writes_does_not_mark_type_as_consumed() {
let spec = AccessSpec::new().reads_writes::<Alpha>();
assert_eq!(spec.consume_entries().count(), 0);
}
#[test]
fn reads_is_chainable_across_multiple_types() {
let spec = AccessSpec::new().reads::<Alpha>().reads::<Beta>();
assert!(spec.can_read(TypeId::of::<Alpha>()));
assert!(spec.can_read(TypeId::of::<Beta>()));
}
#[test]
fn read_entries_yields_typeid_and_type_name() {
let spec = AccessSpec::new().reads::<Alpha>();
let entries: Vec<_> = spec.read_entries().collect();
assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
}
#[test]
fn write_entries_yields_typeid_and_type_name() {
let spec = AccessSpec::new().writes::<Alpha>();
let entries: Vec<_> = spec.write_entries().collect();
assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
}
#[test]
fn clone_preserves_read_and_write_grants() {
let spec = AccessSpec::new().reads::<Alpha>().writes::<Beta>();
let cloned = spec.clone();
assert!(cloned.can_read(TypeId::of::<Alpha>()));
assert!(cloned.can_write(TypeId::of::<Beta>()));
assert!(!cloned.can_write(TypeId::of::<Alpha>()));
assert!(!cloned.can_read(TypeId::of::<Beta>()));
}
#[test]
fn can_read_returns_false_for_unregistered_type() {
let spec = AccessSpec::new().writes::<Alpha>();
assert!(!spec.can_read(TypeId::of::<Alpha>()));
}
#[test]
fn can_write_returns_false_for_unregistered_type() {
let spec = AccessSpec::new().reads::<Alpha>();
assert!(!spec.can_write(TypeId::of::<Alpha>()));
}
#[test]
fn read_entries_is_empty_for_new_spec() {
assert_eq!(AccessSpec::new().read_entries().count(), 0);
}
#[test]
fn write_entries_is_empty_for_new_spec() {
assert_eq!(AccessSpec::new().write_entries().count(), 0);
}
#[test]
fn eq_returns_true_for_same_variant() {
assert_eq!(AccessKind::Read, AccessKind::Read);
}
#[test]
fn eq_returns_false_for_different_variant() {
assert_ne!(AccessKind::Read, AccessKind::Write);
}
#[test]
fn clone_and_copy_produce_equal_value() {
let a = AccessKind::Write;
let b = a;
assert_eq!(a, b);
assert_eq!(a, a.clone());
}
fn sample_violation() -> AccessViolation {
AccessViolation {
step: "load".to_string(),
entry: "Alpha",
kind: AccessKind::Read,
}
}
#[test]
fn clone_produces_equal_value() {
let violation = sample_violation();
assert_eq!(violation.clone(), violation);
}
#[test]
fn eq_returns_true_for_identical_fields() {
assert_eq!(sample_violation(), sample_violation());
}
#[test]
fn eq_returns_false_for_different_step() {
let mut other = sample_violation();
other.step = "save".to_string();
assert_ne!(sample_violation(), other);
}
#[test]
fn eq_returns_false_for_different_entry() {
let mut other = sample_violation();
other.entry = "Beta";
assert_ne!(sample_violation(), other);
}
#[test]
fn eq_returns_false_for_different_kind() {
let mut other = sample_violation();
other.kind = AccessKind::Write;
assert_ne!(sample_violation(), other);
}
#[test]
fn construct_with_empty_step_string_is_allowed() {
let violation = AccessViolation {
step: String::new(),
entry: "Alpha",
kind: AccessKind::Write,
};
assert_eq!(violation.step, "");
}
#[test]
fn new_creates_empty_context() {
let mut ctx = Context::new();
assert!(!ctx.contains::<Alpha>());
assert!(ctx.get::<Alpha>().is_none());
}
#[test]
fn default_behaves_like_new() {
let mut ctx = Context::default();
assert!(!ctx.contains::<Alpha>());
assert!(ctx.get::<Alpha>().is_none());
}
#[test]
fn contains_returns_true_after_insert() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
assert!(ctx.contains::<Alpha>());
}
#[test]
fn insert_returns_none_for_first_value() {
let mut ctx = Context::new();
assert!(ctx.insert(Alpha(1)).is_none());
}
#[test]
fn insert_returns_previous_value_when_overwriting_same_type() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
let previous = ctx.insert(Alpha(2));
assert_eq!(previous.map(|a| a.0), Some(1));
}
#[test]
fn get_returns_reference_to_inserted_value() {
let mut ctx = Context::new();
ctx.insert(Alpha(42));
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(42));
}
#[test]
fn get_mut_mutation_is_visible_via_get() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.get_mut::<Alpha>().unwrap().0 = 99;
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(99));
}
#[test]
fn take_returns_value_and_removes_it_from_context() {
let mut ctx = Context::new();
ctx.insert(Alpha(7));
assert_eq!(ctx.take::<Alpha>().map(|a| a.0), Some(7));
assert!(!ctx.contains::<Alpha>());
}
#[test]
fn get_allows_holding_references_to_two_distinct_types_simultaneously() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.insert(Beta("hello"));
let a = ctx.get::<Alpha>().unwrap();
let b = ctx.get::<Beta>().unwrap();
assert_eq!(a.0, 1);
assert_eq!(b.0, "hello");
}
#[test]
fn context_stores_multiple_distinct_types_independently() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.insert(Beta("hello"));
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
assert_eq!(ctx.get::<Beta>().map(|b| b.0), Some("hello"));
}
#[test]
fn contains_returns_false_when_type_absent() {
let mut ctx = Context::new();
assert!(!ctx.contains::<Alpha>());
}
#[test]
fn get_returns_none_when_type_absent() {
let ctx = Context::new();
assert!(ctx.get::<Alpha>().is_none());
}
#[test]
fn get_mut_returns_none_when_type_absent() {
let mut ctx = Context::new();
assert!(ctx.get_mut::<Alpha>().is_none());
}
#[test]
fn take_returns_none_when_type_absent() {
let mut ctx = Context::new();
assert!(ctx.take::<Alpha>().is_none());
}
#[test]
fn get_succeeds_when_active_spec_grants_read() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
assert!(ctx.take_violation().is_none());
}
#[test]
fn insert_succeeds_when_active_spec_grants_write() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
assert!(ctx.insert(Alpha(1)).is_none());
ctx.clear_active();
assert!(ctx.contains::<Alpha>());
assert!(ctx.take_violation().is_none());
}
#[test]
fn insert_does_not_require_read_access() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
ctx.insert(Alpha(1));
ctx.clear_active();
assert!(ctx.contains::<Alpha>());
assert!(ctx.take_violation().is_none());
}
#[test]
fn get_mut_succeeds_when_active_spec_grants_read_and_write() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active(
"step".to_string(),
AccessSpec::new().reads_writes::<Alpha>(),
);
ctx.get_mut::<Alpha>().unwrap().0 = 2;
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(2));
assert!(ctx.take_violation().is_none());
}
#[test]
fn take_succeeds_when_active_spec_grants_consumes() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().consumes::<Alpha>());
assert_eq!(ctx.take::<Alpha>().map(|a| a.0), Some(1));
assert!(ctx.take_violation().is_none());
}
#[test]
fn take_denied_and_records_consume_violation_when_only_reads_writes_is_granted() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active(
"step".to_string(),
AccessSpec::new().reads_writes::<Alpha>(),
);
assert!(ctx.take::<Alpha>().is_none());
assert!(ctx.contains::<Alpha>());
assert_eq!(
ctx.take_violation(),
Some(AccessViolation {
step: "step".to_string(),
entry: type_name::<Alpha>(),
kind: AccessKind::Consume,
})
);
}
#[test]
fn get_without_active_step_ignores_access_spec() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
assert!(ctx.take_violation().is_none());
}
#[test]
fn clear_active_removes_restriction_and_allows_subsequent_access() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new());
ctx.clear_active();
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
assert!(ctx.take_violation().is_none());
}
#[test]
fn get_denied_and_records_violation_when_read_not_granted() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new());
assert!(ctx.get::<Alpha>().is_none());
assert_eq!(
ctx.take_violation(),
Some(AccessViolation {
step: "step".to_string(),
entry: type_name::<Alpha>(),
kind: AccessKind::Read,
})
);
}
#[test]
fn insert_does_not_return_previous_value_without_read_access() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
let previous = ctx.insert(Alpha(2));
assert!(previous.is_none());
assert!(ctx.take_violation().is_none());
ctx.clear_active();
assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(2));
}
#[test]
fn insert_denied_and_records_violation_when_write_not_granted() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new());
assert!(ctx.insert(Alpha(1)).is_none());
assert!(!ctx.contains::<Alpha>());
assert_eq!(
ctx.take_violation(),
Some(AccessViolation {
step: "step".to_string(),
entry: type_name::<Alpha>(),
kind: AccessKind::Write,
})
);
}
#[test]
fn insert_denied_even_when_read_is_granted_but_write_is_not() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
assert!(ctx.insert(Alpha(1)).is_none());
assert!(!ctx.contains::<Alpha>());
assert_eq!(
ctx.take_violation().map(|v| v.kind),
Some(AccessKind::Write)
);
}
#[test]
fn get_mut_denied_and_records_read_violation_when_read_not_granted() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
assert!(ctx.get_mut::<Alpha>().is_none());
assert_eq!(ctx.take_violation().map(|v| v.kind), Some(AccessKind::Read));
}
#[test]
fn get_mut_denied_and_records_write_violation_when_read_granted_but_write_not() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
assert!(ctx.get_mut::<Alpha>().is_none());
assert_eq!(
ctx.take_violation().map(|v| v.kind),
Some(AccessKind::Write)
);
}
#[test]
fn take_denied_and_records_read_violation_when_read_not_granted() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
assert!(ctx.take::<Alpha>().is_none());
assert_eq!(ctx.take_violation().map(|v| v.kind), Some(AccessKind::Read));
}
#[test]
fn take_denied_and_records_write_violation_when_read_granted_but_write_not() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
assert!(ctx.take::<Alpha>().is_none());
assert!(ctx.contains::<Alpha>());
assert_eq!(
ctx.take_violation().map(|v| v.kind),
Some(AccessKind::Write)
);
}
#[test]
fn contains_succeeds_when_active_spec_grants_read() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
assert!(ctx.contains::<Alpha>());
assert!(ctx.take_violation().is_none());
}
#[test]
fn contains_denied_and_records_violation_when_read_not_granted() {
let mut ctx = Context::new();
ctx.insert(Alpha(1));
ctx.set_active("step".to_string(), AccessSpec::new());
assert!(!ctx.contains::<Alpha>());
assert_eq!(
ctx.take_violation(),
Some(AccessViolation {
step: "step".to_string(),
entry: type_name::<Alpha>(),
kind: AccessKind::Read,
})
);
}
#[test]
fn take_violation_returns_none_when_no_violation_recorded() {
let mut ctx = Context::new();
assert!(ctx.take_violation().is_none());
}
#[test]
fn take_violation_removes_stored_violation() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new());
ctx.insert(Alpha(1));
assert!(ctx.take_violation().is_some());
assert!(ctx.take_violation().is_none());
}
#[test]
fn take_violation_keeps_first_recorded_violation_when_multiple_denied_calls_occur() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new());
ctx.insert(Alpha(1));
ctx.insert(Beta("x"));
let violation = ctx.take_violation().unwrap();
assert_eq!(violation.entry, type_name::<Alpha>());
}
#[test]
fn clear_active_does_not_erase_already_recorded_violation() {
let mut ctx = Context::new();
ctx.set_active("step".to_string(), AccessSpec::new());
ctx.insert(Alpha(1));
ctx.clear_active();
assert!(ctx.take_violation().is_some());
}
}