Skip to main content

tuwunel_database/map/
keys_prefix.rs

1use std::{fmt::Debug, sync::Arc};
2
3use futures::{Stream, StreamExt, TryStreamExt, future};
4use serde::{Deserialize, Serialize};
5use tuwunel_core::{Result, implement};
6
7use crate::keyval::{Key, result_deserialize_key, serialize_key};
8
9/// Streams deserialized keys matching a serialized prefix in ascending order.
10///
11/// The scan begins at the encoded prefix and stops at the first nonmatching
12/// key. Any borrowed key must not be retained across another poll.
13///
14/// # Panics
15///
16/// Panics if the prefix cannot be serialized.
17#[implement(super::Map)]
18pub fn keys_prefix<'a, K, P>(
19	self: &'a Arc<Self>,
20	prefix: &P,
21) -> impl Stream<Item = Result<Key<'_, K>>> + Send + use<'a, K, P>
22where
23	P: Serialize + ?Sized + Debug,
24	K: Deserialize<'a> + Send,
25{
26	self.keys_prefix_raw(prefix)
27		.map(result_deserialize_key::<K>)
28}
29
30/// Streams raw keys matching a serialized prefix in ascending order.
31///
32/// The scan begins at the encoded prefix and stops at the first nonmatching
33/// key. Yielded keys borrow cursor storage and must not be retained across
34/// another poll.
35///
36/// # Panics
37///
38/// Panics if the prefix cannot be serialized.
39#[implement(super::Map)]
40#[tracing::instrument(skip(self), level = "trace")]
41pub fn keys_prefix_raw<P>(
42	self: &Arc<Self>,
43	prefix: &P,
44) -> impl Stream<Item = Result<Key<'_>>> + Send + use<'_, P>
45where
46	P: Serialize + ?Sized + Debug,
47{
48	let key = serialize_key(prefix).expect("failed to serialize query key");
49	self.raw_keys_from(&key)
50		.try_take_while(move |k: &Key<'_>| future::ok(k.starts_with(&key)))
51}
52
53/// Streams deserialized keys matching a raw prefix in ascending order.
54///
55/// The supplied bytes are used directly for the seek and prefix test. Any
56/// borrowed key must not be retained across another poll.
57#[implement(super::Map)]
58pub fn keys_raw_prefix<'a, K, P>(
59	self: &'a Arc<Self>,
60	prefix: &'a P,
61) -> impl Stream<Item = Result<Key<'_, K>>> + Send + 'a
62where
63	P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
64	K: Deserialize<'a> + Send + 'a,
65{
66	self.raw_keys_prefix(prefix)
67		.map(result_deserialize_key::<K>)
68}
69
70/// Streams raw keys matching a raw prefix in ascending order.
71///
72/// The supplied bytes are used directly for the seek and prefix test. Yielded
73/// keys borrow cursor storage and must not be retained across another poll.
74#[implement(super::Map)]
75pub fn raw_keys_prefix<'a, P>(
76	self: &'a Arc<Self>,
77	prefix: &'a P,
78) -> impl Stream<Item = Result<Key<'_>>> + Send + 'a
79where
80	P: AsRef<[u8]> + ?Sized + Debug + Sync + 'a,
81{
82	self.raw_keys_from(prefix)
83		.try_take_while(|k: &Key<'_>| future::ok(k.starts_with(prefix.as_ref())))
84}