Skip to main content

rax/
lib.rs

1#![cfg_attr(test, feature(test))]
2
3///  Representation of a radix tree as implemented in this file, that contains
4///  the strings "foo", "foobar" and "footer" after the insertion of each
5///  word. When the node represents a key inside the radix tree, we write it
6///  between [], otherwise it is written between ().
7///
8///  This is the vanilla representation:
9///
10/// ```text
11///               (f) ""
12///                 \
13///                 (o) "f"
14///                   \
15///                   (o) "fo"
16///                     \
17///                   [t   b] "foo"
18///                   /     \
19///          "foot" (e)     (a) "foob"
20///                 /         \
21///       "foote" (r)         (r) "fooba"
22///               /             \
23///     "footer" []             [] "foobar"
24/// ```
25///
26///  However, this implementation implements a very common optimization where
27///  successive nodes having a single child are "compressed" into the node
28///  itself as a string of characters, each representing a next-level child,
29///  and only the link to the node representing the last character node is
30///  provided inside the representation. So the above representation is turned
31///  into:
32///
33/// ```text
34///                   ["foo"] ""
35///                      |
36///                   [t   b] "foo"
37///                   /     \
38///         "foot" ("er")    ("ar") "foob"
39///                  /          \
40///        "footer" []          [] "foobar"
41/// ```
42///
43///  However this optimization makes the implementation a bit more complex.
44///  For instance if a key "first" is added in the above radix tree, a
45///  "node splitting" operation is needed, since the "foo" prefix is no longer
46///  composed of nodes having a single child one after the other. This is the
47///  above tree and the resulting node splitting after this event happens:
48///
49///
50/// ```text
51///                     (f) ""
52///                     /
53///                  (i o) "f"
54///                  /   \
55///     "firs"  ("rst")  (o) "fo"
56///               /        \
57///     "first" []       [t   b] "foo"
58///                      /     \
59///            "foot" ("er")    ("ar") "foob"
60///                     /          \
61///           "footer" []          [] "foobar"
62/// ```
63///
64///  Similarly after deletion, if a new chain of nodes having a single child
65///  is created (the chain must also not include nodes that represent keys),
66///  it must be compressed back into a single node.
67extern crate libc;
68extern crate nix;
69
70use std::{
71    error, fmt,
72    mem::{size_of, MaybeUninit},
73    ptr,
74};
75
76use nix::errno::Errno;
77
78pub const GREATER: &str = ">";
79pub const GREATER_EQUAL: &str = ">=";
80pub const LESSER: &str = "<";
81pub const LESSER_EQUAL: &str = "<=";
82pub const EQUAL: &str = "=";
83pub const BEGIN: &str = "^";
84pub const END: &str = "$";
85
86pub const RAX_NODE_MAX_SIZE: libc::c_int = (1 << 29) - 1;
87pub const RAX_STACK_STATIC_ITEMS: libc::c_int = 32;
88pub const RAX_ITER_STATIC_LEN: libc::c_int = 128;
89pub const RAX_ITER_JUST_SEEKED: libc::c_int = 1 << 0;
90pub const RAX_ITER_EOF: libc::c_int = 1 << 1;
91pub const RAX_ITER_SAFE: libc::c_int = 1 << 2;
92
93/// Return the existing Rax allocator.
94///
95/// # Safety
96///
97/// Must only be called when no other thread is modifying the allocator.
98pub unsafe fn allocator() -> (
99    extern "C" fn(size: libc::size_t) -> *mut u8,
100    extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8,
101    extern "C" fn(ptr: *mut libc::c_void),
102) {
103    (rax_malloc, rax_realloc, rax_free)
104}
105
106/// Rax internally makes calls to "malloc", "realloc" and "free" for all of it's
107/// heap memory needs. These calls can be patched with the supplied hooks.
108/// Do not call this method after Rax has been used at all. This must
109/// be called before using or calling any other Rax API function.
110///
111/// # Safety
112///
113/// Must be called before any Rax allocation occurs. Not thread-safe.
114pub unsafe fn set_allocator(
115    malloc: extern "C" fn(size: libc::size_t) -> *mut u8,
116    realloc: extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8,
117    free: extern "C" fn(ptr: *mut libc::c_void),
118) {
119    rax_malloc = malloc;
120    rax_realloc = realloc;
121    rax_free = free;
122}
123
124#[derive(Debug)]
125pub enum RaxError {
126    Generic(GenericError),
127    OutOfMemory(),
128}
129
130impl RaxError {
131    pub fn generic(message: &str) -> RaxError {
132        RaxError::Generic(GenericError::new(message))
133    }
134}
135
136/// Redis has a beautiful Radix Tree implementation in ANSI C.
137/// This brings it to Rust and creates a safe Map like wrapper
138/// for it. This is very similar in utility to a BTreeMap, but
139/// RAX is likely much faster and more efficient. Naive testing
140/// showed a 2x-4x improvement for all common operations. The only
141/// disadvantage to BTreeMap is that BTree's allow much more flexibility
142/// in regards to comparing keys. Radix trees are lexicographically only.
143/// Composite keys where the non-last member is variable length could
144/// be something BTrees could handle much easier.
145///
146/// Internal RAX Node Layout
147///
148/// uint32_t iskey:1;     /* Does this node contain a key? */
149/// uint32_t isnull:1;    /* Associated value is NULL (don't store it). */
150/// uint32_t iscompr:1;   /* Node is compressed. */
151/// uint32_t size:29;     /* Number of children, or compressed string len. */
152///
153/// +----+---+--------+--------+--------+--------+
154/// |HDR |xyz| x-ptr  | y-ptr  | z-ptr  |dataptr |
155/// +----+---+--------+--------+--------+--------+
156///
157/// As is evident above, there is no storage penalty for NULL values.
158///
159/// Keys are represented in compressed form therefore, there is no
160/// need to pump in Boxed keys or any sort of heap allocated chunk of
161/// memory. Stack or heap keys may be used from rust. Values can either
162/// be a sizeof<usize> size integer or it's a data pointer to a heap
163/// allocated / Boxed value.
164///
165/// Iterators were designed to be fast and attempt to only use stack
166/// allocated memory. RaxMap provides a model to take full advantage
167/// of stack allocated iterators through wrapping in a closure.
168///
169/// #Examples
170///
171/// ```
172/// use rax::RaxMap;
173/// let mut r = RaxMap::new();
174/// r.insert(1, Box::new("my heap allocation".to_string()));
175/// r.insert(2, Box::new("my other heap allocation".to_string()));
176///
177/// r.iter(|r, iter| {
178///     // Place iterator at the first entry.
179///     if !iter.seek_min() {
180///         // EOF
181///         return;
182///     }
183///
184///     // Can test EOF at any time.
185///     if iter.eof() {
186///         // EOF
187///         return;
188///     }
189///
190///     while iter.forward() {
191///         iter.key();
192///         iter.value();
193///     }
194///     // In reverse
195///     // Place iterator at the end.
196///     if !iter.seek_max() {
197///         // EOF
198///         return;
199///     }
200///     while iter.back() {
201///         iter.key();
202///         iter.value();
203///     }
204///
205///     // Seek
206///     if !iter.seek(">=", 2) {
207///         // EOF
208///     }
209///     while iter.forward() {
210///         iter.key();
211///         iter.value();
212///     }
213/// });
214/// ```
215pub struct RaxMap<K: RaxKey, V> {
216    pub rax: *mut rax,
217    phantom: std::marker::PhantomData<(K, V)>,
218}
219
220impl<K: RaxKey, V> Drop for RaxMap<K, V> {
221    fn drop(&mut self) {
222        // SAFETY: self.rax is non-null (guaranteed by try_new/new).
223        // raxFreeWithCallback frees all nodes and invokes the callback
224        // on each stored value pointer so we can drop the Box<V>.
225        unsafe {
226            raxFreeWithCallback(self.rax, RaxFreeWithCallbackWrapper::<V>);
227        }
228    }
229}
230
231// SAFETY: RaxMap owns a unique heap allocation. No shared mutable
232// state, therefore safe to transfer between threads.
233unsafe impl<K: RaxKey + Send, V: Send> Send for RaxMap<K, V> {}
234
235// SAFETY: &RaxMap only allows read-only access (find/get) which don't
236// mutate the underlying C tree, therefore safe to share across threads.
237unsafe impl<K: RaxKey + Sync, V: Sync> Sync for RaxMap<K, V> {}
238
239impl<K: RaxKey, V> Default for RaxMap<K, V> {
240    fn default() -> Self {
241        Self::new()
242    }
243}
244
245/// Implementation of RaxMap
246impl<K: RaxKey, V> RaxMap<K, V> {
247    /// Create a new RaxMap.
248    ///
249    /// # Panics
250    ///
251    /// Panics if `raxNew()` returns NULL (out of memory).
252    pub fn new() -> RaxMap<K, V> {
253        Self::try_new().expect("raxNew: out of memory")
254    }
255
256    /// Fallible constructor.
257    ///
258    /// Returns `Err(OutOfMemory)` when `raxNew()` returns NULL.
259    pub fn try_new() -> Result<RaxMap<K, V>, RaxError> {
260        // SAFETY: raxNew() allocates a new rax tree.
261        // We check for NULL before storing the pointer.
262        let ptr = unsafe { raxNew() };
263
264        if ptr.is_null() {
265            return Err(RaxError::OutOfMemory());
266        }
267
268        Ok(RaxMap {
269            rax: ptr,
270            phantom: std::marker::PhantomData,
271        })
272    }
273
274    /// The number of entries in the RAX
275    pub fn len(&self) -> u64 {
276        unsafe { raxSize(self.rax) }
277    }
278
279    /// The number of entries in the RAX
280    pub fn size(&self) -> u64 {
281        unsafe { raxSize(self.rax) }
282    }
283
284    /// Returns true if the RAX is empty.
285    pub fn is_empty(&self) -> bool {
286        self.len() == 0
287    }
288
289    /// Prints the Rax as ASCII art to stdout.
290    pub fn show(&self) {
291        unsafe { raxShow(self.rax) }
292    }
293
294    /// Insert or replace existing key with a NULL value.
295    pub fn insert_null(&mut self, key: K) -> Result<Option<Box<V>>, RaxError> {
296        unsafe {
297            // Allocate a pointer to catch the old value.
298            let old: &mut *mut u8 = &mut ptr::null_mut();
299
300            // Integer values require Big Endian to allow the Rax to fully optimize
301            // storing them since it will be able to compress the prefixes especially
302            // for 64/128bit numbers.
303            let k = key.encode();
304            let (ptr, len) = k.to_buf();
305
306            let r = raxInsert(
307                self.rax,
308                // Grab a raw pointer to the key. Keys are most likely allocated
309                // on the stack. The rax will keep it's own copy of the key so we
310                // don't want to keep in in the heap twice and it exists in the
311                // rax in it's compressed form.
312                ptr,
313                len,
314                std::ptr::null_mut(),
315                old,
316            );
317
318            if r == 0 && Errno::last() == Errno::ENOMEM {
319                Err(RaxError::OutOfMemory())
320            } else if old.is_null() {
321                Ok(None)
322            } else {
323                // Box the previous value since Rax is done with it and it's our
324                // responsibility now to drop it. Once this Box goes out of scope
325                // the value is dropped and memory reclaimed.
326                Ok(Some(Box::from_raw(*old as *mut V)))
327            }
328        }
329    }
330
331    /// Insert a new entry into the RAX if an existing one does not exist.
332    pub fn try_insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
333        unsafe {
334            // Allocate a pointer to catch the old value.
335            let old: &mut *mut u8 = &mut ptr::null_mut();
336
337            // Leak the boxed value as we hand it over to Rax to keep track of.
338            // These must be heap allocated unless we want to store sizeof(usize) or
339            // less bytes, then the value can be the pointer.
340            let value: &mut V = Box::leak(data);
341
342            // Integer values require Big Endian to allow the Rax to fully optimize
343            // storing them since it will be able to compress the prefixes especially
344            // for 64/128bit numbers.
345            let k = key.encode();
346            let (ptr, len) = k.to_buf();
347
348            let r = raxTryInsert(
349                self.rax,
350                // Grab a raw pointer to the key. Keys are most likely allocated
351                // on the stack. The rax will keep it's own copy of the key so we
352                // don't want to keep in in the heap twice and it exists in the
353                // rax in it's compressed form.
354                ptr,
355                len,
356                value as *mut V as *mut u8,
357                old,
358            );
359
360            if r == 0 {
361                if Errno::last() == Errno::ENOMEM {
362                    Err(RaxError::OutOfMemory())
363                } else {
364                    Ok(Some(Box::from_raw(value as *mut V)))
365                }
366            } else if old.is_null() {
367                Ok(None)
368            } else {
369                // This shouldn't happen, but if it does let's be safe and
370                // not leak memory.
371                Ok(Some(Box::from_raw(*old as *mut V)))
372            }
373        }
374    }
375
376    /// Try to insert a raw pointer value into the RAX.
377    ///
378    /// # Safety
379    ///
380    /// `value` must be a valid pointer or null.
381    pub unsafe fn try_insert_ptr(
382        &mut self,
383        key: K,
384        value: *mut u8,
385    ) -> Result<Option<*mut u8>, RaxError> {
386        // Allocate a pointer to catch the old value.
387        let old: &mut *mut u8 = &mut ptr::null_mut();
388
389        // Integer values require Big Endian to allow the Rax to fully optimize
390        // storing them since it will be able to compress the prefixes especially
391        // for 64/128bit numbers.
392        let k = key.encode();
393        let (ptr, len) = k.to_buf();
394
395        let r = raxTryInsert(
396            self.rax,
397            // Grab a raw pointer to the key. Keys are most likely allocated
398            // on the stack. The rax will keep it's own copy of the key so we
399            // don't want to keep in in the heap twice and it exists in the
400            // rax in it's compressed form.
401            ptr, len, value, old,
402        );
403
404        if r == 0 {
405            if Errno::last() == Errno::ENOMEM {
406                Err(RaxError::OutOfMemory())
407            } else {
408                Ok(Some(value))
409            }
410        } else if old.is_null() {
411            Ok(None)
412        } else {
413            // This shouldn't happen, but if it does let's be safe and
414            // not leak memory.
415            Ok(Some(*old))
416        }
417    }
418
419    /// Insert a new entry into the RAX replacing and returning the existing
420    /// entry for the supplied key.
421    pub fn insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
422        unsafe {
423            // Allocate a pointer to catch the old value.
424            let old: &mut *mut u8 = &mut ptr::null_mut();
425
426            // Leak the boxed value as we hand it over to Rax to keep track of.
427            // These must be heap allocated unless we want to store sizeof(usize) or
428            // less bytes, then the value can be the pointer.
429            let value: &mut V = Box::leak(data);
430
431            // Integer values require Big Endian to allow the Rax to fully optimize
432            // storing them since it will be able to compress the prefixes especially
433            // for 64/128bit numbers.
434            let k = key.encode();
435            let (ptr, len) = k.to_buf();
436
437            let r = raxInsert(
438                self.rax,
439                // Grab a raw pointer to the key. Keys are most likely allocated
440                // on the stack. The rax will keep it's own copy of the key so we
441                // don't want to keep in in the heap twice and it exists in the
442                // rax in it's compressed form.
443                ptr,
444                len,
445                value as *mut V as *mut u8,
446                old,
447            );
448
449            if r == 0 && Errno::last() == Errno::ENOMEM {
450                Err(RaxError::OutOfMemory())
451            } else if old.is_null() {
452                Ok(None)
453            } else {
454                // Box the previous value since Rax is done with it and it's our
455                // responsibility now to drop it. Once this Box goes out of scope
456                // the value is dropped and memory reclaimed.
457                Ok(Some(Box::from_raw(*old as *mut V)))
458            }
459        }
460    }
461
462    /// Insert a raw pointer value into the RAX.
463    ///
464    /// # Safety
465    ///
466    /// `value` must be a valid pointer or null.
467    pub unsafe fn insert_ptr(
468        &mut self,
469        key: K,
470        value: *mut u8,
471    ) -> Result<Option<*mut u8>, RaxError> {
472        // Allocate a pointer to catch the old value.
473        let old: &mut *mut u8 = &mut ptr::null_mut();
474
475        // Integer values require Big Endian to allow the Rax to fully optimize
476        // storing them since it will be able to compress the prefixes especially
477        // for 64/128bit numbers.
478        let k = key.encode();
479        let (ptr, len) = k.to_buf();
480
481        let r = raxInsert(
482            self.rax,
483            // Grab a raw pointer to the key. Keys are most likely allocated
484            // on the stack. The rax will keep it's own copy of the key so we
485            // don't want to keep in in the heap twice and it exists in the
486            // rax in it's compressed form.
487            ptr, len, value, old,
488        );
489
490        if r == 0 && Errno::last() == Errno::ENOMEM {
491            Err(RaxError::OutOfMemory())
492        } else if old.is_null() {
493            Ok(None)
494        } else {
495            // Box the previous value since Rax is done with it and it's our
496            // responsibility now to drop it. Once this Box goes out of scope
497            // the value is dropped and memory reclaimed.
498            Ok(Some(*old))
499        }
500    }
501
502    /// Remove an entry from the RAX and return the associated value.
503    pub fn remove(&mut self, key: K) -> (bool, Option<Box<V>>) {
504        unsafe {
505            let old: &mut *mut u8 = &mut ptr::null_mut();
506            let k = key.encode();
507            let (ptr, len) = k.to_buf();
508
509            let r = raxRemove(self.rax, ptr, len, old);
510
511            if old.is_null() {
512                (r == 1, None)
513            } else {
514                (r == 1, Some(Box::from_raw(*old as *mut V)))
515            }
516        }
517    }
518
519    /// Find a key and return whether it exists along with its value.
520    pub fn find_exists(&self, key: K) -> (bool, Option<&V>) {
521        unsafe {
522            let k = key.encode();
523            let (ptr, len) = k.to_buf();
524
525            let value = raxFind(self.rax, ptr, len);
526
527            if value.is_null() {
528                (true, None)
529            } else if value == raxNotFound {
530                (false, None)
531            } else {
532                // transmute to the value so we don't drop the actual value accidentally.
533                // While the key associated to the value is in the RAX then we cannot
534                // drop it.
535                (true, Some(&*(value as *const V)))
536            }
537        }
538    }
539
540    /// Same as get but added for semantics parity.
541    pub fn find(&self, key: K) -> Option<&V> {
542        unsafe {
543            let k = key.encode();
544            let (ptr, len) = k.to_buf();
545
546            let value = raxFind(self.rax, ptr, len);
547
548            if value.is_null() || value == raxNotFound {
549                None
550            } else {
551                // transmute to the value so we don't drop the actual value accidentally.
552                // While the key associated to the value is in the RAX then we cannot
553                // drop it.
554                Some(&*(value as *const V))
555            }
556        }
557    }
558
559    /// Get the value associated with the key.
560    pub fn get(&self, key: K) -> Option<&V> {
561        unsafe {
562            let k = key.encode();
563            let (ptr, len) = k.to_buf();
564
565            let value = raxFind(self.rax, ptr, len);
566
567            if value.is_null() || value == raxNotFound {
568                None
569            } else {
570                // transmute to the value so we don't drop the actual value accidentally.
571                // While the key associated to the value is in the RAX then we cannot
572                // drop it.
573                Some(&*(value as *const V))
574            }
575        }
576    }
577
578    /// Determines if the supplied key exists in the Rax.
579    pub fn exists(&self, key: K) -> bool {
580        unsafe {
581            let k = key.encode();
582            let (ptr, len) = k.to_buf();
583
584            let value = raxFind(self.rax, ptr, len);
585
586            !(value.is_null() || value == raxNotFound)
587        }
588    }
589
590    /// Seek to the minimum key and execute the closure.
591    ///
592    /// # Safety
593    ///
594    /// Mutating the map inside the closure is undefined behaviour.
595    pub fn seek_min<F>(&mut self, f: F)
596    where
597        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
598    {
599        // SAFETY: Iterator is initialized with raxStart before use.
600        unsafe {
601            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
602            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
603            let mut iter = iter.assume_init();
604            iter.fixup();
605            iter.seek_min();
606            f(self, &mut iter)
607        }
608    }
609
610    /// Seek to the minimum key and execute the closure, returning a result.
611    ///
612    /// # Safety
613    ///
614    /// Mutating the map inside the closure is undefined behaviour.
615    pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
616    where
617        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
618    {
619        // SAFETY: Iterator is initialized with raxStart before use.
620        unsafe {
621            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
622            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
623            let mut iter = iter.assume_init();
624            iter.fixup();
625            iter.seek_min();
626            f(self, &mut iter)
627        }
628    }
629
630    /// Seek to the maximum key and execute the closure.
631    ///
632    /// # Safety
633    ///
634    /// Mutating the map inside the closure is undefined behaviour.
635    pub fn seek_max<F>(&mut self, f: F)
636    where
637        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
638    {
639        // SAFETY: Iterator is initialized with raxStart before use.
640        unsafe {
641            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
642            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
643            let mut iter = iter.assume_init();
644            iter.fixup();
645            iter.seek_max();
646            f(self, &mut iter)
647        }
648    }
649
650    /// Seek to the maximum key and execute the closure, returning a result.
651    ///
652    /// # Safety
653    ///
654    /// Mutating the map inside the closure is undefined behaviour.
655    pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
656    where
657        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
658    {
659        // SAFETY: Iterator is initialized with raxStart before use.
660        unsafe {
661            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
662            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
663            let mut iter = iter.assume_init();
664            iter.fixup();
665            iter.seek_max();
666            f(self, &mut iter)
667        }
668    }
669
670    /// Seek to the given key using the specified operator and execute the closure.
671    ///
672    /// # Safety
673    ///
674    /// Mutating the map inside the closure is undefined behaviour.
675    pub fn seek<F>(&mut self, op: &str, key: K, f: F)
676    where
677        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
678    {
679        // SAFETY: Iterator is initialized with raxStart before use.
680        unsafe {
681            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
682            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
683            let mut iter = iter.assume_init();
684            iter.fixup();
685            iter.seek(op, key);
686            f(self, &mut iter)
687        }
688    }
689
690    /// Seek to the given key using the specified operator and execute the closure, returning a result.
691    ///
692    /// # Safety
693    ///
694    /// Mutating the map inside the closure is undefined behaviour.
695    pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
696    where
697        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
698    {
699        // SAFETY: Iterator is initialized with raxStart before use.
700        unsafe {
701            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
702            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
703            let mut iter = iter.assume_init();
704            iter.fixup();
705            iter.seek(op, key);
706            f(self, &mut iter)
707        }
708    }
709
710    /// Create an iterator and execute the closure.
711    ///
712    /// # Safety
713    ///
714    /// Mutating the map inside the closure is undefined behaviour.
715    pub fn iter<F>(&mut self, f: F)
716    where
717        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
718    {
719        // SAFETY: Iterator is initialized with raxStart before use.
720        unsafe {
721            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
722            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
723            let mut iter = iter.assume_init();
724            iter.fixup();
725            f(self, &mut iter)
726        }
727    }
728
729    /// Create an iterator and execute the closure, returning a result.
730    ///
731    /// # Safety
732    ///
733    /// Mutating the map inside the closure is undefined behaviour.
734    pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
735    where
736        F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
737    {
738        // SAFETY: Iterator is initialized with raxStart before use.
739        unsafe {
740            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
741            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
742            let mut iter = iter.assume_init();
743            iter.fixup();
744            f(self, &mut iter)
745        }
746    }
747}
748
749/// RaxMap but without the values. The "isnull" bit will be set for
750/// all entries.
751/// #Examples
752///
753/// ```
754/// use rax::RaxSet;
755/// let mut r = RaxSet::new();
756/// r.insert(1);
757/// r.insert(2);
758///
759/// r.iter(|r, iter| {
760///     // Place iterator at the first entry.
761///     if !iter.seek_min() {
762///         // EOF
763///         return;
764///     }
765///
766///     // Can test EOF at any time.
767///     if iter.eof() {
768///         // EOF
769///         return;
770///     }
771///
772///     while iter.forward() {
773///         iter.key();
774///     }
775///     // In reverse
776///     // Place iterator at the end.
777///     if !iter.seek_max() {
778///         // EOF
779///         return;
780///     }
781///     while iter.back() {
782///         iter.key();
783///     }
784///
785///     // Seek
786///     if !iter.seek(">=", 2) {
787///         // EOF
788///     }
789///     while iter.forward() {
790///         iter.key();
791///     }
792/// });
793/// ```
794pub struct RaxSet<K: RaxKey> {
795    rax: *mut rax,
796    _marker: std::marker::PhantomData<K>,
797}
798
799impl<K: RaxKey> Drop for RaxSet<K> {
800    fn drop(&mut self) {
801        // SAFETY: self.rax is non-null.
802        unsafe { raxFree(self.rax) }
803    }
804}
805
806// SAFETY: RaxSet owns a unique heap allocation. No shared mutable
807// state, therefore safe to transfer between threads.
808unsafe impl<K: RaxKey + Send> Send for RaxSet<K> {}
809
810// SAFETY: &RaxSet only allows read-only access (find/get) which don't
811// mutate the underlying C tree, therefore safe to share across threads.
812unsafe impl<K: RaxKey + Sync> Sync for RaxSet<K> {}
813
814impl<K: RaxKey> Default for RaxSet<K> {
815    fn default() -> Self {
816        Self::new()
817    }
818}
819
820/// Implementation of RaxSet.
821impl<K: RaxKey> RaxSet<K> {
822    /// Create a new RaxSet.
823    ///
824    /// # Panics
825    ///
826    /// Panics if `raxNew()` returns NULL (out of memory).
827    pub fn new() -> RaxSet<K> {
828        Self::try_new().expect("raxNew: out of memory")
829    }
830
831    /// Fallible constructor.
832    ///
833    /// Returns `Err(OutOfMemory)` when `raxNew()` returns NULL.
834    pub fn try_new() -> Result<RaxSet<K>, RaxError> {
835        // SAFETY: raxNew() allocates a new rax tree. We check for NULL
836        // before storing the pointer.
837        let ptr = unsafe { raxNew() };
838
839        if ptr.is_null() {
840            return Err(RaxError::OutOfMemory());
841        }
842
843        Ok(RaxSet {
844            rax: ptr,
845            _marker: std::marker::PhantomData,
846        })
847    }
848
849    /// The number of entries in the RAX
850    pub fn len(&self) -> u64 {
851        unsafe { raxSize(self.rax) }
852    }
853
854    /// The number of entries in the RAX
855    pub fn size(&self) -> u64 {
856        unsafe { raxSize(self.rax) }
857    }
858
859    /// Prints the Rax as ASCII art to stdout.
860    pub fn show(&self) {
861        unsafe { raxShow(self.rax) }
862    }
863
864    /// Returns true if the RAX is empty.
865    pub fn is_empty(&self) -> bool {
866        self.len() == 0
867    }
868
869    /// Insert a new entry into the RAX replacing and returning the existing
870    /// entry for the supplied key.
871    pub fn insert(&mut self, key: K) -> Result<bool, RaxError> {
872        unsafe {
873            // Integer values require Big Endian to allow the Rax to fully optimize
874            // storing them since it will be able to compress the prefixes especially
875            // for 64/128bit numbers.
876            let k = key.encode();
877            let (ptr, len) = k.to_buf();
878
879            let r = raxTryInsert(
880                self.rax,
881                // Grab a raw pointer to the key. Keys are most likely allocated
882                // on the stack. The rax will keep it's own copy of the key so we
883                // don't want to keep in in the heap twice and it exists in the
884                // rax in it's compressed form.
885                ptr,
886                len,
887                std::ptr::null_mut(),
888                std::ptr::null_mut(),
889            );
890
891            if r == 0 {
892                if Errno::last() == Errno::ENOMEM {
893                    Err(RaxError::OutOfMemory())
894                } else {
895                    Ok(false)
896                }
897            } else {
898                Ok(true)
899            }
900        }
901    }
902
903    pub fn remove(&mut self, key: K) -> bool {
904        unsafe {
905            let k = key.encode();
906            let (ptr, len) = k.to_buf();
907
908            let r = raxRemove(self.rax, ptr, len, &mut std::ptr::null_mut());
909
910            r == 1
911        }
912    }
913
914    /// Determines if the supplied key exists in the Rax.
915    pub fn exists(&self, key: K) -> bool {
916        unsafe {
917            let k = key.encode();
918            let (ptr, len) = k.to_buf();
919
920            let value = raxFind(self.rax, ptr, len);
921
922            value != raxNotFound
923        }
924    }
925
926    /// Seek to the minimum key and execute the closure.
927    ///
928    /// # Safety
929    ///
930    /// Mutating the set inside the closure is undefined behaviour.
931    pub fn seek_min<F>(&mut self, f: F)
932    where
933        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
934    {
935        // SAFETY: Iterator is initialized with raxStart before use.
936        unsafe {
937            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
938            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
939            let mut iter = iter.assume_init();
940            iter.fixup();
941            iter.seek_min();
942            f(self, &mut iter)
943        }
944    }
945
946    /// Seek to the minimum key and execute the closure, returning a result.
947    ///
948    /// # Safety
949    ///
950    /// Mutating the set inside the closure is undefined behaviour.
951    pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
952    where
953        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
954    {
955        // SAFETY: Iterator is initialized with raxStart before use.
956        unsafe {
957            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
958            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
959            let mut iter = iter.assume_init();
960            iter.fixup();
961            iter.seek_min();
962            f(self, &mut iter)
963        }
964    }
965
966    /// Seek to the maximum key and execute the closure.
967    ///
968    /// # Safety
969    ///
970    /// Mutating the set inside the closure is undefined behaviour.
971    pub fn seek_max<F>(&mut self, f: F)
972    where
973        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
974    {
975        // SAFETY: Iterator is initialized with raxStart before use.
976        unsafe {
977            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
978            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
979            let mut iter = iter.assume_init();
980            iter.fixup();
981            iter.seek_max();
982            f(self, &mut iter)
983        }
984    }
985
986    /// Seek to the maximum key and execute the closure, returning a result.
987    ///
988    /// # Safety
989    ///
990    /// Mutating the set inside the closure is undefined behaviour.
991    pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
992    where
993        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
994    {
995        // SAFETY: Iterator is initialized with raxStart before use.
996        unsafe {
997            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
998            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
999            let mut iter = iter.assume_init();
1000            iter.fixup();
1001            iter.seek_max();
1002            f(self, &mut iter)
1003        }
1004    }
1005
1006    /// Seek to the given key using the specified operator and execute the closure.
1007    ///
1008    /// # Safety
1009    ///
1010    /// Mutating the set inside the closure is undefined behaviour.
1011    pub fn seek<F>(&mut self, op: &str, key: K, f: F)
1012    where
1013        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1014    {
1015        // SAFETY: Iterator is initialized with raxStart before use.
1016        unsafe {
1017            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1018            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1019            let mut iter = iter.assume_init();
1020            iter.fixup();
1021            iter.seek(op, key);
1022            f(self, &mut iter)
1023        }
1024    }
1025
1026    /// Seek to the given key using the specified operator and execute the closure, returning a result.
1027    ///
1028    /// # Safety
1029    ///
1030    /// Mutating the set inside the closure is undefined behaviour.
1031    pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
1032    where
1033        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1034    {
1035        // SAFETY: Iterator is initialized with raxStart before use.
1036        unsafe {
1037            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1038            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1039            let mut iter = iter.assume_init();
1040            iter.fixup();
1041            iter.seek(op, key);
1042            f(self, &mut iter)
1043        }
1044    }
1045
1046    /// Create an iterator and execute the closure.
1047    ///
1048    /// # Safety
1049    ///
1050    /// Mutating the set inside the closure is undefined behaviour.
1051    pub fn iter<F>(&mut self, f: F)
1052    where
1053        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1054    {
1055        // SAFETY: Iterator is initialized with raxStart before use.
1056        unsafe {
1057            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1058            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1059            let mut iter = iter.assume_init();
1060            iter.fixup();
1061            f(self, &mut iter)
1062        }
1063    }
1064
1065    /// Create an iterator and execute the closure, returning a result.
1066    ///
1067    /// # Safety
1068    ///
1069    /// Mutating the set inside the closure is undefined behaviour.
1070    pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
1071    where
1072        F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1073    {
1074        // SAFETY: Iterator is initialized with raxStart before use.
1075        unsafe {
1076            let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1077            raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1078            let mut iter = iter.assume_init();
1079            iter.fixup();
1080            f(self, &mut iter)
1081        }
1082    }
1083}
1084
1085// Same as RaxMap except values are not pointers to heap allocations.
1086// Instead the "data pointer" in the RAX is the value. This means we
1087// have sizeof<usize> worth of bytes to play with. Perhaps, in the future
1088// we could create data values of any size, but for now we have the size
1089// of pointers to work with or null which has no added size to a rax node.
1090//pub struct RaxIntMap<K: RaxKey> {
1091//    rax: *mut rax,
1092//    _marker: std::marker::PhantomData<K>,
1093//}
1094//
1095//impl<K: RaxKey> RaxIntMap<K> {
1096//    pub fn new() -> RaxIntMap<K> {
1097//        RaxIntMap {
1098//            rax: unsafe { raxNew() },
1099//            _marker: std::marker::PhantomData,
1100//        }
1101//    }
1102//
1103//    /// Insert a new entry into the RAX replacing and returning the existing
1104//    /// entry for the supplied key.
1105//    pub fn insert(&mut self, key: K, value: usize) -> Result<Option<usize>, RaxError> {
1106//        unsafe {
1107//            // Allocate a pointer to catch the old value.
1108//            let old: &mut *mut u8 = &mut ptr::null_mut();
1109//
1110//            // Integer values require Big Endian to allow the Rax to fully optimize
1111//            // storing them since it will be able to compress the prefixes especially
1112//            // for 64/128bit numbers.
1113//            let k = key.encode();
1114//            let (ptr, len) = k.to_buf();
1115//
1116//            let r = raxInsert(
1117//                self.rax,
1118//                // Grab a raw pointer to the key. Keys are most likely allocated
1119//                // on the stack. The rax will keep it's own copy of the key so we
1120//                // don't want to keep in in the heap twice and it exists in the
1121//                // rax in it's compressed form.
1122//                ptr,
1123//                len,
1124//                &value as *const _ as *mut u8,
1125//                old,
1126//            );
1127//
1128//            if r == 0 && Errno::last() == Errno::ENOMEM {
1129//                Err(RaxError::OutOfMemory())
1130//            } else if old.is_null() {
1131//                Ok(None)
1132//            } else {
1133//                Ok(Some(std::mem::transmute(*old)))
1134//            }
1135//        }
1136//    }
1137//
1138//    /// Insert a new entry into the RAX if an existing one does not exist.
1139//    pub fn try_insert(&mut self, key: K, data: usize) -> Result<Option<usize>, RaxError> {
1140//        unsafe {
1141//            // Allocate a pointer to catch the old value.
1142//            let old: &mut *mut u8 = &mut ptr::null_mut();
1143//
1144//            // Integer values require Big Endian to allow the Rax to fully optimize
1145//            // storing them since it will be able to compress the prefixes especially
1146//            // for 64/128bit numbers.
1147//            let k = key.encode();
1148//            let (ptr, len) = k.to_buf();
1149//
1150//            let r = raxTryInsert(
1151//                self.rax,
1152//                // Grab a raw pointer to the key. Keys are most likely allocated
1153//                // on the stack. The rax will keep it's own copy of the key so we
1154//                // don't want to keep in in the heap twice and it exists in the
1155//                // rax in it's compressed form.
1156//                ptr,
1157//                len,
1158//                &data as *const _ as *mut u8,
1159//                old,
1160//            );
1161//
1162//            if r == 0 {
1163//                if Errno::last() == Errno::ENOMEM {
1164//                    Err(RaxError::OutOfMemory())
1165//                } else if old.is_null() {
1166//                    Ok(None)
1167//                } else {
1168//                    Ok(Some(transmute(*old)))
1169//                }
1170//            } else if old.is_null() {
1171//                Ok(None)
1172//            } else {
1173//                Ok(Some(std::mem::transmute(*old)))
1174//            }
1175//        }
1176//    }
1177//}
1178
1179pub trait RaxKey<RHS = Self>: Clone + Default + std::fmt::Debug {
1180    type Output: RaxKey;
1181
1182    fn encode(self) -> Self::Output;
1183
1184    fn to_buf(&self) -> (*const u8, usize);
1185
1186    /// # Safety
1187    ///
1188    /// `ptr` must be valid for reads of `len` bytes.
1189    unsafe fn from_buf(ptr: *const u8, len: usize) -> RHS;
1190}
1191
1192impl RaxKey for f32 {
1193    type Output = u32;
1194
1195    fn encode(self) -> Self::Output {
1196        // Encode as u32 Big Endian
1197        self.to_bits().to_be()
1198    }
1199
1200    fn to_buf(&self) -> (*const u8, usize) {
1201        // This should never get called since we represent as a u32
1202        (
1203            self as *const _ as *const u8,
1204            std::mem::size_of::<Self::Output>(),
1205        )
1206    }
1207
1208    unsafe fn from_buf(ptr: *const u8, len: usize) -> f32 {
1209        assert_eq!(len, std::mem::size_of::<f32>());
1210        if len != size_of::<Self::Output>() {
1211            return Self::default();
1212        }
1213        unsafe {
1214            // We used a BigEndian u32 to encode so let's reverse it
1215            f32::from_bits(u32::from_be(
1216                *(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32),
1217            ))
1218        }
1219    }
1220}
1221
1222impl RaxKey for f64 {
1223    type Output = u64;
1224
1225    fn encode(self) -> Self::Output {
1226        // Encode as u64 Big Endian
1227        self.to_bits().to_be()
1228    }
1229
1230    fn to_buf(&self) -> (*const u8, usize) {
1231        // This should never get called since we represent as a u64
1232        (self as *const _ as *const u8, size_of::<Self::Output>())
1233    }
1234
1235    unsafe fn from_buf(ptr: *const u8, len: usize) -> f64 {
1236        assert_eq!(len, std::mem::size_of::<f64>());
1237        if len != size_of::<Self::Output>() {
1238            return Self::default();
1239        }
1240        unsafe {
1241            // We used a BigEndian u64 to encode so let's reverse it
1242            f64::from_bits(u64::from_be(
1243                *(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64),
1244            ))
1245        }
1246    }
1247}
1248
1249impl RaxKey for isize {
1250    type Output = isize;
1251
1252    fn encode(self) -> Self::Output {
1253        self.to_be()
1254    }
1255
1256    fn to_buf(&self) -> (*const u8, usize) {
1257        (self as *const _ as *const u8, size_of::<Self::Output>())
1258    }
1259
1260    unsafe fn from_buf(ptr: *const u8, len: usize) -> isize {
1261        assert_eq!(len, std::mem::size_of::<isize>());
1262        if len != size_of::<Self::Output>() {
1263            return Self::default();
1264        }
1265        unsafe { isize::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut isize)) }
1266    }
1267}
1268
1269impl RaxKey for usize {
1270    type Output = usize;
1271
1272    fn encode(self) -> Self::Output {
1273        self.to_be()
1274    }
1275
1276    fn to_buf(&self) -> (*const u8, usize) {
1277        (
1278            self as *const _ as *const u8,
1279            std::mem::size_of::<Self::Output>(),
1280        )
1281    }
1282
1283    unsafe fn from_buf(ptr: *const u8, len: usize) -> usize {
1284        assert_eq!(len, std::mem::size_of::<usize>());
1285        if len != size_of::<Self::Output>() {
1286            return Self::default();
1287        }
1288        unsafe {
1289            usize::from_be(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut usize))
1290        }
1291    }
1292}
1293
1294impl RaxKey for i16 {
1295    type Output = i16;
1296
1297    fn encode(self) -> Self::Output {
1298        self.to_be()
1299    }
1300
1301    fn to_buf(&self) -> (*const u8, usize) {
1302        (self as *const _ as *const u8, size_of::<Self::Output>())
1303    }
1304
1305    unsafe fn from_buf(ptr: *const u8, len: usize) -> Self {
1306        if len != size_of::<Self::Output>() {
1307            return Self::default();
1308        }
1309        unsafe { i16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i16)) }
1310    }
1311}
1312
1313impl RaxKey for u16 {
1314    type Output = u16;
1315
1316    fn encode(self) -> Self::Output {
1317        self.to_be()
1318    }
1319
1320    fn to_buf(&self) -> (*const u8, usize) {
1321        (self as *const _ as *const u8, size_of::<Self::Output>())
1322    }
1323
1324    unsafe fn from_buf(ptr: *const u8, len: usize) -> u16 {
1325        assert_eq!(len, std::mem::size_of::<u16>());
1326        if len != size_of::<Self::Output>() {
1327            return Self::default();
1328        }
1329        unsafe { u16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u16)) }
1330    }
1331}
1332
1333impl RaxKey for i32 {
1334    type Output = i32;
1335
1336    fn encode(self) -> Self::Output {
1337        self.to_be()
1338    }
1339
1340    fn to_buf(&self) -> (*const u8, usize) {
1341        (self as *const _ as *const u8, size_of::<Self::Output>())
1342    }
1343
1344    unsafe fn from_buf(ptr: *const u8, len: usize) -> i32 {
1345        assert_eq!(len, std::mem::size_of::<i32>());
1346        if len != size_of::<Self::Output>() {
1347            return Self::default();
1348        }
1349        unsafe { i32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i32)) }
1350    }
1351}
1352
1353impl RaxKey for u32 {
1354    type Output = u32;
1355
1356    fn encode(self) -> Self::Output {
1357        self.to_be()
1358    }
1359
1360    fn to_buf(&self) -> (*const u8, usize) {
1361        (self as *const _ as *const u8, size_of::<Self::Output>())
1362    }
1363
1364    unsafe fn from_buf(ptr: *const u8, len: usize) -> u32 {
1365        assert_eq!(len, std::mem::size_of::<u32>());
1366        if len != size_of::<Self::Output>() {
1367            return Self::default();
1368        }
1369        unsafe { u32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u32)) }
1370    }
1371}
1372
1373impl RaxKey for i64 {
1374    type Output = i64;
1375
1376    fn encode(self) -> Self::Output {
1377        self.to_be()
1378    }
1379
1380    fn to_buf(&self) -> (*const u8, usize) {
1381        (self as *const _ as *const u8, size_of::<Self::Output>())
1382    }
1383
1384    unsafe fn from_buf(ptr: *const u8, len: usize) -> i64 {
1385        assert_eq!(len, std::mem::size_of::<i64>());
1386        if len != size_of::<Self::Output>() {
1387            return Self::default();
1388        }
1389        unsafe { i64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i64)) }
1390    }
1391}
1392
1393impl RaxKey for u64 {
1394    type Output = u64;
1395
1396    fn encode(self) -> Self::Output {
1397        self.to_be()
1398    }
1399
1400    fn to_buf(&self) -> (*const u8, usize) {
1401        (self as *const _ as *const u8, size_of::<Self::Output>())
1402    }
1403
1404    unsafe fn from_buf(ptr: *const u8, len: usize) -> u64 {
1405        assert_eq!(len, std::mem::size_of::<u64>());
1406        if len != size_of::<Self::Output>() {
1407            return Self::default();
1408        }
1409        unsafe { u64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64)) }
1410    }
1411}
1412
1413impl RaxKey for i128 {
1414    type Output = i128;
1415
1416    fn encode(self) -> Self::Output {
1417        self.to_be()
1418    }
1419
1420    fn to_buf(&self) -> (*const u8, usize) {
1421        (self as *const _ as *const u8, size_of::<Self::Output>())
1422    }
1423
1424    unsafe fn from_buf(ptr: *const u8, len: usize) -> i128 {
1425        assert_eq!(len, std::mem::size_of::<i128>());
1426        if len != size_of::<Self::Output>() {
1427            return Self::default();
1428        }
1429        unsafe { i128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i128)) }
1430    }
1431}
1432
1433impl RaxKey for u128 {
1434    type Output = u128;
1435
1436    fn encode(self) -> Self::Output {
1437        self.to_be()
1438    }
1439
1440    fn to_buf(&self) -> (*const u8, usize) {
1441        (self as *const _ as *const u8, size_of::<Self::Output>())
1442    }
1443
1444    unsafe fn from_buf(ptr: *const u8, len: usize) -> u128 {
1445        assert_eq!(len, std::mem::size_of::<u128>());
1446        if len != size_of::<Self::Output>() {
1447            return Self::default();
1448        }
1449        unsafe { u128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u128)) }
1450    }
1451}
1452
1453impl RaxKey for Vec<u8> {
1454    type Output = Vec<u8>;
1455
1456    fn encode(self) -> Vec<u8> {
1457        self
1458    }
1459
1460    fn to_buf(&self) -> (*const u8, usize) {
1461        (self.as_ptr(), self.len())
1462    }
1463
1464    unsafe fn from_buf(ptr: *const u8, len: usize) -> Vec<u8> {
1465        unsafe { std::slice::from_raw_parts(ptr, len).to_vec() }
1466    }
1467}
1468
1469impl<'a> RaxKey for &'a [u8] {
1470    type Output = &'a [u8];
1471
1472    fn encode(self) -> &'a [u8] {
1473        self
1474    }
1475
1476    fn to_buf(&self) -> (*const u8, usize) {
1477        (self.as_ptr(), self.len())
1478    }
1479
1480    unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a [u8] {
1481        unsafe { std::slice::from_raw_parts(ptr, len) }
1482    }
1483}
1484
1485//impl RaxKey for SDS {
1486//    type Output = SDS;
1487//
1488//    fn encode(self) -> Self::Output {
1489//        self
1490//    }
1491//
1492//    fn to_buf(&self) -> (*const u8, usize) {
1493//        (self.as_ptr(), self.len())
1494//    }
1495//
1496//    unsafe fn from_buf(ptr: *const u8, len: usize) -> SDS {
1497//        SDS::from_ptr(ptr, len)
1498//    }
1499//}
1500
1501impl<'a> RaxKey for &'a str {
1502    type Output = &'a str;
1503
1504    fn encode(self) -> Self::Output {
1505        self
1506    }
1507
1508    fn to_buf(&self) -> (*const u8, usize) {
1509        ((*self).as_ptr(), self.len())
1510    }
1511
1512    unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a str {
1513        unsafe { std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap_or_default() }
1514    }
1515}
1516
1517#[repr(C)]
1518pub struct RaxIterator<K: RaxKey, V> {
1519    pub flags: libc::c_int,
1520    pub rt: *mut rax,
1521    pub key: *mut u8,
1522    pub data: *mut libc::c_void,
1523    pub key_len: libc::size_t,
1524    pub key_max: libc::size_t,
1525    pub key_static_string: [u8; 128],
1526    pub node: *mut raxNode,
1527    pub stack: raxStack,
1528    pub node_cb: Option<raxNodeCallback>,
1529    _marker: std::marker::PhantomData<(K, V)>,
1530}
1531
1532/// Free up memory.
1533impl<K: RaxKey, V> Drop for RaxIterator<K, V> {
1534    fn drop(&mut self) {
1535        unsafe {
1536            // Fix key pointer if it still points at the (moved) inline buffer.
1537            if self.key_max == RAX_ITER_STATIC_LEN as usize {
1538                self.key = self.key_static_string.as_mut_ptr();
1539            }
1540
1541            // Fix stack pointer if it still points at the (moved) inline array.
1542            if self.stack.maxitems == RAX_STACK_STATIC_ITEMS as usize {
1543                self.stack.stack = self.stack.static_items.as_mut_ptr();
1544            }
1545
1546            raxStop(&raw mut *self as *mut raxIterator);
1547        }
1548    }
1549}
1550
1551/// Implement std::Iterator
1552impl<K: RaxKey, V: 'static> Iterator for RaxIterator<K, V> {
1553    type Item = (K, Option<&'static V>);
1554
1555    fn next(&mut self) -> Option<<Self as Iterator>::Item> {
1556        unsafe {
1557            if raxNext(&raw mut *self as *mut raxIterator) == 1 {
1558                let data: *mut libc::c_void = self.data;
1559                if data.is_null() {
1560                    None
1561                } else {
1562                    let val = data as *const V;
1563                    if val.is_null() {
1564                        Some((self.key(), None))
1565                    } else {
1566                        Some((self.key(), Some(&*val)))
1567                    }
1568                }
1569            } else {
1570                None
1571            }
1572        }
1573    }
1574}
1575
1576/// Implement std::DoubleEndedIterator
1577impl<K: RaxKey, V: 'static> DoubleEndedIterator for RaxIterator<K, V> {
1578    fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
1579        unsafe {
1580            if raxPrev(&raw mut *self as *mut raxIterator) == 1 {
1581                let data: *mut libc::c_void = self.data;
1582                if data.is_null() {
1583                    None
1584                } else {
1585                    let val = data as *const V;
1586                    if val.is_null() {
1587                        Some((self.key(), None))
1588                    } else {
1589                        Some((self.key(), Some(&*val)))
1590                    }
1591                }
1592            } else {
1593                None
1594            }
1595        }
1596    }
1597}
1598
1599/// Core iterator implementation
1600impl<K: RaxKey, V> RaxIterator<K, V> {
1601    /// Create a new iterator for the given RaxMap.
1602    pub fn new(r: RaxMap<K, V>) -> RaxIterator<K, V> {
1603        // SAFETY: Iterator is initialized with raxStart before use.
1604        unsafe {
1605            let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
1606            raxStart(iter.as_mut_ptr() as *mut raxIterator, r.rax);
1607            let mut iter = iter.assume_init();
1608            iter.fixup();
1609            iter
1610        }
1611    }
1612
1613    pub fn print_ptr(&self) {
1614        println!("ptr = {:p}", self);
1615        println!("ptr = {:p}", self as *const _ as *const raxIterator);
1616    }
1617
1618    pub fn seek_min(&mut self) -> bool {
1619        unsafe {
1620            if raxSeek(
1621                &raw mut *self as *mut raxIterator,
1622                BEGIN.as_ptr(),
1623                std::ptr::null(),
1624                0,
1625            ) == 1
1626            {
1627                self.forward()
1628            } else {
1629                false
1630            }
1631        }
1632    }
1633
1634    pub fn seek_max(&mut self) -> bool {
1635        unsafe {
1636            if raxSeek(
1637                &raw mut *self as *mut raxIterator,
1638                END.as_ptr(),
1639                std::ptr::null(),
1640                0,
1641            ) == 1
1642            {
1643                self.back()
1644            } else {
1645                false
1646            }
1647        }
1648    }
1649
1650    pub fn back(&mut self) -> bool {
1651        unsafe { raxPrev(&raw mut *self as *mut raxIterator) == 1 }
1652    }
1653
1654    pub fn forward(&mut self) -> bool {
1655        unsafe { raxNext(&raw mut *self as *mut raxIterator) == 1 }
1656    }
1657
1658    /// Key at current position
1659    pub fn key(&self) -> K {
1660        unsafe { K::from_buf(self.key, self.key_len) }
1661    }
1662
1663    /// Data at current position.
1664    pub fn value(&self) -> Option<&V> {
1665        unsafe {
1666            let data: *mut libc::c_void = self.data;
1667            if data.is_null() {
1668                None
1669            } else {
1670                Some(&*(data as *const V))
1671            }
1672        }
1673    }
1674
1675    pub fn lesser(&mut self, key: K) -> bool {
1676        self.seek(LESSER, key)
1677    }
1678
1679    pub fn lesser_equal(&mut self, key: K) -> bool {
1680        self.seek(LESSER_EQUAL, key)
1681    }
1682
1683    pub fn greater(&mut self, key: K) -> bool {
1684        self.seek(GREATER, key)
1685    }
1686
1687    pub fn greater_equal(&mut self, key: K) -> bool {
1688        self.seek(GREATER_EQUAL, key)
1689    }
1690
1691    pub fn seek(&mut self, op: &str, key: K) -> bool {
1692        unsafe {
1693            let k = key.encode();
1694            let (p, len) = k.to_buf();
1695            raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len) == 1
1696                && self.flags & RAX_ITER_EOF != 0
1697        }
1698    }
1699
1700    pub fn seek_raw(&mut self, op: &str, key: K) -> i32 {
1701        unsafe {
1702            let k = key.encode();
1703            let (p, len) = k.to_buf();
1704            raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len)
1705        }
1706    }
1707
1708    pub fn seek_bytes(&mut self, op: &str, ele: &[u8]) -> bool {
1709        unsafe {
1710            raxSeek(
1711                &raw mut *self as *mut raxIterator,
1712                op.as_ptr(),
1713                ele.as_ptr(),
1714                ele.len() as libc::size_t,
1715            ) == 1
1716        }
1717    }
1718
1719    /// Return if the iterator is in an EOF state. This happens when raxSeek()
1720    /// failed to seek an appropriate element, so that raxNext() or raxPrev()
1721    /// will return zero, or when an EOF condition was reached while iterating
1722    /// with next() and prev().
1723    pub fn eof(&self) -> bool {
1724        self.flags & RAX_ITER_EOF != 0
1725    }
1726
1727    /// Fix self-referential pointers invalidated by a move.
1728    pub fn fixup(&mut self) {
1729        self.key = self.key_static_string.as_mut_ptr();
1730        self.stack.stack = self.stack.static_items.as_mut_ptr();
1731    }
1732}
1733
1734impl fmt::Display for RaxError {
1735    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1736        match *self {
1737            RaxError::Generic(ref err) => write!(f, "{err}"),
1738            RaxError::OutOfMemory() => write!(f, "out of memory"),
1739        }
1740    }
1741}
1742
1743impl error::Error for RaxError {
1744    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1745        match *self {
1746            // N.B. Both of these implicitly cast `err` from their concrete
1747            // types (either `&io::Error` or `&num::ParseIntError`)
1748            // to a trait object `&Error`. This works because both error types
1749            // implement `Error`.
1750            RaxError::Generic(ref err) => Some(err),
1751            RaxError::OutOfMemory() => Some(self),
1752        }
1753    }
1754}
1755
1756#[derive(Debug)]
1757pub struct GenericError {
1758    message: String,
1759}
1760
1761impl GenericError {
1762    pub fn new(message: &str) -> GenericError {
1763        GenericError {
1764            message: String::from(message),
1765        }
1766    }
1767}
1768
1769impl fmt::Display for GenericError {
1770    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1771        write!(f, "Store error: {}", self.message)
1772    }
1773}
1774
1775impl error::Error for GenericError {}
1776
1777#[repr(C)]
1778pub struct rax;
1779
1780#[repr(C)]
1781pub struct raxNode;
1782
1783#[repr(C)]
1784pub struct raxStack {
1785    stack: *mut *mut libc::c_void,
1786    items: libc::size_t,
1787    maxitems: libc::size_t,
1788    static_items: [*mut libc::c_void; 32],
1789    oom: libc::c_int,
1790}
1791
1792#[repr(C)]
1793pub struct raxIterator;
1794
1795#[allow(non_snake_case)]
1796#[allow(non_camel_case_types)]
1797extern "C" fn RaxFreeWithCallbackWrapper<V>(v: *mut libc::c_void) {
1798    unsafe {
1799        // Re-box it so it can drop it immediately after it leaves this scope.
1800        drop(Box::from_raw(v as *mut V));
1801    }
1802}
1803
1804#[allow(non_camel_case_types)]
1805type raxNodeCallback = extern "C" fn(v: *mut libc::c_void);
1806
1807type RaxFreeCallback = extern "C" fn(v: *mut libc::c_void);
1808
1809#[allow(improper_ctypes)]
1810#[allow(non_snake_case)]
1811#[allow(non_camel_case_types)]
1812#[link(name = "rax", kind = "static")]
1813extern "C" {
1814    pub static raxNotFound: *mut u8;
1815
1816    pub static mut rax_malloc: extern "C" fn(size: libc::size_t) -> *mut u8;
1817    pub static mut rax_realloc:
1818        extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8;
1819    pub static mut rax_free: extern "C" fn(ptr: *mut libc::c_void);
1820
1821    pub fn raxIteratorSize() -> libc::c_int;
1822
1823    pub fn raxNew() -> *mut rax;
1824
1825    pub fn raxFree(rax: *mut rax);
1826
1827    pub fn raxFreeWithCallback(rax: *mut rax, callback: RaxFreeCallback);
1828
1829    pub fn raxInsert(
1830        rax: *mut rax,
1831        s: *const u8,
1832        len: libc::size_t,
1833        data: *const u8,
1834        old: &mut *mut u8,
1835    ) -> libc::c_int;
1836
1837    pub fn raxTryInsert(
1838        rax: *mut rax,
1839        s: *const u8,
1840        len: libc::size_t,
1841        data: *const u8,
1842        old: *mut *mut u8,
1843    ) -> libc::c_int;
1844
1845    pub fn raxRemove(
1846        rax: *mut rax,
1847        s: *const u8,
1848        len: libc::size_t,
1849        old: &mut *mut u8,
1850    ) -> libc::c_int;
1851
1852    pub fn raxFind(rax: *mut rax, s: *const u8, len: libc::size_t) -> *mut u8;
1853
1854    pub fn raxIteratorNew(rt: *mut rax) -> *mut raxIterator;
1855
1856    pub fn raxStart(it: *mut raxIterator, rt: *mut rax);
1857
1858    pub fn raxSeek(
1859        it: *mut raxIterator,
1860        op: *const u8,
1861        ele: *const u8,
1862        len: libc::size_t,
1863    ) -> libc::c_int;
1864
1865    pub fn raxNext(it: *mut raxIterator) -> libc::c_int;
1866
1867    pub fn raxPrev(it: *mut raxIterator) -> libc::c_int;
1868
1869    pub fn raxRandomWalk(it: *mut raxIterator, steps: libc::size_t) -> libc::c_int;
1870
1871    pub fn raxCompare(
1872        it: *mut raxIterator,
1873        op: *const u8,
1874        key: *mut u8,
1875        key_len: libc::size_t,
1876    ) -> libc::c_int;
1877
1878    pub fn raxStop(it: *mut raxIterator);
1879
1880    pub fn raxEOF(it: *mut raxIterator) -> libc::c_int;
1881
1882    pub fn raxShow(rax: *mut rax);
1883
1884    pub fn raxSize(rax: *mut rax) -> u64;
1885}
1886
1887#[cfg(test)]
1888mod tests {
1889    extern crate test;
1890    use std::{
1891        self,
1892        default::Default,
1893        fmt,
1894        time::{Duration, Instant},
1895    };
1896
1897    use super::*;
1898
1899    extern "C" fn rax_malloc_hook(size: libc::size_t) -> *mut u8 {
1900        unsafe {
1901            println!("malloc");
1902            libc::malloc(size) as *mut u8
1903        }
1904    }
1905
1906    extern "C" fn rax_realloc_hook(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8 {
1907        unsafe {
1908            println!("realloc");
1909            libc::realloc(ptr, size) as *mut u8
1910        }
1911    }
1912
1913    extern "C" fn rax_free_hook(ptr: *mut libc::c_void) {
1914        unsafe {
1915            println!("free");
1916            libc::free(ptr)
1917        }
1918    }
1919
1920    pub struct MyMsg<'a>(&'a str);
1921
1922    impl<'a> Drop for MyMsg<'a> {
1923        fn drop(&mut self) {
1924            println!("dropped -> {}", self.0);
1925        }
1926    }
1927
1928    #[derive(Clone, Copy)]
1929    pub struct Stopwatch {
1930        start_time: Option<Instant>,
1931        elapsed: Duration,
1932    }
1933
1934    impl Default for Stopwatch {
1935        fn default() -> Stopwatch {
1936            Stopwatch {
1937                start_time: None,
1938                elapsed: Duration::from_secs(0),
1939            }
1940        }
1941    }
1942
1943    impl fmt::Display for Stopwatch {
1944        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1945            return write!(f, "{}ms", self.elapsed_ms());
1946        }
1947    }
1948
1949    #[expect(unused)]
1950    impl Stopwatch {
1951        pub fn new() -> Stopwatch {
1952            let sw: Stopwatch = Default::default();
1953            return sw;
1954        }
1955        pub fn start_new() -> Stopwatch {
1956            let mut sw = Stopwatch::new();
1957            sw.start();
1958            return sw;
1959        }
1960
1961        pub fn start(&mut self) {
1962            self.start_time = Some(Instant::now());
1963        }
1964        pub fn stop(&mut self) {
1965            self.elapsed = self.elapsed();
1966            self.start_time = None;
1967        }
1968        pub fn reset(&mut self) {
1969            self.elapsed = Duration::from_secs(0);
1970            self.start_time = None;
1971        }
1972        pub fn restart(&mut self) {
1973            self.reset();
1974            self.start();
1975        }
1976
1977        pub fn is_running(&self) -> bool {
1978            return self.start_time.is_some();
1979        }
1980
1981        pub fn elapsed(&self) -> Duration {
1982            match self.start_time {
1983                Some(t1) => {
1984                    return t1.elapsed() + self.elapsed;
1985                }
1986                None => {
1987                    return self.elapsed;
1988                }
1989            }
1990        }
1991        pub fn elapsed_ms(&self) -> i64 {
1992            let dur = self.elapsed();
1993            return (dur.as_secs() * 1000 + (dur.subsec_nanos() / 1000000) as u64) as i64;
1994        }
1995    }
1996
1997    #[test]
1998    fn bench() {
1999        let ops = 1000000;
2000        println!("{} operations per function", ops);
2001
2002        for _ in 0..2 {
2003            println!();
2004            println!("Gets...");
2005            {
2006                let r = &mut RaxSet::<u64>::new();
2007                for x in 0..2000 {
2008                    r.insert(x).expect("whoops!");
2009                }
2010
2011                let sw = Stopwatch::start_new();
2012                for _po in 0..ops {
2013                    r.exists(1601);
2014                }
2015
2016                println!("RaxSet::get       {}ms", sw.elapsed_ms());
2017            }
2018            {
2019                let r = &mut RaxMap::<u64, &str>::new();
2020                for x in 0..2000 {
2021                    r.insert_null(x).expect("whoops!");
2022                }
2023
2024                match r.find(1601) {
2025                    Some(v) => println!("{}", v),
2026                    None => {}
2027                }
2028
2029                let sw = Stopwatch::start_new();
2030
2031                for _po in 0..ops {
2032                    r.find(1601);
2033                }
2034
2035                println!("RaxMap::get       {}ms", sw.elapsed_ms());
2036            }
2037
2038            {
2039                let r = &mut RaxMap::<u64, &str>::new();
2040                for x in 0..2000 {
2041                    r.insert_null(x).expect("whoops!");
2042                }
2043                let sw = Stopwatch::start_new();
2044
2045                for _po in 0..ops {
2046                    r.iter(|_, iter| {
2047                        iter.seek(EQUAL, 1601);
2048                    });
2049                }
2050
2051                println!("RaxCursor:seek    {}ms", sw.elapsed_ms());
2052            }
2053            {
2054                let r = &mut std::collections::HashSet::<u64>::new();
2055                for x in 0..2000 {
2056                    r.insert(x);
2057                }
2058
2059                let sw = Stopwatch::start_new();
2060
2061                let xx = 300;
2062                for _po in 0..ops {
2063                    r.get(&xx);
2064                }
2065
2066                println!("HashSet::get      {}ms", sw.elapsed_ms());
2067            }
2068            {
2069                let r = &mut std::collections::HashMap::<u64, &str>::new();
2070                for x in 0..2000 {
2071                    r.insert(x, "");
2072                }
2073
2074                let sw = Stopwatch::start_new();
2075
2076                let xx = 300;
2077                for _po in 0..ops {
2078                    r.get(&xx);
2079                }
2080
2081                println!("HashMap::get      {}ms", sw.elapsed_ms());
2082            }
2083            {
2084                let r = &mut std::collections::BTreeSet::<u64>::new();
2085                for x in 0..2000 {
2086                    r.insert(x);
2087                }
2088
2089                let sw = Stopwatch::start_new();
2090
2091                let xx = 300;
2092                for _po in 0..ops {
2093                    r.get(&xx);
2094                }
2095
2096                println!("BTreeSet::get      {}ms", sw.elapsed_ms());
2097            }
2098            {
2099                let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2100                for x in 0..2000 {
2101                    r.insert(x, "");
2102                }
2103
2104                let sw = Stopwatch::start_new();
2105
2106                let xx = 300;
2107                for _po in 0..ops {
2108                    r.get(&xx);
2109                }
2110
2111                println!("BTreeMap::get     {}ms", sw.elapsed_ms());
2112            }
2113
2114            println!();
2115            println!("Inserts...");
2116            {
2117                let r = &mut RaxMap::<u64, &str>::new();
2118                let sw = Stopwatch::start_new();
2119
2120                for x in 0..ops {
2121                    r.insert(x, Box::new("")).expect("whoops!");
2122                }
2123
2124                println!("RaxMap::insert        {}ms", sw.elapsed_ms());
2125            }
2126
2127            {
2128                let r = &mut RaxSet::<u64>::new();
2129                let sw = Stopwatch::start_new();
2130
2131                for x in 0..ops {
2132                    r.insert(x).expect("whoops!");
2133                }
2134
2135                println!("RaxSet::insert        {}ms", sw.elapsed_ms());
2136            }
2137
2138            {
2139                let r = &mut std::collections::BTreeSet::<u64>::new();
2140                let sw = Stopwatch::start_new();
2141
2142                for x in 0..ops {
2143                    r.insert(x);
2144                }
2145
2146                println!("BTreeSet::insert      {}ms", sw.elapsed_ms());
2147            }
2148            {
2149                let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2150                let sw = Stopwatch::start_new();
2151
2152                for x in 0..ops {
2153                    r.insert(x, "");
2154                }
2155
2156                println!("BTreeMap::insert      {}ms", sw.elapsed_ms());
2157            }
2158
2159            {
2160                let r = &mut std::collections::HashMap::<u64, &str>::new();
2161                let sw = Stopwatch::start_new();
2162
2163                for x in 0..ops {
2164                    r.insert(x, "");
2165                }
2166
2167                println!("HashMap::insert       {}ms", sw.elapsed_ms());
2168            }
2169        }
2170    }
2171
2172    #[test]
2173    fn bench_rax_find() {
2174        for _ in 0..10 {
2175            let r = &mut RaxMap::<u64, &str>::new();
2176            for x in 0..2000 {
2177                r.insert_null(x).expect("whoops!");
2178            }
2179
2180            match r.find(1601) {
2181                Some(v) => println!("{}", v),
2182                None => {}
2183            }
2184
2185            let sw = Stopwatch::start_new();
2186
2187            for _po in 0..1000000 {
2188                r.find(1601);
2189            }
2190
2191            println!("Thing took {}ms", sw.elapsed_ms());
2192        }
2193    }
2194
2195    #[test]
2196    fn bench_rax_cur_find() {
2197        for _ in 0..10 {
2198            let r = &mut RaxMap::<u64, &str>::new();
2199            for x in 0..2000 {
2200                r.insert_null(x).expect("whoops!");
2201            }
2202
2203            match r.find(1601) {
2204                Some(v) => println!("{}", v),
2205                None => {}
2206            }
2207
2208            let sw = Stopwatch::start_new();
2209
2210            for _po in 0..1000000 {
2211                r.iter(|_, iter| {
2212                    iter.seek(EQUAL, 1601);
2213                });
2214            }
2215
2216            println!("RaxMap::cursor_find {}ms", sw.elapsed_ms());
2217        }
2218    }
2219
2220    #[test]
2221    fn bench_rax_insert() {
2222        for _ in 0..10 {
2223            let r = &mut RaxMap::<u64, &str>::new();
2224            //
2225            let sw = Stopwatch::start_new();
2226
2227            for x in 0..1000000 {
2228                r.insert(x, Box::new("")).expect("whoops!");
2229            }
2230
2231            println!("RaxMap::insert {}ms", sw.elapsed_ms());
2232            println!("Size {}", r.size());
2233        }
2234    }
2235
2236    #[test]
2237    fn bench_rax_insert_show() {
2238        let r = &mut RaxMap::<u64, &str>::new();
2239        //
2240        let sw = Stopwatch::start_new();
2241
2242        for x in 0..100 {
2243            r.insert(x, Box::new("")).expect("whoops!");
2244        }
2245
2246        r.show();
2247        println!("RaxMap::insert {}ms", sw.elapsed_ms());
2248        assert_eq!(r.size(), 100);
2249    }
2250
2251    #[test]
2252    fn bench_rax_replace() {
2253        let ops = 1000000;
2254        for _ in 0..2 {
2255            let r = &mut RaxMap::<u64, &str>::new();
2256            // Insert values
2257            for x in 0..ops {
2258                r.insert(x, Box::new("")).expect("whoops!");
2259            }
2260
2261            let sw = Stopwatch::start_new();
2262
2263            for x in 0..ops {
2264                // Replace existing key
2265                r.insert(x, Box::new("")).expect("whoops!");
2266            }
2267
2268            println!("RaxMap::replace {}ms", sw.elapsed_ms());
2269            assert_eq!(r.size(), ops);
2270        }
2271    }
2272
2273    #[test]
2274    fn key_str() {
2275        unsafe {
2276            set_allocator(rax_malloc_hook, rax_realloc_hook, rax_free_hook);
2277        }
2278
2279        let mut r = RaxMap::<&str, MyMsg>::new();
2280
2281        let key = "hello-way";
2282
2283        r.insert(key, Box::new(MyMsg("world 80"))).expect("whoops!");
2284        r.insert("hello-war", Box::new(MyMsg("world 80")))
2285            .expect("whoops!");
2286
2287        r.insert("hello-wares", Box::new(MyMsg("world 80")))
2288            .expect("whoops!");
2289        r.insert("hello", Box::new(MyMsg("world 100")))
2290            .expect("whoops!");
2291
2292        {
2293            match r.find("hello") {
2294                Some(v) => println!("Found {}", v.0),
2295                None => println!("Not Found"),
2296            }
2297        }
2298
2299        r.show();
2300
2301        r.iter(|_, iter| {
2302            if !iter.seek_min() {
2303                return;
2304            }
2305            while iter.forward() {
2306                println!("{}", iter.key());
2307            }
2308            if !iter.seek_max() {
2309                return;
2310            }
2311            while iter.back() {
2312                println!("{}", iter.key());
2313            }
2314        });
2315    }
2316
2317    #[test]
2318    fn key_f64() {
2319        println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<f64, MyMsg>>());
2320
2321        let mut r = RaxMap::<f64, MyMsg>::new();
2322
2323        r.insert(100.01, Box::new(MyMsg("world 100")))
2324            .expect("whoops!");
2325        r.insert(80.20, Box::new(MyMsg("world 80")))
2326            .expect("whoops!");
2327        r.insert(100.00, Box::new(MyMsg("world 200")))
2328            .expect("whoops!");
2329        r.insert(99.10, Box::new(MyMsg("world 1")))
2330            .expect("whoops!");
2331
2332        r.show();
2333
2334        r.iter(|_, iter| {
2335            //            for (k, v) in iter {
2336            //
2337            //            }
2338            iter.seek_min();
2339            while iter.forward() {
2340                println!("{}", iter.key());
2341            }
2342            iter.seek_max();
2343            while iter.back() {
2344                println!("{}", iter.key());
2345            }
2346        });
2347    }
2348
2349    #[test]
2350    fn key_u64() {
2351        println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<u64, MyMsg>>());
2352
2353        let mut r = RaxMap::<u64, MyMsg>::new();
2354
2355        r.insert(100, Box::new(MyMsg("world 100")))
2356            .expect("whoops!");
2357        r.insert(80, Box::new(MyMsg("world 80"))).expect("whoops!");
2358        r.insert(200, Box::new(MyMsg("world 200")))
2359            .expect("whoops!");
2360        r.insert(1, Box::new(MyMsg("world 1"))).expect("whoops!");
2361
2362        r.show();
2363
2364        //        let result = r.iter_result(move |it| {
2365        //
2366        //            if !it.seek(GREATER_EQUAL, 800) {
2367        //                println!("Not Found");
2368        //                return Ok("");
2369        //            }
2370        //
2371        //            if it.eof() {
2372        //                println!("Not Found");
2373        //                return Ok("");
2374        //            }
2375        //
2376        //            while it.forward() {
2377        //                println!("Key Len = {}", it.key());
2378        //                println!("Data = {}", it.data().unwrap().0);
2379        //            }
2380        //
2381        //            Ok("")
2382        //        });
2383
2384        //        r.seek(GREATER_EQUAL, 80, |_, iter| {
2385        //            for (key, value) in iter {
2386        //                println!("Key Len = {}", key);
2387        //                println!("Data = {}", value.unwrap().0);
2388        //            }
2389        //        });
2390
2391        //        r.seek_result(GREATER_EQUAL, 80, |_, iter| {
2392        //            for (key, value) in iter {
2393        //                println!("Key Len = {}", key);
2394        //                println!("Data = {}", value.unwrap().0);
2395        //            }
2396        //            Ok(())
2397        //        });
2398
2399        r.seek_min(|_, it| {
2400            for (key, value) in it.rev() {
2401                println!("Key Len = {}", key);
2402                println!("Data = {}", value.unwrap().0);
2403            }
2404        });
2405
2406        //        r.iter(move |it| {
2407        //            if !it.seek(GREATER_EQUAL, 800) {
2408        //                println!("Not Found");
2409        //                return;
2410        //            }
2411        //
2412        //
2413        //
2414        //            while it.forward() {
2415        //                println!("Key Len = {}", it.key());
2416        //                println!("Data = {}", it.data().unwrap().0);
2417        //            }
2418        //        });
2419
2420        //        let result = r.iter_apply(move |r, it| {
2421        //            if !it.seek(GREATER_EQUAL, 800) {
2422        //                println!("Out of Memory");
2423        //                return Ok("");
2424        //            }
2425        //
2426        //            r.insert(800, Box::new(MyMsg("moved")));
2427        //            it.seek(GREATER_EQUAL, 800);
2428        //
2429        //            if it.eof() {
2430        //                println!("Not Found");
2431        //                return Ok("");
2432        //            }
2433        //
2434        //            while it.back() {
2435        //                println!("Key Len = {}", it.key());
2436        //                println!("Data = {}", it.data().unwrap().0);
2437        //            }
2438        //
2439        //            Ok("")
2440        //        });
2441    }
2442}