radix.rs 1.77 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
4
// SPDX-License-Identifier: Apache-2.0

use dashmap::DashMap;
5
use std::hash::Hash;
6

7
use crate::{PositionalHash, PositionalSequenceHash};
8
9
10

/// Positionally sparse radix tree for efficient indexing of [PositionalSequenceHashes][`crate::PositionalSequenceHash`].
#[derive(Clone)]
11
12
13
14
15
pub struct PositionalRadixTree<V, K = PositionalSequenceHash>
where
    K: PositionalHash + Hash + Eq + Clone,
{
    map: DashMap<u64, DashMap<K, V>>,
16
17
}

18
19
20
21
impl<V, K> PositionalRadixTree<V, K>
where
    K: PositionalHash + Hash + Eq + Clone,
{
22
23
24
25
26
27
28
    /// Creates a new empty [`PositionalRadixTree`].
    pub fn new() -> Self {
        Self {
            map: DashMap::new(),
        }
    }

29
30
31
    /// Provides the entry for the key at the given position.
    pub fn prefix(&self, key: &K) -> dashmap::mapref::one::RefMut<'_, u64, DashMap<K, V>> {
        let position = key.position();
32
33
34
        self.map.entry(position).or_default()
    }

35
    /// Provides the sub-map for all entries at the given position.
36
37
38
    pub fn position(
        &self,
        position: u64,
39
    ) -> Option<dashmap::mapref::one::RefMut<'_, u64, DashMap<K, V>>> {
40
41
42
        self.map.get_mut(&position)
    }

43
    /// Returns the number of entries in the [`PositionalRadixTree`].
44
45
46
47
48
49
50
    pub fn len(&self) -> usize {
        if self.map.is_empty() {
            return 0;
        }
        self.map.iter().map(|level| level.len()).sum()
    }

51
    /// Returns true if the [`PositionalRadixTree`] is empty.
52
53
54
55
56
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

57
58
59
60
impl<V, K> Default for PositionalRadixTree<V, K>
where
    K: PositionalHash + Hash + Eq + Clone,
{
61
62
63
64
65
66
    fn default() -> Self {
        Self {
            map: DashMap::new(),
        }
    }
}