Skip to main content

flow_value/
collection.rs

1//! `List`, `Dict` and `Set` (`data.md`).
2//!
3//! # What each costs
4//!
5//! A [`List`] is a window onto a shared double-ended buffer. Indexing, length
6//! and taking a contiguous part — the `[x, ..rest]` and `[..init, last]`
7//! patterns — cost constant time and share the buffer. Growing at either end
8//! or joining costs time in the elements added when nothing else holds the
9//! buffer, which is the case whenever the evaluator moves a list it will not
10//! read again (`done ++ [item]` in a fold), and copies the window otherwise.
11//! A part kept alive keeps its whole buffer alive.
12//!
13//! A [`Dict`] and a [`Set`] are sorted vectors. Lookup costs logarithmic time;
14//! inserting or removing costs linear time, done in place when nothing else
15//! holds the vector.
16//!
17//! None of this is observable: `data.md` leaves a representation to the
18//! implementation, and two equal values behave equally in every operation.
19
20use std::cmp::Ordering;
21use std::collections::VecDeque;
22use std::sync::Arc;
23
24use crate::error::DataError;
25use crate::int::Int;
26use crate::value::{Meta, Value, compare};
27
28/// Dropping a list nothing else holds hands its nested parts to
29/// `dismantle` in the value module, so a deep value drops without deep
30/// recursion.
31impl Drop for List {
32    fn drop(&mut self) {
33        if let Some(buffer) = self.buffer_mut() {
34            crate::value::dismantle(buffer.iter_mut());
35        }
36    }
37}
38
39/// A list: a finite sequence, in order.
40#[derive(Clone, Debug)]
41pub struct List {
42    pub(crate) buffer: Arc<VecDeque<Value>>,
43    pub(crate) start: usize,
44    length: usize,
45    /// What its elements measure, or what those of the list it was cut
46    /// from did.
47    pub(crate) meta: Meta,
48}
49
50impl Default for List {
51    fn default() -> Self {
52        List {
53            buffer: Arc::default(),
54            start: 0,
55            length: 0,
56            meta: Meta::EMPTY,
57        }
58    }
59}
60
61impl List {
62    /// Returns the empty list.
63    pub fn new() -> Self {
64        List::default()
65    }
66
67    /// Returns how many elements there are.
68    pub fn len(&self) -> usize {
69        self.length
70    }
71
72    /// Returns whether there are none.
73    pub fn is_empty(&self) -> bool {
74        self.length == 0
75    }
76
77    /// Returns the element at a zero-based position.
78    pub fn get(&self, index: usize) -> Option<&Value> {
79        if index >= self.length {
80            return None;
81        }
82        self.buffer.get(self.start + index)
83    }
84
85    /// Returns the element at a zero-based `Int` position: `None` for a
86    /// negative one or one not less than the length (`list.get`).
87    pub fn get_int(&self, index: &Int) -> Option<&Value> {
88        self.get(index.to_index()?)
89    }
90
91    /// Returns the elements, in order.
92    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator {
93        self.elements()
94    }
95
96    /// Returns the whole buffer when nothing else holds it.
97    pub(crate) fn buffer_mut(&mut self) -> Option<&mut VecDeque<Value>> {
98        Arc::get_mut(&mut self.buffer)
99    }
100
101    pub(crate) fn elements(&self) -> std::collections::vec_deque::Iter<'_, Value> {
102        self.buffer.range(self.start..self.start + self.length)
103    }
104
105    /// Returns the elements from `start` up to, not including, `end`, sharing
106    /// this list's buffer, or `None` unless `start ≤ end ≤ length`.
107    pub fn slice(&self, start: usize, end: usize) -> Option<List> {
108        if start > end || end > self.length {
109            return None;
110        }
111        Some(List {
112            buffer: Arc::clone(&self.buffer),
113            start: self.start + start,
114            length: end - start,
115            meta: self.meta,
116        })
117    }
118
119    /// Returns `self` with `item` added at the end.
120    #[must_use]
121    pub fn push_back(mut self, item: Value) -> List {
122        self.meta = self.meta.with(&item);
123        self.owned().push_back(item);
124        self.length += 1;
125        self
126    }
127
128    /// Returns `self` with `item` added at the front.
129    #[must_use]
130    pub fn push_front(mut self, item: Value) -> List {
131        self.meta = self.meta.with(&item);
132        self.owned().push_front(item);
133        self.length += 1;
134        self
135    }
136
137    /// Returns `self ++ other`.
138    ///
139    /// The elements are added to a buffer nothing else holds: `other`'s when
140    /// only it is unshared, or when both are and it is the longer, and
141    /// otherwise `self`'s, copied first if it is shared. A list grown one
142    /// element at a time from either end therefore costs time in what it adds.
143    #[must_use]
144    pub fn concat(mut self, mut other: List) -> List {
145        let meta = self.meta.join(other.meta);
146        let self_free = Arc::get_mut(&mut self.buffer).is_some();
147        let other_free = Arc::get_mut(&mut other.buffer).is_some();
148        let prepend = other_free && (!self_free || self.length < other.length);
149        if prepend {
150            let added = self.length;
151            let buffer = other.owned();
152            for item in self.iter().rev() {
153                buffer.push_front(item.clone());
154            }
155            other.length += added;
156            other.meta = meta;
157            other
158        } else {
159            let added = other.length;
160            let buffer = self.owned();
161            buffer.extend(other.iter().cloned());
162            self.length += added;
163            self.meta = meta;
164            self
165        }
166    }
167
168    /// Returns `items` reordered by `keys`, one key per item, stably: items
169    /// whose keys are equal keep their order (`list.sort_by`).
170    ///
171    /// Returns `None` when there is not exactly one key per item.
172    pub fn sort_by_keys(&self, keys: &[Value]) -> Result<Option<List>, DataError> {
173        if keys.len() != self.length {
174            return Ok(None);
175        }
176        let mut order: Vec<usize> = (0..self.length).collect();
177        let mut failure = None;
178        order.sort_by(|&a, &b| {
179            compare(&keys[a], &keys[b]).unwrap_or_else(|error| {
180                failure = Some(error);
181                Ordering::Equal
182            })
183        });
184        if let Some(error) = failure {
185            return Err(error);
186        }
187        Ok(Some(
188            order
189                .into_iter()
190                .map(|at| self.buffer[self.start + at].clone())
191                .collect(),
192        ))
193    }
194
195    /// Returns the buffer, holding exactly this list's elements and held by
196    /// nothing else, copying the window when the buffer is shared.
197    fn owned(&mut self) -> &mut VecDeque<Value> {
198        if Arc::get_mut(&mut self.buffer).is_none() {
199            self.buffer = Arc::new(self.iter().cloned().collect());
200            self.start = 0;
201        }
202        let (start, length) = (self.start, self.length);
203        self.start = 0;
204        let buffer = Arc::get_mut(&mut self.buffer).expect("the buffer was just made unshared");
205        buffer.truncate(start + length);
206        buffer.drain(..start);
207        buffer
208    }
209}
210
211impl FromIterator<Value> for List {
212    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
213        let buffer: VecDeque<Value> = items.into_iter().collect();
214        List {
215            meta: Meta::around(&buffer),
216            length: buffer.len(),
217            buffer: Arc::new(buffer),
218            start: 0,
219        }
220    }
221}
222
223/// Finds `key` in sorted `items`, comparing with `key_of`.
224fn search<T>(
225    items: &[T],
226    key: &Value,
227    key_of: impl Fn(&T) -> &Value,
228) -> Result<Result<usize, usize>, DataError> {
229    let mut failure = None;
230    let found = items.binary_search_by(|item| {
231        compare(key_of(item), key).unwrap_or_else(|error| {
232            failure = Some(error);
233            Ordering::Equal
234        })
235    });
236    failure.map_or(Ok(found), Err)
237}
238
239/// Sorts `items` stably by `key_of`, then keeps one item per key: the last,
240/// when `keep_last`, and otherwise the first.
241fn sort_unique<T>(
242    mut items: Vec<T>,
243    key_of: impl Fn(&T) -> &Value,
244    keep_last: bool,
245) -> Result<Vec<T>, DataError> {
246    let mut failure = None;
247    items.sort_by(|a, b| {
248        compare(key_of(a), key_of(b)).unwrap_or_else(|error| {
249            failure = Some(error);
250            Ordering::Equal
251        })
252    });
253    if let Some(error) = failure {
254        return Err(error);
255    }
256    if keep_last {
257        items.reverse();
258    }
259    // Equal keys are adjacent, and every comparison above succeeded, so
260    // these cannot fail; the stable sort put the first-written first, and the
261    // reversal put the last-written first, which is the one `dedup` keeps.
262    items.dedup_by(|later, earlier| compare(key_of(later), key_of(earlier)) == Ok(Ordering::Equal));
263    if keep_last {
264        items.reverse();
265    }
266    Ok(items)
267}
268
269impl Drop for Dict {
270    fn drop(&mut self) {
271        if let Some(entries) = self.entries_mut() {
272            crate::value::dismantle(entries.iter_mut().flat_map(|(key, value)| [key, value]));
273        }
274    }
275}
276
277/// A dictionary: keys mapped to values, sorted by key.
278#[derive(Clone, Debug)]
279pub struct Dict {
280    entries: Arc<Vec<(Value, Value)>>,
281    /// What its keys and values measure, or more once an entry was
282    /// replaced or removed.
283    pub(crate) meta: Meta,
284}
285
286impl Default for Dict {
287    fn default() -> Self {
288        Dict {
289            entries: Arc::default(),
290            meta: Meta::EMPTY,
291        }
292    }
293}
294
295impl Dict {
296    /// Returns the empty dictionary.
297    pub fn new() -> Self {
298        Dict::default()
299    }
300
301    /// Returns the dictionary of `entries`, where a later entry with a key
302    /// equal to an earlier one's wins (the dictionary literal's rule).
303    pub fn from_entries(
304        entries: impl IntoIterator<Item = (Value, Value)>,
305    ) -> Result<Dict, DataError> {
306        let entries = sort_unique(entries.into_iter().collect(), |(key, _)| key, true)?;
307        Ok(Dict {
308            meta: Meta::around(entries.iter().flat_map(|(key, value)| [key, value])),
309            entries: Arc::new(entries),
310        })
311    }
312
313    /// Returns how many entries there are.
314    pub fn len(&self) -> usize {
315        self.entries.len()
316    }
317
318    /// Returns whether there are none.
319    pub fn is_empty(&self) -> bool {
320        self.entries.is_empty()
321    }
322
323    pub(crate) fn entries(&self) -> &[(Value, Value)] {
324        &self.entries
325    }
326
327    /// Returns the entries when nothing else holds them.
328    pub(crate) fn entries_mut(&mut self) -> Option<&mut Vec<(Value, Value)>> {
329        Arc::get_mut(&mut self.entries)
330    }
331
332    /// Returns the entries, in key order.
333    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Value, &Value)> {
334        self.entries.iter().map(|(key, value)| (key, value))
335    }
336
337    /// Returns the keys, in key order.
338    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Value> {
339        self.entries.iter().map(|(key, _)| key)
340    }
341
342    /// Returns the values, in key order.
343    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
344        self.entries.iter().map(|(_, value)| value)
345    }
346
347    /// Returns the value at `key`.
348    pub fn get(&self, key: &Value) -> Result<Option<&Value>, DataError> {
349        Ok(search(&self.entries, key, |(candidate, _)| candidate)?
350            .ok()
351            .map(|at| &self.entries[at].1))
352    }
353
354    /// Returns `self` with `key` mapped to `value`, replacing any earlier
355    /// value.
356    pub fn insert(mut self, key: Value, value: Value) -> Result<Dict, DataError> {
357        let found = search(&self.entries, &key, |(candidate, _)| candidate)?;
358        self.meta = self.meta.with(&key).with(&value);
359        let entries = Arc::make_mut(&mut self.entries);
360        match found {
361            Ok(at) => entries[at] = (key, value),
362            Err(at) => entries.insert(at, (key, value)),
363        }
364        Ok(self)
365    }
366
367    /// Returns `self` without `key`.
368    pub fn remove(mut self, key: &Value) -> Result<Dict, DataError> {
369        if let Ok(at) = search(&self.entries, key, |(candidate, _)| candidate)? {
370            Arc::make_mut(&mut self.entries).remove(at);
371        }
372        Ok(self)
373    }
374}
375
376impl Drop for Set {
377    fn drop(&mut self) {
378        if let Some(items) = self.items_mut() {
379            crate::value::dismantle(items.iter_mut());
380        }
381    }
382}
383
384/// A set: distinct values, sorted.
385#[derive(Clone, Debug)]
386pub struct Set {
387    items: Arc<Vec<Value>>,
388    /// What its elements measure.
389    pub(crate) meta: Meta,
390}
391
392impl Default for Set {
393    fn default() -> Self {
394        Set {
395            items: Arc::default(),
396            meta: Meta::EMPTY,
397        }
398    }
399}
400
401impl Set {
402    /// Returns the set of `items`' distinct elements (`set.from`).
403    pub fn from_items(items: impl IntoIterator<Item = Value>) -> Result<Set, DataError> {
404        let items = sort_unique(items.into_iter().collect(), |item| item, false)?;
405        Ok(Set {
406            meta: Meta::around(&items),
407            items: Arc::new(items),
408        })
409    }
410
411    /// Returns how many elements there are.
412    pub fn len(&self) -> usize {
413        self.items.len()
414    }
415
416    /// Returns whether there are none.
417    pub fn is_empty(&self) -> bool {
418        self.items.is_empty()
419    }
420
421    /// Returns the elements, in order.
422    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Value> {
423        self.items.iter()
424    }
425
426    pub(crate) fn as_slice(&self) -> &[Value] {
427        &self.items
428    }
429
430    /// Returns the elements when nothing else holds them.
431    pub(crate) fn items_mut(&mut self) -> Option<&mut [Value]> {
432        Arc::get_mut(&mut self.items).map(Vec::as_mut_slice)
433    }
434
435    /// Returns whether `item` is an element.
436    pub fn contains(&self, item: &Value) -> Result<bool, DataError> {
437        Ok(search(&self.items, item, |candidate| candidate)?.is_ok())
438    }
439}