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
//! Replacing the content of the list with stored rows.
use core::cmp::Ordering;
use std::collections::HashSet;
use super::spacing::{fill, respace};
use super::{Item, LexicalItem, LexicalList, Replaced};
use crate::{LexicalError, Position, Rejected};
impl<T: Item> LexicalList<T> {
/// Replaces the content of the list with these values, already ordered by their stored positions (for
/// example rows loaded from a database sorted by position). The positions are verified, not changed.
///
/// Use it when the positions are known to be valid and sorted (`ORDER BY position`), it is the fastest way to
/// load a list. Returns the affected items, always none for this trusted input.
///
/// ```
/// # use staquia::{Item, LexicalList, Position, Staquia};
/// # #[derive(Debug)]
/// # struct Task { id: u32, done: bool, position: String }
/// # impl Item for Task {
/// # type Id = u32;
/// # fn id(&self) -> &u32 { &self.id }
/// # fn position(&self) -> &str { &self.position }
/// # fn set_position(&mut self, position: &Position) { self.position = position.to_string(); }
/// # }
/// # let task = |id| Task { id, done: false, position: String::new() };
/// # let stored = |id, position: &str| Task { id, done: false, position: position.to_string() };
/// use staquia::LexicalError;
///
/// let mut list = LexicalList::new(Staquia::create('!', 'a', 'z', 5, 15, 0.15)?);
///
/// // Rows loaded with `ORDER BY position`
/// list.set(vec![stored(1, "mmmmm!"), stored(2, "mmmmn!")])?;
/// assert_eq!(list.len(), 2);
///
/// // Out of order: nothing changes, the rows come back
/// let rejected = list.set(vec![stored(3, "mmmmn!"), stored(4, "mmmmm!")]).unwrap_err();
/// assert_eq!(rejected.error, LexicalError::NotOrdered { index: 1, previous: 3, id: 4 });
/// assert_eq!(rejected.into_value().len(), 2);
/// assert!(list.contains(&1));
/// # Ok::<(), staquia::Error<u32>>(())
/// ```
///
///
/// # Errors
///
/// The values are given back, and the list is not changed, with [`LexicalError::DuplicateId`],
/// [`LexicalError::InvalidPosition`] for a missing or invalid position, or [`LexicalError::NotOrdered`].
/// Use [`set_untrusted`](Self::set_untrusted) to repair them instead.
pub fn set(&mut self, values: Vec<T>) -> Replaced<'_, T> {
self.replace(values, false)
}
/// Replaces the content of the list with these values, repairing their stored positions: they are sorted
/// by position, an equal position keeps the first value and the others get a new position right after it,
/// and the values without a valid position are added at the end. When there is no room to repair them,
/// every position is spaced again from the start.
///
/// Use it for rows whose positions may be missing, repeated or unsorted: rows created before the column
/// existed, imported data, or positions written by concurrent clients. Returns the affected items: the ones
/// whose position changed, to save them.
///
/// ```
/// # use staquia::{Item, LexicalList, Position, Staquia};
/// # #[derive(Debug)]
/// # struct Task { id: u32, done: bool, position: String }
/// # impl Item for Task {
/// # type Id = u32;
/// # fn id(&self) -> &u32 { &self.id }
/// # fn position(&self) -> &str { &self.position }
/// # fn set_position(&mut self, position: &Position) { self.position = position.to_string(); }
/// # }
/// # let task = |id| Task { id, done: false, position: String::new() };
/// # let stored = |id, position: &str| Task { id, done: false, position: position.to_string() };
/// let mut list = LexicalList::new(Staquia::create('!', 'a', 'z', 5, 15, 0.15)?);
///
/// let rows = vec![
/// stored(1, "mmmmn!"),
/// stored(2, "mmmmm!"),
/// stored(3, ""), // no position yet
/// stored(4, "mmmmm!"), // the same position as 2
/// ];
/// let affected: Vec<u32> = list.set_untrusted(rows)?.iter().map(|item| item.value().id).collect();
/// assert_eq!(affected, [4, 3]); // save these two rows
///
/// let order: Vec<String> = list.iter().map(|item| format!("{} {}", item.id(), item.position())).collect();
/// assert_eq!(order, ["2 mmmmm!", "4 mmmmmn", "1 mmmmn!", "3 mmmmo!"]);
/// # Ok::<(), staquia::Error<u32>>(())
/// ```
///
/// # Errors
///
/// The values are given back, and the list is not changed, with [`LexicalError::DuplicateId`] or
/// [`LexicalError::Position`] when not even spacing every position again works.
pub fn set_untrusted(&mut self, values: Vec<T>) -> Replaced<'_, T> {
self.replace(values, true)
}
fn replace(&mut self, values: Vec<T>, untrusted: bool) -> Replaced<'_, T> {
// Validates the ids before touching the current content
let duplicate = {
let mut ids = HashSet::with_capacity(values.len());
values
.iter()
.map(Item::id)
.find(|id| !ids.insert(*id))
.cloned()
};
if let Some(id) = duplicate {
return Err(Rejected {
error: LexicalError::DuplicateId(id),
value: values,
});
}
// Forges the positions without writing them into the values, nothing must change on failure
let mut originals: Vec<Option<Position>> = Vec::with_capacity(values.len());
for value in &values {
let stored = value.position();
let forged = (!stored.is_empty()).then(|| self.system.forge(stored));
match forged {
Some(Ok(position)) => originals.push(Some(position)),
forged if !untrusted => {
let error = LexicalError::InvalidPosition {
id: value.id().clone(),
reason: forged.and_then(Result::err),
};
return Err(Rejected {
error,
value: values,
});
}
_ => originals.push(None),
}
}
// The order of the values (indexes) and their final positions
let mut order: Vec<usize> = (0..values.len()).collect();
let mut positions: Vec<Option<Position>>;
if !untrusted {
// Trusted: only verifies that the incoming order is valid
for i in 1..values.len() {
if originals[i - 1].cmp(&originals[i]) != Ordering::Less {
let error = LexicalError::NotOrdered {
index: i,
previous: values[i - 1].id().clone(),
id: values[i].id().clone(),
};
return Err(Rejected {
error,
value: values,
});
}
}
positions = originals.clone();
} else {
// Untrusted: sorts by position (stable), the values without position go at the end
let (mut positioned, unpositioned): (Vec<usize>, Vec<usize>) =
order.iter().copied().partition(|i| originals[*i].is_some());
positioned.sort_by(|a, b| originals[*a].cmp(&originals[*b]));
order = positioned;
order.extend(unpositioned);
positions = order.iter().map(|i| originals[*i]).collect();
// Equal positions keep the first one, the others will be given a new position after it
let mut kept: Option<Position> = None;
for position in positions.iter_mut() {
match (*position, kept) {
(Some(current), Some(previous)) if current == previous => *position = None,
(Some(current), _) => kept = Some(current),
(None, _) => {}
}
}
// Fills the missing positions, if there is no room spaces every position again
if !fill(&self.system, &mut positions) {
if let Err(error) = respace(&self.system, &mut positions) {
return Err(Rejected {
error: error.into(),
value: values,
});
}
}
}
// Everything is valid, replaces the content
self.clear();
self.items.reserve(values.len());
let mut slots: Vec<Option<T>> = values.into_iter().map(Some).collect();
let mut affected: Vec<T::Id> = Vec::new();
let mut previous: Option<T::Id> = None;
for (k, index) in order.iter().enumerate() {
let (Some(value), Some(position)) = (slots[*index].take(), positions[k]) else {
continue;
};
let id = value.id().clone();
let mut item = LexicalItem::new(value, position);
if originals[*index] != Some(position) {
affected.push(id.clone());
}
item.previous = previous.clone();
match previous
.as_ref()
.and_then(|previous| self.items.get_mut(previous))
{
Some(before) => before.next = Some(id.clone()),
None => self.first = Some(id.clone()),
}
self.items.insert(id.clone(), item);
previous = Some(id);
}
self.last = previous;
Ok(affected
.iter()
.filter_map(|id| self.items.get(id))
.collect())
}
}