Skip to main content

clips_bindings/
multifield.rs

1//! Multifield values and the builder that produces them.
2
3use std::ffi::CString;
4use std::marker::PhantomData;
5use std::ptr::NonNull;
6
7use crate::{Environment, Fact, Instance, Result, Value, ffi};
8
9/// A retained CLIPS multifield: an ordered sequence of values.
10///
11/// Multifields do not nest. A field holding a multifield only arises from a
12/// slot; appending one to a builder splices its fields in.
13pub struct Multifield<'env> {
14    value: Value<'env>,
15}
16impl<'env> Multifield<'env> {
17    pub(crate) fn from_value(value: Value<'env>) -> Self {
18        Self { value }
19    }
20    /// The multifield as a plain CLIPS value, for APIs that accept any value.
21    pub fn value(&self) -> &Value<'env> {
22        &self.value
23    }
24    /// The number of fields.
25    pub fn len(&self) -> usize {
26        unsafe { (*self.raw()).length }
27    }
28
29    /// Whether the multifield has no fields.
30    pub fn is_empty(&self) -> bool {
31        self.len() == 0
32    }
33
34    /// The field at a zero-based index, retained independently of this
35    /// multifield. `None` if the index is out of range.
36    pub fn get(&self, index: usize) -> Option<Value<'env>> {
37        if index >= self.len() {
38            return None;
39        }
40        unsafe {
41            let first = std::ptr::addr_of!((*self.raw()).contents) as *const ffi::CLIPSValue;
42            let mut raw = *first.add(index);
43            ffi::RetainCV(self.value.environment().raw.as_ptr(), &mut raw);
44            Some(Value::from_retained_raw(self.value.environment(), raw))
45        }
46    }
47    /// Iterates the fields in order, each retained.
48    pub fn iter(&self) -> impl Iterator<Item = Value<'env>> + '_ {
49        (0..self.len()).map(|index| self.get(index).expect("validated multifield index"))
50    }
51    /// Joins the fields into a single string exactly as CLIPS `implode$` does:
52    /// fields separated by single spaces, with strings quoted and escaped.
53    pub fn implode(&self) -> String {
54        let environment = self.value.environment();
55        let mut argument = ffi::UDFValue {
56            supplemental_info: std::ptr::null_mut(),
57            value: self.value.raw(),
58            begin: 0,
59            range: self.len(),
60            next: std::ptr::null_mut(),
61        };
62        // The returned lexeme is ephemeral, so its contents are copied out
63        // before returning to CLIPS.
64        let lexeme = unsafe { ffi::ImplodeMultifield(environment.raw.as_ptr(), &mut argument) };
65        if lexeme.is_null() {
66            return String::new();
67        }
68        unsafe { std::ffi::CStr::from_ptr((*lexeme).contents) }
69            .to_string_lossy()
70            .into_owned()
71    }
72    pub(crate) fn raw(&self) -> *mut ffi::Multifield {
73        unsafe { self.value.raw().multifield }
74    }
75}
76
77/// Builds a multifield by appending fields in order.
78///
79/// The builder is reusable: [`MultifieldBuilder::build`] leaves it empty and
80/// ready for the next multifield.
81pub struct MultifieldBuilder<'env> {
82    raw: NonNull<ffi::MultifieldBuilder>,
83    environment: &'env Environment,
84    marker: PhantomData<&'env Environment>,
85}
86impl<'env> MultifieldBuilder<'env> {
87    pub(crate) fn new(environment: &'env Environment, capacity: usize) -> Result<Self> {
88        NonNull::new(unsafe { ffi::CreateMultifieldBuilder(environment.raw.as_ptr(), capacity) })
89            .map(|raw| Self {
90                raw,
91                environment,
92                marker: PhantomData,
93            })
94            .ok_or(crate::Error::EnvironmentCreation)
95    }
96    /// Appends an integer field.
97    pub fn integer(&mut self, value: i64) -> &mut Self {
98        unsafe { ffi::MBAppendInteger(self.raw.as_ptr(), value) };
99        self
100    }
101    /// Appends a float field.
102    pub fn float(&mut self, value: f64) -> &mut Self {
103        unsafe { ffi::MBAppendFloat(self.raw.as_ptr(), value) };
104        self
105    }
106    /// Appends a symbol field.
107    pub fn symbol(&mut self, value: &str) -> Result<&mut Self> {
108        let value = CString::new(value)?;
109        unsafe { ffi::MBAppendSymbol(self.raw.as_ptr(), value.as_ptr()) };
110        Ok(self)
111    }
112    /// Appends a string field.
113    pub fn string(&mut self, value: &str) -> Result<&mut Self> {
114        let value = CString::new(value)?;
115        unsafe { ffi::MBAppendString(self.raw.as_ptr(), value.as_ptr()) };
116        Ok(self)
117    }
118    /// Appends an instance-name field.
119    pub fn instance_name(&mut self, value: &str) -> Result<&mut Self> {
120        let value = CString::new(value)?;
121        unsafe { ffi::MBAppendInstanceName(self.raw.as_ptr(), value.as_ptr()) };
122        Ok(self)
123    }
124    /// Appends a fact address as a field.
125    pub fn fact(&mut self, value: &Fact<'env>) -> &mut Self {
126        unsafe { ffi::MBAppendFact(self.raw.as_ptr(), value.raw.as_ptr()) };
127        self
128    }
129    /// Appends an instance address as a field.
130    pub fn instance(&mut self, value: &Instance<'env>) -> &mut Self {
131        unsafe { ffi::MBAppendInstance(self.raw.as_ptr(), value.raw.as_ptr()) };
132        self
133    }
134    /// Appends another multifield.
135    ///
136    /// CLIPS multifields do not nest: its fields are spliced into this one.
137    pub fn multifield(&mut self, value: &Multifield<'env>) -> &mut Self {
138        unsafe { ffi::MBAppendMultifield(self.raw.as_ptr(), value.raw()) };
139        self
140    }
141    /// Appends an already existing CLIPS value.
142    ///
143    /// Fails with [`crate::Error::ForeignEnvironment`] if `value` belongs to
144    /// another environment, since CLIPS atoms are interned per environment.
145    pub fn value(&mut self, value: &Value<'env>) -> Result<&mut Self> {
146        let mut cv = self.environment.check_value(value)?;
147        unsafe { ffi::MBAppend(self.raw.as_ptr(), &mut cv) };
148        Ok(self)
149    }
150    /// Discards the appended fields without building anything.
151    pub fn reset(&mut self) {
152        unsafe { ffi::MBReset(self.raw.as_ptr()) }
153    }
154
155    /// Builds the multifield from the appended fields and empties the builder.
156    pub fn build(&mut self) -> Multifield<'env> {
157        let mut raw = ffi::CLIPSValue {
158            multifield: unsafe { ffi::MBCreate(self.raw.as_ptr()) },
159        };
160        unsafe { ffi::RetainCV(self.environment.raw.as_ptr(), &mut raw) };
161        Multifield::from_value(Value::from_retained_raw(self.environment, raw))
162    }
163}
164impl Drop for MultifieldBuilder<'_> {
165    fn drop(&mut self) {
166        unsafe { ffi::MBDispose(self.raw.as_ptr()) }
167    }
168}