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