lace_data/
traits.rs

1use crate::Datum;
2use std::convert::TryFrom;
3
4pub trait AccumScore<T> {
5    /// Compute scores on the data using `score_fn` and add them to `scores`
6    fn accum_score<F: Fn(&T) -> f64>(&self, scores: &mut [f64], score_fn: &F);
7}
8
9/// A data container
10pub trait Container<T: Clone + TryFrom<Datum>> {
11    /// get the data slices and the start indices
12    fn get_slices(&self) -> Vec<(usize, &[T])>;
13
14    /// Get the entry at ix if it exists
15    fn get(&self, ix: usize) -> Option<T>;
16
17    /// Insert or overwrite an entry at ix
18    fn insert_overwrite(&mut self, ix: usize, x: T);
19
20    /// Append a new datum to the end of the container
21    fn push(&mut self, xopt: Option<T>);
22
23    /// Append n new empty entries to the container
24    fn upsize(&mut self, n: usize) {
25        (0..n).for_each(|_| self.push(None));
26    }
27
28    /// Get as cloned vector containing only the present data
29    fn present_cloned(&self) -> Vec<T>;
30
31    /// Remove and return the entry at ix if it exists. Used to mark a present
32    /// datum as missing, not to completely remove a record. Does not decrease
33    /// the length.
34    fn remove(&mut self, ix: usize) -> Option<T>;
35
36    // TODO: should return result type
37    fn push_datum(&mut self, x: Datum) {
38        match x {
39            Datum::Missing => self.push(None),
40            _ => {
41                if let Ok(val) = T::try_from(x) {
42                    self.push(Some(val));
43                } else {
44                    panic!("failed to convert datum");
45                }
46            }
47        }
48    }
49
50    fn insert_datum(&mut self, row_ix: usize, x: Datum) {
51        match x {
52            Datum::Missing => {
53                self.remove(row_ix);
54            }
55            _ => {
56                if let Ok(val) = T::try_from(x) {
57                    self.insert_overwrite(row_ix, val)
58                } else {
59                    panic!("failed to convert datum");
60                }
61            }
62        }
63    }
64}