clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Typed per-environment Rust data.
//!
//! CLIPS lets C extensions stash their own state in an environment through
//! `AllocateEnvironmentData` and `GetEnvironmentData`, keyed by an integer slot
//! from a registry shared with CLIPS itself and every other extension. That
//! design exists so a C callback holding only an `Environment *` can find its
//! state again.
//!
//! Rust callbacks in this crate never need that: each registration is handed
//! its own context pointer directly. So instead of claiming CLIPS slots, which
//! risks colliding with CLIPS or another extension, per-environment Rust state
//! lives in the [`Environment`] itself, keyed by type. Nothing crosses the C
//! boundary, values are dropped by Rust when the environment is dropped, and no
//! cleanup callback can unwind into C.

use std::any::{Any, TypeId};
use std::collections::HashMap;

use crate::Environment;

/// Type-keyed storage attached to an environment.
#[derive(Default)]
pub(crate) struct EnvironmentData {
    values: HashMap<TypeId, Box<dyn Any>>,
}

impl Environment {
    /// Attaches a value to this environment, replacing and returning any
    /// previous value of the same type.
    pub fn insert_data<T: Any>(&mut self, value: T) -> Option<T> {
        self.data
            .values
            .insert(TypeId::of::<T>(), Box::new(value))
            .and_then(|previous| previous.downcast().ok())
            .map(|previous| *previous)
    }

    /// Borrows the value of type `T` attached to this environment.
    pub fn data<T: Any>(&self) -> Option<&T> {
        self.data
            .values
            .get(&TypeId::of::<T>())
            .and_then(|value| value.downcast_ref())
    }

    /// Mutably borrows the value of type `T` attached to this environment.
    pub fn data_mut<T: Any>(&mut self) -> Option<&mut T> {
        self.data
            .values
            .get_mut(&TypeId::of::<T>())
            .and_then(|value| value.downcast_mut())
    }

    /// Detaches and returns the value of type `T`.
    pub fn remove_data<T: Any>(&mut self) -> Option<T> {
        self.data
            .values
            .remove(&TypeId::of::<T>())
            .and_then(|value| value.downcast().ok())
            .map(|value| *value)
    }
}