keyspace/
interval.rs

1use super::{KeyPosition, KeyspaceNode, NodeRef};
2
3/// A range of keys in the keyspace.
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum KeyRange {
6    Bounded(KeyPosition, KeyPosition),
7    Unbounded(KeyPosition),
8}
9
10impl KeyRange {
11    /// Create a new key range from the given start and end positions.
12    pub fn new(start: KeyPosition, end: Option<KeyPosition>) -> Self {
13        match end {
14            Some(end) => KeyRange::Bounded(start, end),
15            None => KeyRange::Unbounded(start),
16        }
17    }
18
19    /// Check if the given key is in the range.
20    ///
21    /// Note not the key itself, but the hash of the key provides the position
22    /// within keyspace.
23    pub fn contains(&self, key_hash: KeyPosition) -> bool {
24        match self {
25            KeyRange::Bounded(start, end) => key_hash >= *start && key_hash < *end,
26            KeyRange::Unbounded(start) => key_hash >= *start,
27        }
28    }
29}
30
31/// A half-open interval of the keyspace with responsible nodes assigned.
32///
33/// Range bounded inclusively below and exclusively above i.e.
34/// `[start..end)`.
35#[derive(Debug, PartialEq, Eq)]
36pub struct Interval<N: KeyspaceNode> {
37    key_range: KeyRange,
38    nodes: Vec<NodeRef<N>>,
39}
40
41impl<N: KeyspaceNode> Clone for Interval<N> {
42    fn clone(&self) -> Self {
43        Self {
44            key_range: self.key_range,
45            nodes: self.nodes.clone(),
46        }
47    }
48}
49
50impl<N: KeyspaceNode> Interval<N> {
51    /// Creates a new interval with the given key range and nodes.
52    pub(crate) fn new<I: IntoIterator<Item = NodeRef<N>>>(key_range: KeyRange, nodes: I) -> Self {
53        let nodes = nodes.into_iter().collect::<Vec<_>>();
54        Self { key_range, nodes }
55    }
56
57    /// Returns the key range of the interval.
58    pub fn key_range(&self) -> &KeyRange {
59        &self.key_range
60    }
61
62    /// Returns the nodes responsible for the interval.
63    pub fn nodes(&self) -> &Vec<NodeRef<N>> {
64        &self.nodes
65    }
66}