clips_bindings/data.rs
1//! Typed per-environment Rust data.
2//!
3//! CLIPS lets C extensions stash their own state in an environment through
4//! `AllocateEnvironmentData` and `GetEnvironmentData`, keyed by an integer slot
5//! from a registry shared with CLIPS itself and every other extension. That
6//! design exists so a C callback holding only an `Environment *` can find its
7//! state again.
8//!
9//! Rust callbacks in this crate never need that: each registration is handed
10//! its own context pointer directly. So instead of claiming CLIPS slots, which
11//! risks colliding with CLIPS or another extension, per-environment Rust state
12//! lives in the [`Environment`] itself, keyed by type. Nothing crosses the C
13//! boundary, values are dropped by Rust when the environment is dropped, and no
14//! cleanup callback can unwind into C.
15
16use std::any::{Any, TypeId};
17use std::collections::HashMap;
18
19use crate::Environment;
20
21/// Type-keyed storage attached to an environment.
22#[derive(Default)]
23pub(crate) struct EnvironmentData {
24 values: HashMap<TypeId, Box<dyn Any>>,
25}
26
27impl Environment {
28 /// Attaches a value to this environment, replacing and returning any
29 /// previous value of the same type.
30 pub fn insert_data<T: Any>(&mut self, value: T) -> Option<T> {
31 self.data
32 .values
33 .insert(TypeId::of::<T>(), Box::new(value))
34 .and_then(|previous| previous.downcast().ok())
35 .map(|previous| *previous)
36 }
37
38 /// Borrows the value of type `T` attached to this environment.
39 pub fn data<T: Any>(&self) -> Option<&T> {
40 self.data
41 .values
42 .get(&TypeId::of::<T>())
43 .and_then(|value| value.downcast_ref())
44 }
45
46 /// Mutably borrows the value of type `T` attached to this environment.
47 pub fn data_mut<T: Any>(&mut self) -> Option<&mut T> {
48 self.data
49 .values
50 .get_mut(&TypeId::of::<T>())
51 .and_then(|value| value.downcast_mut())
52 }
53
54 /// Detaches and returns the value of type `T`.
55 pub fn remove_data<T: Any>(&mut self) -> Option<T> {
56 self.data
57 .values
58 .remove(&TypeId::of::<T>())
59 .and_then(|value| value.downcast().ok())
60 .map(|value| *value)
61 }
62}