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