1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#![allow(unused_results)]
#[cfg(not(feature = "testing"))]
use std::collections::HashMap as Map;
// we avoid HashMap while testing because
// it makes tests non-deterministic
#[cfg(feature = "testing")]
use std::collections::BTreeMap as Map;
use super::*;
/// A batch of updates that will
/// be applied atomically to the
/// Tree.
///
/// # Examples
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use sled::{Batch, open};
///
/// # let _ = std::fs::remove_dir_all("batch_db_2");
/// let db = open("batch_db_2")?;
/// db.insert("key_0", "val_0")?;
///
/// let mut batch = Batch::default();
/// batch.insert("key_a", "val_a");
/// batch.insert("key_b", "val_b");
/// batch.insert("key_c", "val_c");
/// batch.remove("key_0");
///
/// db.apply_batch(batch)?;
/// // key_0 no longer exists, and key_a, key_b, and key_c
/// // now do exist.
/// # let _ = std::fs::remove_dir_all("batch_db_2");
/// # Ok(()) }
/// ```
#[derive(Debug, Default, Clone)]
pub struct Batch {
pub(crate) writes: Map<IVec, Option<IVec>>,
}
impl Batch {
/// Set a key to a new value
pub fn insert<K, V>(&mut self, key: K, value: V)
where
K: Into<IVec>,
V: Into<IVec>,
{
self.writes.insert(key.into(), Some(value.into()));
}
/// Remove a key
pub fn remove<K>(&mut self, key: K)
where
K: Into<IVec>,
{
self.writes.insert(key.into(), None);
}
}