composable_indexes/core/index.rs
1pub use super::Key;
2
3/// Seal type to restrict modification of indexes outside
4/// of the [`crate::Collection`] API.
5///
6/// If you are writing tests and need to create a seal,
7/// you can use the `unsafe_mk_seal` function under the
8/// `testutils` feature flag.
9#[derive(Clone, Copy)]
10pub struct Seal {
11 _seal: (),
12}
13
14pub(crate) const SEAL: Seal = Seal { _seal: () };
15
16impl Seal {
17 #[cfg(feature = "testutils")]
18 pub fn unsafe_mk_seal() -> Self {
19 Seal { _seal: () }
20 }
21}
22
23/// Types that can be used as indexes in a [`crate::Collection`].
24///
25/// An index processes items of type `T` - and can be accessed through the
26/// [`crate::Collection::query`]-family of methods to expose queries over the
27/// indexed data.
28///
29/// You should only need to know about this trait if you are implementing a
30/// custom index.
31///
32/// # Implementing an Index
33///
34/// An [`Index`] receives insertions, removals, and updates of items of type `T`,
35/// and maintains some internal state to answer queries about the indexed data.
36///
37/// Indexes must (minimally) handle insertion and removal of items. (Update
38/// operation has a default implementation that calls remove followed by insert;
39/// override it if a more efficient implementation is possible.)
40///
41/// All trait functions receive a `Seal` parameter that prevents external code
42/// from calling them directly. You can safely ignore this parameter.
43///
44/// All operations receive an operation struct (`Insert`, `Remove`, or `Update`)
45/// [`Insert`] guarantees that the key did not previously exists, [`Remove`] and
46/// [`Update`] guarantee carry a pointer to the existing value. This usually
47/// allows for more efficient implementations.
48///
49/// The queries themselves are not part of this trait - they are implemented
50/// as inherent on the index type itself.
51pub trait Index<T> {
52 fn insert(&mut self, seal: Seal, op: &Insert<T>);
53
54 fn remove(&mut self, seal: Seal, op: &Remove<T>);
55
56 #[inline]
57 fn update(&mut self, seal: Seal, op: &Update<T>) {
58 self.remove(
59 seal,
60 &Remove {
61 key: op.key,
62 existing: op.existing,
63 },
64 );
65 self.insert(
66 seal,
67 &Insert {
68 key: op.key,
69 new: op.new,
70 },
71 );
72 }
73}
74
75#[derive(Clone)]
76pub struct Insert<'t, In> {
77 pub key: Key,
78 pub new: &'t In,
79}
80
81#[derive(Clone)]
82pub struct Update<'t, In> {
83 pub key: Key,
84 pub new: &'t In,
85 pub existing: &'t In,
86}
87
88#[derive(Clone)]
89pub struct Remove<'t, In> {
90 pub key: Key,
91 pub existing: &'t In,
92}