libdictenstein 0.1.0

High-performance dictionary data structures (trie, DAWG, double-array trie, suffix automaton, lock-free durable persistent ART) behind one trait API; pairs with liblevenshtein for fuzzy matching
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Node48: ART node for 17-48 children with index array lookup.
//!
//! Uses a 256-byte index array to map key bytes to child positions.
//! This provides O(1) lookup while still being more space-efficient than Node256.
//!
//! # Layout
//!
//! ```text
//! ┌───────────────────────────────────────────────────────────┐
//! │ NodeHeader (16 bytes)                                     │
//! ├───────────────────────────────────────────────────────────┤
//! │ CompressedPrefix (12 bytes)                               │
//! ├───────────────────────────────────────────────────────────┤
//! │ index: [u8; 256]  │ Maps key byte -> child slot (or 255) │
//! ├───────────────────────────────────────────────────────────┤
//! │ children: [SwizzledPtr; 48] │ Child pointers (384 bytes)  │
//! └───────────────────────────────────────────────────────────┘
//! Total: ~668 bytes
//! ```
//!
//! # Index Array
//!
//! - `index[key] == 255` means the key is not present
//! - `index[key] < 48` means the child is at `children[index[key]]`
//!
//! This provides O(1) lookup with a single array access plus bounds check.

use super::{AddChildError, ArtNode, CompressedPrefix, NodeHeader};
use crate::persistent_artrie::swizzled_ptr::SwizzledPtr;

/// Maximum number of children in a Node48
pub const NODE48_MAX_CHILDREN: usize = 48;

/// Sentinel value indicating no child at this key
pub const NO_CHILD: u8 = 255;

/// ART node with 17-48 children
///
/// Uses a 256-byte index array for O(1) key lookup.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct Node48 {
    /// Common node header
    pub header: NodeHeader,
    /// Compressed prefix for path compression
    pub prefix: CompressedPrefix,
    /// Index array: maps key byte to child slot (255 = no child)
    pub index: [u8; 256],
    /// Child pointers (only first num_children are valid)
    pub children: [SwizzledPtr; NODE48_MAX_CHILDREN],
}

impl Node48 {
    /// Create a new empty Node48
    pub fn new() -> Self {
        Self {
            header: NodeHeader::new(48),
            prefix: CompressedPrefix::empty(),
            index: [NO_CHILD; 256],
            children: std::array::from_fn(|_| SwizzledPtr::null()),
        }
    }

    /// Create a Node48 with a prefix
    pub fn with_prefix(prefix: &[u8]) -> Self {
        let mut node = Self::new();
        node.prefix = CompressedPrefix::from_bytes(prefix);
        node.header.prefix_len = prefix.len() as u8;
        node
    }

    /// Find the first free slot in the children array
    fn find_free_slot(&self) -> Option<usize> {
        let count = self.header.num_children as usize;
        if count < NODE48_MAX_CHILDREN {
            Some(count)
        } else {
            None
        }
    }
}

impl Default for Node48 {
    fn default() -> Self {
        Self::new()
    }
}

impl ArtNode for Node48 {
    fn find_child(&self, key: u8) -> Option<&SwizzledPtr> {
        let slot = self.index[key as usize];
        if slot == NO_CHILD {
            None
        } else {
            Some(&self.children[slot as usize])
        }
    }

    fn find_child_mut(&mut self, key: u8) -> Option<&mut SwizzledPtr> {
        let slot = self.index[key as usize];
        if slot == NO_CHILD {
            None
        } else {
            Some(&mut self.children[slot as usize])
        }
    }

    fn add_child(&mut self, key: u8, child: SwizzledPtr) -> Result<(), AddChildError> {
        // Check for duplicate
        if self.index[key as usize] != NO_CHILD {
            return Err(AddChildError::KeyExists);
        }

        // Find a free slot
        let slot = self.find_free_slot().ok_or(AddChildError::NodeFull)?;

        // Add the child
        self.index[key as usize] = slot as u8;
        self.children[slot] = child;
        self.header.num_children += 1;

        Ok(())
    }

    fn remove_child(&mut self, key: u8) -> Option<SwizzledPtr> {
        let slot = self.index[key as usize];
        if slot == NO_CHILD {
            return None;
        }

        let removed = self.children[slot as usize].clone();
        self.index[key as usize] = NO_CHILD;

        // Move the last child to fill the gap (if not already the last)
        let last = self.header.num_children as usize - 1;
        if (slot as usize) != last {
            // Find the key that points to the last slot
            for i in 0..256 {
                if self.index[i] == last as u8 {
                    self.index[i] = slot;
                    break;
                }
            }
            self.children[slot as usize] = self.children[last].clone();
        }

        self.children[last] = SwizzledPtr::null();
        self.header.num_children -= 1;

        Some(removed)
    }

    fn is_full(&self) -> bool {
        self.header.num_children as usize >= NODE48_MAX_CHILDREN
    }

    fn iter_children(&self) -> impl Iterator<Item = (u8, &SwizzledPtr)> {
        self.index.iter().enumerate().filter_map(|(key, &slot)| {
            if slot != NO_CHILD {
                Some((key as u8, &self.children[slot as usize]))
            } else {
                None
            }
        })
    }
}

impl Node48 {
    /// Shrink this node to a Node16
    pub fn shrink(&self) -> super::Node16 {
        debug_assert!(
            self.header.num_children <= 16,
            "cannot shrink Node48 with {} children",
            self.header.num_children
        );

        let mut node16 = super::Node16::new();
        node16.header = self.header.clone();
        node16.header.node_type = 16;
        node16.prefix = self.prefix;

        // Collect keys in sorted order
        let mut idx = 0;
        for key in 0..=255u8 {
            let slot = self.index[key as usize];
            if slot != NO_CHILD {
                node16.keys[idx] = key;
                node16.children[idx] = self.children[slot as usize].clone();
                idx += 1;
            }
        }

        node16
    }

    /// Grow this node to a Node256
    pub fn grow(&self) -> super::Node256 {
        let mut node256 = super::Node256::new();
        node256.header = self.header.clone();
        node256.header.node_type = 0; // Node256 uses 0
        node256.prefix = self.prefix;

        // Copy children to direct array
        for key in 0..=255u8 {
            let slot = self.index[key as usize];
            if slot != NO_CHILD {
                node256.children[key as usize] = self.children[slot as usize].clone();
            }
        }

        node256
    }

    // =========================================================================
    // Atomic Child Access for Lock-Free Operations
    // =========================================================================

    /// Get a child pointer by key with atomic read.
    ///
    /// This returns a clone of the SwizzledPtr, loading the value atomically.
    /// O(1) lookup via index array.
    pub fn get_child_atomic(&self, key: u8) -> Option<SwizzledPtr> {
        let slot = self.index[key as usize];
        if slot == NO_CHILD {
            None
        } else {
            Some(self.children[slot as usize].clone())
        }
    }

    /// Get a reference to the child slot for CAS operations.
    #[inline]
    pub fn child_slot(&self, index: usize) -> &SwizzledPtr {
        debug_assert!(index < NODE48_MAX_CHILDREN, "index {} out of bounds", index);
        &self.children[index]
    }

    /// Get the child slot index for a key.
    ///
    /// Returns `Ok(slot_index)` if the key exists, `Err(next_slot)` otherwise.
    pub fn find_slot_for_key(&self, key: u8) -> Result<usize, usize> {
        let slot = self.index[key as usize];
        if slot != NO_CHILD {
            Ok(slot as usize)
        } else {
            // Return the next available slot
            Err(self.header.num_children as usize)
        }
    }

    /// Get the next available child slot index.
    pub fn next_slot(&self) -> Option<usize> {
        let count = self.header.num_children as usize;
        if count < NODE48_MAX_CHILDREN {
            Some(count)
        } else {
            None
        }
    }

    /// Get the slot index for a key (raw access to index array).
    ///
    /// Returns NO_CHILD (255) if the key has no child.
    #[inline]
    pub fn slot_for_key(&self, key: u8) -> u8 {
        self.index[key as usize]
    }

    /// Get an iterator over (key, slot_index, &SwizzledPtr) triples.
    ///
    /// This iterates over all keys (0-255) and yields only those with children.
    pub fn iter_indexed(&self) -> impl Iterator<Item = (u8, usize, &SwizzledPtr)> + '_ {
        (0..=255u8).filter_map(move |key| {
            let slot = self.index[key as usize];
            if slot != NO_CHILD {
                Some((key, slot as usize, &self.children[slot as usize]))
            } else {
                None
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_node48() {
        let node = Node48::new();
        assert_eq!(node.header.node_type, 48);
        assert_eq!(node.header.num_children, 0);
        assert!(!node.is_full());
    }

    #[test]
    fn test_add_and_find_children() {
        let mut node = Node48::new();

        // Add children with various keys
        for key in [0, 50, 100, 150, 200, 255u8] {
            let child =
                SwizzledPtr::on_disk(key as u32, 0, crate::persistent_artrie::NodeType::Node4);
            assert!(node.add_child(key, child).is_ok());
        }

        assert_eq!(node.header.num_children, 6);

        // Find all children
        for key in [0, 50, 100, 150, 200, 255u8] {
            assert!(node.find_child(key).is_some(), "should find key {}", key);
        }

        // Should not find non-existent keys
        assert!(node.find_child(1).is_none());
        assert!(node.find_child(51).is_none());
    }

    #[test]
    fn test_node48_full() {
        let mut node = Node48::new();

        for i in 0..48 {
            let child =
                SwizzledPtr::on_disk(i as u32, 0, crate::persistent_artrie::NodeType::Node4);
            assert!(node.add_child(i as u8, child).is_ok());
        }

        assert!(node.is_full());

        let child = SwizzledPtr::on_disk(48, 0, crate::persistent_artrie::NodeType::Node4);
        assert_eq!(node.add_child(48, child), Err(AddChildError::NodeFull));
    }

    #[test]
    fn test_remove_child() {
        let mut node = Node48::new();

        for i in 0..20 {
            let child =
                SwizzledPtr::on_disk(i as u32, 0, crate::persistent_artrie::NodeType::Node4);
            node.add_child(i as u8, child).expect("add should succeed");
        }

        // Remove middle element
        let removed = node.remove_child(10);
        assert!(removed.is_some());
        assert_eq!(node.header.num_children, 19);
        assert!(node.find_child(10).is_none());

        // Other children should still be present
        for i in 0..20 {
            if i != 10 {
                assert!(node.find_child(i).is_some(), "should find key {}", i);
            }
        }
    }

    #[test]
    fn test_iter_children() {
        let mut node = Node48::new();

        let keys = [5, 10, 15, 20, 25u8];
        for &key in &keys {
            let child =
                SwizzledPtr::on_disk(key as u32, 0, crate::persistent_artrie::NodeType::Node4);
            node.add_child(key, child).expect("add should succeed");
        }

        let found_keys: Vec<_> = node.iter_children().map(|(k, _)| k).collect();
        assert_eq!(found_keys, keys.to_vec()); // iter_children returns sorted
    }

    #[test]
    fn test_shrink_to_node16() {
        let mut node = Node48::new();

        for i in 0..16 {
            let child =
                SwizzledPtr::on_disk(i as u32, 0, crate::persistent_artrie::NodeType::Node4);
            node.add_child(i as u8, child).expect("add should succeed");
        }

        let node16 = node.shrink();
        assert_eq!(node16.header.node_type, 16);
        assert_eq!(node16.header.num_children, 16);

        // Verify children transferred
        for i in 0..16 {
            assert!(node16.find_child(i as u8).is_some());
        }
    }

    #[test]
    fn test_duplicate_key() {
        let mut node = Node48::new();

        let child = SwizzledPtr::on_disk(1, 0, crate::persistent_artrie::NodeType::Node4);
        assert!(node.add_child(42, child).is_ok());

        let child = SwizzledPtr::on_disk(2, 0, crate::persistent_artrie::NodeType::Node4);
        assert_eq!(node.add_child(42, child), Err(AddChildError::KeyExists));
    }
}