Skip to main content

clips_bindings/
persistence.rs

1//! Saving and loading constructs, facts, and instances, in text and binary
2//! form.
3//!
4//! CLIPS reports counts with negative sentinels for failure; those become
5//! typed errors here.
6
7use std::ffi::CString;
8
9use crate::error::{Error, Result};
10use crate::{Environment, ffi};
11
12/// Selects which constructs are included when facts or instances are saved.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[repr(u32)]
15pub enum SaveScope {
16    /// Only constructs defined in the current module.
17    Local = 0,
18    /// Everything visible from the current module, including imports.
19    Visible = 1,
20}
21
22/// Identifies a persistence operation which CLIPS could not complete.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum PersistenceError {
25    /// Constructs could not be written as text, usually because the file could
26    /// not be opened.
27    SaveConstructs,
28    /// Constructs could not be written as a binary image.
29    BinarySaveConstructs,
30    /// The file could not be read, or is not a CLIPS binary construct image.
31    BinaryLoadConstructs,
32    /// Facts could not be written as text.
33    SaveFacts,
34    /// The file could not be read, or does not contain loadable facts.
35    LoadFacts,
36    /// Facts could not be written as a binary image.
37    BinarySaveFacts,
38    /// The file could not be read, or is not a CLIPS binary facts image.
39    BinaryLoadFacts,
40    /// Instances could not be written as text.
41    SaveInstances,
42    /// The file could not be read, or does not contain loadable instances.
43    LoadInstances,
44    /// The file could not be read, or does not contain restorable instances.
45    RestoreInstances,
46    /// Instances could not be written as a binary image.
47    BinarySaveInstances,
48    /// The file could not be read, or is not a CLIPS binary instances image.
49    BinaryLoadInstances,
50}
51
52fn count(result: std::ffi::c_long, operation: PersistenceError) -> Result<usize> {
53    usize::try_from(result).map_err(|_| Error::Persistence(operation))
54}
55
56impl Environment {
57    /// Saves all construct definitions as CLIPS source text.
58    pub fn save_constructs(&self, path: &str) -> Result<()> {
59        let path = CString::new(path)?;
60        unsafe { ffi::Save(self.raw.as_ptr(), path.as_ptr()) }
61            .then_some(())
62            .ok_or(Error::Persistence(PersistenceError::SaveConstructs))
63    }
64
65    /// Saves construct definitions in CLIPS' binary format.
66    pub fn binary_save_constructs(&self, path: &str) -> Result<()> {
67        let path = CString::new(path)?;
68        unsafe { ffi::Bsave(self.raw.as_ptr(), path.as_ptr()) }
69            .then_some(())
70            .ok_or(Error::Persistence(PersistenceError::BinarySaveConstructs))
71    }
72
73    /// Replaces the current construct set with a CLIPS binary image.
74    pub fn binary_load_constructs(&mut self, path: &str) -> Result<()> {
75        let path = CString::new(path)?;
76        unsafe { ffi::Bload(self.raw.as_ptr(), path.as_ptr()) }
77            .then_some(())
78            .ok_or(Error::Persistence(PersistenceError::BinaryLoadConstructs))
79    }
80
81    /// Whether a binary construct image is currently loaded.
82    ///
83    /// While it is, CLIPS refuses to define further constructs; clearing the
84    /// environment releases the image.
85    pub fn constructs_are_binary_loaded(&self) -> bool {
86        unsafe { ffi::Bloaded(self.raw.as_ptr()) }
87    }
88
89    /// Writes facts as `assert` text, returning how many were saved.
90    pub fn save_facts(&self, path: &str, scope: SaveScope) -> Result<usize> {
91        let path = CString::new(path)?;
92        count(
93            unsafe { ffi::SaveFacts(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
94            PersistenceError::SaveFacts,
95        )
96    }
97
98    /// Asserts the facts in a file written by [`Environment::save_facts`],
99    /// returning how many were loaded.
100    ///
101    /// The facts are added to whatever is already asserted; nothing is cleared
102    /// first.
103    pub fn load_facts(&mut self, path: &str) -> Result<usize> {
104        let path = CString::new(path)?;
105        count(
106            unsafe { ffi::LoadFacts(self.raw.as_ptr(), path.as_ptr()) },
107            PersistenceError::LoadFacts,
108        )
109    }
110
111    /// Asserts facts from CLIPS text rather than a file.
112    pub fn load_facts_str(&mut self, source: &str) -> Result<usize> {
113        let source = CString::new(source)?;
114        count(
115            unsafe {
116                ffi::LoadFactsFromString(
117                    self.raw.as_ptr(),
118                    source.as_ptr(),
119                    source.as_bytes().len(),
120                )
121            },
122            PersistenceError::LoadFacts,
123        )
124    }
125
126    /// Writes facts in CLIPS's binary format, which loads faster than text but
127    /// is not portable across CLIPS builds.
128    pub fn binary_save_facts(&self, path: &str, scope: SaveScope) -> Result<usize> {
129        let path = CString::new(path)?;
130        count(
131            unsafe { ffi::BinarySaveFacts(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
132            PersistenceError::BinarySaveFacts,
133        )
134    }
135
136    /// Asserts the facts in a binary file, returning how many were loaded.
137    pub fn binary_load_facts(&mut self, path: &str) -> Result<usize> {
138        let path = CString::new(path)?;
139        count(
140            unsafe { ffi::BinaryLoadFacts(self.raw.as_ptr(), path.as_ptr()) },
141            PersistenceError::BinaryLoadFacts,
142        )
143    }
144
145    /// Writes instances as `make-instance` text, returning how many were saved.
146    pub fn save_instances(&self, path: &str, scope: SaveScope) -> Result<usize> {
147        let path = CString::new(path)?;
148        count(
149            unsafe { ffi::SaveInstances(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
150            PersistenceError::SaveInstances,
151        )
152    }
153
154    /// Creates instances from a saved file through message passing, so
155    /// `init-slots` and slot daemons run.
156    ///
157    /// Use [`Environment::restore_instances`] to bypass message passing.
158    pub fn load_instances(&mut self, path: &str) -> Result<usize> {
159        let path = CString::new(path)?;
160        count(
161            unsafe { ffi::LoadInstances(self.raw.as_ptr(), path.as_ptr()) },
162            PersistenceError::LoadInstances,
163        )
164    }
165
166    /// Creates instances from CLIPS text rather than a file, with message
167    /// passing.
168    pub fn load_instances_str(&mut self, source: &str) -> Result<usize> {
169        let source = CString::new(source)?;
170        count(
171            unsafe {
172                ffi::LoadInstancesFromString(
173                    self.raw.as_ptr(),
174                    source.as_ptr(),
175                    source.as_bytes().len(),
176                )
177            },
178            PersistenceError::LoadInstances,
179        )
180    }
181
182    /// Creates instances from a saved file without message passing, so slots
183    /// are written directly and no handler runs.
184    ///
185    /// This restores the saved state exactly, where
186    /// [`Environment::load_instances`] would let handlers alter it.
187    pub fn restore_instances(&mut self, path: &str) -> Result<usize> {
188        let path = CString::new(path)?;
189        count(
190            unsafe { ffi::RestoreInstances(self.raw.as_ptr(), path.as_ptr()) },
191            PersistenceError::RestoreInstances,
192        )
193    }
194
195    /// Restores instances from CLIPS text rather than a file, without message
196    /// passing.
197    pub fn restore_instances_str(&mut self, source: &str) -> Result<usize> {
198        let source = CString::new(source)?;
199        count(
200            unsafe {
201                ffi::RestoreInstancesFromString(
202                    self.raw.as_ptr(),
203                    source.as_ptr(),
204                    source.as_bytes().len(),
205                )
206            },
207            PersistenceError::RestoreInstances,
208        )
209    }
210
211    /// Writes instances in CLIPS's binary format.
212    pub fn binary_save_instances(&self, path: &str, scope: SaveScope) -> Result<usize> {
213        let path = CString::new(path)?;
214        count(
215            unsafe { ffi::BinarySaveInstances(self.raw.as_ptr(), path.as_ptr(), scope as u32) },
216            PersistenceError::BinarySaveInstances,
217        )
218    }
219
220    /// Creates instances from a binary file, without message passing.
221    pub fn binary_load_instances(&mut self, path: &str) -> Result<usize> {
222        let path = CString::new(path)?;
223        count(
224            unsafe { ffi::BinaryLoadInstances(self.raw.as_ptr(), path.as_ptr()) },
225            PersistenceError::BinaryLoadInstances,
226        )
227    }
228}