use core::fmt;
use core::future::Future;
use core::pin::Pin;
use crate::maybe_send::MaybeSend;
#[derive(Clone, PartialEq, Eq)]
pub struct KvPair {
pub key: Vec<u8>,
pub value: Vec<u8>,
}
impl fmt::Debug for KvPair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"KvPair {{ key: <elided>, value: <{} bytes> }}",
self.value.len()
)
}
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
type KvStreamFuture<'a, E> =
Pin<Box<dyn Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + Send + 'a>>;
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
type KvStreamFuture<'a, E> =
Pin<Box<dyn Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + 'a>>;
#[must_use = "a KvStream does nothing unless awaited"]
pub struct KvStream<'a, E> {
inner: KvStreamFuture<'a, E>,
}
impl<E> fmt::Debug for KvStream<'_, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("KvStream(..)")
}
}
impl<'a, E> KvStream<'a, E> {
pub fn new<F>(fut: F) -> Self
where
F: Future<Output = Result<Option<(KvPair, KvStream<'a, E>)>, E>> + MaybeSend + 'a,
{
Self {
inner: Box::pin(fut),
}
}
pub fn empty() -> Self
where
E: 'a,
{
Self {
inner: Box::pin(async { Ok(None) }),
}
}
pub fn failed(err: E) -> Self
where
E: MaybeSend + 'a,
{
Self {
inner: Box::pin(async move { Err(err) }),
}
}
pub async fn next(self) -> Result<Option<(KvPair, KvStream<'a, E>)>, E> {
self.inner.await
}
pub async fn collect(self) -> Result<Vec<KvPair>, E> {
let mut results = Vec::new();
let mut current = self;
while let Some((pair, next)) = current.next().await? {
results.push(pair);
current = next;
}
Ok(results)
}
pub async fn take(self, limit: usize) -> Result<Vec<KvPair>, E> {
let mut results = Vec::with_capacity(limit.min(64));
let mut current = self;
for _ in 0..limit {
match current.next().await? {
Some((pair, next)) => {
results.push(pair);
current = next;
}
None => break,
}
}
Ok(results)
}
pub async fn for_each<F>(self, mut f: F) -> Result<(), E>
where
F: FnMut(KvPair),
{
let mut current = self;
while let Some((pair, next)) = current.next().await? {
f(pair);
current = next;
}
Ok(())
}
}