From 3b2ef02749006b9bd5ccf13ae941e90acef16202 Mon Sep 17 00:00:00 2001 From: Michael Goldenberg Date: Mon, 20 Oct 2025 10:51:05 -0400 Subject: [PATCH] refactor(indexeddb): add fn for prefixed key ranges from existing key ranges Signed-off-by: Michael Goldenberg --- .../src/serializer/indexed_type/range.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/crates/matrix-sdk-indexeddb/src/serializer/indexed_type/range.rs b/crates/matrix-sdk-indexeddb/src/serializer/indexed_type/range.rs index bd2d74851..952b0573e 100644 --- a/crates/matrix-sdk-indexeddb/src/serializer/indexed_type/range.rs +++ b/crates/matrix-sdk-indexeddb/src/serializer/indexed_type/range.rs @@ -60,6 +60,9 @@ impl<'a, C: 'a> IndexedKeyRange { } impl IndexedKeyRange { + /// Applies the function `f` to transform keys of type `K` to keys of type + /// `T`. The function `f` is applied to all values - i.e., the value in + /// [`IndexedKeyRange::Only`] and both bounds in [`IndexedKeyRange::Bound`]. pub fn map(self, f: F) -> IndexedKeyRange where F: Fn(K) -> T, @@ -70,6 +73,7 @@ impl IndexedKeyRange { } } + /// Represents all keys of type `K` pub fn all(serializer: &SafeEncodeSerializer) -> IndexedKeyRange where T: Indexed, @@ -78,6 +82,7 @@ impl IndexedKeyRange { IndexedKeyRange::Bound(K::lower_key(serializer), K::upper_key(serializer)) } + /// Represents all keys of type `K` which begin with `prefix` pub fn all_with_prefix(prefix: P, serializer: &SafeEncodeSerializer) -> IndexedKeyRange where T: Indexed, @@ -89,6 +94,32 @@ impl IndexedKeyRange { K::upper_key_with_prefix(prefix, serializer), ) } + + /// Transforms keys of type `K` into keys of type `K2` by using `K` as the + /// prefix for `K2`. + /// + /// For [`IndexedKeyRange::Only`] variants, the resulting value will be an + /// [`IndexedKeyRange::Bound`] that represents all keys that begin with + /// [`IndexedKeyRange::Only::0`]. + /// + /// For [`IndexedKeyRange::Bound`] variants, the resulting value will be an + /// [`IndexedKeyRange::Bound`] that represents all keys in a range where + /// the lower bound begins with [`IndexedKeyRange::Bound::0`] and the upper + /// bound begins with [`IndexedKeyRange::Bound::1`]. + pub fn into_prefix(self, serializer: &SafeEncodeSerializer) -> IndexedKeyRange + where + T: Indexed, + K: Clone, + K2: IndexedPrefixKeyBounds, + { + match self { + IndexedKeyRange::Only(key) => IndexedKeyRange::all_with_prefix(key, serializer), + IndexedKeyRange::Bound(lower, upper) => IndexedKeyRange::Bound( + K2::lower_key_with_prefix(lower, serializer), + K2::upper_key_with_prefix(upper, serializer), + ), + } + } } impl From<(K, K)> for IndexedKeyRange {