1use alloc::{
12 boxed::Box,
13 collections::BTreeMap,
14 string::String,
15 sync::{Arc, Weak},
16};
17use core::{
18 fmt,
19 ops::Deref,
20 sync::atomic::{AtomicBool, AtomicUsize, Ordering},
21};
22
23pub trait IdAllocator: Send + Sync + 'static {
35 fn lease(&self) -> Result<String, IdsExhausted>;
42
43 fn claim(&self, word: &str) -> Result<(), WordUnavailable>;
51
52 fn release(&self, word: &str);
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
60#[error("every model-facing id is leased")]
61pub struct IdsExhausted;
62
63#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
66#[error("the model-facing id '{0}' is leased or not one this allocator hands out")]
67pub struct WordUnavailable(pub String);
68
69#[derive(Clone)]
74pub struct AnyIdAllocator(Arc<dyn IdAllocator>);
75
76impl AnyIdAllocator {
77 pub fn new(allocator: impl IdAllocator) -> Self {
79 Self(Arc::new(allocator))
80 }
81
82 pub fn lease(&self) -> Result<IdLease, IdsExhausted> {
94 let word = self.0.lease()?;
95 assert!(
96 is_word(&word),
97 "the id allocator handed out '{word}', which is not one or more lowercase ASCII letters"
98 );
99 Ok(self.held(word))
100 }
101
102 pub fn claim(&self, word: &str) -> Result<IdLease, WordUnavailable> {
110 self.0.claim(word)?;
111 Ok(self.held(String::from(word)))
112 }
113
114 fn held(&self, word: String) -> IdLease {
115 IdLease(Arc::new(Held {
116 word,
117 allocator: self.clone(),
118 }))
119 }
120}
121
122fn is_word(word: &str) -> bool {
124 !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase())
125}
126
127impl Default for AnyIdAllocator {
128 fn default() -> Self {
129 Self::new(WordAllocator::default())
130 }
131}
132
133impl fmt::Debug for AnyIdAllocator {
134 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135 f.debug_struct("AnyIdAllocator").finish_non_exhaustive()
136 }
137}
138
139#[derive(Clone)]
144pub struct IdLease(Arc<Held>);
145
146struct Held {
148 word: String,
149 allocator: AnyIdAllocator,
150}
151
152impl Drop for Held {
153 fn drop(&mut self) {
154 self.allocator.0.release(&self.word);
155 }
156}
157
158impl IdLease {
159 #[must_use]
161 pub fn as_str(&self) -> &str {
162 &self.0.word
163 }
164
165 #[must_use]
168 pub fn same_lease(&self, other: &Self) -> bool {
169 Arc::ptr_eq(&self.0, &other.0)
170 }
171
172 #[must_use]
174 pub fn downgrade(&self) -> WeakIdLease {
175 WeakIdLease(Arc::downgrade(&self.0))
176 }
177}
178
179#[derive(Clone)]
182pub struct WeakIdLease(Weak<Held>);
183
184impl WeakIdLease {
185 #[must_use]
189 pub fn upgrade(&self) -> Option<IdLease> {
190 self.0.upgrade().map(IdLease)
191 }
192
193 #[must_use]
196 pub fn refers_to(&self, lease: &IdLease) -> bool {
197 core::ptr::eq(self.0.as_ptr(), Arc::as_ptr(&lease.0))
200 }
201}
202
203impl fmt::Debug for WeakIdLease {
204 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205 f.write_str("WeakIdLease")
206 }
207}
208
209impl Deref for IdLease {
210 type Target = str;
211
212 fn deref(&self) -> &str {
213 self.as_str()
214 }
215}
216
217impl AsRef<str> for IdLease {
218 fn as_ref(&self) -> &str {
219 self.as_str()
220 }
221}
222
223impl fmt::Display for IdLease {
224 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 f.write_str(self.as_str())
226 }
227}
228
229impl fmt::Debug for IdLease {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.debug_tuple("IdLease").field(&self.as_str()).finish()
232 }
233}
234
235const ENGLISH_WORDS: &str = include_str!("ids/english.txt");
239
240pub struct WordAllocator {
246 words: Box<[Box<str>]>,
247 positions: BTreeMap<Box<str>, usize>,
249 leased: Box<[AtomicBool]>,
250 cursor: AtomicUsize,
252}
253
254impl WordAllocator {
255 pub fn new<W: Into<Box<str>>>(words: impl IntoIterator<Item = W>) -> Self {
262 let words: Box<[Box<str>]> = words.into_iter().map(Into::into).collect();
263 assert!(!words.is_empty(), "a word allocator needs words");
264 let mut positions = BTreeMap::new();
265 for (position, word) in words.iter().enumerate() {
266 assert!(
267 is_word(word),
268 "'{word}' is not one or more lowercase ASCII letters"
269 );
270 assert!(
271 positions.insert(word.clone(), position).is_none(),
272 "the word '{word}' is listed twice"
273 );
274 }
275 let leased = words.iter().map(|_| AtomicBool::new(false)).collect();
276 Self {
277 words,
278 positions,
279 leased,
280 cursor: AtomicUsize::new(0),
281 }
282 }
283}
284
285impl Default for WordAllocator {
286 fn default() -> Self {
287 Self::new(ENGLISH_WORDS.lines())
288 }
289}
290
291impl fmt::Debug for WordAllocator {
292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293 f.debug_struct("WordAllocator")
294 .field("words", &self.words.len())
295 .finish_non_exhaustive()
296 }
297}
298
299impl IdAllocator for WordAllocator {
300 fn lease(&self) -> Result<String, IdsExhausted> {
301 let count = self.words.len();
302 for _ in 0..count {
303 let position = self.cursor.fetch_add(1, Ordering::Relaxed) % count;
304 if !self.leased[position].swap(true, Ordering::AcqRel) {
305 return Ok(String::from(&*self.words[position]));
306 }
307 }
308 Err(IdsExhausted)
309 }
310
311 fn claim(&self, word: &str) -> Result<(), WordUnavailable> {
312 let unavailable = || WordUnavailable(String::from(word));
313 let position = *self.positions.get(word).ok_or_else(unavailable)?;
314 if self.leased[position].swap(true, Ordering::AcqRel) {
315 return Err(unavailable());
316 }
317 Ok(())
318 }
319
320 fn release(&self, word: &str) {
321 let position = *self
322 .positions
323 .get(word)
324 .unwrap_or_else(|| panic!("released '{word}', which this allocator never leased"));
325 assert!(
326 self.leased[position].swap(false, Ordering::AcqRel),
327 "released '{word}', which is not leased"
328 );
329 }
330}
331
332#[cfg(test)]
333mod tests {
334 use alloc::string::ToString;
335
336 use super::*;
337
338 #[test]
339 fn the_default_list_is_single_lowercase_words() {
340 assert_eq!(ENGLISH_WORDS.lines().count(), 2048);
341 let _ = WordAllocator::default();
343 }
344
345 #[test]
346 #[should_panic(expected = "is not one or more lowercase ASCII letters")]
347 fn a_word_of_another_shape_is_refused() {
348 let _ = WordAllocator::new(["river", "task-1"]);
349 }
350
351 struct Numbered;
353
354 impl IdAllocator for Numbered {
355 fn lease(&self) -> Result<String, IdsExhausted> {
356 Ok("7".to_string())
357 }
358
359 fn claim(&self, word: &str) -> Result<(), WordUnavailable> {
360 Err(WordUnavailable(word.to_string()))
361 }
362
363 fn release(&self, _word: &str) {}
364 }
365
366 #[test]
367 #[should_panic(expected = "handed out '7'")]
368 fn an_embedder_word_of_another_shape_fails_the_lease() {
369 let _ = AnyIdAllocator::new(Numbered).lease();
370 }
371
372 #[test]
373 fn live_leases_never_share_a_word_and_a_released_word_comes_back() {
374 let ids = AnyIdAllocator::new(WordAllocator::new(["river", "stone"]));
375 let river = ids.lease().expect("a free word");
376 let stone = ids.lease().expect("a free word");
377 assert_eq!((river.as_str(), stone.as_str()), ("river", "stone"));
378 assert_eq!(ids.lease().unwrap_err(), IdsExhausted);
379
380 drop(river);
381 assert_eq!(
382 ids.lease().expect("river is free again").to_string(),
383 "river"
384 );
385 }
386
387 #[test]
388 fn a_lease_ends_with_its_last_clone() {
389 let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
390 let lease = ids.lease().expect("a free word");
391 let held = lease.clone();
392 drop(lease);
393 assert_eq!(
394 ids.lease().unwrap_err(),
395 IdsExhausted,
396 "a clone still holds it"
397 );
398 drop(held);
399 assert_eq!(
400 &*ids.lease().expect("released with the last clone"),
401 "river"
402 );
403 }
404
405 #[test]
406 fn only_clones_are_the_same_lease() {
407 let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
408 let lease = ids.lease().expect("a free word");
409 assert!(lease.same_lease(&lease.clone()));
410 drop(lease);
411 let again = ids.lease().expect("river is free again");
412 let other = AnyIdAllocator::new(WordAllocator::new(["river"]))
413 .lease()
414 .expect("a free word");
415 assert_eq!(again.as_str(), other.as_str());
416 assert!(!again.same_lease(&other), "a word alone is not the lease");
417
418 let weak = again.downgrade();
419 assert!(weak.refers_to(&again));
420 assert!(!weak.refers_to(&other));
421 drop(again);
422 let after = ids.lease().expect("river is free again");
423 assert!(
424 !weak.refers_to(&after),
425 "a released lease is not its successor"
426 );
427 }
428
429 #[test]
430 fn a_weak_lease_upgrades_only_while_the_word_is_held() {
431 let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
432 let lease = ids.lease().expect("a free word");
433 let weak = lease.downgrade();
434 assert_eq!(weak.upgrade().as_deref(), Some("river"));
435 drop(lease);
436 assert!(weak.upgrade().is_none(), "the word went back");
437 let again = ids.lease().expect("river is free again");
438 assert!(
439 weak.upgrade().is_none(),
440 "a word leased again names something else: {again}"
441 );
442 }
443
444 #[test]
445 fn a_claimed_word_is_leased_until_its_lease_drops() {
446 let ids = AnyIdAllocator::new(WordAllocator::new(["river", "stone"]));
447 let river = ids.claim("river").expect("river is free");
448 assert_eq!(river.as_str(), "river");
449 assert_eq!(
450 ids.claim("river").unwrap_err(),
451 WordUnavailable("river".to_string()),
452 "a live lease holds it"
453 );
454 let stone = ids.lease().expect("stone is free");
455 assert_eq!(stone.as_str(), "stone");
456 assert_eq!(ids.lease().unwrap_err(), IdsExhausted, "river is claimed");
457 drop(river);
458 assert_eq!(&*ids.claim("river").expect("released"), "river");
459 }
460
461 #[test]
462 fn a_word_outside_the_list_cannot_be_claimed() {
463 let ids = AnyIdAllocator::new(WordAllocator::new(["river"]));
464 assert_eq!(
465 ids.claim("stone").unwrap_err(),
466 WordUnavailable("stone".to_string())
467 );
468 }
469
470 #[test]
471 #[should_panic(expected = "is listed twice")]
472 fn a_word_listed_twice_is_refused() {
473 let _ = WordAllocator::new(["river", "river"]);
474 }
475
476 #[test]
477 #[should_panic(expected = "which is not leased")]
478 fn releasing_a_free_word_is_a_bug() {
479 WordAllocator::new(["river"]).release("river");
480 }
481}