1#![cfg_attr(test, feature(test))]
2
3extern crate libc;
68extern crate nix;
69
70use std::{
71 error, fmt,
72 mem::{size_of, MaybeUninit},
73 ptr,
74};
75
76use nix::errno::Errno;
77
78pub const GREATER: &str = ">";
79pub const GREATER_EQUAL: &str = ">=";
80pub const LESSER: &str = "<";
81pub const LESSER_EQUAL: &str = "<=";
82pub const EQUAL: &str = "=";
83pub const BEGIN: &str = "^";
84pub const END: &str = "$";
85
86pub const RAX_NODE_MAX_SIZE: libc::c_int = (1 << 29) - 1;
87pub const RAX_STACK_STATIC_ITEMS: libc::c_int = 32;
88pub const RAX_ITER_STATIC_LEN: libc::c_int = 128;
89pub const RAX_ITER_JUST_SEEKED: libc::c_int = 1 << 0;
90pub const RAX_ITER_EOF: libc::c_int = 1 << 1;
91pub const RAX_ITER_SAFE: libc::c_int = 1 << 2;
92
93pub unsafe fn allocator() -> (
99 extern "C" fn(size: libc::size_t) -> *mut u8,
100 extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8,
101 extern "C" fn(ptr: *mut libc::c_void),
102) {
103 (rax_malloc, rax_realloc, rax_free)
104}
105
106pub unsafe fn set_allocator(
115 malloc: extern "C" fn(size: libc::size_t) -> *mut u8,
116 realloc: extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8,
117 free: extern "C" fn(ptr: *mut libc::c_void),
118) {
119 rax_malloc = malloc;
120 rax_realloc = realloc;
121 rax_free = free;
122}
123
124#[derive(Debug)]
125pub enum RaxError {
126 Generic(GenericError),
127 OutOfMemory(),
128}
129
130impl RaxError {
131 pub fn generic(message: &str) -> RaxError {
132 RaxError::Generic(GenericError::new(message))
133 }
134}
135
136pub struct RaxMap<K: RaxKey, V> {
216 pub rax: *mut rax,
217 phantom: std::marker::PhantomData<(K, V)>,
218}
219
220impl<K: RaxKey, V> Drop for RaxMap<K, V> {
221 fn drop(&mut self) {
222 unsafe {
226 raxFreeWithCallback(self.rax, RaxFreeWithCallbackWrapper::<V>);
227 }
228 }
229}
230
231unsafe impl<K: RaxKey + Send, V: Send> Send for RaxMap<K, V> {}
234
235unsafe impl<K: RaxKey + Sync, V: Sync> Sync for RaxMap<K, V> {}
238
239impl<K: RaxKey, V> Default for RaxMap<K, V> {
240 fn default() -> Self {
241 Self::new()
242 }
243}
244
245impl<K: RaxKey, V> RaxMap<K, V> {
247 pub fn new() -> Self {
253 match Self::try_new() {
254 Ok(r) => r,
255 Err(_) => panic!("raxNew: out of memory"),
256 }
257 }
258
259 pub fn try_new() -> Result<RaxMap<K, V>, RaxError> {
263 let ptr = unsafe { raxNew() };
266
267 if ptr.is_null() {
268 return Err(RaxError::OutOfMemory());
269 }
270
271 Ok(RaxMap {
272 rax: ptr,
273 phantom: std::marker::PhantomData,
274 })
275 }
276
277 pub fn len(&self) -> u64 {
279 unsafe { raxSize(self.rax) }
280 }
281
282 pub fn size(&self) -> u64 {
284 unsafe { raxSize(self.rax) }
285 }
286
287 pub fn is_empty(&self) -> bool {
289 self.len() == 0
290 }
291
292 pub fn show(&self) {
294 unsafe { raxShow(self.rax) }
295 }
296
297 pub fn insert_null(&mut self, key: K) -> Result<Option<Box<V>>, RaxError> {
299 unsafe {
300 let old: &mut *mut u8 = &mut ptr::null_mut();
302
303 let k = key.encode();
307 let (ptr, len) = k.to_buf();
308
309 let r = raxInsert(
310 self.rax,
311 ptr,
316 len,
317 std::ptr::null_mut(),
318 old,
319 );
320
321 if r == 0 && Errno::last() == Errno::ENOMEM {
322 Err(RaxError::OutOfMemory())
323 } else if old.is_null() {
324 Ok(None)
325 } else {
326 Ok(Some(Box::from_raw(*old as *mut V)))
330 }
331 }
332 }
333
334 pub fn try_insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
336 unsafe {
337 let old: &mut *mut u8 = &mut ptr::null_mut();
339
340 let value: &mut V = Box::leak(data);
344
345 let k = key.encode();
349 let (ptr, len) = k.to_buf();
350
351 let r = raxTryInsert(
352 self.rax,
353 ptr,
358 len,
359 value as *mut V as *mut u8,
360 old,
361 );
362
363 if r == 0 {
364 if Errno::last() == Errno::ENOMEM {
365 Err(RaxError::OutOfMemory())
366 } else {
367 Ok(Some(Box::from_raw(value as *mut V)))
368 }
369 } else if old.is_null() {
370 Ok(None)
371 } else {
372 Ok(Some(Box::from_raw(*old as *mut V)))
375 }
376 }
377 }
378
379 pub unsafe fn try_insert_ptr(
385 &mut self,
386 key: K,
387 value: *mut u8,
388 ) -> Result<Option<*mut u8>, RaxError> {
389 let old: &mut *mut u8 = &mut ptr::null_mut();
391
392 let k = key.encode();
396 let (ptr, len) = k.to_buf();
397
398 let r = raxTryInsert(
399 self.rax,
400 ptr, len, value, old,
405 );
406
407 if r == 0 {
408 if Errno::last() == Errno::ENOMEM {
409 Err(RaxError::OutOfMemory())
410 } else {
411 Ok(Some(value))
412 }
413 } else if old.is_null() {
414 Ok(None)
415 } else {
416 Ok(Some(*old))
419 }
420 }
421
422 pub fn insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
425 unsafe {
426 let old: &mut *mut u8 = &mut ptr::null_mut();
428
429 let value: &mut V = Box::leak(data);
433
434 let k = key.encode();
438 let (ptr, len) = k.to_buf();
439
440 let r = raxInsert(
441 self.rax,
442 ptr,
447 len,
448 value as *mut V as *mut u8,
449 old,
450 );
451
452 if r == 0 && Errno::last() == Errno::ENOMEM {
453 Err(RaxError::OutOfMemory())
454 } else if old.is_null() {
455 Ok(None)
456 } else {
457 Ok(Some(Box::from_raw(*old as *mut V)))
461 }
462 }
463 }
464
465 pub unsafe fn insert_ptr(
471 &mut self,
472 key: K,
473 value: *mut u8,
474 ) -> Result<Option<*mut u8>, RaxError> {
475 let old: &mut *mut u8 = &mut ptr::null_mut();
477
478 let k = key.encode();
482 let (ptr, len) = k.to_buf();
483
484 let r = raxInsert(
485 self.rax,
486 ptr, len, value, old,
491 );
492
493 if r == 0 && Errno::last() == Errno::ENOMEM {
494 Err(RaxError::OutOfMemory())
495 } else if old.is_null() {
496 Ok(None)
497 } else {
498 Ok(Some(*old))
502 }
503 }
504
505 pub fn remove(&mut self, key: K) -> (bool, Option<Box<V>>) {
507 unsafe {
508 let old: &mut *mut u8 = &mut ptr::null_mut();
509 let k = key.encode();
510 let (ptr, len) = k.to_buf();
511
512 let r = raxRemove(self.rax, ptr, len, old);
513
514 if old.is_null() {
515 (r == 1, None)
516 } else {
517 (r == 1, Some(Box::from_raw(*old as *mut V)))
518 }
519 }
520 }
521
522 pub fn find_exists(&self, key: K) -> (bool, Option<&V>) {
524 unsafe {
525 let k = key.encode();
526 let (ptr, len) = k.to_buf();
527
528 let value = raxFind(self.rax, ptr, len);
529
530 if value.is_null() {
531 (true, None)
532 } else if value == raxNotFound {
533 (false, None)
534 } else {
535 (true, Some(&*(value as *const V)))
539 }
540 }
541 }
542
543 pub fn find(&self, key: K) -> Option<&V> {
545 unsafe {
546 let k = key.encode();
547 let (ptr, len) = k.to_buf();
548
549 let value = raxFind(self.rax, ptr, len);
550
551 if value.is_null() || value == raxNotFound {
552 None
553 } else {
554 Some(&*(value as *const V))
558 }
559 }
560 }
561
562 pub fn get(&self, key: K) -> Option<&V> {
564 unsafe {
565 let k = key.encode();
566 let (ptr, len) = k.to_buf();
567
568 let value = raxFind(self.rax, ptr, len);
569
570 if value.is_null() || value == raxNotFound {
571 None
572 } else {
573 Some(&*(value as *const V))
577 }
578 }
579 }
580
581 pub fn exists(&self, key: K) -> bool {
583 unsafe {
584 let k = key.encode();
585 let (ptr, len) = k.to_buf();
586
587 let value = raxFind(self.rax, ptr, len);
588
589 !(value.is_null() || value == raxNotFound)
590 }
591 }
592
593 pub fn seek_min<F>(&mut self, f: F)
599 where
600 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
601 {
602 unsafe {
604 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
605 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
606 let mut iter = iter.assume_init();
607 iter.fixup();
608 iter.seek_min();
609 f(self, &mut iter)
610 }
611 }
612
613 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
619 where
620 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
621 {
622 unsafe {
624 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
625 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
626 let mut iter = iter.assume_init();
627 iter.fixup();
628 iter.seek_min();
629 f(self, &mut iter)
630 }
631 }
632
633 pub fn seek_max<F>(&mut self, f: F)
639 where
640 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
641 {
642 unsafe {
644 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
645 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
646 let mut iter = iter.assume_init();
647 iter.fixup();
648 iter.seek_max();
649 f(self, &mut iter)
650 }
651 }
652
653 pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
659 where
660 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
661 {
662 unsafe {
664 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
665 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
666 let mut iter = iter.assume_init();
667 iter.fixup();
668 iter.seek_max();
669 f(self, &mut iter)
670 }
671 }
672
673 pub fn seek<F>(&mut self, op: &str, key: K, f: F)
679 where
680 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
681 {
682 unsafe {
684 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
685 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
686 let mut iter = iter.assume_init();
687 iter.fixup();
688 iter.seek(op, key);
689 f(self, &mut iter)
690 }
691 }
692
693 pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
699 where
700 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
701 {
702 unsafe {
704 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
705 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
706 let mut iter = iter.assume_init();
707 iter.fixup();
708 iter.seek(op, key);
709 f(self, &mut iter)
710 }
711 }
712
713 pub fn iter<F>(&mut self, f: F)
719 where
720 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
721 {
722 unsafe {
724 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
725 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
726 let mut iter = iter.assume_init();
727 iter.fixup();
728 f(self, &mut iter)
729 }
730 }
731
732 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
738 where
739 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
740 {
741 unsafe {
743 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
744 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
745 let mut iter = iter.assume_init();
746 iter.fixup();
747 f(self, &mut iter)
748 }
749 }
750
751 pub fn clear(&mut self) {
753 if self.is_empty() {
754 return;
755 }
756
757 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
758
759 unsafe { raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax) };
761
762 let mut iter = unsafe { iter.assume_init() };
764 iter.fixup();
765
766 while !self.is_empty() {
767 if !iter.seek_min() || iter.eof() {
768 break;
769 }
770
771 let mut old: *mut u8 = std::ptr::null_mut();
772
773 unsafe {
775 raxRemove(self.rax, iter.key, iter.key_len, &mut old);
776 }
777
778 if !old.is_null() {
779 drop(unsafe { Box::from_raw(old as *mut V) });
781 }
782 }
783 }
784}
785
786pub struct RaxSet<K: RaxKey> {
832 rax: *mut rax,
833 _marker: std::marker::PhantomData<K>,
834}
835
836impl<K: RaxKey> Drop for RaxSet<K> {
837 fn drop(&mut self) {
838 unsafe { raxFree(self.rax) }
840 }
841}
842
843unsafe impl<K: RaxKey + Send> Send for RaxSet<K> {}
846
847unsafe impl<K: RaxKey + Sync> Sync for RaxSet<K> {}
850
851impl<K: RaxKey> Default for RaxSet<K> {
852 fn default() -> Self {
853 Self::new()
854 }
855}
856
857impl<K: RaxKey> RaxSet<K> {
859 pub fn new() -> Self {
865 match Self::try_new() {
866 Ok(r) => r,
867 Err(_) => panic!("raxNew: out of memory"),
868 }
869 }
870
871 pub fn try_new() -> Result<RaxSet<K>, RaxError> {
875 let ptr = unsafe { raxNew() };
878
879 if ptr.is_null() {
880 return Err(RaxError::OutOfMemory());
881 }
882
883 Ok(RaxSet {
884 rax: ptr,
885 _marker: std::marker::PhantomData,
886 })
887 }
888
889 pub fn len(&self) -> u64 {
891 unsafe { raxSize(self.rax) }
892 }
893
894 pub fn size(&self) -> u64 {
896 unsafe { raxSize(self.rax) }
897 }
898
899 pub fn show(&self) {
901 unsafe { raxShow(self.rax) }
902 }
903
904 pub fn is_empty(&self) -> bool {
906 self.len() == 0
907 }
908
909 pub fn insert(&mut self, key: K) -> Result<bool, RaxError> {
912 unsafe {
913 let k = key.encode();
917 let (ptr, len) = k.to_buf();
918
919 let r = raxTryInsert(
920 self.rax,
921 ptr,
926 len,
927 std::ptr::null_mut(),
928 std::ptr::null_mut(),
929 );
930
931 if r == 0 {
932 if Errno::last() == Errno::ENOMEM {
933 Err(RaxError::OutOfMemory())
934 } else {
935 Ok(false)
936 }
937 } else {
938 Ok(true)
939 }
940 }
941 }
942
943 pub fn remove(&mut self, key: K) -> bool {
944 unsafe {
945 let k = key.encode();
946 let (ptr, len) = k.to_buf();
947
948 let r = raxRemove(self.rax, ptr, len, &mut std::ptr::null_mut());
949
950 r == 1
951 }
952 }
953
954 pub fn exists(&self, key: K) -> bool {
956 unsafe {
957 let k = key.encode();
958 let (ptr, len) = k.to_buf();
959
960 let value = raxFind(self.rax, ptr, len);
961
962 value != raxNotFound
963 }
964 }
965
966 pub fn seek_min<F>(&mut self, f: F)
972 where
973 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
974 {
975 unsafe {
977 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
978 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
979 let mut iter = iter.assume_init();
980 iter.fixup();
981 iter.seek_min();
982 f(self, &mut iter)
983 }
984 }
985
986 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
992 where
993 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
994 {
995 unsafe {
997 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
998 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
999 let mut iter = iter.assume_init();
1000 iter.fixup();
1001 iter.seek_min();
1002 f(self, &mut iter)
1003 }
1004 }
1005
1006 pub fn seek_max<F>(&mut self, f: F)
1012 where
1013 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1014 {
1015 unsafe {
1017 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1018 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1019 let mut iter = iter.assume_init();
1020 iter.fixup();
1021 iter.seek_max();
1022 f(self, &mut iter)
1023 }
1024 }
1025
1026 pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
1032 where
1033 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1034 {
1035 unsafe {
1037 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1038 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1039 let mut iter = iter.assume_init();
1040 iter.fixup();
1041 iter.seek_max();
1042 f(self, &mut iter)
1043 }
1044 }
1045
1046 pub fn seek<F>(&mut self, op: &str, key: K, f: F)
1052 where
1053 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1054 {
1055 unsafe {
1057 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1058 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1059 let mut iter = iter.assume_init();
1060 iter.fixup();
1061 iter.seek(op, key);
1062 f(self, &mut iter)
1063 }
1064 }
1065
1066 pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
1072 where
1073 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1074 {
1075 unsafe {
1077 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1078 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1079 let mut iter = iter.assume_init();
1080 iter.fixup();
1081 iter.seek(op, key);
1082 f(self, &mut iter)
1083 }
1084 }
1085
1086 pub fn iter<F>(&mut self, f: F)
1092 where
1093 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1094 {
1095 unsafe {
1097 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1098 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1099 let mut iter = iter.assume_init();
1100 iter.fixup();
1101 f(self, &mut iter)
1102 }
1103 }
1104
1105 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
1111 where
1112 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1113 {
1114 unsafe {
1116 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1117 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1118 let mut iter = iter.assume_init();
1119 iter.fixup();
1120 f(self, &mut iter)
1121 }
1122 }
1123
1124 pub fn clear(&mut self) {
1126 if self.is_empty() {
1127 return;
1128 }
1129
1130 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1131
1132 unsafe { raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax) };
1134
1135 let mut iter = unsafe { iter.assume_init() };
1137 iter.fixup();
1138
1139 while !self.is_empty() {
1140 if !iter.seek_min() || iter.eof() {
1141 break;
1142 }
1143
1144 let mut old: *mut u8 = std::ptr::null_mut();
1145
1146 unsafe {
1148 raxRemove(self.rax, iter.key, iter.key_len, &mut old);
1149 }
1150 }
1151 }
1152}
1153
1154pub trait RaxKey<RHS = Self>: Clone + Default + std::fmt::Debug {
1249 type Output: RaxKey;
1250
1251 fn encode(self) -> Self::Output;
1252
1253 fn to_buf(&self) -> (*const u8, usize);
1254
1255 unsafe fn from_buf(ptr: *const u8, len: usize) -> RHS;
1259}
1260
1261impl RaxKey for f32 {
1262 type Output = u32;
1263
1264 fn encode(self) -> Self::Output {
1265 self.to_bits().to_be()
1267 }
1268
1269 fn to_buf(&self) -> (*const u8, usize) {
1270 (
1272 self as *const _ as *const u8,
1273 std::mem::size_of::<Self::Output>(),
1274 )
1275 }
1276
1277 unsafe fn from_buf(ptr: *const u8, len: usize) -> f32 {
1278 assert_eq!(len, std::mem::size_of::<f32>());
1279 if len != size_of::<Self::Output>() {
1280 return Self::default();
1281 }
1282 unsafe {
1283 f32::from_bits(u32::from_be(
1285 *(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32),
1286 ))
1287 }
1288 }
1289}
1290
1291impl RaxKey for f64 {
1292 type Output = u64;
1293
1294 fn encode(self) -> Self::Output {
1295 self.to_bits().to_be()
1297 }
1298
1299 fn to_buf(&self) -> (*const u8, usize) {
1300 (self as *const _ as *const u8, size_of::<Self::Output>())
1302 }
1303
1304 unsafe fn from_buf(ptr: *const u8, len: usize) -> f64 {
1305 assert_eq!(len, std::mem::size_of::<f64>());
1306 if len != size_of::<Self::Output>() {
1307 return Self::default();
1308 }
1309 unsafe {
1310 f64::from_bits(u64::from_be(
1312 *(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64),
1313 ))
1314 }
1315 }
1316}
1317
1318impl RaxKey for isize {
1319 type Output = isize;
1320
1321 fn encode(self) -> Self::Output {
1322 self.to_be()
1323 }
1324
1325 fn to_buf(&self) -> (*const u8, usize) {
1326 (self as *const _ as *const u8, size_of::<Self::Output>())
1327 }
1328
1329 unsafe fn from_buf(ptr: *const u8, len: usize) -> isize {
1330 assert_eq!(len, std::mem::size_of::<isize>());
1331 if len != size_of::<Self::Output>() {
1332 return Self::default();
1333 }
1334 unsafe { isize::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut isize)) }
1335 }
1336}
1337
1338impl RaxKey for usize {
1339 type Output = usize;
1340
1341 fn encode(self) -> Self::Output {
1342 self.to_be()
1343 }
1344
1345 fn to_buf(&self) -> (*const u8, usize) {
1346 (
1347 self as *const _ as *const u8,
1348 std::mem::size_of::<Self::Output>(),
1349 )
1350 }
1351
1352 unsafe fn from_buf(ptr: *const u8, len: usize) -> usize {
1353 assert_eq!(len, std::mem::size_of::<usize>());
1354 if len != size_of::<Self::Output>() {
1355 return Self::default();
1356 }
1357 unsafe {
1358 usize::from_be(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut usize))
1359 }
1360 }
1361}
1362
1363impl RaxKey for i16 {
1364 type Output = i16;
1365
1366 fn encode(self) -> Self::Output {
1367 self.to_be()
1368 }
1369
1370 fn to_buf(&self) -> (*const u8, usize) {
1371 (self as *const _ as *const u8, size_of::<Self::Output>())
1372 }
1373
1374 unsafe fn from_buf(ptr: *const u8, len: usize) -> Self {
1375 if len != size_of::<Self::Output>() {
1376 return Self::default();
1377 }
1378 unsafe { i16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i16)) }
1379 }
1380}
1381
1382impl RaxKey for u16 {
1383 type Output = u16;
1384
1385 fn encode(self) -> Self::Output {
1386 self.to_be()
1387 }
1388
1389 fn to_buf(&self) -> (*const u8, usize) {
1390 (self as *const _ as *const u8, size_of::<Self::Output>())
1391 }
1392
1393 unsafe fn from_buf(ptr: *const u8, len: usize) -> u16 {
1394 assert_eq!(len, std::mem::size_of::<u16>());
1395 if len != size_of::<Self::Output>() {
1396 return Self::default();
1397 }
1398 unsafe { u16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u16)) }
1399 }
1400}
1401
1402impl RaxKey for i32 {
1403 type Output = i32;
1404
1405 fn encode(self) -> Self::Output {
1406 self.to_be()
1407 }
1408
1409 fn to_buf(&self) -> (*const u8, usize) {
1410 (self as *const _ as *const u8, size_of::<Self::Output>())
1411 }
1412
1413 unsafe fn from_buf(ptr: *const u8, len: usize) -> i32 {
1414 assert_eq!(len, std::mem::size_of::<i32>());
1415 if len != size_of::<Self::Output>() {
1416 return Self::default();
1417 }
1418 unsafe { i32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i32)) }
1419 }
1420}
1421
1422impl RaxKey for u32 {
1423 type Output = u32;
1424
1425 fn encode(self) -> Self::Output {
1426 self.to_be()
1427 }
1428
1429 fn to_buf(&self) -> (*const u8, usize) {
1430 (self as *const _ as *const u8, size_of::<Self::Output>())
1431 }
1432
1433 unsafe fn from_buf(ptr: *const u8, len: usize) -> u32 {
1434 assert_eq!(len, std::mem::size_of::<u32>());
1435 if len != size_of::<Self::Output>() {
1436 return Self::default();
1437 }
1438 unsafe { u32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u32)) }
1439 }
1440}
1441
1442impl RaxKey for i64 {
1443 type Output = i64;
1444
1445 fn encode(self) -> Self::Output {
1446 self.to_be()
1447 }
1448
1449 fn to_buf(&self) -> (*const u8, usize) {
1450 (self as *const _ as *const u8, size_of::<Self::Output>())
1451 }
1452
1453 unsafe fn from_buf(ptr: *const u8, len: usize) -> i64 {
1454 assert_eq!(len, std::mem::size_of::<i64>());
1455 if len != size_of::<Self::Output>() {
1456 return Self::default();
1457 }
1458 unsafe { i64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i64)) }
1459 }
1460}
1461
1462impl RaxKey for u64 {
1463 type Output = u64;
1464
1465 fn encode(self) -> Self::Output {
1466 self.to_be()
1467 }
1468
1469 fn to_buf(&self) -> (*const u8, usize) {
1470 (self as *const _ as *const u8, size_of::<Self::Output>())
1471 }
1472
1473 unsafe fn from_buf(ptr: *const u8, len: usize) -> u64 {
1474 assert_eq!(len, std::mem::size_of::<u64>());
1475 if len != size_of::<Self::Output>() {
1476 return Self::default();
1477 }
1478 unsafe { u64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64)) }
1479 }
1480}
1481
1482impl RaxKey for i128 {
1483 type Output = i128;
1484
1485 fn encode(self) -> Self::Output {
1486 self.to_be()
1487 }
1488
1489 fn to_buf(&self) -> (*const u8, usize) {
1490 (self as *const _ as *const u8, size_of::<Self::Output>())
1491 }
1492
1493 unsafe fn from_buf(ptr: *const u8, len: usize) -> i128 {
1494 assert_eq!(len, std::mem::size_of::<i128>());
1495 if len != size_of::<Self::Output>() {
1496 return Self::default();
1497 }
1498 unsafe { i128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i128)) }
1499 }
1500}
1501
1502impl RaxKey for u128 {
1503 type Output = u128;
1504
1505 fn encode(self) -> Self::Output {
1506 self.to_be()
1507 }
1508
1509 fn to_buf(&self) -> (*const u8, usize) {
1510 (self as *const _ as *const u8, size_of::<Self::Output>())
1511 }
1512
1513 unsafe fn from_buf(ptr: *const u8, len: usize) -> u128 {
1514 assert_eq!(len, std::mem::size_of::<u128>());
1515 if len != size_of::<Self::Output>() {
1516 return Self::default();
1517 }
1518 unsafe { u128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u128)) }
1519 }
1520}
1521
1522impl RaxKey for Vec<u8> {
1523 type Output = Vec<u8>;
1524
1525 fn encode(self) -> Vec<u8> {
1526 self
1527 }
1528
1529 fn to_buf(&self) -> (*const u8, usize) {
1530 (self.as_ptr(), self.len())
1531 }
1532
1533 unsafe fn from_buf(ptr: *const u8, len: usize) -> Vec<u8> {
1534 unsafe { std::slice::from_raw_parts(ptr, len).to_vec() }
1535 }
1536}
1537
1538impl<'a> RaxKey for &'a [u8] {
1539 type Output = &'a [u8];
1540
1541 fn encode(self) -> &'a [u8] {
1542 self
1543 }
1544
1545 fn to_buf(&self) -> (*const u8, usize) {
1546 (self.as_ptr(), self.len())
1547 }
1548
1549 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a [u8] {
1550 unsafe { std::slice::from_raw_parts(ptr, len) }
1551 }
1552}
1553
1554impl<'a> RaxKey for &'a str {
1571 type Output = &'a str;
1572
1573 fn encode(self) -> Self::Output {
1574 self
1575 }
1576
1577 fn to_buf(&self) -> (*const u8, usize) {
1578 ((*self).as_ptr(), self.len())
1579 }
1580
1581 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a str {
1582 unsafe { std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap_or_default() }
1583 }
1584}
1585
1586#[repr(C)]
1587pub struct RaxIterator<K: RaxKey, V> {
1588 pub flags: libc::c_int,
1589 pub rt: *mut rax,
1590 pub key: *mut u8,
1591 pub data: *mut libc::c_void,
1592 pub key_len: libc::size_t,
1593 pub key_max: libc::size_t,
1594 pub key_static_string: [u8; 128],
1595 pub node: *mut raxNode,
1596 pub stack: raxStack,
1597 pub node_cb: Option<raxNodeCallback>,
1598 _marker: std::marker::PhantomData<(K, V)>,
1599}
1600
1601impl<K: RaxKey, V> Drop for RaxIterator<K, V> {
1603 fn drop(&mut self) {
1604 unsafe {
1605 if self.key_max == RAX_ITER_STATIC_LEN as usize {
1607 self.key = self.key_static_string.as_mut_ptr();
1608 }
1609
1610 if self.stack.maxitems == RAX_STACK_STATIC_ITEMS as usize {
1612 self.stack.stack = self.stack.static_items.as_mut_ptr();
1613 }
1614
1615 raxStop(&raw mut *self as *mut raxIterator);
1616 }
1617 }
1618}
1619
1620impl<K: RaxKey, V: 'static> Iterator for RaxIterator<K, V> {
1622 type Item = (K, Option<&'static V>);
1623
1624 fn next(&mut self) -> Option<<Self as Iterator>::Item> {
1625 unsafe {
1626 if raxNext(&raw mut *self as *mut raxIterator) == 1 {
1627 let data: *mut libc::c_void = self.data;
1628 if data.is_null() {
1629 None
1630 } else {
1631 let val = data as *const V;
1632 if val.is_null() {
1633 Some((self.key(), None))
1634 } else {
1635 Some((self.key(), Some(&*val)))
1636 }
1637 }
1638 } else {
1639 None
1640 }
1641 }
1642 }
1643}
1644
1645impl<K: RaxKey, V: 'static> DoubleEndedIterator for RaxIterator<K, V> {
1647 fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
1648 unsafe {
1649 if raxPrev(&raw mut *self as *mut raxIterator) == 1 {
1650 let data: *mut libc::c_void = self.data;
1651 if data.is_null() {
1652 None
1653 } else {
1654 let val = data as *const V;
1655 if val.is_null() {
1656 Some((self.key(), None))
1657 } else {
1658 Some((self.key(), Some(&*val)))
1659 }
1660 }
1661 } else {
1662 None
1663 }
1664 }
1665 }
1666}
1667
1668impl<K: RaxKey, V> RaxIterator<K, V> {
1670 pub fn new(r: RaxMap<K, V>) -> RaxIterator<K, V> {
1672 unsafe {
1674 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
1675 raxStart(iter.as_mut_ptr() as *mut raxIterator, r.rax);
1676 let mut iter = iter.assume_init();
1677 iter.fixup();
1678 iter
1679 }
1680 }
1681
1682 pub fn print_ptr(&self) {
1683 println!("ptr = {:p}", self);
1684 println!("ptr = {:p}", self as *const _ as *const raxIterator);
1685 }
1686
1687 pub fn seek_min(&mut self) -> bool {
1688 unsafe {
1689 if raxSeek(
1690 &raw mut *self as *mut raxIterator,
1691 BEGIN.as_ptr(),
1692 std::ptr::null(),
1693 0,
1694 ) == 1
1695 {
1696 self.forward()
1697 } else {
1698 false
1699 }
1700 }
1701 }
1702
1703 pub fn seek_max(&mut self) -> bool {
1704 unsafe {
1705 if raxSeek(
1706 &raw mut *self as *mut raxIterator,
1707 END.as_ptr(),
1708 std::ptr::null(),
1709 0,
1710 ) == 1
1711 {
1712 self.back()
1713 } else {
1714 false
1715 }
1716 }
1717 }
1718
1719 pub fn back(&mut self) -> bool {
1720 unsafe { raxPrev(&raw mut *self as *mut raxIterator) == 1 }
1721 }
1722
1723 pub fn forward(&mut self) -> bool {
1724 unsafe { raxNext(&raw mut *self as *mut raxIterator) == 1 }
1725 }
1726
1727 pub fn key(&self) -> K {
1729 unsafe { K::from_buf(self.key, self.key_len) }
1730 }
1731
1732 pub fn value(&self) -> Option<&V> {
1734 unsafe {
1735 let data: *mut libc::c_void = self.data;
1736 if data.is_null() {
1737 None
1738 } else {
1739 Some(&*(data as *const V))
1740 }
1741 }
1742 }
1743
1744 pub fn lesser(&mut self, key: K) -> bool {
1745 self.seek(LESSER, key)
1746 }
1747
1748 pub fn lesser_equal(&mut self, key: K) -> bool {
1749 self.seek(LESSER_EQUAL, key)
1750 }
1751
1752 pub fn greater(&mut self, key: K) -> bool {
1753 self.seek(GREATER, key)
1754 }
1755
1756 pub fn greater_equal(&mut self, key: K) -> bool {
1757 self.seek(GREATER_EQUAL, key)
1758 }
1759
1760 pub fn seek(&mut self, op: &str, key: K) -> bool {
1761 unsafe {
1762 let k = key.encode();
1763 let (p, len) = k.to_buf();
1764 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len) == 1
1765 && self.flags & RAX_ITER_EOF != 0
1766 }
1767 }
1768
1769 pub fn seek_raw(&mut self, op: &str, key: K) -> i32 {
1770 unsafe {
1771 let k = key.encode();
1772 let (p, len) = k.to_buf();
1773 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len)
1774 }
1775 }
1776
1777 pub fn seek_bytes(&mut self, op: &str, ele: &[u8]) -> bool {
1778 unsafe {
1779 raxSeek(
1780 &raw mut *self as *mut raxIterator,
1781 op.as_ptr(),
1782 ele.as_ptr(),
1783 ele.len() as libc::size_t,
1784 ) == 1
1785 }
1786 }
1787
1788 pub fn eof(&self) -> bool {
1793 self.flags & RAX_ITER_EOF != 0
1794 }
1795
1796 pub fn fixup(&mut self) {
1798 self.key = self.key_static_string.as_mut_ptr();
1799 self.stack.stack = self.stack.static_items.as_mut_ptr();
1800 }
1801}
1802
1803impl fmt::Display for RaxError {
1804 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1805 match *self {
1806 RaxError::Generic(ref err) => write!(f, "{err}"),
1807 RaxError::OutOfMemory() => write!(f, "out of memory"),
1808 }
1809 }
1810}
1811
1812impl error::Error for RaxError {
1813 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1814 match *self {
1815 RaxError::Generic(ref err) => Some(err),
1820 RaxError::OutOfMemory() => Some(self),
1821 }
1822 }
1823}
1824
1825#[derive(Debug)]
1826pub struct GenericError {
1827 message: String,
1828}
1829
1830impl GenericError {
1831 pub fn new(message: &str) -> GenericError {
1832 GenericError {
1833 message: String::from(message),
1834 }
1835 }
1836}
1837
1838impl fmt::Display for GenericError {
1839 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1840 write!(f, "Store error: {}", self.message)
1841 }
1842}
1843
1844impl error::Error for GenericError {}
1845
1846#[repr(C)]
1847pub struct rax;
1848
1849#[repr(C)]
1850pub struct raxNode;
1851
1852#[repr(C)]
1853pub struct raxStack {
1854 stack: *mut *mut libc::c_void,
1855 items: libc::size_t,
1856 maxitems: libc::size_t,
1857 static_items: [*mut libc::c_void; 32],
1858 oom: libc::c_int,
1859}
1860
1861#[repr(C)]
1862pub struct raxIterator;
1863
1864#[allow(non_snake_case)]
1865#[allow(non_camel_case_types)]
1866extern "C" fn RaxFreeWithCallbackWrapper<V>(v: *mut libc::c_void) {
1867 unsafe {
1868 drop(Box::from_raw(v as *mut V));
1870 }
1871}
1872
1873#[allow(non_camel_case_types)]
1874type raxNodeCallback = extern "C" fn(v: *mut libc::c_void);
1875
1876type RaxFreeCallback = extern "C" fn(v: *mut libc::c_void);
1877
1878#[allow(improper_ctypes)]
1879#[allow(non_snake_case)]
1880#[allow(non_camel_case_types)]
1881#[link(name = "rax", kind = "static")]
1882extern "C" {
1883 pub static raxNotFound: *mut u8;
1884
1885 pub static mut rax_malloc: extern "C" fn(size: libc::size_t) -> *mut u8;
1886 pub static mut rax_realloc:
1887 extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8;
1888 pub static mut rax_free: extern "C" fn(ptr: *mut libc::c_void);
1889
1890 pub fn raxIteratorSize() -> libc::c_int;
1891
1892 pub fn raxNew() -> *mut rax;
1893
1894 pub fn raxFree(rax: *mut rax);
1895
1896 pub fn raxFreeWithCallback(rax: *mut rax, callback: RaxFreeCallback);
1897
1898 pub fn raxInsert(
1899 rax: *mut rax,
1900 s: *const u8,
1901 len: libc::size_t,
1902 data: *const u8,
1903 old: &mut *mut u8,
1904 ) -> libc::c_int;
1905
1906 pub fn raxTryInsert(
1907 rax: *mut rax,
1908 s: *const u8,
1909 len: libc::size_t,
1910 data: *const u8,
1911 old: *mut *mut u8,
1912 ) -> libc::c_int;
1913
1914 pub fn raxRemove(
1915 rax: *mut rax,
1916 s: *const u8,
1917 len: libc::size_t,
1918 old: &mut *mut u8,
1919 ) -> libc::c_int;
1920
1921 pub fn raxFind(rax: *mut rax, s: *const u8, len: libc::size_t) -> *mut u8;
1922
1923 pub fn raxIteratorNew(rt: *mut rax) -> *mut raxIterator;
1924
1925 pub fn raxStart(it: *mut raxIterator, rt: *mut rax);
1926
1927 pub fn raxSeek(
1928 it: *mut raxIterator,
1929 op: *const u8,
1930 ele: *const u8,
1931 len: libc::size_t,
1932 ) -> libc::c_int;
1933
1934 pub fn raxNext(it: *mut raxIterator) -> libc::c_int;
1935
1936 pub fn raxPrev(it: *mut raxIterator) -> libc::c_int;
1937
1938 pub fn raxRandomWalk(it: *mut raxIterator, steps: libc::size_t) -> libc::c_int;
1939
1940 pub fn raxCompare(
1941 it: *mut raxIterator,
1942 op: *const u8,
1943 key: *mut u8,
1944 key_len: libc::size_t,
1945 ) -> libc::c_int;
1946
1947 pub fn raxStop(it: *mut raxIterator);
1948
1949 pub fn raxEOF(it: *mut raxIterator) -> libc::c_int;
1950
1951 pub fn raxShow(rax: *mut rax);
1952
1953 pub fn raxSize(rax: *mut rax) -> u64;
1954}
1955
1956#[cfg(test)]
1957mod tests {
1958 extern crate test;
1959 use std::{
1960 self,
1961 default::Default,
1962 fmt,
1963 time::{Duration, Instant},
1964 };
1965
1966 use super::*;
1967
1968 extern "C" fn rax_malloc_hook(size: libc::size_t) -> *mut u8 {
1969 unsafe {
1970 println!("malloc");
1971 libc::malloc(size) as *mut u8
1972 }
1973 }
1974
1975 extern "C" fn rax_realloc_hook(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8 {
1976 unsafe {
1977 println!("realloc");
1978 libc::realloc(ptr, size) as *mut u8
1979 }
1980 }
1981
1982 extern "C" fn rax_free_hook(ptr: *mut libc::c_void) {
1983 unsafe {
1984 println!("free");
1985 libc::free(ptr)
1986 }
1987 }
1988
1989 pub struct MyMsg<'a>(&'a str);
1990
1991 impl<'a> Drop for MyMsg<'a> {
1992 fn drop(&mut self) {
1993 println!("dropped -> {}", self.0);
1994 }
1995 }
1996
1997 #[derive(Clone, Copy)]
1998 pub struct Stopwatch {
1999 start_time: Option<Instant>,
2000 elapsed: Duration,
2001 }
2002
2003 impl Default for Stopwatch {
2004 fn default() -> Stopwatch {
2005 Stopwatch {
2006 start_time: None,
2007 elapsed: Duration::from_secs(0),
2008 }
2009 }
2010 }
2011
2012 impl fmt::Display for Stopwatch {
2013 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2014 return write!(f, "{}ms", self.elapsed_ms());
2015 }
2016 }
2017
2018 #[expect(unused)]
2019 impl Stopwatch {
2020 pub fn new() -> Stopwatch {
2021 let sw: Stopwatch = Default::default();
2022 return sw;
2023 }
2024 pub fn start_new() -> Stopwatch {
2025 let mut sw = Stopwatch::new();
2026 sw.start();
2027 return sw;
2028 }
2029
2030 pub fn start(&mut self) {
2031 self.start_time = Some(Instant::now());
2032 }
2033 pub fn stop(&mut self) {
2034 self.elapsed = self.elapsed();
2035 self.start_time = None;
2036 }
2037 pub fn reset(&mut self) {
2038 self.elapsed = Duration::from_secs(0);
2039 self.start_time = None;
2040 }
2041 pub fn restart(&mut self) {
2042 self.reset();
2043 self.start();
2044 }
2045
2046 pub fn is_running(&self) -> bool {
2047 return self.start_time.is_some();
2048 }
2049
2050 pub fn elapsed(&self) -> Duration {
2051 match self.start_time {
2052 Some(t1) => {
2053 return t1.elapsed() + self.elapsed;
2054 }
2055 None => {
2056 return self.elapsed;
2057 }
2058 }
2059 }
2060 pub fn elapsed_ms(&self) -> i64 {
2061 let dur = self.elapsed();
2062 return (dur.as_secs() * 1000 + (dur.subsec_nanos() / 1000000) as u64) as i64;
2063 }
2064 }
2065
2066 #[test]
2067 fn test_rax_map_clear() {
2068 let mut map = RaxMap::new();
2069 let _ = map.insert(1, Box::new("hello".to_string()));
2070 assert!(map.get(1).is_some());
2071
2072 map.clear();
2073
2074 assert!(map.get(1).is_none());
2075 assert_eq!(map.len(), 0);
2076
2077 let _ = map.insert(2, Box::new("world".to_string()));
2078 assert!(map.get(2).is_some());
2079 }
2080
2081 #[test]
2082 fn test_rax_set_clear() {
2083 let mut set = RaxSet::<u64>::new();
2084 assert!(set.insert(1).is_ok());
2085 assert!(set.insert(2).is_ok());
2086 assert!(set.exists(1));
2087 assert!(set.exists(2));
2088 assert_eq!(set.len(), 2);
2089
2090 set.clear();
2091
2092 assert!(!set.exists(1));
2093 assert!(!set.exists(2));
2094 assert_eq!(set.len(), 0);
2095
2096 assert!(set.insert(3).is_ok());
2097 assert!(set.exists(3));
2098 assert_eq!(set.len(), 1);
2099 }
2100
2101 #[test]
2102 fn bench() {
2103 let ops = 1000000;
2104 println!("{} operations per function", ops);
2105
2106 for _ in 0..2 {
2107 println!();
2108 println!("Gets...");
2109 {
2110 let r = &mut RaxSet::<u64>::new();
2111 for x in 0..2000 {
2112 r.insert(x).expect("whoops!");
2113 }
2114
2115 let sw = Stopwatch::start_new();
2116 for _po in 0..ops {
2117 r.exists(1601);
2118 }
2119
2120 println!("RaxSet::get {}ms", sw.elapsed_ms());
2121 }
2122 {
2123 let r = &mut RaxMap::<u64, &str>::new();
2124 for x in 0..2000 {
2125 r.insert_null(x).expect("whoops!");
2126 }
2127
2128 match r.find(1601) {
2129 Some(v) => println!("{}", v),
2130 None => {}
2131 }
2132
2133 let sw = Stopwatch::start_new();
2134
2135 for _po in 0..ops {
2136 r.find(1601);
2137 }
2138
2139 println!("RaxMap::get {}ms", sw.elapsed_ms());
2140 }
2141
2142 {
2143 let r = &mut RaxMap::<u64, &str>::new();
2144 for x in 0..2000 {
2145 r.insert_null(x).expect("whoops!");
2146 }
2147 let sw = Stopwatch::start_new();
2148
2149 for _po in 0..ops {
2150 r.iter(|_, iter| {
2151 iter.seek(EQUAL, 1601);
2152 });
2153 }
2154
2155 println!("RaxCursor:seek {}ms", sw.elapsed_ms());
2156 }
2157 {
2158 let r = &mut std::collections::HashSet::<u64>::new();
2159 for x in 0..2000 {
2160 r.insert(x);
2161 }
2162
2163 let sw = Stopwatch::start_new();
2164
2165 let xx = 300;
2166 for _po in 0..ops {
2167 r.get(&xx);
2168 }
2169
2170 println!("HashSet::get {}ms", sw.elapsed_ms());
2171 }
2172 {
2173 let r = &mut std::collections::HashMap::<u64, &str>::new();
2174 for x in 0..2000 {
2175 r.insert(x, "");
2176 }
2177
2178 let sw = Stopwatch::start_new();
2179
2180 let xx = 300;
2181 for _po in 0..ops {
2182 r.get(&xx);
2183 }
2184
2185 println!("HashMap::get {}ms", sw.elapsed_ms());
2186 }
2187 {
2188 let r = &mut std::collections::BTreeSet::<u64>::new();
2189 for x in 0..2000 {
2190 r.insert(x);
2191 }
2192
2193 let sw = Stopwatch::start_new();
2194
2195 let xx = 300;
2196 for _po in 0..ops {
2197 r.get(&xx);
2198 }
2199
2200 println!("BTreeSet::get {}ms", sw.elapsed_ms());
2201 }
2202 {
2203 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2204 for x in 0..2000 {
2205 r.insert(x, "");
2206 }
2207
2208 let sw = Stopwatch::start_new();
2209
2210 let xx = 300;
2211 for _po in 0..ops {
2212 r.get(&xx);
2213 }
2214
2215 println!("BTreeMap::get {}ms", sw.elapsed_ms());
2216 }
2217
2218 println!();
2219 println!("Inserts...");
2220 {
2221 let r = &mut RaxMap::<u64, &str>::new();
2222 let sw = Stopwatch::start_new();
2223
2224 for x in 0..ops {
2225 r.insert(x, Box::new("")).expect("whoops!");
2226 }
2227
2228 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2229 }
2230
2231 {
2232 let r = &mut RaxSet::<u64>::new();
2233 let sw = Stopwatch::start_new();
2234
2235 for x in 0..ops {
2236 r.insert(x).expect("whoops!");
2237 }
2238
2239 println!("RaxSet::insert {}ms", sw.elapsed_ms());
2240 }
2241
2242 {
2243 let r = &mut std::collections::BTreeSet::<u64>::new();
2244 let sw = Stopwatch::start_new();
2245
2246 for x in 0..ops {
2247 r.insert(x);
2248 }
2249
2250 println!("BTreeSet::insert {}ms", sw.elapsed_ms());
2251 }
2252 {
2253 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2254 let sw = Stopwatch::start_new();
2255
2256 for x in 0..ops {
2257 r.insert(x, "");
2258 }
2259
2260 println!("BTreeMap::insert {}ms", sw.elapsed_ms());
2261 }
2262
2263 {
2264 let r = &mut std::collections::HashMap::<u64, &str>::new();
2265 let sw = Stopwatch::start_new();
2266
2267 for x in 0..ops {
2268 r.insert(x, "");
2269 }
2270
2271 println!("HashMap::insert {}ms", sw.elapsed_ms());
2272 }
2273 }
2274 }
2275
2276 #[test]
2277 fn bench_rax_find() {
2278 for _ in 0..10 {
2279 let r = &mut RaxMap::<u64, &str>::new();
2280 for x in 0..2000 {
2281 r.insert_null(x).expect("whoops!");
2282 }
2283
2284 match r.find(1601) {
2285 Some(v) => println!("{}", v),
2286 None => {}
2287 }
2288
2289 let sw = Stopwatch::start_new();
2290
2291 for _po in 0..1000000 {
2292 r.find(1601);
2293 }
2294
2295 println!("Thing took {}ms", sw.elapsed_ms());
2296 }
2297 }
2298
2299 #[test]
2300 fn bench_rax_cur_find() {
2301 for _ in 0..10 {
2302 let r = &mut RaxMap::<u64, &str>::new();
2303 for x in 0..2000 {
2304 r.insert_null(x).expect("whoops!");
2305 }
2306
2307 match r.find(1601) {
2308 Some(v) => println!("{}", v),
2309 None => {}
2310 }
2311
2312 let sw = Stopwatch::start_new();
2313
2314 for _po in 0..1000000 {
2315 r.iter(|_, iter| {
2316 iter.seek(EQUAL, 1601);
2317 });
2318 }
2319
2320 println!("RaxMap::cursor_find {}ms", sw.elapsed_ms());
2321 }
2322 }
2323
2324 #[test]
2325 fn bench_rax_insert() {
2326 for _ in 0..10 {
2327 let r = &mut RaxMap::<u64, &str>::new();
2328 let sw = Stopwatch::start_new();
2330
2331 for x in 0..1000000 {
2332 r.insert(x, Box::new("")).expect("whoops!");
2333 }
2334
2335 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2336 println!("Size {}", r.size());
2337 }
2338 }
2339
2340 #[test]
2341 fn bench_rax_insert_show() {
2342 let r = &mut RaxMap::<u64, &str>::new();
2343 let sw = Stopwatch::start_new();
2345
2346 for x in 0..100 {
2347 r.insert(x, Box::new("")).expect("whoops!");
2348 }
2349
2350 r.show();
2351 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2352 assert_eq!(r.size(), 100);
2353 }
2354
2355 #[test]
2356 fn bench_rax_replace() {
2357 let ops = 1000000;
2358 for _ in 0..2 {
2359 let r = &mut RaxMap::<u64, &str>::new();
2360 for x in 0..ops {
2362 r.insert(x, Box::new("")).expect("whoops!");
2363 }
2364
2365 let sw = Stopwatch::start_new();
2366
2367 for x in 0..ops {
2368 r.insert(x, Box::new("")).expect("whoops!");
2370 }
2371
2372 println!("RaxMap::replace {}ms", sw.elapsed_ms());
2373 assert_eq!(r.size(), ops);
2374 }
2375 }
2376
2377 #[test]
2378 fn key_str() {
2379 unsafe {
2380 set_allocator(rax_malloc_hook, rax_realloc_hook, rax_free_hook);
2381 }
2382
2383 let mut r = RaxMap::<&str, MyMsg>::new();
2384
2385 let key = "hello-way";
2386
2387 r.insert(key, Box::new(MyMsg("world 80"))).expect("whoops!");
2388 r.insert("hello-war", Box::new(MyMsg("world 80")))
2389 .expect("whoops!");
2390
2391 r.insert("hello-wares", Box::new(MyMsg("world 80")))
2392 .expect("whoops!");
2393 r.insert("hello", Box::new(MyMsg("world 100")))
2394 .expect("whoops!");
2395
2396 {
2397 match r.find("hello") {
2398 Some(v) => println!("Found {}", v.0),
2399 None => println!("Not Found"),
2400 }
2401 }
2402
2403 r.show();
2404
2405 r.iter(|_, iter| {
2406 if !iter.seek_min() {
2407 return;
2408 }
2409 while iter.forward() {
2410 println!("{}", iter.key());
2411 }
2412 if !iter.seek_max() {
2413 return;
2414 }
2415 while iter.back() {
2416 println!("{}", iter.key());
2417 }
2418 });
2419 }
2420
2421 #[test]
2422 fn key_f64() {
2423 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<f64, MyMsg>>());
2424
2425 let mut r = RaxMap::<f64, MyMsg>::new();
2426
2427 r.insert(100.01, Box::new(MyMsg("world 100")))
2428 .expect("whoops!");
2429 r.insert(80.20, Box::new(MyMsg("world 80")))
2430 .expect("whoops!");
2431 r.insert(100.00, Box::new(MyMsg("world 200")))
2432 .expect("whoops!");
2433 r.insert(99.10, Box::new(MyMsg("world 1")))
2434 .expect("whoops!");
2435
2436 r.show();
2437
2438 r.iter(|_, iter| {
2439 iter.seek_min();
2443 while iter.forward() {
2444 println!("{}", iter.key());
2445 }
2446 iter.seek_max();
2447 while iter.back() {
2448 println!("{}", iter.key());
2449 }
2450 });
2451 }
2452
2453 #[test]
2454 fn key_u64() {
2455 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<u64, MyMsg>>());
2456
2457 let mut r = RaxMap::<u64, MyMsg>::new();
2458
2459 r.insert(100, Box::new(MyMsg("world 100")))
2460 .expect("whoops!");
2461 r.insert(80, Box::new(MyMsg("world 80"))).expect("whoops!");
2462 r.insert(200, Box::new(MyMsg("world 200")))
2463 .expect("whoops!");
2464 r.insert(1, Box::new(MyMsg("world 1"))).expect("whoops!");
2465
2466 r.show();
2467
2468 r.seek_min(|_, it| {
2504 for (key, value) in it.rev() {
2505 println!("Key Len = {}", key);
2506 println!("Data = {}", value.unwrap().0);
2507 }
2508 });
2509
2510 }
2546}