splinter_rs/
traits.rs

1use std::ops::RangeBounds;
2
3use crate::level::Level;
4use num::cast::AsPrimitive;
5use u24::u24;
6
7pub trait PartitionRead<L: Level> {
8    /// the total number of values accessible via this partition.
9    fn cardinality(&self) -> usize;
10
11    /// returns true if this partition is empty
12    fn is_empty(&self) -> bool;
13
14    /// returns true if this partition contains the given value
15    fn contains(&self, value: L::Value) -> bool;
16
17    /// returns the number of values contained in this partition up to and
18    /// including the value.
19    fn rank(&self, value: L::Value) -> usize;
20
21    /// returns the value at position `idx`.
22    fn select(&self, idx: usize) -> Option<L::Value>;
23
24    /// returns the last value in the partition
25    fn last(&self) -> Option<L::Value>;
26
27    /// returns an iterator over all values in this partition
28    fn iter(&self) -> impl Iterator<Item = L::Value>;
29
30    /// returns an iterator over all values in this partition restricted by the provided range.
31    fn range<R>(&self, range: R) -> impl Iterator<Item = L::Value>
32    where
33        R: RangeBounds<L::Value> + Clone,
34    {
35        let r2 = range.clone();
36        self.iter()
37            .skip_while(move |s| !range.contains(s))
38            .take_while(move |s| r2.contains(s))
39    }
40}
41
42pub trait PartitionWrite<L: Level> {
43    /// Inserts the value into the partition unless it already exists.
44    /// Returns `true` if the insertion occurred, `false` otherwise.
45    fn insert(&mut self, value: L::Value) -> bool;
46
47    /// Removes the value from the partition if it exists.
48    /// Returns `true` if the removal occurred, `false` otherwise.
49    fn remove(&mut self, value: L::Value) -> bool;
50}
51
52#[doc(hidden)]
53pub trait TruncateFrom<T> {
54    fn truncate_from(other: T) -> Self;
55}
56
57macro_rules! impl_truncate_from_usize {
58    ($($ty:ty),*) => {
59        $(
60            impl TruncateFrom<usize> for $ty {
61                #[inline(always)]
62                fn truncate_from(other: usize) -> Self {
63                    other.as_()
64                }
65            }
66        )*
67    };
68}
69impl_truncate_from_usize!(u32, u24, u16, u8);
70
71pub trait Optimizable {
72    /// Optimize memory usage. Should be run after batch inserts or before serialization.
73    fn optimize(&mut self);
74}
75
76pub trait Merge<Rhs = Self> {
77    /// Merges rhs into self
78    fn merge(&mut self, rhs: &Rhs);
79}
80
81pub trait Cut<Rhs = Self> {
82    type Out;
83
84    /// Returns the intersection between self and other while removing the
85    /// intersection from self
86    fn cut(&mut self, rhs: &Rhs) -> Self::Out;
87}