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