Struct sled::Tree

source ·
pub struct Tree { /* private fields */ }
Expand description

A flash-sympathetic persistent lock-free B+ tree

Examples

let t = sled::Db::start_default("path_to_my_database").unwrap();

t.set(b"yo!", b"v1".to_vec());
assert!(t.get(b"yo!").unwrap().unwrap() == &*b"v1".to_vec());

t.cas(
    b"yo!",                // key
    Some(b"v1"),           // old value, None for not present
    Some(b"v2".to_vec()),  // new value, None for delete
).unwrap();

let mut iter = t.scan(b"a non-present key before yo!");
// assert_eq!(iter.next(), Some(Ok((b"yo!".to_vec(), b"v2".to_vec()))));
// assert_eq!(iter.next(), None);

t.del(b"yo!");
assert_eq!(t.get(b"yo!"), Ok(None));

Implementations

Subscribe to Events that happen to keys that have the specified prefix. Events for particular keys are guaranteed to be witnessed in the same order by all threads, but threads may witness different interleavings of Events across different keys. If subscribers don’t keep up with new writes, they will cause new writes to block. There is a buffer of 1024 items per Subscriber. This can be used to build reactive and replicated systems.

Examples
use sled::{Event, ConfigBuilder};
let config = ConfigBuilder::new().temporary(true).build();

let tree = sled::Db::start(config).unwrap();

// watch all events by subscribing to the empty prefix
let mut events = tree.watch_prefix(vec![]);

let tree_2 = tree.clone();
let thread = std::thread::spawn(move || {
    tree.set(vec![0], vec![1]).unwrap();
});

// events is a blocking `Iterator` over `Event`s
for event in events.take(1) {
    match event {
        Event::Set(key, value) => assert_eq!(key, vec![0]),
        Event::Merge(key, partial_value) => {}
        Event::Del(key) => {}
    }
}

thread.join().unwrap();

Clears the Tree, removing all values.

Note that this is not atomic.

Flushes all dirty IO buffers and calls fsync. If this succeeds, it is guaranteed that all previous writes will be recovered if the system crashes.

Returns true if the Tree contains a value for the specified key.

Retrieve a value from the Tree if it exists.

Retrieve the key and value before the provided key, if one exists.

Examples
use sled::{ConfigBuilder, Error};
let config = ConfigBuilder::new().temporary(true).build();

let tree = sled::Db::start(config).unwrap();

for i in 0..10 {
    tree.set(vec![i], vec![i]).expect("should write successfully");
}

assert!(tree.get_lt(vec![]).unwrap().is_none());
assert!(tree.get_lt(vec![0]).unwrap().is_none());
assert!(tree.get_lt(vec![1]).unwrap().unwrap().1 == vec![0]);
assert!(tree.get_lt(vec![9]).unwrap().unwrap().1 == vec![8]);
assert!(tree.get_lt(vec![10]).unwrap().unwrap().1 == vec![9]);
assert!(tree.get_lt(vec![255]).unwrap().unwrap().1 == vec![9]);

Retrieve the next key and value from the Tree after the provided key.

Examples
use sled::{ConfigBuilder, Error};
let config = ConfigBuilder::new().temporary(true).build();

let tree = sled::Db::start(config).unwrap();

for i in 0..10 {
    tree.set(vec![i], vec![i]).expect("should write successfully");
}

assert!(tree.get_gt(vec![]).unwrap().unwrap().1 == vec![0]);
assert!(tree.get_gt(vec![0]).unwrap().unwrap().1 == vec![1]);
assert!(tree.get_gt(vec![1]).unwrap().unwrap().1 == vec![2]);
assert!(tree.get_gt(vec![8]).unwrap().unwrap().1 == vec![9]);
assert!(tree.get_gt(vec![9]).unwrap().is_none());

Compare and swap. Capable of unique creation, conditional modification, or deletion. If old is None, this will only set the value if it doesn’t exist yet. If new is None, will delete the value if old is correct. If both old and new are Some, will modify the value if old is correct. If Tree is read-only, will do nothing.

Examples
use sled::{ConfigBuilder, Error};
let config = ConfigBuilder::new().temporary(true).build();
let t = sled::Db::start(config).unwrap();

// unique creation
assert_eq!(t.cas(&[1], None, Some(vec![1])), Ok(()));
// assert_eq!(t.cas(&[1], None, Some(vec![1])), Err(Error::CasFailed(Some(vec![1]))));

// conditional modification
assert_eq!(t.cas(&[1], Some(&*vec![1]), Some(vec![2])), Ok(()));
// assert_eq!(t.cas(&[1], Some(vec![1]), Some(vec![2])), Err(Error::CasFailed(Some(vec![2]))));

// conditional deletion
assert_eq!(t.cas(&[1], Some(&[2]), None), Ok(()));
assert_eq!(t.get(&[1]), Ok(None));

Set a key to a new value, returning the old value if it was set.

Delete a value, returning the last result if it existed.

Examples
let config = sled::ConfigBuilder::new().temporary(true).build();
let t = sled::Db::start(config).unwrap();
t.set(&[1], vec![1]);
assert_eq!(t.del(&*vec![1]).unwrap().unwrap(), vec![1]);
assert_eq!(t.del(&*vec![1]), Ok(None));

Merge state directly into a given key’s value using the configured merge operator. This allows state to be written into a value directly, without any read-modify-write steps. Merge operators can be used to implement arbitrary data structures.

Panics

Calling merge will panic if no merge operator has been configured.

Examples
fn concatenate_merge(
  _key: &[u8],               // the key being merged
  old_value: Option<&[u8]>,  // the previous value, if one existed
  merged_bytes: &[u8]        // the new bytes being merged in
) -> Option<Vec<u8>> {       // set the new value, return None to delete
  let mut ret = old_value
    .map(|ov| ov.to_vec())
    .unwrap_or_else(|| vec![]);

  ret.extend_from_slice(merged_bytes);

  Some(ret)
}

let config = sled::ConfigBuilder::new()
  .temporary(true)
  .merge_operator(concatenate_merge)
  .build();

let tree = sled::Db::start(config).unwrap();

let k = b"k1";

tree.set(k, vec![0]);
tree.merge(k, vec![1]);
tree.merge(k, vec![2]);
// assert_eq!(tree.get(k).unwrap().unwrap(), vec![0, 1, 2]);

// sets replace previously merged data,
// bypassing the merge function.
tree.set(k, vec![3]);
// assert_eq!(tree.get(k), Ok(Some(vec![3])));

// merges on non-present values will add them
tree.del(k);
tree.merge(k, vec![4]);
// assert_eq!(tree.get(k).unwrap().unwrap(), vec![4]);

Create a double-ended iterator over the tuples of keys and values in this tree.

Examples
let config = sled::ConfigBuilder::new().temporary(true).build();
let t = sled::Db::start(config).unwrap();
t.set(&[1], vec![10]);
t.set(&[2], vec![20]);
t.set(&[3], vec![30]);
let mut iter = t.iter();
// assert_eq!(iter.next(), Some(Ok((vec![1], vec![10]))));
// assert_eq!(iter.next(), Some(Ok((vec![2], vec![20]))));
// assert_eq!(iter.next(), Some(Ok((vec![3], vec![30]))));
// assert_eq!(iter.next(), None);

Create a double-ended iterator over tuples of keys and values, starting at the provided key.

Examples
let config = sled::ConfigBuilder::new()
    .temporary(true)
    .build();
let t = sled::Db::start(config).unwrap();

t.set(b"0", vec![0]).unwrap();
t.set(b"1", vec![10]).unwrap();
t.set(b"2", vec![20]).unwrap();
t.set(b"3", vec![30]).unwrap();
t.set(b"4", vec![40]).unwrap();
t.set(b"5", vec![50]).unwrap();

let mut r = t.scan(b"2");
assert_eq!(r.next().unwrap().unwrap().0, b"2");
assert_eq!(r.next().unwrap().unwrap().0, b"3");
assert_eq!(r.next().unwrap().unwrap().0, b"4");
assert_eq!(r.next().unwrap().unwrap().0, b"5");
assert_eq!(r.next(), None);
let mut r = t.scan(b"2").rev();
assert_eq!(r.next().unwrap().unwrap().0, b"2");
assert_eq!(r.next().unwrap().unwrap().0, b"1");
assert_eq!(r.next().unwrap().unwrap().0, b"0");
assert_eq!(r.next(), None);

Create a double-ended iterator over tuples of keys and values, where the keys fall within the specified range.

Examples
let config = sled::ConfigBuilder::new()
    .temporary(true)
    .build();
let t = sled::Db::start(config).unwrap();

t.set(b"0", vec![0]).unwrap();
t.set(b"1", vec![10]).unwrap();
t.set(b"2", vec![20]).unwrap();
t.set(b"3", vec![30]).unwrap();
t.set(b"4", vec![40]).unwrap();
t.set(b"5", vec![50]).unwrap();

let start: &[u8] = b"2";
let end: &[u8] = b"4";
let mut r = t.range(start..end);
assert_eq!(r.next().unwrap().unwrap().0, b"2");
assert_eq!(r.next().unwrap().unwrap().0, b"3");
assert_eq!(r.next(), None);

let start = b"2".to_vec();
let end = b"4".to_vec();
let mut r = t.range(start..end).rev();
assert_eq!(r.next().unwrap().unwrap().0, b"3");
assert_eq!(r.next().unwrap().unwrap().0, b"2");
assert_eq!(r.next(), None);

Create a double-ended iterator over keys, starting at the provided key.

Examples
let config = sled::ConfigBuilder::new().temporary(true).build();
let t = sled::Db::start(config).unwrap();
t.set(&[1], vec![10]);
t.set(&[2], vec![20]);
t.set(&[3], vec![30]);
let mut iter = t.scan(&*vec![2]);
// assert_eq!(iter.next(), Some(Ok(vec![2])));
// assert_eq!(iter.next(), Some(Ok(vec![3])));
// assert_eq!(iter.next(), None);

Create a double-ended iterator over values, starting at the provided key.

Examples
let config = sled::ConfigBuilder::new().temporary(true).build();
let t = sled::Db::start(config).unwrap();
t.set(&[1], vec![10]);
t.set(&[2], vec![20]);
t.set(&[3], vec![30]);
let mut iter = t.scan(&*vec![2]);
// assert_eq!(iter.next(), Some(Ok(vec![20])));
// assert_eq!(iter.next(), Some(Ok(vec![30])));
// assert_eq!(iter.next(), None);

Returns the number of elements in this tree.

Beware: performs a full O(n) scan under the hood.

Returns true if the Tree contains no elements.

Trait Implementations

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The alignment of pointer.
The type for initializers.
Initializes a with the given initializer. Read more
Dereferences the given pointer. Read more
Mutably dereferences the given pointer. Read more
Drops the object pointed to by the given pointer. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.