rax/
lib.rs

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