1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
//! The facts module is used to separate the fact generation logic from the engine.
#[macro_use]
extern crate serde_derive;

use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::collections::hash_map::DefaultHasher;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::rc::Rc;

use compact::{CString, CVec};
use generational_arena::{Arena, Index as Handle};
use serde::export::fmt::Error;
use serde::export::Formatter;

/// Core of a fact consists of three strings
/// Type for ease of use
pub type FactCore = (CString, CString, CString);

/// Facts contains grouped information around a single class
///
/// Example: A Car can have multiple pieces of information associated:
///  The color is red.
///  It has 4 wheels, and 3 doors.
///  The brand is Ferrari
///
/// This information is stored in a standardized way for the phreak algorithm, in order to
/// efficiently match conditions against the known facts.
#[derive(Serialize, Deserialize)]
pub struct Facts {
    // note: for now we store this using multiple allocations, but ideally this would be
    // a single allocation of continues memory
    class: String,
    attrs: Vec<Rc<FactCore>>,
}

impl Facts {
    pub fn get_name(&self) -> &String {
        &self.class
    }

    pub fn iter_attrs(&self) -> std::slice::Iter<'_, Rc<(CString, CString, CString)>> {
        self.attrs.iter()
    }
}

impl Debug for Facts {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        let v: Vec<(&str, &str, &str)> = self.attrs.iter().map(|rc| {
            let b: &(CString, CString, CString) = rc.borrow();
            (&*b.0, &*b.1, &*b.2)
        }).collect();
        write!(f, "Facts{{ class='{}', attrs={:?} }}", self.class, v)
    }
}

impl Clone for Facts {
    fn clone(&self) -> Self {
        Facts{ class: self.class.to_owned(), attrs: self.attrs.clone() }
    }
}

impl Hash for Facts {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.class.hash(state);
        for attr in self.attrs.iter() {
            let b: &(CString, CString, CString) = attr.borrow();
            b.0.hash(state);
            b.1.hash(state);
            b.2.hash(state);
        }
    }
}

impl PartialEq for Facts {
    fn eq(&self, other: &Self) -> bool {
        let mut b = self.class == other.class && self.attrs.len() == other.attrs.len();
        let mut i = 0;
        while b && i < self.attrs.len() {
            let left: &(CString, CString, CString) = self.attrs[i].borrow();
            let right: &(CString, CString, CString) = other.attrs[i].borrow();
            b = *left.0 == *right.0 && *left.1 == *right.1 && *left.2 == *right.2;
            i = i + 1;
        }
        b
    }
}

/// To facilitate the creation of facts, we offer a builder pattern.
pub struct FactsBuilder {
    f: Option<Facts>,
}

impl FactsBuilder {
    /// Start building a new Facts object with the given class name
    pub fn new(name: String) -> Self {
        FactsBuilder { f: Some(Facts { class: name, attrs: vec!() }) }
    }

    /// Add one triple of information
    ///
    /// Triples can be of the format ( instance-id, attribute, value )
    pub fn add_attributes(mut self, field1: String, field2: String, field3: String) -> Self {
        match &mut self.f {
            None => panic!("Set classname first"),
            Some(facts) => {
                facts.attrs.push(Rc::new((
                    CString::from(field1),
                    CString::from(field2),
                    CString::from(field3))
                ));
            }
        }
        self
    }

    /// Add one triple of information
    ///
    /// Triples can be of the format ( instance-id, attribute, value )
    pub fn add_attributes_from_slice(mut self, field1: &str, field2: &str, field3: &str) -> Self {
        match &mut self.f {
            None => panic!("Set classname first"),
            Some(facts) => {
                let mut f = (
                    CString::new(),
                    CString::new(),
                    CString::new()
                );
                f.0.push_str(field1);
                f.1.push_str(field2);
                f.2.push_str(field3);
                facts.attrs.push(Rc::new(f));
            }
        }
        self
    }

    /// Finalize the facts object and return it
    pub fn build(self) -> Facts {
        self.f.unwrap()
    }
}

/// Long-time storage of facts
pub struct Store {
    arena: Arena<Facts>,
    handles: BTreeMap<u64, CVec<Handle>>,
}

impl Store {
    /// Create a new Store
    pub fn new() -> Self {
        Store { arena: Arena::new(), handles: BTreeMap::new() }
    }

    /// Add a single Facts object to the store, and return a Handle to it
    pub fn add_facts(&mut self, facts: Facts) -> Handle {
        let mut s = DefaultHasher::new();
        facts.hash(&mut s);
        let hash = s.finish();

        let handle = self.arena.insert(facts);

        match &mut self.handles.get_mut(&hash) {
            None => {
                let mut v = CVec::with_capacity(1);
                v.push(handle);
                self.handles.insert(hash, v);
            }
            Some(v) => {
                v.push(handle);
            }
        }
        handle
    }

    /// Remove a Facts object by its handle
    pub fn remove_facts(&mut self, handle: Handle) -> Option<Facts> {
        let facts = self.arena.remove(handle);
        match &facts {
            None => {}
            Some(f) => {
                let mut s = DefaultHasher::new();
                f.hash(&mut s);
                let hash = s.finish();
                match self.handles.get_mut(&hash) {
                    None => { panic!("Handle not found in Arena: {:?}", handle) }
                    Some(v) => {
                        let i = v.iter().enumerate().find(|h| h.1 == &handle).expect("Handle not found in bucket").0;
                        if v.len() == 1 {
                            v.pop();
                        } else {
                            if i == v.len() - 1 {
                                v.remove(i);
                            } else {
                                v.swap_remove(i);
                            }
                        }
                    }
                }
                self.handles.remove(&hash);
            }
        }
        facts
    }

    /// get the handle to a facts object
    pub fn find_facts(&self, facts: &Facts) -> Option<Handle> {
        let mut s = DefaultHasher::new();
        facts.hash(&mut s);
        let hash = s.finish();

        // get the handle for the given facts object from the bucket
        self.handles.get(&hash).and_then(|bucket| { // get the bucket
            bucket.iter().find(|index| { // find the entry
                self.arena[**index] == *facts
            }).and_then(|handle| { // return the handle
                Some(handle.clone())
            })
        })
    }
}


#[cfg(test)]
mod tests {
    use test_case::test_case;

    use super::*;

    // all below facts must hash to unique numbers
    #[test_case("class1", "1", "2", "3" => 16158846878046716253)]
    #[test_case("class1", "1", "2", "4" => 613009299209267635)]
    #[test_case("class1", "1", "4", "3" => 12936075590442499815)]
    #[test_case("class1", "4", "2", "3" => 13760569843112578439)]
    #[test_case("class2", "1", "2", "3" => 14167361993846938746)]
    fn test_hash(class: &str, f1: &str, f2: &str, f3: &str) -> u64 {
        let fact1 = FactsBuilder::new(class.to_owned())
            .add_attributes_from_slice(f1, f2, f3)
            .build();
        let mut h1 = DefaultHasher::new();
        fact1.hash(&mut h1);
        h1.finish()
    }

    #[test_case("1", "2", "3")]
    fn test_facts_store(f1: &str, f2: &str, f3: &str) {
        let fact = FactsBuilder::new("class1".to_owned())
            .add_attributes_from_slice(f1, f2, f3)
            .build();

        let mut s = Store::new();
        let index = s.add_facts(fact);

        let fact = FactsBuilder::new("class1".to_owned())
            .add_attributes_from_slice(f1, f2, f3)
            .build();
        assert_eq!(s.find_facts(&fact), Some(index));

        s.remove_facts(index);
        assert_eq!(s.find_facts(&fact), None);
    }
}