1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#![allow(clippy::module_name_repetitions)]

use crate::{Node, SetTrie};

/// `EntryBuilder` for the [entry](SetTrie::entry) method. Entries are lazily evaluated, thus the builder
/// is used to provide the configuration, while the [entry](Entry) is already evaluated.
pub struct EntryBuilder<'a, K, T, IK>
where
    IK: Iterator<Item = K> + 'a,
    K: Ord,
{
    node: &'a mut Node<K, T>,
    keys: IK,
}

impl<'a, K, T, IK> EntryBuilder<'a, K, T, IK>
where
    IK: Iterator<Item = K> + 'a,
    K: Ord,
{
    pub(crate) fn new(trie: &'a mut SetTrie<K, T>, keys: IK) -> Self {
        EntryBuilder {
            node: &mut trie.0,
            keys,
        }
    }

    pub(crate) fn from_node(node: &'a mut Node<K, T>, keys: IK) -> Self {
        EntryBuilder { node, keys }
    }
}

/// A view into a node of a [`SetTrie`](SetTrie), either created or already existing.
pub enum Entry<'a, K, T>
where
    K: Ord,
{
    /// Indicates that the entry was created.
    Created(CreatedEntry<'a, K, T>),

    /// Indicates that the entry already existed.
    Existing(ExistingEntry<'a, K, T>),
}

/// Indicates that the entry was created.
pub struct CreatedEntry<'a, K, T>
where
    K: Ord,
{
    node: &'a mut Node<K, T>,
}

/// Indicates that the entry already exists.
pub struct ExistingEntry<'a, K, T>
where
    K: Ord,
{
    node: &'a mut Node<K, T>,
}

impl<'a, K, T, IK> EntryBuilder<'a, K, T, IK>
where
    IK: Iterator<Item = K> + 'a,
    K: Ord,
{
    /// Extends the entry, creating it if needed
    pub fn and_extend(self, default: impl IntoIterator<Item = T>) -> Entry<'a, K, T> {
        match self.or_create() {
            Entry::Existing(e) => {
                e.node.leaves.extend(default.into_iter());
                Entry::Existing(e)
            }
            Entry::Created(e) => {
                e.node.leaves.extend(default.into_iter());
                Entry::Created(e)
            }
        }
    }

    /// Inserts into the entry, creating it if needed
    pub fn and_insert(self, default: T) -> Entry<'a, K, T> {
        match self.or_create() {
            Entry::Existing(e) => {
                e.node.leaves.push(default);
                Entry::Existing(e)
            }
            Entry::Created(e) => {
                e.node.leaves.push(default);
                Entry::Created(e)
            }
        }
    }

    /// Finds the entry, and if it does not exist, extends with the provided value.
    pub fn or_extend(self, default: impl IntoIterator<Item = T>) -> Entry<'a, K, T> {
        match self.or_create() {
            entry @ Entry::Existing(_) => entry,
            Entry::Created(e) => {
                e.node.leaves.extend(default.into_iter());
                Entry::Created(e)
            }
        }
    }

    /// Finds the entry, and if it does not exist, inserts the value.
    pub fn or_insert(self, default: T) -> Entry<'a, K, T> {
        match self.or_create() {
            entry @ Entry::Existing(_) => entry,
            Entry::Created(e) => {
                e.node.leaves.push(default);
                Entry::Created(e)
            }
        }
    }

    /// Finds the entry, and if it does not exist, creates it.
    pub fn or_create(self) -> Entry<'a, K, T> {
        let mut node = self.node;
        let mut created = false;

        for key in self.keys {
            node = match node.children.binary_search_by(|(k, _)| k.cmp(&key)) {
                Ok(idx) => &mut (node.children[idx].1),
                Err(idx) => {
                    created = true;
                    node.children.insert(idx, (key, Node::new()));
                    &mut (node.children[idx].1)
                }
            }
        }

        if created {
            return Entry::Created(CreatedEntry { node });
        }
        Entry::Existing(ExistingEntry { node })
    }

    /// Finds the entry, but does not create one. This method short circuits on the first missing
    /// key.
    pub fn find(self) -> Option<ExistingEntry<'a, K, T>> {
        let mut node = self.node;

        for key in self.keys {
            node = match node.children.binary_search_by(|(k, _)| k.cmp(&key)) {
                Ok(idx) => &mut (node.children[idx].1),
                Err(_) => return None,
            }
        }
        Some(ExistingEntry { node })
    }

    /// Returns all associated items of an entry.
    pub fn items(self) -> Option<&'a Vec<T>> {
        self.find().map(|node| &node.node.leaves)
    }

    /// Mutably returns all associated items of an entry.
    pub fn items_mut(self) -> Option<&'a mut Vec<T>> {
        self.find().map(|node| &mut node.node.leaves)
    }
}

impl<'a, K, T> Entry<'a, K, T>
where
    K: Ord,
{
    fn node(&self) -> &Node<K, T> {
        match self {
            Entry::Existing(e) => e.node,
            Entry::Created(e) => e.node,
        }
    }

    fn node_mut(&mut self) -> &mut Node<K, T> {
        match self {
            Entry::Existing(e) => e.node,
            Entry::Created(e) => e.node,
        }
    }

    /// Returns all associated items of an entry.
    #[must_use]
    pub fn items(&self) -> &Vec<T> {
        &self.node().leaves
    }

    /// Mutably returns all associated items of an entry.
    #[must_use]
    pub fn items_mut(&mut self) -> &mut Vec<T> {
        &mut self.node_mut().leaves
    }

    /// Provides a view into a child of the entry. If you are sequentially inserting longer keys,
    /// reusing the entry is more efficient than starting from the root.
    ///
    /// ```rust
    /// // Equivalent to first inserting 0..1, then 0..2 etc.
    ///
    /// let mut trie = set_trie::SetTrie::new();
    /// let mut current = trie.entry(0..1).or_insert(0);
    ///     for i in 1..5000 {
    ///         current = {
    ///             current.entry(i-1..i).or_insert(i)
    ///         }
    ///     }
    /// ```
    #[must_use]
    pub fn entry<IK: IntoIterator<Item = K>>(
        self,
        keys: IK,
    ) -> EntryBuilder<'a, K, T, IK::IntoIter> {
        match self {
            Entry::Created(e) => EntryBuilder::from_node(e.node, keys.into_iter()),
            Entry::Existing(e) => EntryBuilder::from_node(e.node, keys.into_iter()),
        }
    }
}