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 init(&mut self) -> Result<(), RaxError> {
283 let rc = unsafe { raxInit(self.rax) };
285 if rc != 0 {
286 return Err(RaxError::OutOfMemory());
287 }
288 Ok(())
289 }
290
291 pub fn len(&self) -> u64 {
293 unsafe { raxSize(self.rax) }
294 }
295
296 pub fn size(&self) -> u64 {
298 unsafe { raxSize(self.rax) }
299 }
300
301 pub fn is_empty(&self) -> bool {
303 self.len() == 0
304 }
305
306 pub fn show(&self) {
308 unsafe { raxShow(self.rax) }
309 }
310
311 pub fn insert_null(&mut self, key: K) -> Result<Option<Box<V>>, RaxError> {
313 unsafe {
314 let old: &mut *mut u8 = &mut ptr::null_mut();
316
317 let k = key.encode();
321 let (ptr, len) = k.to_buf();
322
323 let r = raxInsert(
324 self.rax,
325 ptr,
330 len,
331 std::ptr::null_mut(),
332 old,
333 );
334
335 if r == 0 && Errno::last() == Errno::ENOMEM {
336 Err(RaxError::OutOfMemory())
337 } else if old.is_null() {
338 Ok(None)
339 } else {
340 Ok(Some(Box::from_raw(*old as *mut V)))
344 }
345 }
346 }
347
348 pub fn try_insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
350 unsafe {
351 let old: &mut *mut u8 = &mut ptr::null_mut();
353
354 let value: &mut V = Box::leak(data);
358
359 let k = key.encode();
363 let (ptr, len) = k.to_buf();
364
365 let r = raxTryInsert(
366 self.rax,
367 ptr,
372 len,
373 value as *mut V as *mut u8,
374 old,
375 );
376
377 if r == 0 {
378 if Errno::last() == Errno::ENOMEM {
379 Err(RaxError::OutOfMemory())
380 } else {
381 Ok(Some(Box::from_raw(value as *mut V)))
382 }
383 } else if old.is_null() {
384 Ok(None)
385 } else {
386 Ok(Some(Box::from_raw(*old as *mut V)))
389 }
390 }
391 }
392
393 pub unsafe fn try_insert_ptr(
399 &mut self,
400 key: K,
401 value: *mut u8,
402 ) -> Result<Option<*mut u8>, RaxError> {
403 let old: &mut *mut u8 = &mut ptr::null_mut();
405
406 let k = key.encode();
410 let (ptr, len) = k.to_buf();
411
412 let r = raxTryInsert(
413 self.rax,
414 ptr, len, value, old,
419 );
420
421 if r == 0 {
422 if Errno::last() == Errno::ENOMEM {
423 Err(RaxError::OutOfMemory())
424 } else {
425 Ok(Some(value))
426 }
427 } else if old.is_null() {
428 Ok(None)
429 } else {
430 Ok(Some(*old))
433 }
434 }
435
436 pub fn insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
439 unsafe {
440 let old: &mut *mut u8 = &mut ptr::null_mut();
442
443 let value: &mut V = Box::leak(data);
447
448 let k = key.encode();
452 let (ptr, len) = k.to_buf();
453
454 let r = raxInsert(
455 self.rax,
456 ptr,
461 len,
462 value as *mut V as *mut u8,
463 old,
464 );
465
466 if r == 0 && Errno::last() == Errno::ENOMEM {
467 Err(RaxError::OutOfMemory())
468 } else if old.is_null() {
469 Ok(None)
470 } else {
471 Ok(Some(Box::from_raw(*old as *mut V)))
475 }
476 }
477 }
478
479 pub unsafe fn insert_ptr(
485 &mut self,
486 key: K,
487 value: *mut u8,
488 ) -> Result<Option<*mut u8>, RaxError> {
489 let old: &mut *mut u8 = &mut ptr::null_mut();
491
492 let k = key.encode();
496 let (ptr, len) = k.to_buf();
497
498 let r = raxInsert(
499 self.rax,
500 ptr, len, value, old,
505 );
506
507 if r == 0 && Errno::last() == Errno::ENOMEM {
508 Err(RaxError::OutOfMemory())
509 } else if old.is_null() {
510 Ok(None)
511 } else {
512 Ok(Some(*old))
516 }
517 }
518
519 pub fn remove(&mut self, key: K) -> (bool, Option<Box<V>>) {
521 unsafe {
522 let old: &mut *mut u8 = &mut ptr::null_mut();
523 let k = key.encode();
524 let (ptr, len) = k.to_buf();
525
526 let r = raxRemove(self.rax, ptr, len, old);
527
528 if old.is_null() {
529 (r == 1, None)
530 } else {
531 (r == 1, Some(Box::from_raw(*old as *mut V)))
532 }
533 }
534 }
535
536 pub fn clear(&mut self) {
542 if self.is_empty() {
543 return;
544 }
545
546 unsafe {
550 raxClearWithCallback(self.rax, Some(RaxFreeWithCallbackWrapper::<V>));
551 }
552 }
553
554 pub fn find_exists(&self, key: K) -> (bool, Option<&V>) {
556 unsafe {
557 let k = key.encode();
558 let (ptr, len) = k.to_buf();
559
560 let value = raxFind(self.rax, ptr, len);
561
562 if value.is_null() {
563 (true, None)
564 } else if value == raxNotFound {
565 (false, None)
566 } else {
567 (true, Some(&*(value as *const V)))
571 }
572 }
573 }
574
575 pub fn find(&self, key: K) -> Option<&V> {
577 unsafe {
578 let k = key.encode();
579 let (ptr, len) = k.to_buf();
580
581 let value = raxFind(self.rax, ptr, len);
582
583 if value.is_null() || value == raxNotFound {
584 None
585 } else {
586 Some(&*(value as *const V))
590 }
591 }
592 }
593
594 pub fn get(&self, key: K) -> Option<&V> {
596 unsafe {
597 let k = key.encode();
598 let (ptr, len) = k.to_buf();
599
600 let value = raxFind(self.rax, ptr, len);
601
602 if value.is_null() || value == raxNotFound {
603 None
604 } else {
605 Some(&*(value as *const V))
609 }
610 }
611 }
612
613 pub fn exists(&self, key: K) -> bool {
615 unsafe {
616 let k = key.encode();
617 let (ptr, len) = k.to_buf();
618
619 let value = raxFind(self.rax, ptr, len);
620
621 !(value.is_null() || value == raxNotFound)
622 }
623 }
624
625 pub fn seek_min<F>(&mut self, f: F)
631 where
632 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
633 {
634 unsafe {
636 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
637 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
638 let mut iter = iter.assume_init();
639 iter.fixup();
640 iter.seek_min();
641 f(self, &mut iter)
642 }
643 }
644
645 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
651 where
652 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
653 {
654 unsafe {
656 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
657 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
658 let mut iter = iter.assume_init();
659 iter.fixup();
660 iter.seek_min();
661 f(self, &mut iter)
662 }
663 }
664
665 pub fn seek_max<F>(&mut self, f: F)
671 where
672 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
673 {
674 unsafe {
676 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
677 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
678 let mut iter = iter.assume_init();
679 iter.fixup();
680 iter.seek_max();
681 f(self, &mut iter)
682 }
683 }
684
685 pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
691 where
692 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
693 {
694 unsafe {
696 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
697 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
698 let mut iter = iter.assume_init();
699 iter.fixup();
700 iter.seek_max();
701 f(self, &mut iter)
702 }
703 }
704
705 pub fn seek<F>(&mut self, op: &str, key: K, f: F)
711 where
712 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
713 {
714 unsafe {
716 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
717 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
718 let mut iter = iter.assume_init();
719 iter.fixup();
720 iter.seek(op, key);
721 f(self, &mut iter)
722 }
723 }
724
725 pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
731 where
732 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
733 {
734 unsafe {
736 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
737 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
738 let mut iter = iter.assume_init();
739 iter.fixup();
740 iter.seek(op, key);
741 f(self, &mut iter)
742 }
743 }
744
745 pub fn iter<F>(&mut self, f: F)
751 where
752 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
753 {
754 unsafe {
756 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
757 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
758 let mut iter = iter.assume_init();
759 iter.fixup();
760 f(self, &mut iter)
761 }
762 }
763
764 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
770 where
771 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
772 {
773 unsafe {
775 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
776 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
777 let mut iter = iter.assume_init();
778 iter.fixup();
779 f(self, &mut iter)
780 }
781 }
782}
783
784pub struct RaxSet<K: RaxKey> {
830 rax: *mut rax,
831 _marker: std::marker::PhantomData<K>,
832}
833
834impl<K: RaxKey> Drop for RaxSet<K> {
835 fn drop(&mut self) {
836 unsafe { raxFree(self.rax) }
838 }
839}
840
841unsafe impl<K: RaxKey + Send> Send for RaxSet<K> {}
844
845unsafe impl<K: RaxKey + Sync> Sync for RaxSet<K> {}
848
849impl<K: RaxKey> Default for RaxSet<K> {
850 fn default() -> Self {
851 Self::new()
852 }
853}
854
855impl<K: RaxKey> RaxSet<K> {
857 pub fn new() -> Self {
863 match Self::try_new() {
864 Ok(r) => r,
865 Err(_) => panic!("raxNew: out of memory"),
866 }
867 }
868
869 pub fn try_new() -> Result<RaxSet<K>, RaxError> {
873 let ptr = unsafe { raxNew() };
876
877 if ptr.is_null() {
878 return Err(RaxError::OutOfMemory());
879 }
880
881 Ok(RaxSet {
882 rax: ptr,
883 _marker: std::marker::PhantomData,
884 })
885 }
886
887 pub fn init(&mut self) -> Result<(), RaxError> {
893 let rc = unsafe { raxInit(self.rax) };
895 if rc != 0 {
896 return Err(RaxError::OutOfMemory());
897 }
898 Ok(())
899 }
900
901 pub fn len(&self) -> u64 {
903 unsafe { raxSize(self.rax) }
904 }
905
906 pub fn size(&self) -> u64 {
908 unsafe { raxSize(self.rax) }
909 }
910
911 pub fn show(&self) {
913 unsafe { raxShow(self.rax) }
914 }
915
916 pub fn is_empty(&self) -> bool {
918 self.len() == 0
919 }
920
921 pub fn insert(&mut self, key: K) -> Result<bool, RaxError> {
924 unsafe {
925 let k = key.encode();
929 let (ptr, len) = k.to_buf();
930
931 let r = raxTryInsert(
932 self.rax,
933 ptr,
938 len,
939 std::ptr::null_mut(),
940 std::ptr::null_mut(),
941 );
942
943 if r == 0 {
944 if Errno::last() == Errno::ENOMEM {
945 Err(RaxError::OutOfMemory())
946 } else {
947 Ok(false)
948 }
949 } else {
950 Ok(true)
951 }
952 }
953 }
954
955 pub fn remove(&mut self, key: K) -> bool {
957 unsafe {
958 let k = key.encode();
959 let (ptr, len) = k.to_buf();
960
961 let r = raxRemove(self.rax, ptr, len, &mut std::ptr::null_mut());
962
963 r == 1
964 }
965 }
966
967 pub fn clear(&mut self) {
973 if self.is_empty() {
974 return;
975 }
976
977 unsafe {
981 raxClearWithCallback(self.rax, None);
982 }
983 }
984
985 pub fn exists(&self, key: K) -> bool {
987 unsafe {
988 let k = key.encode();
989 let (ptr, len) = k.to_buf();
990
991 let value = raxFind(self.rax, ptr, len);
992
993 value != raxNotFound
994 }
995 }
996
997 pub fn seek_min<F>(&mut self, f: F)
1003 where
1004 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1005 {
1006 unsafe {
1008 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1009 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1010 let mut iter = iter.assume_init();
1011 iter.fixup();
1012 iter.seek_min();
1013 f(self, &mut iter)
1014 }
1015 }
1016
1017 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
1023 where
1024 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1025 {
1026 unsafe {
1028 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1029 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1030 let mut iter = iter.assume_init();
1031 iter.fixup();
1032 iter.seek_min();
1033 f(self, &mut iter)
1034 }
1035 }
1036
1037 pub fn seek_max<F>(&mut self, f: F)
1043 where
1044 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1045 {
1046 unsafe {
1048 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1049 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1050 let mut iter = iter.assume_init();
1051 iter.fixup();
1052 iter.seek_max();
1053 f(self, &mut iter)
1054 }
1055 }
1056
1057 pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
1063 where
1064 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1065 {
1066 unsafe {
1068 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1069 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1070 let mut iter = iter.assume_init();
1071 iter.fixup();
1072 iter.seek_max();
1073 f(self, &mut iter)
1074 }
1075 }
1076
1077 pub fn seek<F>(&mut self, op: &str, key: K, f: F)
1083 where
1084 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1085 {
1086 unsafe {
1088 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1089 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1090 let mut iter = iter.assume_init();
1091 iter.fixup();
1092 iter.seek(op, key);
1093 f(self, &mut iter)
1094 }
1095 }
1096
1097 pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
1103 where
1104 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1105 {
1106 unsafe {
1108 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1109 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1110 let mut iter = iter.assume_init();
1111 iter.fixup();
1112 iter.seek(op, key);
1113 f(self, &mut iter)
1114 }
1115 }
1116
1117 pub fn iter<F>(&mut self, f: F)
1123 where
1124 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
1125 {
1126 unsafe {
1128 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1129 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1130 let mut iter = iter.assume_init();
1131 iter.fixup();
1132 f(self, &mut iter)
1133 }
1134 }
1135
1136 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
1142 where
1143 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1144 {
1145 unsafe {
1147 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1148 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1149 let mut iter = iter.assume_init();
1150 iter.fixup();
1151 f(self, &mut iter)
1152 }
1153 }
1154}
1155
1156pub trait RaxKey<RHS = Self>: Clone + Default + std::fmt::Debug {
1251 type Output: RaxKey;
1252
1253 fn encode(self) -> Self::Output;
1254
1255 fn to_buf(&self) -> (*const u8, usize);
1256
1257 unsafe fn from_buf(ptr: *const u8, len: usize) -> RHS;
1261}
1262
1263impl RaxKey for f32 {
1264 type Output = u32;
1265
1266 fn encode(self) -> Self::Output {
1267 self.to_bits().to_be()
1269 }
1270
1271 fn to_buf(&self) -> (*const u8, usize) {
1272 (
1274 self as *const _ as *const u8,
1275 std::mem::size_of::<Self::Output>(),
1276 )
1277 }
1278
1279 unsafe fn from_buf(ptr: *const u8, len: usize) -> f32 {
1280 assert_eq!(len, std::mem::size_of::<f32>());
1281 if len != size_of::<Self::Output>() {
1282 return Self::default();
1283 }
1284 unsafe {
1285 f32::from_bits(u32::from_be(
1287 *(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32),
1288 ))
1289 }
1290 }
1291}
1292
1293impl RaxKey for f64 {
1294 type Output = u64;
1295
1296 fn encode(self) -> Self::Output {
1297 self.to_bits().to_be()
1299 }
1300
1301 fn to_buf(&self) -> (*const u8, usize) {
1302 (self as *const _ as *const u8, size_of::<Self::Output>())
1304 }
1305
1306 unsafe fn from_buf(ptr: *const u8, len: usize) -> f64 {
1307 assert_eq!(len, std::mem::size_of::<f64>());
1308 if len != size_of::<Self::Output>() {
1309 return Self::default();
1310 }
1311 unsafe {
1312 f64::from_bits(u64::from_be(
1314 *(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64),
1315 ))
1316 }
1317 }
1318}
1319
1320impl RaxKey for isize {
1321 type Output = isize;
1322
1323 fn encode(self) -> Self::Output {
1324 self.to_be()
1325 }
1326
1327 fn to_buf(&self) -> (*const u8, usize) {
1328 (self as *const _ as *const u8, size_of::<Self::Output>())
1329 }
1330
1331 unsafe fn from_buf(ptr: *const u8, len: usize) -> isize {
1332 assert_eq!(len, std::mem::size_of::<isize>());
1333 if len != size_of::<Self::Output>() {
1334 return Self::default();
1335 }
1336 unsafe { isize::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut isize)) }
1337 }
1338}
1339
1340impl RaxKey for usize {
1341 type Output = usize;
1342
1343 fn encode(self) -> Self::Output {
1344 self.to_be()
1345 }
1346
1347 fn to_buf(&self) -> (*const u8, usize) {
1348 (
1349 self as *const _ as *const u8,
1350 std::mem::size_of::<Self::Output>(),
1351 )
1352 }
1353
1354 unsafe fn from_buf(ptr: *const u8, len: usize) -> usize {
1355 assert_eq!(len, std::mem::size_of::<usize>());
1356 if len != size_of::<Self::Output>() {
1357 return Self::default();
1358 }
1359 unsafe {
1360 usize::from_be(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut usize))
1361 }
1362 }
1363}
1364
1365impl RaxKey for i16 {
1366 type Output = i16;
1367
1368 fn encode(self) -> Self::Output {
1369 self.to_be()
1370 }
1371
1372 fn to_buf(&self) -> (*const u8, usize) {
1373 (self as *const _ as *const u8, size_of::<Self::Output>())
1374 }
1375
1376 unsafe fn from_buf(ptr: *const u8, len: usize) -> Self {
1377 if len != size_of::<Self::Output>() {
1378 return Self::default();
1379 }
1380 unsafe { i16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i16)) }
1381 }
1382}
1383
1384impl RaxKey for u16 {
1385 type Output = u16;
1386
1387 fn encode(self) -> Self::Output {
1388 self.to_be()
1389 }
1390
1391 fn to_buf(&self) -> (*const u8, usize) {
1392 (self as *const _ as *const u8, size_of::<Self::Output>())
1393 }
1394
1395 unsafe fn from_buf(ptr: *const u8, len: usize) -> u16 {
1396 assert_eq!(len, std::mem::size_of::<u16>());
1397 if len != size_of::<Self::Output>() {
1398 return Self::default();
1399 }
1400 unsafe { u16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u16)) }
1401 }
1402}
1403
1404impl RaxKey for i32 {
1405 type Output = i32;
1406
1407 fn encode(self) -> Self::Output {
1408 self.to_be()
1409 }
1410
1411 fn to_buf(&self) -> (*const u8, usize) {
1412 (self as *const _ as *const u8, size_of::<Self::Output>())
1413 }
1414
1415 unsafe fn from_buf(ptr: *const u8, len: usize) -> i32 {
1416 assert_eq!(len, std::mem::size_of::<i32>());
1417 if len != size_of::<Self::Output>() {
1418 return Self::default();
1419 }
1420 unsafe { i32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i32)) }
1421 }
1422}
1423
1424impl RaxKey for u32 {
1425 type Output = u32;
1426
1427 fn encode(self) -> Self::Output {
1428 self.to_be()
1429 }
1430
1431 fn to_buf(&self) -> (*const u8, usize) {
1432 (self as *const _ as *const u8, size_of::<Self::Output>())
1433 }
1434
1435 unsafe fn from_buf(ptr: *const u8, len: usize) -> u32 {
1436 assert_eq!(len, std::mem::size_of::<u32>());
1437 if len != size_of::<Self::Output>() {
1438 return Self::default();
1439 }
1440 unsafe { u32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u32)) }
1441 }
1442}
1443
1444impl RaxKey for i64 {
1445 type Output = i64;
1446
1447 fn encode(self) -> Self::Output {
1448 self.to_be()
1449 }
1450
1451 fn to_buf(&self) -> (*const u8, usize) {
1452 (self as *const _ as *const u8, size_of::<Self::Output>())
1453 }
1454
1455 unsafe fn from_buf(ptr: *const u8, len: usize) -> i64 {
1456 assert_eq!(len, std::mem::size_of::<i64>());
1457 if len != size_of::<Self::Output>() {
1458 return Self::default();
1459 }
1460 unsafe { i64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i64)) }
1461 }
1462}
1463
1464impl RaxKey for u64 {
1465 type Output = u64;
1466
1467 fn encode(self) -> Self::Output {
1468 self.to_be()
1469 }
1470
1471 fn to_buf(&self) -> (*const u8, usize) {
1472 (self as *const _ as *const u8, size_of::<Self::Output>())
1473 }
1474
1475 unsafe fn from_buf(ptr: *const u8, len: usize) -> u64 {
1476 assert_eq!(len, std::mem::size_of::<u64>());
1477 if len != size_of::<Self::Output>() {
1478 return Self::default();
1479 }
1480 unsafe { u64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64)) }
1481 }
1482}
1483
1484impl RaxKey for i128 {
1485 type Output = i128;
1486
1487 fn encode(self) -> Self::Output {
1488 self.to_be()
1489 }
1490
1491 fn to_buf(&self) -> (*const u8, usize) {
1492 (self as *const _ as *const u8, size_of::<Self::Output>())
1493 }
1494
1495 unsafe fn from_buf(ptr: *const u8, len: usize) -> i128 {
1496 assert_eq!(len, std::mem::size_of::<i128>());
1497 if len != size_of::<Self::Output>() {
1498 return Self::default();
1499 }
1500 unsafe { i128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i128)) }
1501 }
1502}
1503
1504impl RaxKey for u128 {
1505 type Output = u128;
1506
1507 fn encode(self) -> Self::Output {
1508 self.to_be()
1509 }
1510
1511 fn to_buf(&self) -> (*const u8, usize) {
1512 (self as *const _ as *const u8, size_of::<Self::Output>())
1513 }
1514
1515 unsafe fn from_buf(ptr: *const u8, len: usize) -> u128 {
1516 assert_eq!(len, std::mem::size_of::<u128>());
1517 if len != size_of::<Self::Output>() {
1518 return Self::default();
1519 }
1520 unsafe { u128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u128)) }
1521 }
1522}
1523
1524impl RaxKey for Vec<u8> {
1525 type Output = Vec<u8>;
1526
1527 fn encode(self) -> Vec<u8> {
1528 self
1529 }
1530
1531 fn to_buf(&self) -> (*const u8, usize) {
1532 (self.as_ptr(), self.len())
1533 }
1534
1535 unsafe fn from_buf(ptr: *const u8, len: usize) -> Vec<u8> {
1536 unsafe { std::slice::from_raw_parts(ptr, len).to_vec() }
1537 }
1538}
1539
1540impl<'a> RaxKey for &'a [u8] {
1541 type Output = &'a [u8];
1542
1543 fn encode(self) -> &'a [u8] {
1544 self
1545 }
1546
1547 fn to_buf(&self) -> (*const u8, usize) {
1548 (self.as_ptr(), self.len())
1549 }
1550
1551 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a [u8] {
1552 unsafe { std::slice::from_raw_parts(ptr, len) }
1553 }
1554}
1555
1556impl<'a> RaxKey for &'a str {
1573 type Output = &'a str;
1574
1575 fn encode(self) -> Self::Output {
1576 self
1577 }
1578
1579 fn to_buf(&self) -> (*const u8, usize) {
1580 ((*self).as_ptr(), self.len())
1581 }
1582
1583 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a str {
1584 unsafe { std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap_or_default() }
1585 }
1586}
1587
1588#[repr(C)]
1589pub struct RaxIterator<K: RaxKey, V> {
1590 pub flags: libc::c_int,
1591 pub rt: *mut rax,
1592 pub key: *mut u8,
1593 pub data: *mut libc::c_void,
1594 pub key_len: libc::size_t,
1595 pub key_max: libc::size_t,
1596 pub key_static_string: [u8; 128],
1597 pub node: *mut raxNode,
1598 pub stack: raxStack,
1599 pub node_cb: Option<raxNodeCallback>,
1600 _marker: std::marker::PhantomData<(K, V)>,
1601}
1602
1603impl<K: RaxKey, V> Drop for RaxIterator<K, V> {
1605 fn drop(&mut self) {
1606 unsafe {
1607 if self.key_max == RAX_ITER_STATIC_LEN as usize {
1609 self.key = self.key_static_string.as_mut_ptr();
1610 }
1611
1612 if self.stack.maxitems == RAX_STACK_STATIC_ITEMS as usize {
1614 self.stack.stack = self.stack.static_items.as_mut_ptr();
1615 }
1616
1617 raxStop(&raw mut *self as *mut raxIterator);
1618 }
1619 }
1620}
1621
1622impl<K: RaxKey, V: 'static> Iterator for RaxIterator<K, V> {
1624 type Item = (K, Option<&'static V>);
1625
1626 fn next(&mut self) -> Option<<Self as Iterator>::Item> {
1627 unsafe {
1628 if raxNext(&raw mut *self as *mut raxIterator) == 1 {
1629 let data: *mut libc::c_void = self.data;
1630 if data.is_null() {
1631 None
1632 } else {
1633 let val = data as *const V;
1634 if val.is_null() {
1635 Some((self.key(), None))
1636 } else {
1637 Some((self.key(), Some(&*val)))
1638 }
1639 }
1640 } else {
1641 None
1642 }
1643 }
1644 }
1645}
1646
1647impl<K: RaxKey, V: 'static> DoubleEndedIterator for RaxIterator<K, V> {
1649 fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
1650 unsafe {
1651 if raxPrev(&raw mut *self as *mut raxIterator) == 1 {
1652 let data: *mut libc::c_void = self.data;
1653 if data.is_null() {
1654 None
1655 } else {
1656 let val = data as *const V;
1657 if val.is_null() {
1658 Some((self.key(), None))
1659 } else {
1660 Some((self.key(), Some(&*val)))
1661 }
1662 }
1663 } else {
1664 None
1665 }
1666 }
1667 }
1668}
1669
1670impl<K: RaxKey, V> RaxIterator<K, V> {
1672 pub fn new(r: RaxMap<K, V>) -> RaxIterator<K, V> {
1674 unsafe {
1676 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
1677 raxStart(iter.as_mut_ptr() as *mut raxIterator, r.rax);
1678 let mut iter = iter.assume_init();
1679 iter.fixup();
1680 iter
1681 }
1682 }
1683
1684 pub fn print_ptr(&self) {
1685 println!("ptr = {:p}", self);
1686 println!("ptr = {:p}", self as *const _ as *const raxIterator);
1687 }
1688
1689 pub fn seek_min(&mut self) -> bool {
1690 unsafe {
1691 if raxSeek(
1692 &raw mut *self as *mut raxIterator,
1693 BEGIN.as_ptr(),
1694 std::ptr::null(),
1695 0,
1696 ) == 1
1697 {
1698 self.forward()
1699 } else {
1700 false
1701 }
1702 }
1703 }
1704
1705 pub fn seek_max(&mut self) -> bool {
1706 unsafe {
1707 if raxSeek(
1708 &raw mut *self as *mut raxIterator,
1709 END.as_ptr(),
1710 std::ptr::null(),
1711 0,
1712 ) == 1
1713 {
1714 self.back()
1715 } else {
1716 false
1717 }
1718 }
1719 }
1720
1721 pub fn back(&mut self) -> bool {
1722 unsafe { raxPrev(&raw mut *self as *mut raxIterator) == 1 }
1723 }
1724
1725 pub fn forward(&mut self) -> bool {
1726 unsafe { raxNext(&raw mut *self as *mut raxIterator) == 1 }
1727 }
1728
1729 pub fn key(&self) -> K {
1731 unsafe { K::from_buf(self.key, self.key_len) }
1732 }
1733
1734 pub fn value(&self) -> Option<&V> {
1736 unsafe {
1737 let data: *mut libc::c_void = self.data;
1738 if data.is_null() {
1739 None
1740 } else {
1741 Some(&*(data as *const V))
1742 }
1743 }
1744 }
1745
1746 pub fn lesser(&mut self, key: K) -> bool {
1747 self.seek(LESSER, key)
1748 }
1749
1750 pub fn lesser_equal(&mut self, key: K) -> bool {
1751 self.seek(LESSER_EQUAL, key)
1752 }
1753
1754 pub fn greater(&mut self, key: K) -> bool {
1755 self.seek(GREATER, key)
1756 }
1757
1758 pub fn greater_equal(&mut self, key: K) -> bool {
1759 self.seek(GREATER_EQUAL, key)
1760 }
1761
1762 pub fn seek(&mut self, op: &str, key: K) -> bool {
1763 unsafe {
1764 let k = key.encode();
1765 let (p, len) = k.to_buf();
1766 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len) == 1
1767 && self.flags & RAX_ITER_EOF != 0
1768 }
1769 }
1770
1771 pub fn seek_raw(&mut self, op: &str, key: K) -> i32 {
1772 unsafe {
1773 let k = key.encode();
1774 let (p, len) = k.to_buf();
1775 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len)
1776 }
1777 }
1778
1779 pub fn seek_bytes(&mut self, op: &str, ele: &[u8]) -> bool {
1780 unsafe {
1781 raxSeek(
1782 &raw mut *self as *mut raxIterator,
1783 op.as_ptr(),
1784 ele.as_ptr(),
1785 ele.len() as libc::size_t,
1786 ) == 1
1787 }
1788 }
1789
1790 pub fn eof(&self) -> bool {
1795 self.flags & RAX_ITER_EOF != 0
1796 }
1797
1798 pub fn fixup(&mut self) {
1800 self.key = self.key_static_string.as_mut_ptr();
1801 self.stack.stack = self.stack.static_items.as_mut_ptr();
1802 }
1803}
1804
1805impl fmt::Display for RaxError {
1806 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1807 match *self {
1808 RaxError::Generic(ref err) => write!(f, "{err}"),
1809 RaxError::OutOfMemory() => write!(f, "out of memory"),
1810 }
1811 }
1812}
1813
1814impl error::Error for RaxError {
1815 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1816 match *self {
1817 RaxError::Generic(ref err) => Some(err),
1822 RaxError::OutOfMemory() => Some(self),
1823 }
1824 }
1825}
1826
1827#[derive(Debug)]
1828pub struct GenericError {
1829 message: String,
1830}
1831
1832impl GenericError {
1833 pub fn new(message: &str) -> GenericError {
1834 GenericError {
1835 message: String::from(message),
1836 }
1837 }
1838}
1839
1840impl fmt::Display for GenericError {
1841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1842 write!(f, "Store error: {}", self.message)
1843 }
1844}
1845
1846impl error::Error for GenericError {}
1847
1848#[repr(C)]
1849pub struct rax;
1850
1851#[repr(C)]
1852pub struct raxNode;
1853
1854#[repr(C)]
1855pub struct raxStack {
1856 stack: *mut *mut libc::c_void,
1857 items: libc::size_t,
1858 maxitems: libc::size_t,
1859 static_items: [*mut libc::c_void; 32],
1860 oom: libc::c_int,
1861}
1862
1863#[repr(C)]
1864pub struct raxIterator;
1865
1866#[allow(non_snake_case)]
1867#[allow(non_camel_case_types)]
1868extern "C" fn RaxFreeWithCallbackWrapper<V>(v: *mut libc::c_void) {
1869 unsafe {
1870 drop(Box::from_raw(v as *mut V));
1872 }
1873}
1874
1875#[allow(non_camel_case_types)]
1876type raxNodeCallback = extern "C" fn(v: *mut libc::c_void);
1877
1878type RaxFreeCallback = extern "C" fn(v: *mut libc::c_void);
1879
1880#[allow(improper_ctypes)]
1881#[allow(non_snake_case)]
1882#[allow(non_camel_case_types)]
1883#[link(name = "rax", kind = "static")]
1884extern "C" {
1885 pub static raxNotFound: *mut u8;
1886
1887 pub static mut rax_malloc: extern "C" fn(size: libc::size_t) -> *mut u8;
1888 pub static mut rax_realloc:
1889 extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8;
1890 pub static mut rax_free: extern "C" fn(ptr: *mut libc::c_void);
1891
1892 pub fn raxIteratorSize() -> libc::c_int;
1893
1894 pub fn raxNew() -> *mut rax;
1895
1896 pub fn raxFree(rax: *mut rax);
1897
1898 pub fn raxFreeWithCallback(rax: *mut rax, callback: RaxFreeCallback);
1899
1900 pub fn raxClearWithCallback(rax: *mut rax, callback: Option<RaxFreeCallback>);
1901
1902 pub fn raxInit(rax: *mut rax) -> libc::c_int;
1903
1904 pub fn raxInsert(
1905 rax: *mut rax,
1906 s: *const u8,
1907 len: libc::size_t,
1908 data: *const u8,
1909 old: &mut *mut u8,
1910 ) -> libc::c_int;
1911
1912 pub fn raxTryInsert(
1913 rax: *mut rax,
1914 s: *const u8,
1915 len: libc::size_t,
1916 data: *const u8,
1917 old: *mut *mut u8,
1918 ) -> libc::c_int;
1919
1920 pub fn raxRemove(
1921 rax: *mut rax,
1922 s: *const u8,
1923 len: libc::size_t,
1924 old: &mut *mut u8,
1925 ) -> libc::c_int;
1926
1927 pub fn raxFind(rax: *mut rax, s: *const u8, len: libc::size_t) -> *mut u8;
1928
1929 pub fn raxIteratorNew(rt: *mut rax) -> *mut raxIterator;
1930
1931 pub fn raxStart(it: *mut raxIterator, rt: *mut rax);
1932
1933 pub fn raxSeek(
1934 it: *mut raxIterator,
1935 op: *const u8,
1936 ele: *const u8,
1937 len: libc::size_t,
1938 ) -> libc::c_int;
1939
1940 pub fn raxNext(it: *mut raxIterator) -> libc::c_int;
1941
1942 pub fn raxPrev(it: *mut raxIterator) -> libc::c_int;
1943
1944 pub fn raxRandomWalk(it: *mut raxIterator, steps: libc::size_t) -> libc::c_int;
1945
1946 pub fn raxCompare(
1947 it: *mut raxIterator,
1948 op: *const u8,
1949 key: *mut u8,
1950 key_len: libc::size_t,
1951 ) -> libc::c_int;
1952
1953 pub fn raxStop(it: *mut raxIterator);
1954
1955 pub fn raxEOF(it: *mut raxIterator) -> libc::c_int;
1956
1957 pub fn raxShow(rax: *mut rax);
1958
1959 pub fn raxSize(rax: *mut rax) -> u64;
1960}
1961
1962#[cfg(test)]
1963mod tests {
1964 extern crate test;
1965 use std::{
1966 self,
1967 default::Default,
1968 fmt,
1969 time::{Duration, Instant},
1970 };
1971
1972 use super::*;
1973
1974 extern "C" fn rax_malloc_hook(size: libc::size_t) -> *mut u8 {
1975 unsafe {
1976 println!("malloc");
1977 libc::malloc(size) as *mut u8
1978 }
1979 }
1980
1981 extern "C" fn rax_realloc_hook(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8 {
1982 unsafe {
1983 println!("realloc");
1984 libc::realloc(ptr, size) as *mut u8
1985 }
1986 }
1987
1988 extern "C" fn rax_free_hook(ptr: *mut libc::c_void) {
1989 unsafe {
1990 println!("free");
1991 libc::free(ptr)
1992 }
1993 }
1994
1995 pub struct MyMsg<'a>(&'a str);
1996
1997 impl<'a> Drop for MyMsg<'a> {
1998 fn drop(&mut self) {
1999 println!("dropped -> {}", self.0);
2000 }
2001 }
2002
2003 #[derive(Clone, Copy)]
2004 pub struct Stopwatch {
2005 start_time: Option<Instant>,
2006 elapsed: Duration,
2007 }
2008
2009 impl Default for Stopwatch {
2010 fn default() -> Stopwatch {
2011 Stopwatch {
2012 start_time: None,
2013 elapsed: Duration::from_secs(0),
2014 }
2015 }
2016 }
2017
2018 impl fmt::Display for Stopwatch {
2019 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2020 return write!(f, "{}ms", self.elapsed_ms());
2021 }
2022 }
2023
2024 #[expect(unused)]
2025 impl Stopwatch {
2026 pub fn new() -> Stopwatch {
2027 let sw: Stopwatch = Default::default();
2028 return sw;
2029 }
2030 pub fn start_new() -> Stopwatch {
2031 let mut sw = Stopwatch::new();
2032 sw.start();
2033 return sw;
2034 }
2035
2036 pub fn start(&mut self) {
2037 self.start_time = Some(Instant::now());
2038 }
2039 pub fn stop(&mut self) {
2040 self.elapsed = self.elapsed();
2041 self.start_time = None;
2042 }
2043 pub fn reset(&mut self) {
2044 self.elapsed = Duration::from_secs(0);
2045 self.start_time = None;
2046 }
2047 pub fn restart(&mut self) {
2048 self.reset();
2049 self.start();
2050 }
2051
2052 pub fn is_running(&self) -> bool {
2053 return self.start_time.is_some();
2054 }
2055
2056 pub fn elapsed(&self) -> Duration {
2057 match self.start_time {
2058 Some(t1) => {
2059 return t1.elapsed() + self.elapsed;
2060 }
2061 None => {
2062 return self.elapsed;
2063 }
2064 }
2065 }
2066 pub fn elapsed_ms(&self) -> i64 {
2067 let dur = self.elapsed();
2068 return (dur.as_secs() * 1000 + (dur.subsec_nanos() / 1000000) as u64) as i64;
2069 }
2070 }
2071
2072 #[test]
2073 fn test_rax_map_clear() {
2074 let mut map = RaxMap::new();
2075 let _ = map.insert(1, Box::new("hello".to_string()));
2076 assert!(map.get(1).is_some());
2077
2078 map.clear();
2079 assert_eq!(map.len(), 0);
2080
2081 map.init().unwrap();
2082
2083 assert!(map.get(1).is_none());
2084
2085 let _ = map.insert(2, Box::new("world".to_string()));
2086 assert!(map.get(2).is_some());
2087 }
2088
2089 #[test]
2090 fn test_rax_set_clear() {
2091 let mut set = RaxSet::<u64>::new();
2092 assert!(set.insert(1).is_ok());
2093 assert!(set.insert(2).is_ok());
2094 assert!(set.exists(1));
2095 assert!(set.exists(2));
2096 assert_eq!(set.len(), 2);
2097
2098 set.clear();
2099 assert_eq!(set.len(), 0);
2100
2101 set.init().unwrap();
2102
2103 assert!(!set.exists(1));
2104 assert!(!set.exists(2));
2105
2106 assert!(set.insert(3).is_ok());
2107 assert!(set.exists(3));
2108 assert_eq!(set.len(), 1);
2109 }
2110
2111 #[test]
2112 fn bench() {
2113 let ops = 1000000;
2114 println!("{} operations per function", ops);
2115
2116 for _ in 0..2 {
2117 println!();
2118 println!("Gets...");
2119 {
2120 let r = &mut RaxSet::<u64>::new();
2121 for x in 0..2000 {
2122 r.insert(x).expect("whoops!");
2123 }
2124
2125 let sw = Stopwatch::start_new();
2126 for _po in 0..ops {
2127 r.exists(1601);
2128 }
2129
2130 println!("RaxSet::get {}ms", sw.elapsed_ms());
2131 }
2132 {
2133 let r = &mut RaxMap::<u64, &str>::new();
2134 for x in 0..2000 {
2135 r.insert_null(x).expect("whoops!");
2136 }
2137
2138 match r.find(1601) {
2139 Some(v) => println!("{}", v),
2140 None => {}
2141 }
2142
2143 let sw = Stopwatch::start_new();
2144
2145 for _po in 0..ops {
2146 r.find(1601);
2147 }
2148
2149 println!("RaxMap::get {}ms", sw.elapsed_ms());
2150 }
2151
2152 {
2153 let r = &mut RaxMap::<u64, &str>::new();
2154 for x in 0..2000 {
2155 r.insert_null(x).expect("whoops!");
2156 }
2157 let sw = Stopwatch::start_new();
2158
2159 for _po in 0..ops {
2160 r.iter(|_, iter| {
2161 iter.seek(EQUAL, 1601);
2162 });
2163 }
2164
2165 println!("RaxCursor:seek {}ms", sw.elapsed_ms());
2166 }
2167 {
2168 let r = &mut std::collections::HashSet::<u64>::new();
2169 for x in 0..2000 {
2170 r.insert(x);
2171 }
2172
2173 let sw = Stopwatch::start_new();
2174
2175 let xx = 300;
2176 for _po in 0..ops {
2177 r.get(&xx);
2178 }
2179
2180 println!("HashSet::get {}ms", sw.elapsed_ms());
2181 }
2182 {
2183 let r = &mut std::collections::HashMap::<u64, &str>::new();
2184 for x in 0..2000 {
2185 r.insert(x, "");
2186 }
2187
2188 let sw = Stopwatch::start_new();
2189
2190 let xx = 300;
2191 for _po in 0..ops {
2192 r.get(&xx);
2193 }
2194
2195 println!("HashMap::get {}ms", sw.elapsed_ms());
2196 }
2197 {
2198 let r = &mut std::collections::BTreeSet::<u64>::new();
2199 for x in 0..2000 {
2200 r.insert(x);
2201 }
2202
2203 let sw = Stopwatch::start_new();
2204
2205 let xx = 300;
2206 for _po in 0..ops {
2207 r.get(&xx);
2208 }
2209
2210 println!("BTreeSet::get {}ms", sw.elapsed_ms());
2211 }
2212 {
2213 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2214 for x in 0..2000 {
2215 r.insert(x, "");
2216 }
2217
2218 let sw = Stopwatch::start_new();
2219
2220 let xx = 300;
2221 for _po in 0..ops {
2222 r.get(&xx);
2223 }
2224
2225 println!("BTreeMap::get {}ms", sw.elapsed_ms());
2226 }
2227
2228 println!();
2229 println!("Inserts...");
2230 {
2231 let r = &mut RaxMap::<u64, &str>::new();
2232 let sw = Stopwatch::start_new();
2233
2234 for x in 0..ops {
2235 r.insert(x, Box::new("")).expect("whoops!");
2236 }
2237
2238 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2239 }
2240
2241 {
2242 let r = &mut RaxSet::<u64>::new();
2243 let sw = Stopwatch::start_new();
2244
2245 for x in 0..ops {
2246 r.insert(x).expect("whoops!");
2247 }
2248
2249 println!("RaxSet::insert {}ms", sw.elapsed_ms());
2250 }
2251
2252 {
2253 let r = &mut std::collections::BTreeSet::<u64>::new();
2254 let sw = Stopwatch::start_new();
2255
2256 for x in 0..ops {
2257 r.insert(x);
2258 }
2259
2260 println!("BTreeSet::insert {}ms", sw.elapsed_ms());
2261 }
2262 {
2263 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2264 let sw = Stopwatch::start_new();
2265
2266 for x in 0..ops {
2267 r.insert(x, "");
2268 }
2269
2270 println!("BTreeMap::insert {}ms", sw.elapsed_ms());
2271 }
2272
2273 {
2274 let r = &mut std::collections::HashMap::<u64, &str>::new();
2275 let sw = Stopwatch::start_new();
2276
2277 for x in 0..ops {
2278 r.insert(x, "");
2279 }
2280
2281 println!("HashMap::insert {}ms", sw.elapsed_ms());
2282 }
2283 }
2284 }
2285
2286 #[test]
2287 fn bench_rax_find() {
2288 for _ in 0..10 {
2289 let r = &mut RaxMap::<u64, &str>::new();
2290 for x in 0..2000 {
2291 r.insert_null(x).expect("whoops!");
2292 }
2293
2294 match r.find(1601) {
2295 Some(v) => println!("{}", v),
2296 None => {}
2297 }
2298
2299 let sw = Stopwatch::start_new();
2300
2301 for _po in 0..1000000 {
2302 r.find(1601);
2303 }
2304
2305 println!("Thing took {}ms", sw.elapsed_ms());
2306 }
2307 }
2308
2309 #[test]
2310 fn bench_rax_cur_find() {
2311 for _ in 0..10 {
2312 let r = &mut RaxMap::<u64, &str>::new();
2313 for x in 0..2000 {
2314 r.insert_null(x).expect("whoops!");
2315 }
2316
2317 match r.find(1601) {
2318 Some(v) => println!("{}", v),
2319 None => {}
2320 }
2321
2322 let sw = Stopwatch::start_new();
2323
2324 for _po in 0..1000000 {
2325 r.iter(|_, iter| {
2326 iter.seek(EQUAL, 1601);
2327 });
2328 }
2329
2330 println!("RaxMap::cursor_find {}ms", sw.elapsed_ms());
2331 }
2332 }
2333
2334 #[test]
2335 fn bench_rax_insert() {
2336 for _ in 0..10 {
2337 let r = &mut RaxMap::<u64, &str>::new();
2338 let sw = Stopwatch::start_new();
2340
2341 for x in 0..1000000 {
2342 r.insert(x, Box::new("")).expect("whoops!");
2343 }
2344
2345 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2346 println!("Size {}", r.size());
2347 }
2348 }
2349
2350 #[test]
2351 fn bench_rax_insert_show() {
2352 let r = &mut RaxMap::<u64, &str>::new();
2353 let sw = Stopwatch::start_new();
2355
2356 for x in 0..100 {
2357 r.insert(x, Box::new("")).expect("whoops!");
2358 }
2359
2360 r.show();
2361 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2362 assert_eq!(r.size(), 100);
2363 }
2364
2365 #[test]
2366 fn bench_rax_replace() {
2367 let ops = 1000000;
2368 for _ in 0..2 {
2369 let r = &mut RaxMap::<u64, &str>::new();
2370 for x in 0..ops {
2372 r.insert(x, Box::new("")).expect("whoops!");
2373 }
2374
2375 let sw = Stopwatch::start_new();
2376
2377 for x in 0..ops {
2378 r.insert(x, Box::new("")).expect("whoops!");
2380 }
2381
2382 println!("RaxMap::replace {}ms", sw.elapsed_ms());
2383 assert_eq!(r.size(), ops);
2384 }
2385 }
2386
2387 #[test]
2388 fn key_str() {
2389 unsafe {
2390 set_allocator(rax_malloc_hook, rax_realloc_hook, rax_free_hook);
2391 }
2392
2393 let mut r = RaxMap::<&str, MyMsg>::new();
2394
2395 let key = "hello-way";
2396
2397 r.insert(key, Box::new(MyMsg("world 80"))).expect("whoops!");
2398 r.insert("hello-war", Box::new(MyMsg("world 80")))
2399 .expect("whoops!");
2400
2401 r.insert("hello-wares", Box::new(MyMsg("world 80")))
2402 .expect("whoops!");
2403 r.insert("hello", Box::new(MyMsg("world 100")))
2404 .expect("whoops!");
2405
2406 {
2407 match r.find("hello") {
2408 Some(v) => println!("Found {}", v.0),
2409 None => println!("Not Found"),
2410 }
2411 }
2412
2413 r.show();
2414
2415 r.iter(|_, iter| {
2416 if !iter.seek_min() {
2417 return;
2418 }
2419 while iter.forward() {
2420 println!("{}", iter.key());
2421 }
2422 if !iter.seek_max() {
2423 return;
2424 }
2425 while iter.back() {
2426 println!("{}", iter.key());
2427 }
2428 });
2429 }
2430
2431 #[test]
2432 fn key_f64() {
2433 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<f64, MyMsg>>());
2434
2435 let mut r = RaxMap::<f64, MyMsg>::new();
2436
2437 r.insert(100.01, Box::new(MyMsg("world 100")))
2438 .expect("whoops!");
2439 r.insert(80.20, Box::new(MyMsg("world 80")))
2440 .expect("whoops!");
2441 r.insert(100.00, Box::new(MyMsg("world 200")))
2442 .expect("whoops!");
2443 r.insert(99.10, Box::new(MyMsg("world 1")))
2444 .expect("whoops!");
2445
2446 r.show();
2447
2448 r.iter(|_, iter| {
2449 iter.seek_min();
2453 while iter.forward() {
2454 println!("{}", iter.key());
2455 }
2456 iter.seek_max();
2457 while iter.back() {
2458 println!("{}", iter.key());
2459 }
2460 });
2461 }
2462
2463 #[test]
2464 fn key_u64() {
2465 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<u64, MyMsg>>());
2466
2467 let mut r = RaxMap::<u64, MyMsg>::new();
2468
2469 r.insert(100, Box::new(MyMsg("world 100")))
2470 .expect("whoops!");
2471 r.insert(80, Box::new(MyMsg("world 80"))).expect("whoops!");
2472 r.insert(200, Box::new(MyMsg("world 200")))
2473 .expect("whoops!");
2474 r.insert(1, Box::new(MyMsg("world 1"))).expect("whoops!");
2475
2476 r.show();
2477
2478 r.seek_min(|_, it| {
2514 for (key, value) in it.rev() {
2515 println!("Key Len = {}", key);
2516 println!("Data = {}", value.unwrap().0);
2517 }
2518 });
2519
2520 }
2556}