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
//! Moving an item between two others.
use super::{Item, LexicalItem, LexicalList};
use crate::LexicalError;
impl<T: Item> LexicalList<T> {
/// Moves the item between `previous` and `next`, the ids of its new neighbors as they are seen once the item
/// left its current place, and returns it. Give only `previous` to move it to the end, only `next` to move it
/// to the start.
///
/// Only the moved item gets a new position, so only its row needs to be saved:
///
/// - between two items, the middle of their positions ([`Staquia::core`](crate::Staquia::core)), which can
/// be one digit longer;
/// - at the end or the start, the next or previous position of that end, which never grows.
///
/// Moving an item to the place it already has changes nothing.
///
/// ```
/// # 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)?);
/// list.push(task(1))?; // "mmmmm!"
/// list.push(task(2))?; // "mmmmn!"
/// list.push(task(3))?; // "mmmmo!"
///
/// // Between 1 and 2
/// let moved = list.move_to(&3, Some(&1), Some(&2))?;
/// assert_eq!(moved.value().position, "mmmmmn");
///
/// // To the end, after 2
/// list.move_to(&1, Some(&2), None)?;
/// // To the start, before 3
/// list.move_to(&2, None, Some(&3))?;
///
/// let ids: Vec<u32> = list.iter().map(|item| item.value().id).collect();
/// assert_eq!(ids, [2, 3, 1]);
/// # Ok::<(), staquia::Error<u32>>(())
/// ```
///
///
/// # Errors
///
/// - [`LexicalError::NotFound`] if an id is not in the list.
/// - [`LexicalError::MissingNeighbors`] without neighbors, [`LexicalError::SelfNeighbor`] if the item is
/// one of them.
/// - [`LexicalError::NotAdjacent`] if the neighbors are not next to each other, or a single neighbor is
/// not at that end.
/// - [`LexicalError::Position`] if there is no room for a new position: [`rebalance`](Self::rebalance)
/// the list and try again.
pub fn move_to(
&mut self,
id: &T::Id,
previous: Option<&T::Id>,
next: Option<&T::Id>,
) -> Result<&LexicalItem<T>, LexicalError<T::Id>> {
let (position, old_previous, old_next) = {
let item = self
.items
.get(id)
.ok_or_else(|| LexicalError::NotFound(id.clone()))?;
let before = match previous {
Some(previous) => Some(
self.items
.get(previous)
.ok_or_else(|| LexicalError::NotFound(previous.clone()))?,
),
None => None,
};
let after = match next {
Some(next) => Some(
self.items
.get(next)
.ok_or_else(|| LexicalError::NotFound(next.clone()))?,
),
None => None,
};
if previous.is_none() && next.is_none() {
return Err(LexicalError::MissingNeighbors(id.clone()));
}
if previous == Some(id) || next == Some(id) {
return Err(LexicalError::SelfNeighbor(id.clone()));
}
// Verifies the adjacency as if the item was already unlinked from its current place:
// - With both neighbors, `previous` must be followed by `next`.
// - With only `previous`, it must be the last item (moving to the bottom).
// - With only `next`, it must be the first item (moving to the top).
let not_adjacent = || LexicalError::NotAdjacent {
previous: previous.cloned(),
next: next.cloned(),
};
if let Some(before) = before {
let following = if before.next.as_ref() == Some(id) {
item.next.as_ref()
} else {
before.next.as_ref()
};
if following != next {
return Err(not_adjacent());
}
} else if let Some(after) = after {
let preceding = if after.previous.as_ref() == Some(id) {
item.previous.as_ref()
} else {
after.previous.as_ref()
};
if preceding.is_some() {
return Err(not_adjacent());
}
}
// The item is already in the requested place, nothing to do
if item.previous.as_ref() == previous && item.next.as_ref() == next {
(None, None, None)
} else {
let position = match (before, after) {
(Some(before), Some(after)) => {
self.system.core(&before.position, &after.position)
}
(Some(before), None) => self.system.next(&before.position),
(None, Some(after)) => self.system.previous(&after.position),
(None, None) => return Err(LexicalError::MissingNeighbors(id.clone())),
}?;
(Some(position), item.previous.clone(), item.next.clone())
}
};
let Some(position) = position else {
return self
.items
.get(id)
.ok_or_else(|| LexicalError::NotFound(id.clone()));
};
// Unlinks the item from its current place and wires it into the new one
self.unlink(old_previous.as_ref(), old_next.as_ref());
match previous.and_then(|previous| self.items.get_mut(previous)) {
Some(before) => before.next = Some(id.clone()),
None => self.first = Some(id.clone()),
}
match next.and_then(|next| self.items.get_mut(next)) {
Some(after) => after.previous = Some(id.clone()),
None => self.last = Some(id.clone()),
}
let item = self
.items
.get_mut(id)
.ok_or_else(|| LexicalError::NotFound(id.clone()))?;
item.previous = previous.cloned();
item.next = next.cloned();
item.reposition(position);
Ok(item)
}
}