use std::fmt;
use crate::value::BorrowedBytes;
use crate::{OwnedBytes, OwnedSlice};
use firewood::api;
pub type OwnedKeyValueBatch = OwnedSlice<OwnedKeyValuePair>;
#[derive(Debug, Clone, Copy)]
#[repr(C, usize)]
pub enum BatchOp<'a> {
Put {
key: BorrowedBytes<'a>,
value: BorrowedBytes<'a>,
},
Delete { key: BorrowedBytes<'a> },
DeleteRange { prefix: BorrowedBytes<'a> },
}
impl<'a> BatchOp<'a> {
pub fn new((key, value): &'a (impl AsRef<[u8]>, impl AsRef<[u8]>)) -> Self {
Self::Put {
key: BorrowedBytes::from_slice(key.as_ref()),
value: BorrowedBytes::from_slice(value.as_ref()),
}
}
}
impl fmt::Display for BatchOp<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let precision = f.precision().unwrap_or(64);
match self {
BatchOp::Put { key, value } => {
write!(f, "Put(Key: {key:.precision$}, Value: {value:.precision$})")
}
BatchOp::Delete { key } => write!(f, "Delete(Key: {key:.precision$})"),
BatchOp::DeleteRange { prefix } => {
write!(f, "DeleteRange(Prefix: {prefix:.precision$})")
}
}
}
}
impl<'a> api::TryIntoBatch for BatchOp<'a> {
type Key = BorrowedBytes<'a>;
type Value = BorrowedBytes<'a>;
type Error = std::convert::Infallible;
#[inline]
fn try_into_batch(self) -> Result<api::BatchOp<Self::Key, Self::Value>, Self::Error> {
Ok(match self {
BatchOp::Put { key, value } => api::BatchOp::Put { key, value },
BatchOp::Delete { key } => api::BatchOp::Delete { key },
BatchOp::DeleteRange { prefix } => api::BatchOp::DeleteRange { prefix },
})
}
}
impl<'a> api::TryIntoBatch for &BatchOp<'a> {
type Key = BorrowedBytes<'a>;
type Value = BorrowedBytes<'a>;
type Error = std::convert::Infallible;
#[inline]
fn try_into_batch(self) -> Result<api::BatchOp<Self::Key, Self::Value>, Self::Error> {
(*self).try_into_batch()
}
}
#[repr(C)]
#[derive(Debug, Clone)]
pub struct OwnedKeyValuePair {
pub key: OwnedBytes,
pub value: OwnedBytes,
}
impl From<(Box<[u8]>, Box<[u8]>)> for OwnedKeyValuePair {
fn from(value: (Box<[u8]>, Box<[u8]>)) -> Self {
OwnedKeyValuePair {
key: value.0.into(),
value: value.1.into(),
}
}
}