Skip to main content

crisol_core/data/
ring.rs

1//! A fixed-capacity ring buffer for streaming measurements.
2
3use std::collections::VecDeque;
4
5use super::column::{Column, DataValue};
6use super::dataset::Dataset;
7use super::source::{ColumnSchema, DataError, DataSource};
8
9/// A ring of the newest rows with a fixed schema.
10#[derive(Clone, Debug)]
11/// # Example
12///
13/// ```
14/// use crisol_core::data::RingBuffer;
15/// ```
16pub struct RingBuffer {
17    capacity: usize,
18    schema: Vec<ColumnSchema>,
19    rows: VecDeque<Vec<DataValue>>,
20    revision: u64,
21}
22
23impl RingBuffer {
24    /// A ring with `capacity` rows. A capacity of zero becomes one.
25    pub fn new(capacity: usize, schema: impl IntoIterator<Item = ColumnSchema>) -> Self {
26        Self {
27            capacity: capacity.max(1),
28            schema: schema.into_iter().collect(),
29            rows: VecDeque::new(),
30            revision: 0,
31        }
32    }
33
34    /// The schema.
35    pub fn schema(&self) -> &[ColumnSchema] {
36        &self.schema
37    }
38
39    /// Number of buffered rows.
40    pub fn len(&self) -> usize {
41        self.rows.len()
42    }
43
44    /// Whether the ring is empty.
45    pub fn is_empty(&self) -> bool {
46        self.rows.is_empty()
47    }
48
49    /// Capacity.
50    pub fn capacity(&self) -> usize {
51        self.capacity
52    }
53
54    /// Append one row. The oldest row is dropped when the ring is full.
55    ///
56    /// # Errors
57    /// When the row length does not match the schema.
58    pub fn push(&mut self, row: impl IntoIterator<Item = DataValue>) -> Result<(), DataError> {
59        let row: Vec<DataValue> = row.into_iter().collect();
60        if row.len() != self.schema.len() {
61            return Err(DataError::Connector(format!(
62                "row has {} values, schema has {}",
63                row.len(),
64                self.schema.len()
65            )));
66        }
67        if self.rows.len() == self.capacity {
68            self.rows.pop_front();
69        }
70        self.rows.push_back(row);
71        self.revision += 1;
72        Ok(())
73    }
74
75    /// Remove every row.
76    pub fn clear(&mut self) {
77        self.rows.clear();
78        self.revision += 1;
79    }
80
81    /// A dataset of the buffered rows, oldest first.
82    pub fn snapshot(&self) -> Dataset {
83        self.snapshot_range(0..self.rows.len())
84    }
85
86    /// A dataset of the buffered rows in `range`, oldest first. A reader that pages
87    /// through the ring pays for its page, not for the whole buffer.
88    fn snapshot_range(&self, range: std::ops::Range<usize>) -> Dataset {
89        let end = range.end.min(self.rows.len());
90        let start = range.start.min(end);
91        let mut columns = Vec::with_capacity(self.schema.len());
92        for (index, schema) in self.schema.iter().enumerate() {
93            columns.push(column_from_schema(
94                schema,
95                self.rows
96                    .range(start..end)
97                    .map(|row| row.get(index).cloned().unwrap_or(DataValue::Null))
98                    .collect(),
99            ));
100        }
101        Dataset::from_columns(columns)
102    }
103}
104
105fn column_from_schema(schema: &ColumnSchema, values: Vec<DataValue>) -> Column {
106    let mut column = match schema.kind {
107        super::column::ColumnType::Float => Column::floats(
108            &schema.name,
109            values
110                .iter()
111                .map(|value| value.as_f64().unwrap_or(f64::NAN))
112                .collect::<Vec<_>>(),
113        ),
114        super::column::ColumnType::Int => Column::ints(
115            &schema.name,
116            values
117                .iter()
118                .map(|value| if let DataValue::Int(value) = value { *value } else { 0 })
119                .collect::<Vec<_>>(),
120        ),
121        super::column::ColumnType::Bool => Column::bools(
122            &schema.name,
123            values
124                .iter()
125                .map(|value| matches!(value, DataValue::Bool(true)))
126                .collect::<Vec<_>>(),
127        ),
128        super::column::ColumnType::Date => Column::dates(
129            &schema.name,
130            values
131                .iter()
132                .map(|value| if let DataValue::Date(value) = value { *value } else { 0 })
133                .collect::<Vec<_>>(),
134        ),
135        super::column::ColumnType::Time => Column::times(
136            &schema.name,
137            values
138                .iter()
139                .map(|value| if let DataValue::Time(value) = value { *value } else { 0 })
140                .collect::<Vec<_>>(),
141        ),
142        super::column::ColumnType::Category => Column::categories(
143            &schema.name,
144            values
145                .iter()
146                .map(|value| value.as_text().unwrap_or_default().to_owned())
147                .collect::<Vec<_>>(),
148        ),
149        _ => Column::text(
150            &schema.name,
151            values
152                .iter()
153                .map(|value| value.as_text().unwrap_or_default().to_owned())
154                .collect::<Vec<_>>(),
155        ),
156    };
157    let validity: Vec<bool> = values.iter().map(|value| !matches!(value, DataValue::Null)).collect();
158    if validity.iter().any(|valid| !valid) {
159        column = column.with_validity(validity);
160    }
161    column.metadata = schema.metadata.clone();
162    if let Some(unit) = &schema.unit {
163        column = column.with_unit(unit.clone());
164    }
165    column
166}
167
168impl DataSource for RingBuffer {
169    fn schema(&self) -> &[ColumnSchema] {
170        &self.schema
171    }
172
173    fn row_count(&self) -> usize {
174        self.rows.len()
175    }
176
177    fn read_range(&self, range: std::ops::Range<usize>) -> Result<Dataset, DataError> {
178        super::source::check_range(&range, self.rows.len())?;
179        Ok(self.snapshot_range(range))
180    }
181
182    fn revision(&self) -> u64 {
183        self.revision
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use super::*;
190    use crate::data::ColumnType;
191
192    fn ring() -> RingBuffer {
193        RingBuffer::new(
194            3,
195            [
196                ColumnSchema::new("t", ColumnType::Float),
197                ColumnSchema::new("v", ColumnType::Float),
198            ],
199        )
200    }
201
202    #[test]
203    fn the_oldest_row_is_dropped() {
204        let mut ring = ring();
205        for index in 0..5 {
206            ring.push([DataValue::Float(index as f64), DataValue::Float(index as f64 * 2.0)])
207                .expect("push");
208        }
209        assert_eq!(ring.len(), 3);
210        let snapshot = ring.snapshot();
211        assert_eq!(snapshot.row_count(), 3);
212        assert_eq!(snapshot.cell(0, 0), crate::data::CellValue::Float(2.0));
213        assert_eq!(ring.read_range(1..3).expect("read").row_count(), 2);
214    }
215
216    #[test]
217    fn row_width_is_checked() {
218        let mut ring = ring();
219        assert!(ring.push([DataValue::Float(1.0)]).is_err());
220        assert!(ring.is_empty());
221    }
222}