spacetimedb_lib/
filterable_value.rs

1use crate::{ConnectionId, Identity};
2use core::ops;
3use spacetimedb_sats::bsatn;
4use spacetimedb_sats::{hash::Hash, i256, u256, Serialize};
5
6/// Types which can appear as an argument to an index filtering operation
7/// for a column of type `Column`.
8///
9/// Types which can appear specifically as a terminating bound in a BTree index,
10/// which may be a range, instead use [`IndexScanRangeBoundsTerminator`].
11///
12/// Because SpacetimeDB supports a only restricted set of types as index keys,
13/// only a small set of `Column` types have corresponding `FilterableValue` implementations.
14/// Specifically, these types are:
15/// - Signed and unsigned integers of various widths.
16/// - [`bool`].
17/// - [`String`], which is also filterable with `&str`.
18/// - [`Identity`].
19/// - [`ConnectionId`].
20/// - [`Hash`](struct@Hash).
21/// - No-payload enums annotated with `#[derive(SpacetimeType)]`.
22///   No-payload enums are sometimes called "plain," "simple" or "C-style."
23///   They are enums where no variant has any payload data.
24///
25/// Because SpacetimeDB indexes are present both on the server
26/// and in clients which use our various SDKs,
27/// implementing `FilterableValue` for a new column type is a significant burden,
28/// and **is not as simple** as adding a new `impl FilterableValue` block to our Rust code.
29/// To implement `FilterableValue` for a new column type, you must also:
30/// - Ensure (with automated tests) that the `spacetimedb-codegen` crate
31///   and accompanying SpacetimeDB client SDK can equality-compare and ordering-compare values of the column type,
32///   and that the resulting ordering is the same as the canonical ordering
33///   implemented by `spacetimedb-sats` for [`spacetimedb_sats::AlgebraicValue`].
34///   This will nearly always require implementing bespoke comparison methods for the type in question,
35///   as most languages do not automatically make product types (structs or classes) sortable.
36/// - Extend our other supported module languages' bindings libraries.
37///   so that they can also define tables with indexes keyed by the new filterable type.
38//
39// General rules for implementors of this type:
40// - See above doc comment for requirements to add implementations for new column types.
41// - It should only be implemented for owned values if those values are `Copy`.
42//   Otherwise it should only be implemented for references.
43//   This is so that rustc and IDEs will recommend rewriting `x` to `&x` rather than `x.clone()`.
44// - `Arg: FilterableValue<Column = Col>`
45//   for any pair of types `(Arg, Col)` which meet the above criteria
46//   is desirable if `Arg` and `Col` have the same BSATN layout.
47//   E.g. `&str: FilterableValue<Column = String>` is desirable.
48#[diagnostic::on_unimplemented(
49    message = "`{Self}` cannot appear as an argument to an index filtering operation",
50    label = "should be an integer type, `bool`, `String`, `&str`, `Identity`, `ConnectionId`, `Hash` or a no-payload enum which derives `SpacetimeType`, not `{Self}`",
51    note = "The allowed set of types are limited to integers, bool, strings, `Identity`, `ConnectionId`, `Hash` and no-payload enums which derive `SpacetimeType`,"
52)]
53pub trait FilterableValue: Serialize + Private {
54    type Column;
55}
56
57/// Hidden supertrait for [`FilterableValue`],
58/// to discourage users from hand-writing implementations.
59///
60/// We want to expose [`FilterableValue`] in the docs, but to prevent users from implementing it.
61/// Normally, we would just make this `Private` trait inaccessible,
62/// but we need to macro-generate implementations, so it must be `pub`.
63/// We mark it `doc(hidden)` to discourage use.
64#[doc(hidden)]
65pub trait Private {}
66
67macro_rules! impl_filterable_value {
68    (@one $arg:ty => $col:ty) => {
69        impl Private for $arg {}
70        impl FilterableValue for $arg {
71            type Column = $col;
72        }
73    };
74    (@one $arg:ty: Copy) => {
75        impl_filterable_value!(@one $arg => $arg);
76        impl_filterable_value!(@one &$arg => $arg);
77    };
78    (@one $arg:ty) => {
79        impl_filterable_value!(@one &$arg => $arg);
80    };
81    ($($arg:ty $(: $copy:ident)? $(=> $col:ty)?),* $(,)?) => {
82        $(impl_filterable_value!(@one $arg $(: $copy)? $(=> $col)?);)*
83    };
84}
85
86impl_filterable_value! {
87    u8: Copy,
88    u16: Copy,
89    u32: Copy,
90    u64: Copy,
91    u128: Copy,
92    u256: Copy,
93
94    i8: Copy,
95    i16: Copy,
96    i32: Copy,
97    i64: Copy,
98    i128: Copy,
99    i256: Copy,
100
101    bool: Copy,
102
103    String,
104    &str => String,
105
106    Identity: Copy,
107    ConnectionId: Copy,
108    Hash: Copy,
109
110    // Some day we will likely also want to support `Vec<u8>` and `[u8]`,
111    // as they have trivial portable equality and ordering,
112    // but @RReverser's proposed filtering rules do not include them.
113    // Vec<u8>,
114    // &[u8] => Vec<u8>,
115}
116
117pub enum TermBound<T> {
118    Single(ops::Bound<T>),
119    Range(ops::Bound<T>, ops::Bound<T>),
120}
121impl<Bound: FilterableValue> TermBound<&Bound> {
122    #[inline]
123    /// If `self` is [`TermBound::Range`], returns the `rend_idx` value for `IndexScanRangeArgs`,
124    /// i.e. the index in `buf` of the first byte in the end range
125    pub fn serialize_into(&self, buf: &mut Vec<u8>) -> Option<usize> {
126        let (start, end) = match self {
127            TermBound::Single(elem) => (elem, None),
128            TermBound::Range(start, end) => (start, Some(end)),
129        };
130        bsatn::to_writer(buf, start).unwrap();
131        end.map(|end| {
132            let rend_idx = buf.len();
133            bsatn::to_writer(buf, end).unwrap();
134            rend_idx
135        })
136    }
137}
138pub trait IndexScanRangeBoundsTerminator {
139    /// Whether this bound terminator is a point.
140    const POINT: bool = false;
141
142    /// The key type of the bound.
143    type Arg;
144
145    /// Returns the point bound, assuming `POINT == true`.
146    fn point(&self) -> &Self::Arg {
147        unimplemented!()
148    }
149
150    /// Returns the terminal bound for the range scan.
151    /// This bound can either be a point, as in most cases, or an actual bound.
152    fn bounds(&self) -> TermBound<&Self::Arg>;
153}
154
155impl<Col, Arg: FilterableValue<Column = Col>> IndexScanRangeBoundsTerminator for Arg {
156    const POINT: bool = true;
157    type Arg = Arg;
158    fn point(&self) -> &Arg {
159        self
160    }
161    fn bounds(&self) -> TermBound<&Arg> {
162        TermBound::Single(ops::Bound::Included(self))
163    }
164}
165
166macro_rules! impl_terminator {
167    ($($range:ty),* $(,)?) => {
168        $(impl<T: FilterableValue> IndexScanRangeBoundsTerminator for $range {
169            type Arg = T;
170            fn bounds(&self) -> TermBound<&T> {
171                TermBound::Range(
172                    ops::RangeBounds::start_bound(self),
173                    ops::RangeBounds::end_bound(self),
174                )
175            }
176        })*
177    };
178}
179
180impl_terminator!(
181    ops::Range<T>,
182    ops::RangeFrom<T>,
183    ops::RangeInclusive<T>,
184    ops::RangeTo<T>,
185    ops::RangeToInclusive<T>,
186    (ops::Bound<T>, ops::Bound<T>),
187);