1#![allow(dead_code)]
2#![feature(test)]
3
4extern 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
88pub 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
96pub 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
121pub 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 raxFreeWithCallback(self.rax, RaxFreeWithCallbackWrapper::<V>);
209 }
210 }
211}
212
213impl<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 pub fn len(&self) -> u64 {
226 unsafe { raxSize(self.rax) }
227 }
228
229 pub fn size(&self) -> u64 {
231 unsafe { raxSize(self.rax) }
232 }
233
234 pub fn show(&self) {
236 unsafe { raxShow(self.rax) }
237 }
238
239 pub fn insert_null(&mut self, key: K) -> Result<Option<Box<V>>, RaxError> {
241 unsafe {
242 let old: &mut *mut u8 = &mut ptr::null_mut();
244
245 let k = key.encode();
249 let (ptr, len) = k.to_buf();
250
251 let r = raxInsert(
252 self.rax,
253 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 Ok(Some(Box::from_raw(*old as *mut V)))
272 }
273 }
274 }
275
276 pub fn try_insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
278 unsafe {
279 let old: &mut *mut u8 = &mut ptr::null_mut();
281
282 let value: &mut V = Box::leak(data);
286
287 let k = key.encode();
291 let (ptr, len) = k.to_buf();
292
293 let r = raxTryInsert(
294 self.rax,
295 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 Ok(Some(Box::from_raw(*old as *mut V)))
317 }
318 }
319 }
320
321 pub unsafe fn try_insert_ptr(&mut self, key: K, value: *mut u8) -> Result<Option<*mut u8>, RaxError> {
323 let old: &mut *mut u8 = &mut ptr::null_mut();
325
326 let k = key.encode();
330 let (ptr, len) = k.to_buf();
331
332 let r = raxTryInsert(
333 self.rax,
334 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 Ok(Some(*old))
356 }
357 }
358
359 pub fn insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
362 unsafe {
363 let old: &mut *mut u8 = &mut ptr::null_mut();
365
366 let value: &mut V = Box::leak(data);
370
371 let k = key.encode();
375 let (ptr, len) = k.to_buf();
376
377 let r = raxInsert(
378 self.rax,
379 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 Ok(Some(Box::from_raw(*old as *mut V)))
398 }
399 }
400 }
401
402 pub unsafe fn insert_ptr(&mut self, key: K, value: *mut u8) -> Result<Option<*mut u8>, RaxError> {
404 let old: &mut *mut u8 = &mut ptr::null_mut();
406
407 let k = key.encode();
411 let (ptr, len) = k.to_buf();
412
413 let r = raxInsert(
414 self.rax,
415 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 Ok(Some(*old))
434 }
435 }
436
437 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 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 (true, Some(transmute(value)))
484 }
485 }
486 }
487
488 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 Some(std::mem::transmute(value))
507 }
508 }
509 }
510
511 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 Some(std::mem::transmute(value))
532 }
533 }
534 }
535
536 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 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
569 raxStart(&iter as *const _ as *const raxIterator, self.rax);
573 iter.seek_min();
574 f(self, &mut iter)
576 }
577 }
578
579 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
593 raxStart(&iter as *const _ as *const raxIterator, self.rax);
597 iter.seek_min();
598 f(self, &mut iter)
600 }
601 }
602
603 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
616 raxStart(&iter as *const _ as *const raxIterator, self.rax);
620 iter.seek_max();
621 f(self, &mut iter)
623 }
624 }
625
626 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
640 raxStart(&iter as *const _ as *const raxIterator, self.rax);
644 iter.seek_max();
645 f(self, &mut iter)
647 }
648 }
649
650 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
665 raxStart(&iter as *const _ as *const raxIterator, self.rax);
669 iter.seek(op, key);
670 f(self, &mut iter)
672 }
673 }
674
675 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
691 raxStart(&iter as *const _ as *const raxIterator, self.rax);
695 iter.seek(op, key);
696 f(self, &mut iter)
698 }
699 }
700
701 #[inline]
703 pub fn iter<F>(&mut self, f: F) where F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) {
704 unsafe {
705 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
707 raxStart(&iter as *const _ as *const raxIterator, self.rax);
711 f(self, &mut iter)
713 }
714 }
715
716 #[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 let mut iter: RaxIterator<K, V> = std::mem::uninitialized();
726 raxStart(&iter as *const _ as *const raxIterator, self.rax);
730 f(self, &mut iter)
732 }
733 }
734}
735
736
737pub 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 raxFree(self.rax)
791 }
792 }
793}
794
795
796impl<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 #[inline]
807 pub fn len(&self) -> u64 {
808 unsafe { raxSize(self.rax) }
809 }
810
811 #[inline]
813 pub fn size(&self) -> u64 {
814 unsafe { raxSize(self.rax) }
815 }
816
817 #[inline]
819 pub fn show(&self) {
820 unsafe { raxShow(self.rax) }
821 }
822
823 pub fn insert(&mut self, key: K) -> Result<bool, RaxError> {
826 unsafe {
827 let k = key.encode();
831 let (ptr, len) = k.to_buf();
832
833 let r = raxTryInsert(
834 self.rax,
835 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 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 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
902 raxStart(&iter as *const _ as *const raxIterator, self.rax);
906 iter.seek_min();
907 f(self, &mut iter)
909 }
910 }
911
912 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
926 raxStart(&iter as *const _ as *const raxIterator, self.rax);
930 iter.seek_min();
931 f(self, &mut iter)
933 }
934 }
935
936 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
949 raxStart(&iter as *const _ as *const raxIterator, self.rax);
953 iter.seek_max();
954 f(self, &mut iter)
956 }
957 }
958
959 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
973 raxStart(&iter as *const _ as *const raxIterator, self.rax);
977 iter.seek_max();
978 f(self, &mut iter)
980 }
981 }
982
983 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
998 raxStart(&iter as *const _ as *const raxIterator, self.rax);
1002 iter.seek(op, key);
1003 f(self, &mut iter)
1005 }
1006 }
1007
1008 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
1024 raxStart(&iter as *const _ as *const raxIterator, self.rax);
1028 iter.seek(op, key);
1029 f(self, &mut iter)
1031 }
1032 }
1033
1034 #[inline]
1036 pub fn iter<F>(&mut self, f: F) where F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) {
1037 unsafe {
1038 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
1040 raxStart(&iter as *const _ as *const raxIterator, self.rax);
1044 f(self, &mut iter)
1046 }
1047 }
1048
1049 #[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 let mut iter: RaxIterator<K, usize> = std::mem::uninitialized();
1059 raxStart(&iter as *const _ as *const raxIterator, self.rax);
1063 f(self, &mut iter)
1065 }
1066 }
1067}
1068
1069
1070pub 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 self.to_bits().to_be()
1182 }
1183
1184 #[inline]
1185 fn to_buf(&self) -> (*const u8, usize) {
1186 (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 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 self.to_bits().to_be()
1213 }
1214
1215 #[inline]
1216 fn to_buf(&self) -> (*const u8, usize) {
1217 (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 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
1495impl<'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
1552impl<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
1561impl<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
1586impl<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
1609impl<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 #[inline]
1672 pub fn key(&self) -> K {
1673 K::from_buf(self.key, self.key_len as usize)
1674 }
1675
1676 #[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 #[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 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 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 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 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::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();
2297let 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();
2312let 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 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 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| {
2429iter.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
2469r.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}
2547}