Skip to main content

pipeline_toolkit/
context.rs

1use std::{
2    any::{Any, TypeId, type_name},
3    cell::RefCell,
4    collections::HashMap,
5};
6
7/// The set of [`Context`] entry types a [`Step`](crate::Step) is allowed to
8/// read, write, or consume, keyed by [`TypeId`].
9///
10/// A step returns its `AccessSpec` from
11/// [`Step::access`](crate::Step::access).
12/// [`PipelineBuilder::build`](crate::PipelineBuilder::build) uses it
13/// statically, to check that every declared read is satisfied by an earlier
14/// step's declared write (or the pipeline input), and [`Context`] uses it
15/// dynamically, at run time, to reject reads, writes, and [`Context::take`]
16/// calls the step didn't declare.
17///
18/// # Examples
19///
20/// ```
21/// use pipeline_toolkit::AccessSpec;
22/// use std::any::TypeId;
23///
24/// struct Config;
25/// struct Report;
26///
27/// let access = AccessSpec::new().reads::<Config>().writes::<Report>();
28/// assert!(access.can_read(TypeId::of::<Config>()));
29/// assert!(access.can_write(TypeId::of::<Report>()));
30/// assert!(!access.can_write(TypeId::of::<Config>()));
31/// ```
32#[derive(Debug, Clone, Default)]
33pub struct AccessSpec {
34    reads: HashMap<TypeId, &'static str>,
35    writes: HashMap<TypeId, &'static str>,
36    consumes: HashMap<TypeId, &'static str>,
37}
38
39impl AccessSpec {
40    /// Creates an empty spec that grants no access.
41    ///
42    /// # Examples
43    ///
44    /// ```
45    /// use pipeline_toolkit::AccessSpec;
46    /// use std::any::TypeId;
47    ///
48    /// struct Config;
49    ///
50    /// let access = AccessSpec::new();
51    /// assert!(!access.can_read(TypeId::of::<Config>()));
52    /// ```
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    /// Grants read access to `T`.
58    ///
59    /// # Examples
60    ///
61    /// ```
62    /// use pipeline_toolkit::AccessSpec;
63    /// use std::any::TypeId;
64    ///
65    /// struct Config;
66    ///
67    /// let access = AccessSpec::new().reads::<Config>();
68    /// assert!(access.can_read(TypeId::of::<Config>()));
69    /// assert!(!access.can_write(TypeId::of::<Config>()));
70    /// ```
71    pub fn reads<T: 'static>(mut self) -> Self {
72        self.reads.insert(TypeId::of::<T>(), type_name::<T>());
73        self
74    }
75
76    /// Grants write access to `T`.
77    ///
78    /// # Examples
79    ///
80    /// ```
81    /// use pipeline_toolkit::AccessSpec;
82    /// use std::any::TypeId;
83    ///
84    /// struct Report;
85    ///
86    /// let access = AccessSpec::new().writes::<Report>();
87    /// assert!(access.can_write(TypeId::of::<Report>()));
88    /// assert!(!access.can_read(TypeId::of::<Report>()));
89    /// ```
90    pub fn writes<T: 'static>(mut self) -> Self {
91        self.writes.insert(TypeId::of::<T>(), type_name::<T>());
92        self
93    }
94
95    /// Grants both read and write access to `T`, for a step that mutates a
96    /// value in place via [`Context::get_mut`] rather than replacing it.
97    ///
98    /// Unlike [`Self::consumes`], this leaves `T` marked as written for
99    /// [`PipelineBuilder::build`](crate::PipelineBuilder::build)'s
100    /// purposes, so a downstream step can still declare a read of it.
101    ///
102    /// # Examples
103    ///
104    /// ```
105    /// use pipeline_toolkit::AccessSpec;
106    /// use std::any::TypeId;
107    ///
108    /// struct Counter;
109    ///
110    /// let access = AccessSpec::new().reads_writes::<Counter>();
111    /// assert!(access.can_read(TypeId::of::<Counter>()));
112    /// assert!(access.can_write(TypeId::of::<Counter>()));
113    /// ```
114    pub fn reads_writes<T: 'static>(self) -> Self {
115        self.reads::<T>().writes::<T>()
116    }
117
118    /// Declares that this step will call [`Context::take`] for `T`, removing
119    /// it from the context. Implies read and write access. Unlike
120    /// [`Self::reads_writes`] (used for in-place mutation via
121    /// [`Context::get_mut`], which leaves the value in place),
122    /// [`PipelineBuilder::build`](crate::PipelineBuilder::build) treats a
123    /// consumed type as no longer written once this step runs, so a
124    /// downstream step reading it without an intervening write is caught at
125    /// build time instead of silently seeing `None` at runtime.
126    ///
127    /// # Examples
128    ///
129    /// ```
130    /// use pipeline_toolkit::AccessSpec;
131    /// use std::any::TypeId;
132    ///
133    /// struct Payload;
134    ///
135    /// let access = AccessSpec::new().consumes::<Payload>();
136    /// assert!(access.can_read(TypeId::of::<Payload>()));
137    /// assert!(access.can_write(TypeId::of::<Payload>()));
138    /// assert!(access.can_consume(TypeId::of::<Payload>()));
139    /// ```
140    pub fn consumes<T: 'static>(mut self) -> Self {
141        self.consumes.insert(TypeId::of::<T>(), type_name::<T>());
142        self.reads::<T>().writes::<T>()
143    }
144
145    /// Reports whether this spec grants read access to the type identified
146    /// by `id`.
147    ///
148    /// # Examples
149    ///
150    /// ```
151    /// use pipeline_toolkit::AccessSpec;
152    /// use std::any::TypeId;
153    ///
154    /// struct Config;
155    ///
156    /// let access = AccessSpec::new().reads::<Config>();
157    /// assert!(access.can_read(TypeId::of::<Config>()));
158    /// ```
159    pub fn can_read(&self, id: TypeId) -> bool {
160        self.reads.contains_key(&id)
161    }
162
163    /// Reports whether this spec grants write access to the type identified
164    /// by `id`.
165    ///
166    /// # Examples
167    ///
168    /// ```
169    /// use pipeline_toolkit::AccessSpec;
170    /// use std::any::TypeId;
171    ///
172    /// struct Report;
173    ///
174    /// let access = AccessSpec::new().writes::<Report>();
175    /// assert!(access.can_write(TypeId::of::<Report>()));
176    /// ```
177    pub fn can_write(&self, id: TypeId) -> bool {
178        self.writes.contains_key(&id)
179    }
180
181    /// Reports whether this spec grants [`Context::take`] access to the type
182    /// identified by `id`.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use pipeline_toolkit::AccessSpec;
188    /// use std::any::TypeId;
189    ///
190    /// struct Payload;
191    ///
192    /// let access = AccessSpec::new().consumes::<Payload>();
193    /// assert!(access.can_consume(TypeId::of::<Payload>()));
194    /// ```
195    pub fn can_consume(&self, id: TypeId) -> bool {
196        self.consumes.contains_key(&id)
197    }
198
199    /// Iterates over every type this spec grants read access to, paired
200    /// with its [`type_name`] for diagnostics.
201    ///
202    /// # Examples
203    ///
204    /// ```
205    /// use pipeline_toolkit::AccessSpec;
206    ///
207    /// struct Config;
208    ///
209    /// let access = AccessSpec::new().reads::<Config>();
210    /// let entries: Vec<_> = access.read_entries().collect();
211    /// assert_eq!(entries.len(), 1);
212    /// ```
213    pub fn read_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
214        self.reads.iter().map(|(id, name)| (*id, *name))
215    }
216
217    /// Iterates over every type this spec grants write access to, paired
218    /// with its [`type_name`] for diagnostics.
219    ///
220    /// # Examples
221    ///
222    /// ```
223    /// use pipeline_toolkit::AccessSpec;
224    ///
225    /// struct Report;
226    ///
227    /// let access = AccessSpec::new().writes::<Report>();
228    /// let entries: Vec<_> = access.write_entries().collect();
229    /// assert_eq!(entries.len(), 1);
230    /// ```
231    pub fn write_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
232        self.writes.iter().map(|(id, name)| (*id, *name))
233    }
234
235    /// Iterates over every type this spec grants [`Context::take`] access
236    /// to, paired with its [`type_name`] for diagnostics.
237    ///
238    /// # Examples
239    ///
240    /// ```
241    /// use pipeline_toolkit::AccessSpec;
242    ///
243    /// struct Payload;
244    ///
245    /// let access = AccessSpec::new().consumes::<Payload>();
246    /// let entries: Vec<_> = access.consume_entries().collect();
247    /// assert_eq!(entries.len(), 1);
248    /// ```
249    pub fn consume_entries(&self) -> impl Iterator<Item = (TypeId, &'static str)> + '_ {
250        self.consumes.iter().map(|(id, name)| (*id, *name))
251    }
252
253    /// Merges additional read grants computed at runtime (e.g. by
254    /// [`Branch`](crate::Branch), unioning its arms' declared reads) into
255    /// this spec. Unlike [`Self::reads`], the entries here aren't known at
256    /// compile time as a single `T`, so they're supplied as raw
257    /// `(TypeId, type_name)` pairs instead.
258    pub(crate) fn extend_reads(
259        &mut self,
260        entries: impl IntoIterator<Item = (TypeId, &'static str)>,
261    ) {
262        self.reads.extend(entries);
263    }
264
265    /// Same as [`Self::extend_reads`], but for write grants.
266    pub(crate) fn extend_writes(
267        &mut self,
268        entries: impl IntoIterator<Item = (TypeId, &'static str)>,
269    ) {
270        self.writes.extend(entries);
271    }
272
273    /// Same as [`Self::extend_reads`], but for consume grants.
274    pub(crate) fn extend_consumes(
275        &mut self,
276        entries: impl IntoIterator<Item = (TypeId, &'static str)>,
277    ) {
278        self.consumes.extend(entries);
279    }
280}
281
282/// The kind of [`Context`] access a [`Step`](crate::Step) performed, used to
283/// describe an [`AccessViolation`].
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
285pub enum AccessKind {
286    /// The step called [`Context::get`] or [`Context::contains`] (or the
287    /// read half of [`Context::get_mut`]/[`Context::take`]).
288    Read,
289    /// The step called [`Context::insert`] (or the write half of
290    /// [`Context::get_mut`]/[`Context::take`]).
291    Write,
292    /// The step called [`Context::take`].
293    Consume,
294}
295
296/// Records an undeclared [`Context`] access: a step read, wrote, or consumed
297/// a type its [`AccessSpec`] didn't grant.
298///
299/// [`Pipeline::run`](crate::Pipeline::run) surfaces this as
300/// [`PipelineError::AccessViolation`](crate::PipelineError::AccessViolation)
301/// as soon as the offending step returns.
302#[derive(Debug, Clone, PartialEq, Eq)]
303pub struct AccessViolation {
304    /// The name of the step that performed the undeclared access.
305    pub step: String,
306    /// The [`type_name`] of the entry that was accessed.
307    pub entry: &'static str,
308    /// Which kind of access was attempted.
309    pub kind: AccessKind,
310}
311
312impl AccessViolation {
313    pub(crate) fn verb(&self) -> &'static str {
314        match self.kind {
315            AccessKind::Read => "read",
316            AccessKind::Write => "wrote",
317            AccessKind::Consume => "consumed",
318        }
319    }
320}
321
322/// A type-keyed store of at most one value per type, shared across the
323/// steps of a running [`Pipeline`](crate::Pipeline).
324///
325/// Values are stored and retrieved by their Rust type rather than by name:
326/// [`insert`](Self::insert) stores at most one `T` at a time, and
327/// [`get`](Self::get)/[`get_mut`](Self::get_mut)/[`take`](Self::take)
328/// retrieve it by inferring `T` from the call site.
329///
330/// While a [`Pipeline`](crate::Pipeline) is running, `Context` also enforces
331/// the active step's [`AccessSpec`]: a `get`/`get_mut`/`insert`/`take`/
332/// `contains` call for a type the step didn't declare returns `None`/`false`
333/// instead of the real value, and records an [`AccessViolation`] that
334/// [`Pipeline::run`](crate::Pipeline::run) turns into an error. Used
335/// directly, outside of a pipeline, a fresh `Context` has no active step and
336/// every access is unrestricted.
337#[derive(Debug, Default)]
338pub struct Context {
339    entries: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
340    active: Option<(String, AccessSpec)>,
341    violation: RefCell<Option<AccessViolation>>,
342}
343
344impl Context {
345    /// Creates an empty context with no stored values and no active step.
346    ///
347    /// # Examples
348    ///
349    /// ```
350    /// use pipeline_toolkit::Context;
351    ///
352    /// let mut ctx = Context::new();
353    /// assert!(!ctx.contains::<i32>());
354    /// ```
355    pub fn new() -> Self {
356        Self::default()
357    }
358
359    /// Reads a value of type `T` from the context.
360    ///
361    /// Returns `None` both when no value of type `T` has been inserted and
362    /// when the active step's [`AccessSpec`] doesn't grant it read access —
363    /// the two cases are indistinguishable from the return value alone.
364    ///
365    /// Takes `&self` (unlike [`Self::get_mut`]/[`Self::take`], which need
366    /// exclusive access to mutate or remove the entry) so that a step can
367    /// read several distinct types without the borrow checker forcing it to
368    /// finish with one reference before requesting another.
369    ///
370    /// # Examples
371    ///
372    /// ```
373    /// use pipeline_toolkit::Context;
374    ///
375    /// struct Marker(i32);
376    ///
377    /// let mut ctx = Context::new();
378    /// ctx.insert(Marker(7));
379    /// assert_eq!(ctx.get::<Marker>().map(|m| m.0), Some(7));
380    /// ```
381    pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T> {
382        if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Read) {
383            return None;
384        }
385        self.entries
386            .get(&TypeId::of::<T>())
387            .and_then(|v| v.downcast_ref())
388    }
389
390    /// Mutably borrows a value of type `T` from the context, for in-place
391    /// mutation.
392    ///
393    /// Returns `None` both when no value of type `T` is present and when
394    /// the active step's [`AccessSpec`] doesn't grant it both read and
395    /// write access — `get_mut` needs both, since it lets the caller
396    /// observe the prior value as well as replace it. Pair this with
397    /// [`AccessSpec::reads_writes`], not [`AccessSpec::writes`] alone.
398    ///
399    /// # Examples
400    ///
401    /// ```
402    /// use pipeline_toolkit::Context;
403    ///
404    /// struct Counter(i32);
405    ///
406    /// let mut ctx = Context::new();
407    /// ctx.insert(Counter(1));
408    /// ctx.get_mut::<Counter>().unwrap().0 += 1;
409    /// assert_eq!(ctx.get::<Counter>().map(|c| c.0), Some(2));
410    /// ```
411    pub fn get_mut<T: Send + Sync + 'static>(&mut self) -> Option<&mut T> {
412        if !self.check_read_and_write(TypeId::of::<T>(), type_name::<T>()) {
413            return None;
414        }
415        self.entries
416            .get_mut(&TypeId::of::<T>())
417            .and_then(|v| v.downcast_mut())
418    }
419
420    /// Stores `value`, replacing any existing value of type `T`.
421    ///
422    /// Returns the replaced value — but only if the active step's
423    /// [`AccessSpec`] also grants read access to `T`. Insert itself only
424    /// requires write access; handing back the overwritten value would let
425    /// a write-only step observe data it never declared reading, so that
426    /// case returns `None` even though the overwrite still happens.
427    ///
428    /// # Examples
429    ///
430    /// ```
431    /// use pipeline_toolkit::Context;
432    ///
433    /// struct Marker(i32);
434    ///
435    /// let mut ctx = Context::new();
436    /// assert!(ctx.insert(Marker(1)).is_none());
437    /// let previous = ctx.insert(Marker(2));
438    /// assert_eq!(previous.map(|m| m.0), Some(1));
439    /// ```
440    pub fn insert<T: Send + Sync + 'static>(&mut self, value: T) -> Option<T> {
441        if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Write) {
442            return None;
443        }
444        let previous = self
445            .entries
446            .insert(TypeId::of::<T>(), Box::new(value))
447            .and_then(|v| v.downcast().ok())
448            .map(|v| *v);
449        if self.can_read_active(TypeId::of::<T>()) {
450            previous
451        } else {
452            None
453        }
454    }
455
456    /// Removes and returns the value of type `T`, if present.
457    ///
458    /// Requires the active step's [`AccessSpec`] to have granted
459    /// [`AccessSpec::consumes`] specifically, not just
460    /// [`AccessSpec::reads_writes`]: the latter only promises in-place
461    /// mutation via [`Self::get_mut`], so
462    /// [`PipelineBuilder::build`](crate::PipelineBuilder::build) still
463    /// treats the type as written afterward. Accepting `reads_writes` here
464    /// too would let a step remove a value that build-time validation
465    /// believes is still present for downstream readers.
466    ///
467    /// # Examples
468    ///
469    /// ```
470    /// use pipeline_toolkit::Context;
471    ///
472    /// struct Payload(i32);
473    ///
474    /// let mut ctx = Context::new();
475    /// ctx.insert(Payload(5));
476    /// assert_eq!(ctx.take::<Payload>().map(|p| p.0), Some(5));
477    /// assert!(!ctx.contains::<Payload>());
478    /// ```
479    pub fn take<T: Send + Sync + 'static>(&mut self) -> Option<T> {
480        let id = TypeId::of::<T>();
481        let entry = type_name::<T>();
482        if !self.check_read_and_write(id, entry) {
483            return None;
484        }
485        if !self.check(id, entry, AccessKind::Consume) {
486            return None;
487        }
488        self.entries
489            .remove(&TypeId::of::<T>())
490            .and_then(|v| v.downcast().ok())
491            .map(|v| *v)
492    }
493
494    /// Reports whether a value of type `T` is currently stored.
495    ///
496    /// Like [`Self::get`], returns `false` both when `T` is absent and when
497    /// the active step's [`AccessSpec`] doesn't grant it read access.
498    ///
499    /// # Examples
500    ///
501    /// ```
502    /// use pipeline_toolkit::Context;
503    ///
504    /// struct Marker;
505    ///
506    /// let mut ctx = Context::new();
507    /// assert!(!ctx.contains::<Marker>());
508    /// ctx.insert(Marker);
509    /// assert!(ctx.contains::<Marker>());
510    /// ```
511    pub fn contains<T: Send + Sync + 'static>(&mut self) -> bool {
512        if !self.check(TypeId::of::<T>(), type_name::<T>(), AccessKind::Read) {
513            return false;
514        }
515        self.entries.contains_key(&TypeId::of::<T>())
516    }
517
518    fn can_read_active(&self, id: TypeId) -> bool {
519        match &self.active {
520            Some((_, spec)) => spec.can_read(id),
521            None => true,
522        }
523    }
524
525    /// Requires both Read and Write access, checking Read first and
526    /// recording only that violation if it fails, matching how
527    /// [`Self::get_mut`] and [`Self::take`] both need exclusive access to
528    /// an entry they're also allowed to read.
529    fn check_read_and_write(&self, id: TypeId, entry: &'static str) -> bool {
530        self.check(id, entry, AccessKind::Read) && self.check(id, entry, AccessKind::Write)
531    }
532
533    fn check(&self, id: TypeId, entry: &'static str, kind: AccessKind) -> bool {
534        let Some((step, spec)) = &self.active else {
535            return true;
536        };
537
538        let allowed = match kind {
539            AccessKind::Read => spec.can_read(id),
540            AccessKind::Write => spec.can_write(id),
541            AccessKind::Consume => spec.can_consume(id),
542        };
543
544        if !allowed {
545            let mut violation = self.violation.borrow_mut();
546            if violation.is_none() {
547                *violation = Some(AccessViolation {
548                    step: step.clone(),
549                    entry,
550                    kind,
551                });
552            }
553        }
554
555        allowed
556    }
557
558    pub(crate) fn set_active(&mut self, step: String, spec: AccessSpec) {
559        self.active = Some((step, spec));
560    }
561
562    pub(crate) fn clear_active(&mut self) {
563        self.active = None;
564    }
565
566    pub(crate) fn take_violation(&mut self) -> Option<AccessViolation> {
567        self.violation.borrow_mut().take()
568    }
569}
570
571#[cfg(test)]
572mod test {
573    use super::*;
574
575    struct Alpha(i32);
576    struct Beta(&'static str);
577
578    #[test]
579    fn new_creates_spec_with_no_access() {
580        let spec = AccessSpec::new();
581        assert!(!spec.can_read(TypeId::of::<Alpha>()));
582        assert!(!spec.can_write(TypeId::of::<Alpha>()));
583    }
584
585    #[test]
586    fn default_creates_spec_with_no_access() {
587        let spec = AccessSpec::default();
588        assert!(!spec.can_read(TypeId::of::<Alpha>()));
589        assert!(!spec.can_write(TypeId::of::<Alpha>()));
590    }
591
592    #[test]
593    fn reads_grants_read_access_for_type() {
594        let spec = AccessSpec::new().reads::<Alpha>();
595        assert!(spec.can_read(TypeId::of::<Alpha>()));
596    }
597
598    #[test]
599    fn reads_does_not_grant_write_access() {
600        let spec = AccessSpec::new().reads::<Alpha>();
601        assert!(!spec.can_write(TypeId::of::<Alpha>()));
602    }
603
604    #[test]
605    fn writes_grants_write_access_for_type() {
606        let spec = AccessSpec::new().writes::<Alpha>();
607        assert!(spec.can_write(TypeId::of::<Alpha>()));
608    }
609
610    #[test]
611    fn writes_does_not_grant_read_access() {
612        let spec = AccessSpec::new().writes::<Alpha>();
613        assert!(!spec.can_read(TypeId::of::<Alpha>()));
614    }
615
616    #[test]
617    fn reads_writes_grants_both_read_and_write_access() {
618        let spec = AccessSpec::new().reads_writes::<Alpha>();
619        assert!(spec.can_read(TypeId::of::<Alpha>()));
620        assert!(spec.can_write(TypeId::of::<Alpha>()));
621    }
622
623    #[test]
624    fn consumes_grants_both_read_and_write_access() {
625        let spec = AccessSpec::new().consumes::<Alpha>();
626        assert!(spec.can_read(TypeId::of::<Alpha>()));
627        assert!(spec.can_write(TypeId::of::<Alpha>()));
628    }
629
630    #[test]
631    fn consume_entries_yields_typeid_and_type_name() {
632        let spec = AccessSpec::new().consumes::<Alpha>();
633        let entries: Vec<_> = spec.consume_entries().collect();
634        assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
635    }
636
637    #[test]
638    fn consume_entries_is_empty_for_new_spec() {
639        assert_eq!(AccessSpec::new().consume_entries().count(), 0);
640    }
641
642    #[test]
643    fn reads_writes_does_not_mark_type_as_consumed() {
644        let spec = AccessSpec::new().reads_writes::<Alpha>();
645        assert_eq!(spec.consume_entries().count(), 0);
646    }
647
648    #[test]
649    fn reads_is_chainable_across_multiple_types() {
650        let spec = AccessSpec::new().reads::<Alpha>().reads::<Beta>();
651        assert!(spec.can_read(TypeId::of::<Alpha>()));
652        assert!(spec.can_read(TypeId::of::<Beta>()));
653    }
654
655    #[test]
656    fn read_entries_yields_typeid_and_type_name() {
657        let spec = AccessSpec::new().reads::<Alpha>();
658        let entries: Vec<_> = spec.read_entries().collect();
659        assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
660    }
661
662    #[test]
663    fn write_entries_yields_typeid_and_type_name() {
664        let spec = AccessSpec::new().writes::<Alpha>();
665        let entries: Vec<_> = spec.write_entries().collect();
666        assert_eq!(entries, vec![(TypeId::of::<Alpha>(), type_name::<Alpha>())]);
667    }
668
669    #[test]
670    fn clone_preserves_read_and_write_grants() {
671        let spec = AccessSpec::new().reads::<Alpha>().writes::<Beta>();
672        let cloned = spec.clone();
673        assert!(cloned.can_read(TypeId::of::<Alpha>()));
674        assert!(cloned.can_write(TypeId::of::<Beta>()));
675        assert!(!cloned.can_write(TypeId::of::<Alpha>()));
676        assert!(!cloned.can_read(TypeId::of::<Beta>()));
677    }
678
679    #[test]
680    fn can_read_returns_false_for_unregistered_type() {
681        let spec = AccessSpec::new().writes::<Alpha>();
682        assert!(!spec.can_read(TypeId::of::<Alpha>()));
683    }
684
685    #[test]
686    fn can_write_returns_false_for_unregistered_type() {
687        let spec = AccessSpec::new().reads::<Alpha>();
688        assert!(!spec.can_write(TypeId::of::<Alpha>()));
689    }
690
691    #[test]
692    fn read_entries_is_empty_for_new_spec() {
693        assert_eq!(AccessSpec::new().read_entries().count(), 0);
694    }
695
696    #[test]
697    fn write_entries_is_empty_for_new_spec() {
698        assert_eq!(AccessSpec::new().write_entries().count(), 0);
699    }
700
701    #[test]
702    fn eq_returns_true_for_same_variant() {
703        assert_eq!(AccessKind::Read, AccessKind::Read);
704    }
705
706    #[test]
707    fn eq_returns_false_for_different_variant() {
708        assert_ne!(AccessKind::Read, AccessKind::Write);
709    }
710
711    #[test]
712    fn clone_and_copy_produce_equal_value() {
713        let a = AccessKind::Write;
714        let b = a;
715        assert_eq!(a, b);
716        assert_eq!(a, a.clone());
717    }
718
719    fn sample_violation() -> AccessViolation {
720        AccessViolation {
721            step: "load".to_string(),
722            entry: "Alpha",
723            kind: AccessKind::Read,
724        }
725    }
726
727    #[test]
728    fn clone_produces_equal_value() {
729        let violation = sample_violation();
730        assert_eq!(violation.clone(), violation);
731    }
732
733    #[test]
734    fn eq_returns_true_for_identical_fields() {
735        assert_eq!(sample_violation(), sample_violation());
736    }
737
738    #[test]
739    fn eq_returns_false_for_different_step() {
740        let mut other = sample_violation();
741        other.step = "save".to_string();
742        assert_ne!(sample_violation(), other);
743    }
744
745    #[test]
746    fn eq_returns_false_for_different_entry() {
747        let mut other = sample_violation();
748        other.entry = "Beta";
749        assert_ne!(sample_violation(), other);
750    }
751
752    #[test]
753    fn eq_returns_false_for_different_kind() {
754        let mut other = sample_violation();
755        other.kind = AccessKind::Write;
756        assert_ne!(sample_violation(), other);
757    }
758
759    #[test]
760    fn construct_with_empty_step_string_is_allowed() {
761        let violation = AccessViolation {
762            step: String::new(),
763            entry: "Alpha",
764            kind: AccessKind::Write,
765        };
766        assert_eq!(violation.step, "");
767    }
768
769    #[test]
770    fn new_creates_empty_context() {
771        let mut ctx = Context::new();
772        assert!(!ctx.contains::<Alpha>());
773        assert!(ctx.get::<Alpha>().is_none());
774    }
775
776    #[test]
777    fn default_behaves_like_new() {
778        let mut ctx = Context::default();
779        assert!(!ctx.contains::<Alpha>());
780        assert!(ctx.get::<Alpha>().is_none());
781    }
782
783    #[test]
784    fn contains_returns_true_after_insert() {
785        let mut ctx = Context::new();
786        ctx.insert(Alpha(1));
787        assert!(ctx.contains::<Alpha>());
788    }
789
790    #[test]
791    fn insert_returns_none_for_first_value() {
792        let mut ctx = Context::new();
793        assert!(ctx.insert(Alpha(1)).is_none());
794    }
795
796    #[test]
797    fn insert_returns_previous_value_when_overwriting_same_type() {
798        let mut ctx = Context::new();
799        ctx.insert(Alpha(1));
800        let previous = ctx.insert(Alpha(2));
801        assert_eq!(previous.map(|a| a.0), Some(1));
802    }
803
804    #[test]
805    fn get_returns_reference_to_inserted_value() {
806        let mut ctx = Context::new();
807        ctx.insert(Alpha(42));
808        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(42));
809    }
810
811    #[test]
812    fn get_mut_mutation_is_visible_via_get() {
813        let mut ctx = Context::new();
814        ctx.insert(Alpha(1));
815        ctx.get_mut::<Alpha>().unwrap().0 = 99;
816        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(99));
817    }
818
819    #[test]
820    fn take_returns_value_and_removes_it_from_context() {
821        let mut ctx = Context::new();
822        ctx.insert(Alpha(7));
823        assert_eq!(ctx.take::<Alpha>().map(|a| a.0), Some(7));
824        assert!(!ctx.contains::<Alpha>());
825    }
826
827    #[test]
828    fn get_allows_holding_references_to_two_distinct_types_simultaneously() {
829        let mut ctx = Context::new();
830        ctx.insert(Alpha(1));
831        ctx.insert(Beta("hello"));
832        let a = ctx.get::<Alpha>().unwrap();
833        let b = ctx.get::<Beta>().unwrap();
834        assert_eq!(a.0, 1);
835        assert_eq!(b.0, "hello");
836    }
837
838    #[test]
839    fn context_stores_multiple_distinct_types_independently() {
840        let mut ctx = Context::new();
841        ctx.insert(Alpha(1));
842        ctx.insert(Beta("hello"));
843        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
844        assert_eq!(ctx.get::<Beta>().map(|b| b.0), Some("hello"));
845    }
846
847    #[test]
848    fn contains_returns_false_when_type_absent() {
849        let mut ctx = Context::new();
850        assert!(!ctx.contains::<Alpha>());
851    }
852
853    #[test]
854    fn get_returns_none_when_type_absent() {
855        let ctx = Context::new();
856        assert!(ctx.get::<Alpha>().is_none());
857    }
858
859    #[test]
860    fn get_mut_returns_none_when_type_absent() {
861        let mut ctx = Context::new();
862        assert!(ctx.get_mut::<Alpha>().is_none());
863    }
864
865    #[test]
866    fn take_returns_none_when_type_absent() {
867        let mut ctx = Context::new();
868        assert!(ctx.take::<Alpha>().is_none());
869    }
870
871    #[test]
872    fn get_succeeds_when_active_spec_grants_read() {
873        let mut ctx = Context::new();
874        ctx.insert(Alpha(1));
875        ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
876        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
877        assert!(ctx.take_violation().is_none());
878    }
879
880    #[test]
881    fn insert_succeeds_when_active_spec_grants_write() {
882        let mut ctx = Context::new();
883        ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
884        assert!(ctx.insert(Alpha(1)).is_none());
885        ctx.clear_active();
886        assert!(ctx.contains::<Alpha>());
887        assert!(ctx.take_violation().is_none());
888    }
889
890    #[test]
891    fn insert_does_not_require_read_access() {
892        let mut ctx = Context::new();
893        ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
894        ctx.insert(Alpha(1));
895        ctx.clear_active();
896        assert!(ctx.contains::<Alpha>());
897        assert!(ctx.take_violation().is_none());
898    }
899
900    #[test]
901    fn get_mut_succeeds_when_active_spec_grants_read_and_write() {
902        let mut ctx = Context::new();
903        ctx.insert(Alpha(1));
904        ctx.set_active(
905            "step".to_string(),
906            AccessSpec::new().reads_writes::<Alpha>(),
907        );
908        ctx.get_mut::<Alpha>().unwrap().0 = 2;
909        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(2));
910        assert!(ctx.take_violation().is_none());
911    }
912
913    #[test]
914    fn take_succeeds_when_active_spec_grants_consumes() {
915        let mut ctx = Context::new();
916        ctx.insert(Alpha(1));
917        ctx.set_active("step".to_string(), AccessSpec::new().consumes::<Alpha>());
918        assert_eq!(ctx.take::<Alpha>().map(|a| a.0), Some(1));
919        assert!(ctx.take_violation().is_none());
920    }
921
922    #[test]
923    fn take_denied_and_records_consume_violation_when_only_reads_writes_is_granted() {
924        let mut ctx = Context::new();
925        ctx.insert(Alpha(1));
926        ctx.set_active(
927            "step".to_string(),
928            AccessSpec::new().reads_writes::<Alpha>(),
929        );
930        assert!(ctx.take::<Alpha>().is_none());
931        assert!(ctx.contains::<Alpha>());
932        assert_eq!(
933            ctx.take_violation(),
934            Some(AccessViolation {
935                step: "step".to_string(),
936                entry: type_name::<Alpha>(),
937                kind: AccessKind::Consume,
938            })
939        );
940    }
941
942    #[test]
943    fn get_without_active_step_ignores_access_spec() {
944        let mut ctx = Context::new();
945        ctx.insert(Alpha(1));
946        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
947        assert!(ctx.take_violation().is_none());
948    }
949
950    #[test]
951    fn clear_active_removes_restriction_and_allows_subsequent_access() {
952        let mut ctx = Context::new();
953        ctx.insert(Alpha(1));
954        ctx.set_active("step".to_string(), AccessSpec::new());
955        ctx.clear_active();
956        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(1));
957        assert!(ctx.take_violation().is_none());
958    }
959
960    #[test]
961    fn get_denied_and_records_violation_when_read_not_granted() {
962        let mut ctx = Context::new();
963        ctx.insert(Alpha(1));
964        ctx.set_active("step".to_string(), AccessSpec::new());
965        assert!(ctx.get::<Alpha>().is_none());
966        assert_eq!(
967            ctx.take_violation(),
968            Some(AccessViolation {
969                step: "step".to_string(),
970                entry: type_name::<Alpha>(),
971                kind: AccessKind::Read,
972            })
973        );
974    }
975
976    #[test]
977    fn insert_does_not_return_previous_value_without_read_access() {
978        let mut ctx = Context::new();
979        ctx.insert(Alpha(1));
980        ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
981        let previous = ctx.insert(Alpha(2));
982        assert!(previous.is_none());
983        assert!(ctx.take_violation().is_none());
984        ctx.clear_active();
985        assert_eq!(ctx.get::<Alpha>().map(|a| a.0), Some(2));
986    }
987
988    #[test]
989    fn insert_denied_and_records_violation_when_write_not_granted() {
990        let mut ctx = Context::new();
991        ctx.set_active("step".to_string(), AccessSpec::new());
992        assert!(ctx.insert(Alpha(1)).is_none());
993        assert!(!ctx.contains::<Alpha>());
994        assert_eq!(
995            ctx.take_violation(),
996            Some(AccessViolation {
997                step: "step".to_string(),
998                entry: type_name::<Alpha>(),
999                kind: AccessKind::Write,
1000            })
1001        );
1002    }
1003
1004    #[test]
1005    fn insert_denied_even_when_read_is_granted_but_write_is_not() {
1006        let mut ctx = Context::new();
1007        ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
1008        assert!(ctx.insert(Alpha(1)).is_none());
1009        assert!(!ctx.contains::<Alpha>());
1010        assert_eq!(
1011            ctx.take_violation().map(|v| v.kind),
1012            Some(AccessKind::Write)
1013        );
1014    }
1015
1016    #[test]
1017    fn get_mut_denied_and_records_read_violation_when_read_not_granted() {
1018        let mut ctx = Context::new();
1019        ctx.insert(Alpha(1));
1020        ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
1021        assert!(ctx.get_mut::<Alpha>().is_none());
1022        assert_eq!(ctx.take_violation().map(|v| v.kind), Some(AccessKind::Read));
1023    }
1024
1025    #[test]
1026    fn get_mut_denied_and_records_write_violation_when_read_granted_but_write_not() {
1027        let mut ctx = Context::new();
1028        ctx.insert(Alpha(1));
1029        ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
1030        assert!(ctx.get_mut::<Alpha>().is_none());
1031        assert_eq!(
1032            ctx.take_violation().map(|v| v.kind),
1033            Some(AccessKind::Write)
1034        );
1035    }
1036
1037    #[test]
1038    fn take_denied_and_records_read_violation_when_read_not_granted() {
1039        let mut ctx = Context::new();
1040        ctx.insert(Alpha(1));
1041        ctx.set_active("step".to_string(), AccessSpec::new().writes::<Alpha>());
1042        assert!(ctx.take::<Alpha>().is_none());
1043        assert_eq!(ctx.take_violation().map(|v| v.kind), Some(AccessKind::Read));
1044    }
1045
1046    #[test]
1047    fn take_denied_and_records_write_violation_when_read_granted_but_write_not() {
1048        let mut ctx = Context::new();
1049        ctx.insert(Alpha(1));
1050        ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
1051        assert!(ctx.take::<Alpha>().is_none());
1052        assert!(ctx.contains::<Alpha>());
1053        assert_eq!(
1054            ctx.take_violation().map(|v| v.kind),
1055            Some(AccessKind::Write)
1056        );
1057    }
1058
1059    #[test]
1060    fn contains_succeeds_when_active_spec_grants_read() {
1061        let mut ctx = Context::new();
1062        ctx.insert(Alpha(1));
1063        ctx.set_active("step".to_string(), AccessSpec::new().reads::<Alpha>());
1064        assert!(ctx.contains::<Alpha>());
1065        assert!(ctx.take_violation().is_none());
1066    }
1067
1068    #[test]
1069    fn contains_denied_and_records_violation_when_read_not_granted() {
1070        let mut ctx = Context::new();
1071        ctx.insert(Alpha(1));
1072        ctx.set_active("step".to_string(), AccessSpec::new());
1073        assert!(!ctx.contains::<Alpha>());
1074        assert_eq!(
1075            ctx.take_violation(),
1076            Some(AccessViolation {
1077                step: "step".to_string(),
1078                entry: type_name::<Alpha>(),
1079                kind: AccessKind::Read,
1080            })
1081        );
1082    }
1083
1084    #[test]
1085    fn take_violation_returns_none_when_no_violation_recorded() {
1086        let mut ctx = Context::new();
1087        assert!(ctx.take_violation().is_none());
1088    }
1089
1090    #[test]
1091    fn take_violation_removes_stored_violation() {
1092        let mut ctx = Context::new();
1093        ctx.set_active("step".to_string(), AccessSpec::new());
1094        ctx.insert(Alpha(1));
1095        assert!(ctx.take_violation().is_some());
1096        assert!(ctx.take_violation().is_none());
1097    }
1098
1099    #[test]
1100    fn take_violation_keeps_first_recorded_violation_when_multiple_denied_calls_occur() {
1101        let mut ctx = Context::new();
1102        ctx.set_active("step".to_string(), AccessSpec::new());
1103        ctx.insert(Alpha(1));
1104        ctx.insert(Beta("x"));
1105        let violation = ctx.take_violation().unwrap();
1106        assert_eq!(violation.entry, type_name::<Alpha>());
1107    }
1108
1109    #[test]
1110    fn clear_active_does_not_erase_already_recorded_violation() {
1111        let mut ctx = Context::new();
1112        ctx.set_active("step".to_string(), AccessSpec::new());
1113        ctx.insert(Alpha(1));
1114        ctx.clear_active();
1115        assert!(ctx.take_violation().is_some());
1116    }
1117}