flow-lang-value 0.1.0

The Flow runtime value model: data values, their equality, order and text, and the operations std's built-in types declare.
Documentation
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! `List`, `Dict` and `Set` (`data.md`).
//!
//! # What each costs
//!
//! A [`List`] is a window onto a shared double-ended buffer. Indexing, length
//! and taking a contiguous part — the `[x, ..rest]` and `[..init, last]`
//! patterns — cost constant time and share the buffer. Growing at either end
//! or joining costs time in the elements added when nothing else holds the
//! buffer, which is the case whenever the evaluator moves a list it will not
//! read again (`done ++ [item]` in a fold), and copies the window otherwise.
//! A part kept alive keeps its whole buffer alive.
//!
//! A [`Dict`] and a [`Set`] are sorted vectors. Lookup costs logarithmic time;
//! inserting or removing costs linear time, done in place when nothing else
//! holds the vector.
//!
//! None of this is observable: `data.md` leaves a representation to the
//! implementation, and two equal values behave equally in every operation.

use std::cmp::Ordering;
use std::collections::VecDeque;
use std::sync::Arc;

use crate::error::DataError;
use crate::int::Int;
use crate::value::{Meta, Value, compare};

/// Dropping a list nothing else holds hands its nested parts to
/// `dismantle` in the value module, so a deep value drops without deep
/// recursion.
impl Drop for List {
    fn drop(&mut self) {
        if let Some(buffer) = self.buffer_mut() {
            crate::value::dismantle(buffer.iter_mut());
        }
    }
}

/// A list: a finite sequence, in order.
#[derive(Clone, Debug)]
pub struct List {
    pub(crate) buffer: Arc<VecDeque<Value>>,
    pub(crate) start: usize,
    length: usize,
    /// What its elements measure, or what those of the list it was cut
    /// from did.
    pub(crate) meta: Meta,
}

impl Default for List {
    fn default() -> Self {
        List {
            buffer: Arc::default(),
            start: 0,
            length: 0,
            meta: Meta::EMPTY,
        }
    }
}

impl List {
    /// Returns the empty list.
    pub fn new() -> Self {
        List::default()
    }

    /// Returns how many elements there are.
    pub fn len(&self) -> usize {
        self.length
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.length == 0
    }

    /// Returns the element at a zero-based position.
    pub fn get(&self, index: usize) -> Option<&Value> {
        if index >= self.length {
            return None;
        }
        self.buffer.get(self.start + index)
    }

    /// Returns the element at a zero-based `Int` position: `None` for a
    /// negative one or one not less than the length (`list.get`).
    pub fn get_int(&self, index: &Int) -> Option<&Value> {
        self.get(index.to_index()?)
    }

    /// Returns the elements, in order.
    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &Value> + ExactSizeIterator {
        self.elements()
    }

    /// Returns the whole buffer when nothing else holds it.
    pub(crate) fn buffer_mut(&mut self) -> Option<&mut VecDeque<Value>> {
        Arc::get_mut(&mut self.buffer)
    }

    pub(crate) fn elements(&self) -> std::collections::vec_deque::Iter<'_, Value> {
        self.buffer.range(self.start..self.start + self.length)
    }

    /// Returns the elements from `start` up to, not including, `end`, sharing
    /// this list's buffer, or `None` unless `start ≤ end ≤ length`.
    pub fn slice(&self, start: usize, end: usize) -> Option<List> {
        if start > end || end > self.length {
            return None;
        }
        Some(List {
            buffer: Arc::clone(&self.buffer),
            start: self.start + start,
            length: end - start,
            meta: self.meta,
        })
    }

    /// Returns `self` with `item` added at the end.
    #[must_use]
    pub fn push_back(mut self, item: Value) -> List {
        self.meta = self.meta.with(&item);
        self.owned().push_back(item);
        self.length += 1;
        self
    }

    /// Returns `self` with `item` added at the front.
    #[must_use]
    pub fn push_front(mut self, item: Value) -> List {
        self.meta = self.meta.with(&item);
        self.owned().push_front(item);
        self.length += 1;
        self
    }

    /// Returns `self ++ other`.
    ///
    /// The elements are added to a buffer nothing else holds: `other`'s when
    /// only it is unshared, or when both are and it is the longer, and
    /// otherwise `self`'s, copied first if it is shared. A list grown one
    /// element at a time from either end therefore costs time in what it adds.
    #[must_use]
    pub fn concat(mut self, mut other: List) -> List {
        let meta = self.meta.join(other.meta);
        let self_free = Arc::get_mut(&mut self.buffer).is_some();
        let other_free = Arc::get_mut(&mut other.buffer).is_some();
        let prepend = other_free && (!self_free || self.length < other.length);
        if prepend {
            let added = self.length;
            let buffer = other.owned();
            for item in self.iter().rev() {
                buffer.push_front(item.clone());
            }
            other.length += added;
            other.meta = meta;
            other
        } else {
            let added = other.length;
            let buffer = self.owned();
            buffer.extend(other.iter().cloned());
            self.length += added;
            self.meta = meta;
            self
        }
    }

    /// Returns `items` reordered by `keys`, one key per item, stably: items
    /// whose keys are equal keep their order (`list.sort_by`).
    ///
    /// Returns `None` when there is not exactly one key per item.
    pub fn sort_by_keys(&self, keys: &[Value]) -> Result<Option<List>, DataError> {
        if keys.len() != self.length {
            return Ok(None);
        }
        let mut order: Vec<usize> = (0..self.length).collect();
        let mut failure = None;
        order.sort_by(|&a, &b| {
            compare(&keys[a], &keys[b]).unwrap_or_else(|error| {
                failure = Some(error);
                Ordering::Equal
            })
        });
        if let Some(error) = failure {
            return Err(error);
        }
        Ok(Some(
            order
                .into_iter()
                .map(|at| self.buffer[self.start + at].clone())
                .collect(),
        ))
    }

    /// Returns the buffer, holding exactly this list's elements and held by
    /// nothing else, copying the window when the buffer is shared.
    fn owned(&mut self) -> &mut VecDeque<Value> {
        if Arc::get_mut(&mut self.buffer).is_none() {
            self.buffer = Arc::new(self.iter().cloned().collect());
            self.start = 0;
        }
        let (start, length) = (self.start, self.length);
        self.start = 0;
        let buffer = Arc::get_mut(&mut self.buffer).expect("the buffer was just made unshared");
        buffer.truncate(start + length);
        buffer.drain(..start);
        buffer
    }
}

impl FromIterator<Value> for List {
    fn from_iter<I: IntoIterator<Item = Value>>(items: I) -> Self {
        let buffer: VecDeque<Value> = items.into_iter().collect();
        List {
            meta: Meta::around(&buffer),
            length: buffer.len(),
            buffer: Arc::new(buffer),
            start: 0,
        }
    }
}

/// Finds `key` in sorted `items`, comparing with `key_of`.
fn search<T>(
    items: &[T],
    key: &Value,
    key_of: impl Fn(&T) -> &Value,
) -> Result<Result<usize, usize>, DataError> {
    let mut failure = None;
    let found = items.binary_search_by(|item| {
        compare(key_of(item), key).unwrap_or_else(|error| {
            failure = Some(error);
            Ordering::Equal
        })
    });
    failure.map_or(Ok(found), Err)
}

/// Sorts `items` stably by `key_of`, then keeps one item per key: the last,
/// when `keep_last`, and otherwise the first.
fn sort_unique<T>(
    mut items: Vec<T>,
    key_of: impl Fn(&T) -> &Value,
    keep_last: bool,
) -> Result<Vec<T>, DataError> {
    let mut failure = None;
    items.sort_by(|a, b| {
        compare(key_of(a), key_of(b)).unwrap_or_else(|error| {
            failure = Some(error);
            Ordering::Equal
        })
    });
    if let Some(error) = failure {
        return Err(error);
    }
    if keep_last {
        items.reverse();
    }
    // Equal keys are adjacent, and every comparison above succeeded, so
    // these cannot fail; the stable sort put the first-written first, and the
    // reversal put the last-written first, which is the one `dedup` keeps.
    items.dedup_by(|later, earlier| compare(key_of(later), key_of(earlier)) == Ok(Ordering::Equal));
    if keep_last {
        items.reverse();
    }
    Ok(items)
}

impl Drop for Dict {
    fn drop(&mut self) {
        if let Some(entries) = self.entries_mut() {
            crate::value::dismantle(entries.iter_mut().flat_map(|(key, value)| [key, value]));
        }
    }
}

/// A dictionary: keys mapped to values, sorted by key.
#[derive(Clone, Debug)]
pub struct Dict {
    entries: Arc<Vec<(Value, Value)>>,
    /// What its keys and values measure, or more once an entry was
    /// replaced or removed.
    pub(crate) meta: Meta,
}

impl Default for Dict {
    fn default() -> Self {
        Dict {
            entries: Arc::default(),
            meta: Meta::EMPTY,
        }
    }
}

impl Dict {
    /// Returns the empty dictionary.
    pub fn new() -> Self {
        Dict::default()
    }

    /// Returns the dictionary of `entries`, where a later entry with a key
    /// equal to an earlier one's wins (the dictionary literal's rule).
    pub fn from_entries(
        entries: impl IntoIterator<Item = (Value, Value)>,
    ) -> Result<Dict, DataError> {
        let entries = sort_unique(entries.into_iter().collect(), |(key, _)| key, true)?;
        Ok(Dict {
            meta: Meta::around(entries.iter().flat_map(|(key, value)| [key, value])),
            entries: Arc::new(entries),
        })
    }

    /// Returns how many entries there are.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    pub(crate) fn entries(&self) -> &[(Value, Value)] {
        &self.entries
    }

    /// Returns the entries when nothing else holds them.
    pub(crate) fn entries_mut(&mut self) -> Option<&mut Vec<(Value, Value)>> {
        Arc::get_mut(&mut self.entries)
    }

    /// Returns the entries, in key order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Value, &Value)> {
        self.entries.iter().map(|(key, value)| (key, value))
    }

    /// Returns the keys, in key order.
    pub fn keys(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.entries.iter().map(|(key, _)| key)
    }

    /// Returns the values, in key order.
    pub fn values(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.entries.iter().map(|(_, value)| value)
    }

    /// Returns the value at `key`.
    pub fn get(&self, key: &Value) -> Result<Option<&Value>, DataError> {
        Ok(search(&self.entries, key, |(candidate, _)| candidate)?
            .ok()
            .map(|at| &self.entries[at].1))
    }

    /// Returns `self` with `key` mapped to `value`, replacing any earlier
    /// value.
    pub fn insert(mut self, key: Value, value: Value) -> Result<Dict, DataError> {
        let found = search(&self.entries, &key, |(candidate, _)| candidate)?;
        self.meta = self.meta.with(&key).with(&value);
        let entries = Arc::make_mut(&mut self.entries);
        match found {
            Ok(at) => entries[at] = (key, value),
            Err(at) => entries.insert(at, (key, value)),
        }
        Ok(self)
    }

    /// Returns `self` without `key`.
    pub fn remove(mut self, key: &Value) -> Result<Dict, DataError> {
        if let Ok(at) = search(&self.entries, key, |(candidate, _)| candidate)? {
            Arc::make_mut(&mut self.entries).remove(at);
        }
        Ok(self)
    }
}

impl Drop for Set {
    fn drop(&mut self) {
        if let Some(items) = self.items_mut() {
            crate::value::dismantle(items.iter_mut());
        }
    }
}

/// A set: distinct values, sorted.
#[derive(Clone, Debug)]
pub struct Set {
    items: Arc<Vec<Value>>,
    /// What its elements measure.
    pub(crate) meta: Meta,
}

impl Default for Set {
    fn default() -> Self {
        Set {
            items: Arc::default(),
            meta: Meta::EMPTY,
        }
    }
}

impl Set {
    /// Returns the set of `items`' distinct elements (`set.from`).
    pub fn from_items(items: impl IntoIterator<Item = Value>) -> Result<Set, DataError> {
        let items = sort_unique(items.into_iter().collect(), |item| item, false)?;
        Ok(Set {
            meta: Meta::around(&items),
            items: Arc::new(items),
        })
    }

    /// Returns how many elements there are.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns whether there are none.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Returns the elements, in order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = &Value> {
        self.items.iter()
    }

    pub(crate) fn as_slice(&self) -> &[Value] {
        &self.items
    }

    /// Returns the elements when nothing else holds them.
    pub(crate) fn items_mut(&mut self) -> Option<&mut [Value]> {
        Arc::get_mut(&mut self.items).map(Vec::as_mut_slice)
    }

    /// Returns whether `item` is an element.
    pub fn contains(&self, item: &Value) -> Result<bool, DataError> {
        Ok(search(&self.items, item, |candidate| candidate)?.is_ok())
    }
}