pub struct Tree<K, V>{ /* 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>
impl<K, V> Tree<K, V>
Sourcepub fn open<T: AsRef<str>>(db: &Db, id: T) -> Self
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?
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(())
}
Sourcepub fn insert(&self, key: &K, value: &V) -> Result<Option<V>>
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?
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(())
}
Sourcepub fn transaction<F, A, E>(&self, f: F) -> TransactionResult<A, E>
pub fn transaction<F, A, E>(&self, f: F) -> TransactionResult<A, E>
Perform a multi-key serializable transaction.
Sourcepub fn apply_batch(&self, batch: Batch<K, V>) -> Result<()>
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.
Sourcepub fn get(&self, key: &K) -> Result<Option<V>>
pub fn get(&self, key: &K) -> Result<Option<V>>
Retrieve a value from the Tree if it exists.
Examples found in repository?
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(())
}
Sourcepub fn get_from_raw<B: AsRef<[u8]>>(&self, key_bytes: B) -> Result<Option<V>>
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.
Sourcepub fn get_kv_from_raw<B: AsRef<[u8]>>(
&self,
key_bytes: B,
) -> Result<Option<(K, V)>>
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.
Sourcepub fn remove(&self, key: &K) -> Result<Option<V>>
pub fn remove(&self, key: &K) -> Result<Option<V>>
Delete a value, returning the old value if it existed.
Sourcepub fn compare_and_swap(
&self,
key: &K,
old: Option<&V>,
new: Option<&V>,
) -> Result<Result<(), CompareAndSwapError<V>>>
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.
Sourcepub fn update_and_fetch<F>(&self, key: &K, f: F) -> Result<Option<V>>
pub fn update_and_fetch<F>(&self, key: &K, f: F) -> Result<Option<V>>
Fetch the value, apply a function to it and return the result.
Sourcepub fn fetch_and_update<F>(&self, key: &K, f: F) -> Result<Option<V>>
pub fn fetch_and_update<F>(&self, key: &K, f: F) -> Result<Option<V>>
Fetch the value, apply a function to it and return the previous value.
Sourcepub fn watch_prefix(&self, prefix: &K) -> Subscriber<K, V> ⓘ
pub fn watch_prefix(&self, prefix: &K) -> Subscriber<K, V> ⓘ
Subscribe to Event
s 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 Event
s 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.
Sourcepub fn watch_all(&self) -> Subscriber<K, V> ⓘ
pub fn watch_all(&self) -> Subscriber<K, V> ⓘ
Subscribe to allEvent
s. Events for particular keys are
guaranteed to be witnessed in the same order by all
threads, but threads may witness different interleavings
of Event
s 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.
Sourcepub fn flush(&self) -> Result<usize>
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.
Sourcepub async fn flush_async(&self) -> Result<usize>
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.
Sourcepub fn contains_key(&self, key: &K) -> Result<bool>
pub fn contains_key(&self, key: &K) -> Result<bool>
Returns true
if the Tree
contains a value for
the specified key.
Sourcepub fn get_lt(&self, key: &K) -> Result<Option<(K, V)>>
pub fn get_lt(&self, key: &K) -> Result<Option<(K, V)>>
Retrieve the key and value before the provided key, if one exists.
Sourcepub fn get_gt(&self, key: &K) -> Result<Option<(K, V)>>
pub fn get_gt(&self, key: &K) -> Result<Option<(K, V)>>
Retrieve the next key and value from the Tree
after the
provided key.
Sourcepub fn merge(&self, key: &K, value: &V) -> Result<Option<V>>
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
Tree
s.
Sourcepub fn set_merge_operator(
&self,
merge_operator: impl MergeOperator<K, V> + 'static,
)
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.
Sourcepub fn iter(&self) -> Iter<K, V> ⓘ
pub fn iter(&self) -> Iter<K, V> ⓘ
Create a double-ended iterator over the tuples of keys and values in this tree.
Sourcepub fn range<R: RangeBounds<K>>(&self, range: R) -> Iter<K, V> ⓘ
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.
Sourcepub fn scan_prefix(&self, prefix: &K) -> Iter<K, V> ⓘ
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.
Sourcepub fn first(&self) -> Result<Option<(K, V)>>
pub fn first(&self) -> Result<Option<(K, V)>>
Returns the first key and value in the Tree
, or
None
if the Tree
is empty.
Sourcepub fn last(&self) -> Result<Option<(K, V)>>
pub fn last(&self) -> Result<Option<(K, V)>>
Returns the last key and value in the Tree
, or
None
if the Tree
is empty.
Sourcepub fn pop_max(&self) -> Result<Option<(K, V)>>
pub fn pop_max(&self) -> Result<Option<(K, V)>>
Atomically removes the maximum item in the Tree
instance.
Sourcepub fn pop_min(&self) -> Result<Option<(K, V)>>
pub fn pop_min(&self) -> Result<Option<(K, V)>>
Atomically removes the minimum item in the Tree
instance.