Struct Tree

Source
pub struct Tree<K, V>
where K: Key, V: Value,
{ /* private fields */ }
Expand description

A flash-sympathetic persistent lock-free B+ tree.

A Tree represents a single logical keyspace / namespace / bucket.

§Example

use bincode::{Encode, Decode};

#[derive(Debug, Clone, Encode, Decode, PartialEq)]
struct SomeValue(u32);

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Creating a temporary sled database.
    // If you want to persist the data use sled::open instead.
    let db = sled::Config::new().temporary(true).open().unwrap();

    // The id is used by sled to identify which Tree in the database (db) to open.
    let tree = bincode_sled::Tree::<String, SomeValue>::open(&db, "unique_id");

    tree.insert(&"some_key".to_owned(), &SomeValue(10))?;

    assert_eq!(tree.get(&"some_key".to_owned())?, Some(SomeValue(10)));
    Ok(())
}

Implementations§

Source§

impl<K, V> Tree<K, V>
where K: Key, V: Value,

Source

pub fn open<T: AsRef<str>>(db: &Db, id: T) -> Self

Initialize a typed tree. The id identifies the tree to be opened from the db.

§Example
use bincode::{Encode, Decode};

#[derive(Debug, Clone, Encode, Decode, PartialEq)]
struct SomeValue(u32);

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Creating a temporary sled database.
    // If you want to persist the data use sled::open instead.
    let db = sled::Config::new().temporary(true).open().unwrap();

    // The id is used by sled to identify which Tree in the database (db) to open.
    let tree = bincode_sled::Tree::<String, SomeValue>::open(&db, "unique_id");

    tree.insert(&"some_key".to_owned(), &SomeValue(10))?;

    assert_eq!(tree.get(&"some_key".to_owned())?, Some(SomeValue(10)));
    Ok(())
}
Examples found in repository?
examples/basic.rs (line 9)
3
4
5
6
7
8
9
10
11
12
13
14
15
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Creating a temporary sled database.
    // If you want to persist the data use sled::open instead.
    let db = sled::Config::new().temporary(true).open().unwrap();

    // The id is used by sled to identify which Tree in the database (db) to open
    let tree = bincode_sled::Tree::<String, SomeValue>::open(&db, "unique_id");

    tree.insert(&"some_key".to_owned(), &SomeValue(10))?;

    assert_eq!(tree.get(&"some_key".to_owned())?, Some(SomeValue(10)));
    Ok(())
}
Source

pub fn insert(&self, key: &K, value: &V) -> Result<Option<V>>

Insert a key to a new value, returning the last value if it was set.

Examples found in repository?
examples/basic.rs (line 11)
3
4
5
6
7
8
9
10
11
12
13
14
15
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Creating a temporary sled database.
    // If you want to persist the data use sled::open instead.
    let db = sled::Config::new().temporary(true).open().unwrap();

    // The id is used by sled to identify which Tree in the database (db) to open
    let tree = bincode_sled::Tree::<String, SomeValue>::open(&db, "unique_id");

    tree.insert(&"some_key".to_owned(), &SomeValue(10))?;

    assert_eq!(tree.get(&"some_key".to_owned())?, Some(SomeValue(10)));
    Ok(())
}
Source

pub fn transaction<F, A, E>(&self, f: F) -> TransactionResult<A, E>
where F: Fn(&TransactionalTree<'_, K, V>) -> ConflictableTransactionResult<A, E>,

Perform a multi-key serializable transaction.

Source

pub fn apply_batch(&self, batch: Batch<K, V>) -> Result<()>

Create a new batched update that can be atomically applied.

It is possible to apply a Batch in a transaction as well, which is the way you can apply a Batch to multiple Trees atomically.

Source

pub fn get(&self, key: &K) -> Result<Option<V>>

Retrieve a value from the Tree if it exists.

Examples found in repository?
examples/basic.rs (line 13)
3
4
5
6
7
8
9
10
11
12
13
14
15
fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Creating a temporary sled database.
    // If you want to persist the data use sled::open instead.
    let db = sled::Config::new().temporary(true).open().unwrap();

    // The id is used by sled to identify which Tree in the database (db) to open
    let tree = bincode_sled::Tree::<String, SomeValue>::open(&db, "unique_id");

    tree.insert(&"some_key".to_owned(), &SomeValue(10))?;

    assert_eq!(tree.get(&"some_key".to_owned())?, Some(SomeValue(10)));
    Ok(())
}
Source

pub fn get_from_raw<B: AsRef<[u8]>>(&self, key_bytes: B) -> Result<Option<V>>

Retrieve a value from the Tree if it exists. The key must be in serialized form.

Source

pub fn get_kv_from_raw<B: AsRef<[u8]>>( &self, key_bytes: B, ) -> Result<Option<(K, V)>>

Deserialize a key and retrieve it’s value from the Tree if it exists. The deserialization is only done if a value was retrieved successfully.

Source

pub fn remove(&self, key: &K) -> Result<Option<V>>

Delete a value, returning the old value if it existed.

Source

pub fn compare_and_swap( &self, key: &K, old: Option<&V>, new: Option<&V>, ) -> Result<Result<(), CompareAndSwapError<V>>>

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.

It returns Ok(Ok(())) if operation finishes successfully.

If it fails it returns: - Ok(Err(CompareAndSwapError(current, proposed))) if operation failed to setup a new value. CompareAndSwapError contains current and proposed values. - Err(Error::Unsupported) if the database is opened in read-only mode.

Source

pub fn update_and_fetch<F>(&self, key: &K, f: F) -> Result<Option<V>>
where F: FnMut(Option<V>) -> Option<V>,

Fetch the value, apply a function to it and return the result.

Source

pub fn fetch_and_update<F>(&self, key: &K, f: F) -> Result<Option<V>>
where F: FnMut(Option<V>) -> Option<V>,

Fetch the value, apply a function to it and return the previous value.

Source

pub fn watch_prefix(&self, prefix: &K) -> Subscriber<K, V>

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.

Source

pub fn watch_all(&self) -> Subscriber<K, V>

Subscribe to allEvents. 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.

Source

pub fn flush(&self) -> Result<usize>

Synchronously 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 the number of bytes flushed during this call.

Flushing can take quite a lot of time, and you should measure the performance impact of using it on realistic sustained workloads running on realistic hardware.

Source

pub async fn flush_async(&self) -> Result<usize>

Asynchronously 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 the number of bytes flushed during this call.

Flushing can take quite a lot of time, and you should measure the performance impact of using it on realistic sustained workloads running on realistic hardware.

Source

pub fn contains_key(&self, key: &K) -> Result<bool>

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

Source

pub fn get_lt(&self, key: &K) -> Result<Option<(K, V)>>

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

Source

pub fn get_gt(&self, key: &K) -> Result<Option<(K, V)>>

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

Source

pub fn merge(&self, key: &K, value: &V) -> Result<Option<V>>

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.

Calling merge will return an Unsupported error if it is called without first setting a merge operator function.

Merge operators are shared by all instances of a particular Tree. Different merge operators may be set on different Trees.

Source

pub fn set_merge_operator( &self, merge_operator: impl MergeOperator<K, V> + 'static, )

Sets a merge operator for use with the merge function.

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.

Source

pub fn iter(&self) -> Iter<K, V>

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

Source

pub fn range<R: RangeBounds<K>>(&self, range: R) -> Iter<K, V>

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

Source

pub fn scan_prefix(&self, prefix: &K) -> Iter<K, V>

Create an iterator over tuples of keys and values, where the all the keys starts with the given prefix.

Source

pub fn first(&self) -> Result<Option<(K, V)>>

Returns the first key and value in the Tree, or None if the Tree is empty.

Source

pub fn last(&self) -> Result<Option<(K, V)>>

Returns the last key and value in the Tree, or None if the Tree is empty.

Source

pub fn pop_max(&self) -> Result<Option<(K, V)>>

Atomically removes the maximum item in the Tree instance.

Source

pub fn pop_min(&self) -> Result<Option<(K, V)>>

Atomically removes the minimum item in the Tree instance.

Source

pub fn len(&self) -> usize

Returns the number of elements in this tree.

Source

pub fn is_empty(&self) -> bool

Returns true if the Tree contains no elements.

Source

pub fn clear(&self) -> Result<()>

Clears the Tree, removing all values.

Note that this is not atomic.

Source

pub fn name(&self) -> IVec

Returns the name of the tree.

Source

pub fn checksum(&self) -> Result<u32>

Returns the CRC32 of all keys and values in this Tree.

This is O(N) and locks the underlying tree for the duration of the entire scan.

Trait Implementations§

Source§

impl<K, V> Clone for Tree<K, V>
where K: Key, V: Value,

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<K, V> Debug for Tree<K, V>
where K: Key + Debug, V: Value + Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<K, V> Freeze for Tree<K, V>

§

impl<K, V> !RefUnwindSafe for Tree<K, V>

§

impl<K, V> Send for Tree<K, V>

§

impl<K, V> Sync for Tree<K, V>

§

impl<K, V> Unpin for Tree<K, V>

§

impl<K, V> !UnwindSafe for Tree<K, V>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.