Skip to main content

yomi_core/value/
list.rs

1//! The contents of a `list` (`ListData`). Sharing, copy on write, and incremental tracking of the total size.
2
3use super::*;
4
5/// The contents of a `list`. Holds the elements in an `Arc`, so cloning only shares them (the same approach as
6/// [`MapData`]).
7///
8/// - Cloning is O(1). The first update after cloning copies the contents if shared (copy on write). A clone is
9///   independent of the original (value semantics; updating one does not change the other).
10/// - If not shared, `push`, `insert`, `remove` and replacing elements are done in place (`push` is amortized O(1)).
11/// - Keeps the total size of the elements (the estimate of [`Value::approx_bytes`]) incrementally, so checking value
12///   sizes is not proportional to the length of the `list`. When a value inside nesting is updated, the outer side
13///   reports it with `adjust_bytes` (within the crate).
14/// - Can be read as `[Value]` (`Deref`). Converts from `Vec<Value>` with `From`, and to `Vec<Value>` with
15///   [`ListData::into_vec`]. `Debug` and serialization are the same as `Vec<Value>` (the save format does not change).
16#[derive(Clone, Default)]
17pub struct ListData(Arc<ListInner>);
18
19/// The contents of a `list` (elements and the total size).
20#[derive(Clone, Default)]
21pub(super) struct ListInner {
22    items: Vec<Value>,
23    /// The total size of the elements (not including the 24 of the `list` itself).
24    bytes: usize,
25}
26
27/// Shows only the sequence of elements (`[…]`), the same as `Vec<Value>` (the output does not change).
28impl std::fmt::Debug for ListData {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        self.0.items.fmt(f)
31    }
32}
33
34/// Only when the length is at most this, recount on every update to check that the total size is correct (with
35/// `debug_assertions`; so that debug tests do not take quadratic time with large `list`s).
36pub(super) const CONSISTENCY_CHECK_MAX_LEN: usize = 256;
37
38impl ListData {
39    /// An empty `list`.
40    pub fn new() -> Self {
41        Self::default()
42    }
43
44    /// The elements.
45    pub fn as_slice(&self) -> &[Value] {
46        &self.0.items
47    }
48
49    /// Takes the elements out. Does not copy if not shared.
50    pub fn into_vec(self) -> Vec<Value> {
51        match Arc::try_unwrap(self.0) {
52            Ok(inner) => inner.items,
53            Err(shared) => shared.items.clone(),
54        }
55    }
56
57    /// Appends to the end (copies the contents first if shared).
58    pub fn push(&mut self, value: Value) {
59        let inner = Arc::make_mut(&mut self.0);
60        inner.bytes += value.approx_bytes();
61        inner.items.push(value);
62        inner.debug_check();
63    }
64
65    /// Inserts at position `at` (`at <= len()`; shifts the rest; proportional to the number of elements).
66    pub fn insert(&mut self, at: usize, value: Value) {
67        let inner = Arc::make_mut(&mut self.0);
68        inner.bytes += value.approx_bytes();
69        inner.items.insert(at, value);
70        inner.debug_check();
71    }
72
73    /// Removes and returns the element at position `at` (`at < len()`; shifts the rest; proportional to the number of
74    /// elements).
75    pub fn remove(&mut self, at: usize) -> Value {
76        let inner = Arc::make_mut(&mut self.0);
77        let v = inner.items.remove(at);
78        inner.bytes = inner.bytes.saturating_sub(v.approx_bytes());
79        inner.debug_check();
80        v
81    }
82
83    /// Swaps the elements at positions `a` and `b` (copies the contents first if shared; the total size is unchanged).
84    pub fn swap(&mut self, a: usize, b: usize) {
85        if a != b {
86            Arc::make_mut(&mut self.0).items.swap(a, b);
87        }
88    }
89
90    /// Empties it.
91    pub fn clear(&mut self) {
92        self.0 = Arc::new(ListInner::default());
93    }
94
95    /// The total size of the elements (not including the 24 of the `list` itself).
96    pub(crate) fn content_bytes(&self) -> usize {
97        self.0.bytes
98    }
99
100    /// Returns the element at position `i` in a mutable form (copies the contents first if shared). After modifying the
101    /// element, report the change in size with [`ListData::adjust_bytes`].
102    pub(crate) fn item_mut(&mut self, i: usize) -> Option<&mut Value> {
103        if i >= self.0.items.len() {
104            return None;
105        }
106        Arc::make_mut(&mut self.0).items.get_mut(i)
107    }
108
109    /// After modifying elements (including inside nesting), corrects the total size as having decreased by `shrink` and
110    /// increased by `grow`.
111    pub(crate) fn adjust_bytes(&mut self, shrink: usize, grow: usize) {
112        let inner = Arc::make_mut(&mut self.0);
113        inner.bytes = (inner.bytes + grow).saturating_sub(shrink);
114        inner.debug_check();
115    }
116
117    /// Whether the total size matches the value recounted from the elements (for tests).
118    #[doc(hidden)]
119    pub fn is_consistent(&self) -> bool {
120        self.0.bytes == self.0.recount()
121    }
122
123    /// Whether it shares the same `Arc` (to confirm that a clone did not copy the contents; for tests).
124    #[doc(hidden)]
125    pub fn shares_storage_with(&self, other: &Self) -> bool {
126        Arc::ptr_eq(&self.0, &other.0)
127    }
128}
129
130impl ListInner {
131    /// Recounts the sizes of the elements.
132    fn recount(&self) -> usize {
133        self.items.iter().map(Value::approx_bytes).sum()
134    }
135
136    /// Checks the consistency of the total size (in debug, only for short `list`s).
137    fn debug_check(&self) {
138        debug_assert!(
139            self.items.len() > CONSISTENCY_CHECK_MAX_LEN || self.bytes == self.recount(),
140            "list の大きさの合計が合っていない(実装の不具合)"
141        );
142    }
143}
144
145impl std::ops::Deref for ListData {
146    type Target = [Value];
147    fn deref(&self) -> &Self::Target {
148        &self.0.items
149    }
150}
151
152impl AsRef<[Value]> for ListData {
153    fn as_ref(&self) -> &[Value] {
154        &self.0.items
155    }
156}
157
158impl<'a> IntoIterator for &'a ListData {
159    type Item = &'a Value;
160    type IntoIter = std::slice::Iter<'a, Value>;
161    fn into_iter(self) -> Self::IntoIter {
162        self.0.items.iter()
163    }
164}
165
166impl IntoIterator for ListData {
167    type Item = Value;
168    type IntoIter = std::vec::IntoIter<Value>;
169    fn into_iter(self) -> Self::IntoIter {
170        self.into_vec().into_iter()
171    }
172}
173
174impl ListData {
175    /// The sequence of integers `lo..hi` (`range`). The total size counts 8 for each (values are not recounted).
176    pub(crate) fn range(lo: i64, hi: i64) -> Self {
177        let items: Vec<Value> = (lo..hi).map(Value::Int).collect();
178        let bytes = items.len() * 8;
179        Self(Arc::new(ListInner { items, bytes }))
180    }
181}
182
183impl From<Vec<Value>> for ListData {
184    fn from(items: Vec<Value>) -> Self {
185        let bytes = items.iter().map(Value::approx_bytes).sum();
186        Self(Arc::new(ListInner { items, bytes }))
187    }
188}
189
190impl From<ListData> for Vec<Value> {
191    fn from(list: ListData) -> Self {
192        list.into_vec()
193    }
194}
195
196impl FromIterator<Value> for ListData {
197    fn from_iter<I: IntoIterator<Item = Value>>(iter: I) -> Self {
198        iter.into_iter().collect::<Vec<_>>().into()
199    }
200}
201
202impl PartialEq for ListData {
203    fn eq(&self, other: &Self) -> bool {
204        Arc::ptr_eq(&self.0, &other.0) || self.0.items == other.0.items
205    }
206}
207
208impl PartialEq<Vec<Value>> for ListData {
209    fn eq(&self, other: &Vec<Value>) -> bool {
210        self.0.items == *other
211    }
212}
213
214impl Serialize for ListData {
215    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
216        self.0.items.serialize(ser)
217    }
218}
219
220impl<'de> Deserialize<'de> for ListData {
221    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
222        Ok(Vec::<Value>::deserialize(de)?.into())
223    }
224}