alibi-core 0.8.0

Shared authentication contracts and backend-independent services for Alibi
Documentation
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::sync::Arc;

/// Typed settings and callbacks published during plugin initialization.
///
/// Registration is complete before requests begin; readers share immutable
/// values rather than interpreting configuration through JSON metadata.
#[derive(Clone, Default)]
pub struct ContextExtensions(HashMap<TypeId, Arc<dyn Any + Send + Sync>>);

impl ContextExtensions {
    pub fn insert<T: Any + Send + Sync>(&mut self, value: T) {
        _ = self.0.insert(TypeId::of::<T>(), Arc::new(value));
    }

    #[must_use]
    pub fn get<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
        Arc::clone(self.0.get(&TypeId::of::<T>())?).downcast().ok()
    }
}

impl ContextExtensions {
    /// An owned copy of the registered value, or its default when absent.
    #[must_use]
    pub(crate) fn cloned_or_default<T: Any + Send + Sync + Clone + Default>(&self) -> T {
        self.get::<T>()
            .map(|value| (*value).clone())
            .unwrap_or_default()
    }
}

impl std::fmt::Debug for ContextExtensions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ContextExtensions").finish_non_exhaustive()
    }
}