clips-bindings 0.1.2+clips-6.4.2

Safe, idiomatic, custom-written Rust bindings for the CLIPS 6.4.2 embedding API
Documentation
//! Retained CLIPS values.
//!
//! Every value handed out by this crate is retained on creation and
//! released exactly once on drop, so it stays valid across CLIPS's
//! garbage-collection points for as long as it is held.

use std::ffi::CStr;
use std::marker::PhantomData;

use crate::{environment::Environment, ffi};

/// A retained CLIPS value.
///
/// The `as_*` accessors return `None` when the value holds a different type,
/// rather than converting, so a type mismatch is visible instead of silent.
pub struct Value<'env> {
    environment: &'env Environment,
    raw: ffi::CLIPSValue,
    marker: PhantomData<&'env Environment>,
}

impl<'env> Value<'env> {
    pub(crate) fn new(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
        Self {
            environment,
            raw,
            marker: PhantomData,
        }
    }
    pub(crate) fn from_retained_raw(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
        Self {
            environment,
            raw,
            marker: PhantomData,
        }
    }
    /// Retains a value CLIPS just created and ties it to `environment`.
    pub(crate) fn retaining(environment: &'env Environment, raw: ffi::CLIPSValue) -> Self {
        let mut raw = raw;
        unsafe { ffi::RetainCV(environment.raw.as_ptr(), &mut raw) };
        Self::from_retained_raw(environment, raw)
    }
    /// The raw CLIPS type tag: 0 float, 1 integer, 2 symbol, 3 string,
    /// 4 multifield, 5 external address, 6 fact, 7 instance, 8 instance name,
    /// 9 void.
    pub fn type_code(&self) -> u16 {
        unsafe { (*self.raw.header).type_ }
    }

    /// The value as an integer, or `None` if it is not one.
    pub fn as_i64(&self) -> Option<i64> {
        (self.type_code() == 1).then(|| unsafe { (*self.raw.integer).contents })
    }

    /// The value as a float, or `None` if it is not one. Integers are not
    /// converted.
    pub fn as_f64(&self) -> Option<f64> {
        (self.type_code() == 0).then(|| unsafe { (*self.raw.float).contents })
    }

    /// The text of a symbol, string, or instance name.
    ///
    /// `None` for other types, and for text that is not valid UTF-8.
    pub fn as_str(&self) -> Option<&str> {
        matches!(self.type_code(), 2 | 3 | 8)
            .then(|| {
                unsafe { CStr::from_ptr((*self.raw.lexeme).contents) }
                    .to_str()
                    .ok()
            })
            .flatten()
    }
    /// A symbol's truth value.
    ///
    /// CLIPS treats every symbol except `FALSE` as true, so this returns
    /// `Some(true)` for any other symbol, and `None` for non-symbols.
    pub fn as_bool(&self) -> Option<bool> {
        (self.type_code() == 2).then(|| self.as_str() != Some("FALSE"))
    }

    /// The value as a multifield, or `None` if it is not one.
    pub fn as_multifield(&self) -> Option<crate::Multifield<'env>> {
        (self.type_code() == 4).then(|| crate::Multifield::from_value(self.clone_retained()))
    }

    /// The value as a retained fact handle, or `None` if it is not a fact
    /// address.
    pub fn as_fact(&self) -> Option<crate::Fact<'env>> {
        if self.type_code() != 6 {
            return None;
        }
        crate::Fact::retained(self.environment, unsafe { self.raw.fact })
    }

    /// The value as a retained instance handle, or `None` if it is not an
    /// instance address.
    pub fn as_instance(&self) -> Option<crate::Instance<'env>> {
        if self.type_code() != 7 {
            return None;
        }
        crate::Instance::retained(self.environment, unsafe { self.raw.instance })
    }
    pub(crate) fn clone_retained(&self) -> Self {
        let mut raw = self.raw;
        unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
        Self::from_retained_raw(self.environment, raw)
    }
    pub(crate) fn raw(&self) -> ffi::CLIPSValue {
        self.raw
    }
    pub(crate) fn environment(&self) -> &'env Environment {
        self.environment
    }
}

impl Drop for Value<'_> {
    fn drop(&mut self) {
        unsafe { ffi::ReleaseCV(self.environment.raw.as_ptr(), &mut self.raw) }
    }
}

impl std::fmt::Debug for Value<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(value) = self.as_i64() {
            return value.fmt(f);
        }
        if let Some(value) = self.as_f64() {
            return value.fmt(f);
        }
        if let Some(value) = self.as_str() {
            return value.fmt(f);
        }
        f.debug_struct("Value")
            .field("type_code", &self.type_code())
            .finish()
    }
}