Skip to main content

nibkeep_log/
list.rs

1//! Ordered lists: items belong to a list through memberships, ordered by position keys.
2
3use std::collections::BTreeSet;
4use std::iter;
5
6use nibkeep_base::{EntityId, StatementId};
7use nibkeep_crypto::rand_core::CryptoRng;
8use nibkeep_model::storage::Statements;
9use nibkeep_model::{
10	FieldDef, Operation, Resolution, State, Statement, TypeDef, TypeName, Value, ValueKind, fields,
11};
12
13/// The type of memberships.
14pub const MEMBERSHIP: TypeName = TypeName::from_static("org.nibkeep.membership");
15
16/// The list a membership belongs to, the item it puts in its list, and its position key.
17pub use nibkeep_model::fields::{ITEM, LIST, POSITION};
18
19/// The digits of position keys, in the order of their bytes.
20const DIGITS: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
21
22/// One item of a list.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct Member {
25	/// The membership that puts the item in the list.
26	pub membership: EntityId,
27	/// The item, if the membership names one.
28	pub item: Option<EntityId>,
29	/// The membership's position key, if it has a valid one.
30	pub position: Option<String>,
31}
32
33/// The definition of the membership type.
34#[must_use]
35pub fn membership_type() -> TypeDef {
36	TypeDef::new(MEMBERSHIP, 1)
37		.with_field(LIST, FieldDef::new(ValueKind::Reference).role())
38		.with_field(ITEM, FieldDef::new(ValueKind::Reference).role())
39		.with_field(POSITION, FieldDef::new(ValueKind::Text).last_writer_wins())
40}
41
42/// The items of a list, in order: the memberships that refer to it and are not deleted,
43/// sorted by position key, and those with equal keys by ID.
44///
45/// # Errors
46///
47/// Returns an error if the state's storage cannot be read.
48pub fn members<S: Statements>(state: &State<S>, list: EntityId) -> Result<Vec<Member>, S::Error> {
49	let membership_type = membership_type();
50	let position = membership_type.field(&POSITION);
51	let mut memberships = BTreeSet::new();
52	for statement in state.referrers(list)? {
53		if statement.field == LIST {
54			let membership = state.canonical(statement.entity)?;
55			if state.types(membership)?.contains(&MEMBERSHIP) {
56				memberships.insert(membership);
57			}
58		}
59	}
60	let mut members = Vec::new();
61	for membership in memberships {
62		if state.is_deleted(membership)? {
63			continue;
64		}
65		let item = state
66			.current(membership, &ITEM)?
67			.iter()
68			.find_map(|statement| statement.value.as_reference());
69		let position = match state.resolve(membership, &POSITION, position)? {
70			Resolution::Values(values) | Resolution::Competing(values) => values
71				.first()
72				.and_then(|statement| statement.value.as_text())
73				.filter(|key| is_position(key))
74				.map(str::to_owned),
75		};
76		members.push(Member {
77			membership,
78			item,
79			position,
80		});
81	}
82	members.sort_by(|a, b| (&a.position, a.membership).cmp(&(&b.position, b.membership)));
83	Ok(members)
84}
85
86/// The operations that add `item` to `list` at `index`: a new membership with its type,
87/// list, item and position. Returns the membership, too.
88///
89/// # Errors
90///
91/// Returns an error if the state's storage cannot be read.
92pub fn insert<S: Statements>(
93	state: &State<S>,
94	list: EntityId,
95	item: EntityId,
96	index: usize,
97	rng: &mut impl CryptoRng,
98) -> Result<(EntityId, Vec<Operation>), S::Error> {
99	let membership = EntityId::random(rng);
100	let mut operations = vec![
101		Operation::assert(Statement::new(
102			StatementId::random(rng),
103			membership,
104			fields::TYPE,
105			Value::Text(MEMBERSHIP.to_string()),
106		)),
107		Operation::assert(Statement::new(
108			StatementId::random(rng),
109			membership,
110			LIST,
111			Value::Reference(list),
112		)),
113		Operation::assert(Statement::new(
114			StatementId::random(rng),
115			membership,
116			ITEM,
117			Value::Reference(item),
118		)),
119	];
120	operations.extend(move_to(state, list, membership, index, rng)?);
121	Ok((membership, operations))
122}
123
124/// The operations that move a membership to `index` in its list, counted among the other
125/// members. Usually that is a new position key for the membership alone; members after
126/// the new place that share the key before it move up with it, in their order.
127///
128/// # Errors
129///
130/// Returns an error if the state's storage cannot be read.
131pub fn move_to<S: Statements>(
132	state: &State<S>,
133	list: EntityId,
134	membership: EntityId,
135	index: usize,
136	rng: &mut impl CryptoRng,
137) -> Result<Vec<Operation>, S::Error> {
138	let membership = state.canonical(membership)?;
139	let order: Vec<Member> = members(state, list)?
140		.into_iter()
141		.filter(|member| member.membership != membership)
142		.collect();
143	let index = index.min(order.len());
144	let lower = index
145		.checked_sub(1)
146		.and_then(|before| order[before].position.clone());
147	let run_end = order[index..]
148		.iter()
149		.position(|member| member.position != lower)
150		.map_or(order.len(), |offset| index + offset);
151	let upper = order
152		.get(run_end)
153		.and_then(|member| member.position.clone());
154
155	let moved =
156		iter::once(membership).chain(order[index..run_end].iter().map(|member| member.membership));
157	let mut previous = lower;
158	let mut operations = Vec::new();
159	for membership in moved {
160		// The members are sorted, and the run ends where the keys grow, so there is
161		// always room.
162		let Some(key) = position_between(previous.as_deref(), upper.as_deref()) else {
163			unreachable!("the key before is smaller than the key after");
164		};
165		operations.push(set_position(state, membership, key.clone(), rng)?);
166		previous = Some(key);
167	}
168	Ok(operations)
169}
170
171/// Whether text is a valid position key: one or more of the characters `0`–`9`, `A`–`Z`
172/// and `a`–`z`, not ending in `0`.
173#[must_use]
174pub fn is_position(key: &str) -> bool {
175	!key.is_empty() && key.bytes().all(|byte| byte.is_ascii_alphanumeric()) && !key.ends_with('0')
176}
177
178/// A position key between `before` and `after`, where `None` stands for the start and the
179/// end of the list. Returns `None` if a key is not valid, or `before` is not smaller than
180/// `after`.
181#[must_use]
182pub fn position_between(before: Option<&str>, after: Option<&str>) -> Option<String> {
183	if before.is_some_and(|key| !is_position(key)) || after.is_some_and(|key| !is_position(key)) {
184		return None;
185	}
186	if let (Some(before), Some(after)) = (before, after)
187		&& before >= after
188	{
189		return None;
190	}
191	let key = midpoint(before.unwrap_or("").as_bytes(), after.map(str::as_bytes));
192	String::from_utf8(key).ok()
193}
194
195/// A key between `lower` and `upper`, after David Greenspan's fractional indexing: keys
196/// are fractions in base 62 without trailing zeros, so there is always room between two
197/// of them. `lower` is empty for the start of the list, and `upper` is `None` for its end.
198fn midpoint(lower: &[u8], upper: Option<&[u8]>) -> Vec<u8> {
199	if let Some(upper) = upper {
200		// Keep the common prefix, reading missing digits of `lower` as zeros.
201		let common = upper
202			.iter()
203			.enumerate()
204			.take_while(|&(index, &digit)| lower.get(index).copied().unwrap_or(b'0') == digit)
205			.count();
206		if common > 0 {
207			let mut key = upper[..common].to_vec();
208			let rest = lower.get(common..).unwrap_or(&[]);
209			key.extend(midpoint(rest, Some(&upper[common..])));
210			return key;
211		}
212	}
213	let low = lower.first().map_or(0, |&byte| digit(byte));
214	let high = upper.map_or(DIGITS.len(), |upper| digit(upper[0]));
215	if high - low > 1 {
216		vec![DIGITS[usize::midpoint(low, high)]]
217	} else if let Some(upper) = upper.filter(|upper| upper.len() > 1) {
218		// The first digits are neighbours, and `upper` goes on: its first digit alone is
219		// between the two.
220		vec![upper[0]]
221	} else {
222		let mut key = vec![DIGITS[low]];
223		key.extend(midpoint(lower.get(1..).unwrap_or(&[]), None));
224		key
225	}
226}
227
228/// The value of a digit of a position key.
229fn digit(byte: u8) -> usize {
230	usize::from(match byte {
231		b'0'..=b'9' => byte - b'0',
232		b'A'..=b'Z' => byte - b'A' + 10,
233		_ => byte - b'a' + 36,
234	})
235}
236
237/// Sets a membership's position key, replacing its current ones.
238fn set_position<S: Statements>(
239	state: &State<S>,
240	membership: EntityId,
241	key: String,
242	rng: &mut impl CryptoRng,
243) -> Result<Operation, S::Error> {
244	let replaced: Vec<StatementId> = state
245		.current(membership, &POSITION)?
246		.iter()
247		.map(|statement| statement.id)
248		.collect();
249	Ok(Operation::replace(
250		Statement::new(
251			StatementId::random(rng),
252			membership,
253			POSITION,
254			Value::Text(key),
255		),
256		replaced,
257	))
258}