use std::future::Future;
use std::ops::Bound;
use std::pin::Pin;
use crate::error::Result;
#[cfg(not(target_arch = "wasm32"))]
mod bounds {
#[diagnostic::on_unimplemented(
note = "on native targets crossbank requires `Send`; this type is not `Send`"
)]
pub trait MaybeSend: Send {}
impl<T: Send> MaybeSend for T {}
#[diagnostic::on_unimplemented(
note = "on native targets crossbank requires `Sync`; this type is not `Sync`"
)]
pub trait MaybeSync: Sync {}
impl<T: Sync> MaybeSync for T {}
}
#[cfg(target_arch = "wasm32")]
mod bounds {
pub trait MaybeSend {}
impl<T> MaybeSend for T {}
pub trait MaybeSync {}
impl<T> MaybeSync for T {}
}
pub use bounds::{MaybeSend, MaybeSync};
#[cfg(not(target_arch = "wasm32"))]
pub type BFut<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + Send + 'a>>;
#[cfg(target_arch = "wasm32")]
pub type BFut<'a, T> = Pin<Box<dyn Future<Output = Result<T>> + 'a>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Table {
Meta,
Records,
Chunks,
}
impl Table {
pub const fn name(self) -> &'static str {
match self {
Self::Meta => "meta",
Self::Records => "records",
Self::Chunks => "chunks",
}
}
pub const ALL: [Table; 3] = [Table::Meta, Table::Records, Table::Chunks];
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyRange {
pub start: Bound<Vec<u8>>,
pub end: Bound<Vec<u8>>,
}
impl KeyRange {
pub fn all() -> Self {
Self {
start: Bound::Unbounded,
end: Bound::Unbounded,
}
}
pub fn prefix(prefix: &[u8]) -> Self {
let start = Bound::Included(prefix.to_vec());
let mut end = prefix.to_vec();
while let Some(last) = end.pop() {
if last != 0xFF {
end.push(last + 1);
return Self {
start,
end: Bound::Excluded(end),
};
}
}
Self {
start,
end: Bound::Unbounded,
}
}
pub fn contains(&self, key: &[u8]) -> bool {
let above_start = match &self.start {
Bound::Unbounded => true,
Bound::Included(s) => key >= s.as_slice(),
Bound::Excluded(s) => key > s.as_slice(),
};
let below_end = match &self.end {
Bound::Unbounded => true,
Bound::Included(e) => key <= e.as_slice(),
Bound::Excluded(e) => key < e.as_slice(),
};
above_start && below_end
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Op {
Put {
table: Table,
key: Vec<u8>,
value: Vec<u8>,
},
Delete {
table: Table,
key: Vec<u8>,
},
DeleteRange {
table: Table,
range: KeyRange,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Durability {
#[default]
Immediate,
Eventual,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CommitOptions {
pub durability: Durability,
}
impl CommitOptions {
pub const fn immediate() -> Self {
Self {
durability: Durability::Immediate,
}
}
pub const fn eventual() -> Self {
Self {
durability: Durability::Eventual,
}
}
}
pub const DEFAULT_SCAN_PAGE: usize = 256;
#[derive(Debug, Clone)]
pub struct ScanRequest {
pub table: Table,
pub range: KeyRange,
pub reverse: bool,
pub limit: usize,
pub want_values: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ScanPage {
pub items: Vec<(Vec<u8>, Option<Vec<u8>>)>,
pub resume: Option<Vec<u8>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Usage {
pub used: u64,
pub available: Option<u64>,
pub persisted: bool,
}
pub trait Backend: MaybeSend + MaybeSync + 'static {
fn get<'a>(&'a self, table: Table, key: &'a [u8]) -> BFut<'a, Option<Vec<u8>>>;
fn get_many<'a>(&'a self, table: Table, keys: Vec<Vec<u8>>) -> BFut<'a, Vec<Option<Vec<u8>>>>;
fn scan(&self, request: ScanRequest) -> BFut<'_, ScanPage>;
fn scan_page_size(&self) -> usize {
DEFAULT_SCAN_PAGE
}
fn commit(&self, ops: Vec<Op>) -> BFut<'_, ()>;
fn commit_with(&self, ops: Vec<Op>, options: CommitOptions) -> BFut<'_, ()> {
let _ = options;
self.commit(ops)
}
fn usage(&self) -> BFut<'_, Option<Usage>>;
fn flush(&self) -> BFut<'_, ()>;
fn close(&self) -> BFut<'_, ()> {
Box::pin(async { Ok(()) })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prefix_range_covers_exactly_the_prefixed_keys() {
let r = KeyRange::prefix(b"ab");
assert!(r.contains(b"ab"));
assert!(r.contains(b"abz"));
assert!(r.contains(b"ab\xFF\xFF"));
assert!(!r.contains(b"aa"));
assert!(!r.contains(b"ac"));
assert!(!r.contains(b"b"));
}
#[test]
fn prefix_of_all_ff_bytes_has_no_upper_bound() {
let r = KeyRange::prefix(&[0xFF, 0xFF]);
assert_eq!(r.end, Bound::Unbounded);
assert!(r.contains(&[0xFF, 0xFF, 0x00]));
assert!(!r.contains(&[0xFE]));
}
#[test]
fn empty_prefix_is_everything() {
let r = KeyRange::prefix(b"");
assert_eq!(r.end, Bound::Unbounded);
assert!(r.contains(b""));
assert!(r.contains(b"anything"));
}
#[test]
fn table_names_are_stable() {
assert_eq!(Table::Meta.name(), "meta");
assert_eq!(Table::Records.name(), "records");
assert_eq!(Table::Chunks.name(), "chunks");
assert_eq!(Table::ALL.len(), 3);
}
}