zrx-store 0.0.10

Store abstractions and utilities
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright (c) 2025-2026 Zensical and contributors

// SPDX-License-Identifier: MIT
// All contributions are certified under the DCO

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.

// ----------------------------------------------------------------------------

//! Queue.

use ahash::HashMap;
use slab::Slab;
use std::borrow::Borrow;
use std::fmt::{self, Debug};
use std::mem;
use std::time::Instant;

use crate::store::decorator::Ordered;
use crate::store::item::{Key, Value};
use crate::store::{
    Store, StoreIterable, StoreIterableMut, StoreMut, StoreMutRef,
};

mod item;
mod iter;

pub use item::Item;
pub use iter::{Iter, IterMut, Keys, Values};

// ----------------------------------------------------------------------------
// Structs
// ----------------------------------------------------------------------------

/// Queue.
///
/// This is a specialization of [`Store`], more specifically [`Ordered`], that
/// maintains insertion order and allows to assign specific deadlines to items.
/// Values themselves don't need to implement [`Ord`], since the ordering is
/// completely independent and induced by the queue.
///
/// When an item is inserted, it is annotated with [`Instant::now`], which on
/// the one hand implements insertion order, and on the other hand allows to
/// change the ordering of an item through [`Queue::set_deadline`]. This allows
/// to remove items from visibility until a certain point in time.
///
/// Additionally, [`Queue`] is not a queue in the traditional sense, since it
/// adds queueing to a [`Store`], an immutable collection of key-value pairs.
/// The queue is self-organizing, and iterating over it will always yield the
/// correct order of items at that specific point in time.
///
/// # Examples
///
/// ```
/// use zrx_store::{Queue, StoreIterable, StoreMut};
///
/// // Create queue and initial state
/// let mut queue = Queue::default();
/// queue.insert("a", 4);
/// queue.insert("b", 2);
/// queue.insert("c", 3);
/// queue.insert("d", 1);
///
/// // Create iterator over the queue
/// for (key, value) in &queue {
///     println!("{key}: {value}");
/// }
/// ```
#[derive(Clone)]
pub struct Queue<K, V, S = HashMap<K, Item>> {
    /// Underlying store.
    store: Ordered<K, Item, S>,
    /// Queue items.
    items: Slab<V>,
}

// ----------------------------------------------------------------------------
// Implementations
// ----------------------------------------------------------------------------

impl<K, V, S> Queue<K, V, S>
where
    K: Key,
    S: Store<K, Item>,
{
    /// Creates a queue.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::collections::HashMap;
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue
    /// let mut queue = Queue::<_, _, HashMap<_, _>>::new();
    /// queue.insert("key", 42);
    /// ```
    #[must_use]
    pub fn new() -> Self
    where
        S: Default,
    {
        Self {
            store: Ordered::new(),
            items: Slab::new(),
        }
    }

    /// Returns the deadline of the item identified by the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Instant;
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Obtain deadline of item
    /// let deadline = queue.get_deadline(&"key");
    /// assert!(deadline < Some(Instant::now()));
    /// ```
    #[inline]
    pub fn get_deadline(&self, key: &K) -> Option<Instant> {
        self.store.get(key).map(Item::deadline)
    }
}

impl<K, V, S> Queue<K, V, S>
where
    K: Key,
    S: StoreMut<K, Item>,
{
    /// Sets the deadline of the item identified by the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Instant;
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Update deadline of item
    /// queue.set_deadline(&"key", Instant::now());
    /// ```
    #[inline]
    pub fn set_deadline(
        &mut self, key: &K, deadline: Instant,
    ) -> Option<Instant> {
        self.store.remove(key).and_then(|mut item| {
            item.set_deadline(deadline);
            self.store
                .insert(key.clone(), item)
                .map(|prior| prior.deadline())
        })
    }
}

impl<K, V, S> Queue<K, V, S>
where
    K: Key,
    V: Value,
    S: StoreMut<K, Item> + StoreIterable<K, Item>,
{
    /// Returns the minimum deadline of all items.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Instant;
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Obtain minimum deadline of all items
    /// let deadline = queue.deadline();
    /// assert!(deadline < Some(Instant::now()));
    ///
    #[inline]
    pub fn deadline(&self) -> Option<Instant> {
        self.store.iter().next().map(|(_, item)| item.deadline())
    }

    /// Takes ownership of the next item that is due.
    ///
    /// Items are considered to be due if [`Instant::now`] has passed the value
    /// stored in [`Item::deadline`], which allows to defer processing.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("a", 4);
    /// queue.insert("b", 2);
    /// queue.insert("c", 3);
    /// queue.insert("d", 1);
    ///
    /// // Obtain items from queue
    /// while let Some((key, value)) = queue.take() {
    ///     println!("{key}: {value}");
    /// }
    /// ```
    #[allow(clippy::missing_panics_doc)]
    #[inline]
    pub fn take(&mut self) -> Option<(K, V)> {
        // Obtain the current instant once to select due items during iteration,
        // or tight loops might experience slowdowns of up to a factor of 6
        let deadline = Instant::now();
        let opt = self.store.iter().next().and_then(|(key, item)| {
            (item.deadline() <= deadline).then(|| key.clone())
        });

        // Remove and return the first item we found, which is the next item
        // in current queue order that can be considered to be due
        opt.map(|key| {
            // We can safely use expect here, since we're iterating over a
            // store that is synchronized with the ordering
            self.remove(&key)
                .map(|value| (key, value))
                .expect("invariant")
        })
    }
}

// ----------------------------------------------------------------------------
// Trait implementations
// ----------------------------------------------------------------------------

impl<K, V, S> Store<K, V> for Queue<K, V, S>
where
    K: Key,
    S: Store<K, Item>,
{
    /// Returns a reference to the value identified by the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, Store, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Obtain reference to value
    /// let value = queue.get(&"key");
    /// assert_eq!(value, Some(&42));
    /// ```
    #[inline]
    fn get<Q>(&self, key: &Q) -> Option<&V>
    where
        K: Borrow<Q>,
        Q: Key,
    {
        match self.store.get(key) {
            Some(item) => self.items.get(*item.data()),
            None => None,
        }
    }

    /// Returns whether the queue contains the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, Store, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Ensure presence of key
    /// let check = queue.contains_key(&"key");
    /// assert_eq!(check, true);
    /// ```
    #[inline]
    fn contains_key<Q>(&self, key: &Q) -> bool
    where
        K: Borrow<Q>,
        Q: Key,
    {
        self.store.contains_key(key)
    }

    /// Returns the number of items in the queue.
    #[inline]
    fn len(&self) -> usize {
        self.store.len()
    }
}

impl<K, V, S> StoreMut<K, V> for Queue<K, V, S>
where
    K: Key,
    V: Value,
    S: StoreMut<K, Item>,
{
    /// Inserts the value identified by the key.
    ///
    /// This method only updates the data of the [`Item`], but does not change
    /// the values of [`Item::deadline`] in case the item already exists.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue
    /// let mut queue = Queue::default();
    ///
    /// // Insert value
    /// let value = queue.insert("key", 42);
    /// assert_eq!(value, None);
    /// ```
    #[inline]
    fn insert(&mut self, key: K, value: V) -> Option<V> {
        if let Some(item) = self.store.get(&key) {
            let prior = &mut self.items[*item.data()];
            (prior != &value).then(|| mem::replace(prior, value))
        } else {
            let index = self.items.insert(value);
            self.store.insert(key, Item::new(index));
            None
        }
    }

    /// Removes the value identified by the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Remove and return value
    /// let value = queue.remove(&"key");
    /// assert_eq!(value, Some(42));
    /// ```
    #[inline]
    fn remove<Q>(&mut self, key: &Q) -> Option<V>
    where
        K: Borrow<Q>,
        Q: Key,
    {
        self.store
            .remove(key)
            .map(|item| self.items.remove(*item.data()))
    }

    /// Removes the value identified by the key and returns both.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Remove and return entry
    /// let entry = queue.remove_entry(&"key");
    /// assert_eq!(entry, Some(("key", 42)));
    /// ```
    #[inline]
    fn remove_entry<Q>(&mut self, key: &Q) -> Option<(K, V)>
    where
        K: Borrow<Q>,
        Q: Key,
    {
        self.store
            .remove_entry(key)
            .map(|(key, item)| (key, self.items.remove(*item.data())))
    }

    /// Clears the queue, removing all items.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, Store, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Clear queue
    /// queue.clear();
    /// assert!(queue.is_empty());
    /// ```
    #[inline]
    fn clear(&mut self) {
        self.store.clear();
        self.items.clear();
    }
}

impl<K, V, S> StoreMutRef<K, V> for Queue<K, V, S>
where
    K: Key,
    S: StoreMut<K, Item>,
{
    /// Returns a mutable reference to the value identified by the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut, StoreMutRef};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Obtain mutable reference to value
    /// let mut value = queue.get_mut(&"key");
    /// assert_eq!(value, Some(&mut 42));
    /// ```
    #[inline]
    fn get_mut<Q>(&mut self, key: &Q) -> Option<&mut V>
    where
        K: Borrow<Q>,
        Q: Key,
    {
        match self.store.get(key) {
            Some(item) => self.items.get_mut(*item.data()),
            None => None,
        }
    }

    /// Returns a mutable reference to the value or creates the default.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMutRef};
    ///
    /// // Create queue
    /// let mut queue = Queue::<_, i32>::default();
    ///
    /// // Obtain mutable reference to value
    /// let value = queue.get_or_insert_default(&"key");
    /// assert_eq!(value, &mut 0);
    /// ```
    #[inline]
    fn get_or_insert_default(&mut self, key: &K) -> &mut V
    where
        V: Default,
    {
        if !self.store.contains_key(key) {
            let index = self.items.insert(V::default());
            self.store.insert(key.clone(), Item::new(index));
        }

        // We can safely use expect here, as the key is present
        self.get_mut(key).expect("invariant")
    }
}

// ----------------------------------------------------------------------------

#[allow(clippy::into_iter_without_iter)]
impl<'a, K, V, S> IntoIterator for &'a Queue<K, V, S>
where
    K: Key,
    V: Value,
    S: StoreIterable<K, Item>,
{
    type Item = (&'a K, &'a V);
    type IntoIter = Iter<'a, K, V>;

    /// Creates an iterator over the queue.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Create iterator over the queue
    /// for (key, value) in &queue {
    ///     println!("{key}: {value}");
    /// }
    /// ```
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

#[allow(clippy::into_iter_without_iter)]
impl<'a, K, V, S> IntoIterator for &'a mut Queue<K, V, S>
where
    K: Key,
    V: Value,
    S: StoreMut<K, Item> + StoreIterable<K, Item>,
{
    type Item = (&'a K, &'a mut V);
    type IntoIter = IterMut<'a, K, V>;

    /// Creates a mutable iterator over the queue.
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue and initial state
    /// let mut queue = Queue::default();
    /// queue.insert("key", 42);
    ///
    /// // Create iterator over the queue
    /// for (key, value) in &mut queue {
    ///     println!("{key}: {value}");
    /// }
    /// ```
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

// ----------------------------------------------------------------------------

impl<K, V> Default for Queue<K, V>
where
    K: Key,
{
    /// Creates a queue with [`HashMap::default`][] as a store.
    ///
    /// Note that this method does not allow to customize the [`BuildHasher`][],
    /// but uses [`ahash`] by default, which is the fastest known hasher.
    ///
    /// [`BuildHasher`]: std::hash::BuildHasher
    /// [`HashMap::default`]: Default::default
    ///
    /// # Examples
    ///
    /// ```
    /// use zrx_store::{Queue, StoreMut};
    ///
    /// // Create queue
    /// let mut queue = Queue::default();
    ///
    /// // Insert value
    /// queue.insert("key", 42);
    /// ```
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

// ----------------------------------------------------------------------------

impl<K, V, S> Debug for Queue<K, V, S>
where
    K: Debug,
    V: Debug,
    S: Debug,
{
    /// Formats the queue for debugging.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Queue")
            .field("store", &self.store)
            .field("items", &self.items)
            .finish()
    }
}