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() -> RaxMap<K, V> {
253 Self::try_new().expect("raxNew: out of memory")
254 }
255
256 pub fn try_new() -> Result<RaxMap<K, V>, RaxError> {
260 let ptr = unsafe { raxNew() };
263
264 if ptr.is_null() {
265 return Err(RaxError::OutOfMemory());
266 }
267
268 Ok(RaxMap {
269 rax: ptr,
270 phantom: std::marker::PhantomData,
271 })
272 }
273
274 pub fn len(&self) -> u64 {
276 unsafe { raxSize(self.rax) }
277 }
278
279 pub fn size(&self) -> u64 {
281 unsafe { raxSize(self.rax) }
282 }
283
284 pub fn is_empty(&self) -> bool {
286 self.len() == 0
287 }
288
289 pub fn show(&self) {
291 unsafe { raxShow(self.rax) }
292 }
293
294 pub fn insert_null(&mut self, key: K) -> Result<Option<Box<V>>, RaxError> {
296 unsafe {
297 let old: &mut *mut u8 = &mut ptr::null_mut();
299
300 let k = key.encode();
304 let (ptr, len) = k.to_buf();
305
306 let r = raxInsert(
307 self.rax,
308 ptr,
313 len,
314 std::ptr::null_mut(),
315 old,
316 );
317
318 if r == 0 && Errno::last() == Errno::ENOMEM {
319 Err(RaxError::OutOfMemory())
320 } else if old.is_null() {
321 Ok(None)
322 } else {
323 Ok(Some(Box::from_raw(*old as *mut V)))
327 }
328 }
329 }
330
331 pub fn try_insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
333 unsafe {
334 let old: &mut *mut u8 = &mut ptr::null_mut();
336
337 let value: &mut V = Box::leak(data);
341
342 let k = key.encode();
346 let (ptr, len) = k.to_buf();
347
348 let r = raxTryInsert(
349 self.rax,
350 ptr,
355 len,
356 value as *mut V as *mut u8,
357 old,
358 );
359
360 if r == 0 {
361 if Errno::last() == Errno::ENOMEM {
362 Err(RaxError::OutOfMemory())
363 } else {
364 Ok(Some(Box::from_raw(value as *mut V)))
365 }
366 } else if old.is_null() {
367 Ok(None)
368 } else {
369 Ok(Some(Box::from_raw(*old as *mut V)))
372 }
373 }
374 }
375
376 pub unsafe fn try_insert_ptr(
382 &mut self,
383 key: K,
384 value: *mut u8,
385 ) -> Result<Option<*mut u8>, RaxError> {
386 let old: &mut *mut u8 = &mut ptr::null_mut();
388
389 let k = key.encode();
393 let (ptr, len) = k.to_buf();
394
395 let r = raxTryInsert(
396 self.rax,
397 ptr, len, value, old,
402 );
403
404 if r == 0 {
405 if Errno::last() == Errno::ENOMEM {
406 Err(RaxError::OutOfMemory())
407 } else {
408 Ok(Some(value))
409 }
410 } else if old.is_null() {
411 Ok(None)
412 } else {
413 Ok(Some(*old))
416 }
417 }
418
419 pub fn insert(&mut self, key: K, data: Box<V>) -> Result<Option<Box<V>>, RaxError> {
422 unsafe {
423 let old: &mut *mut u8 = &mut ptr::null_mut();
425
426 let value: &mut V = Box::leak(data);
430
431 let k = key.encode();
435 let (ptr, len) = k.to_buf();
436
437 let r = raxInsert(
438 self.rax,
439 ptr,
444 len,
445 value as *mut V as *mut u8,
446 old,
447 );
448
449 if r == 0 && Errno::last() == Errno::ENOMEM {
450 Err(RaxError::OutOfMemory())
451 } else if old.is_null() {
452 Ok(None)
453 } else {
454 Ok(Some(Box::from_raw(*old as *mut V)))
458 }
459 }
460 }
461
462 pub unsafe fn insert_ptr(
468 &mut self,
469 key: K,
470 value: *mut u8,
471 ) -> Result<Option<*mut u8>, RaxError> {
472 let old: &mut *mut u8 = &mut ptr::null_mut();
474
475 let k = key.encode();
479 let (ptr, len) = k.to_buf();
480
481 let r = raxInsert(
482 self.rax,
483 ptr, len, value, old,
488 );
489
490 if r == 0 && Errno::last() == Errno::ENOMEM {
491 Err(RaxError::OutOfMemory())
492 } else if old.is_null() {
493 Ok(None)
494 } else {
495 Ok(Some(*old))
499 }
500 }
501
502 pub fn remove(&mut self, key: K) -> (bool, Option<Box<V>>) {
504 unsafe {
505 let old: &mut *mut u8 = &mut ptr::null_mut();
506 let k = key.encode();
507 let (ptr, len) = k.to_buf();
508
509 let r = raxRemove(self.rax, ptr, len, old);
510
511 if old.is_null() {
512 (r == 1, None)
513 } else {
514 (r == 1, Some(Box::from_raw(*old as *mut V)))
515 }
516 }
517 }
518
519 pub fn find_exists(&self, key: K) -> (bool, Option<&V>) {
521 unsafe {
522 let k = key.encode();
523 let (ptr, len) = k.to_buf();
524
525 let value = raxFind(self.rax, ptr, len);
526
527 if value.is_null() {
528 (true, None)
529 } else if value == raxNotFound {
530 (false, None)
531 } else {
532 (true, Some(&*(value as *const V)))
536 }
537 }
538 }
539
540 pub fn find(&self, key: K) -> Option<&V> {
542 unsafe {
543 let k = key.encode();
544 let (ptr, len) = k.to_buf();
545
546 let value = raxFind(self.rax, ptr, len);
547
548 if value.is_null() || value == raxNotFound {
549 None
550 } else {
551 Some(&*(value as *const V))
555 }
556 }
557 }
558
559 pub fn get(&self, key: K) -> Option<&V> {
561 unsafe {
562 let k = key.encode();
563 let (ptr, len) = k.to_buf();
564
565 let value = raxFind(self.rax, ptr, len);
566
567 if value.is_null() || value == raxNotFound {
568 None
569 } else {
570 Some(&*(value as *const V))
574 }
575 }
576 }
577
578 pub fn exists(&self, key: K) -> bool {
580 unsafe {
581 let k = key.encode();
582 let (ptr, len) = k.to_buf();
583
584 let value = raxFind(self.rax, ptr, len);
585
586 !(value.is_null() || value == raxNotFound)
587 }
588 }
589
590 pub fn seek_min<F>(&mut self, f: F)
596 where
597 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
598 {
599 unsafe {
601 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
602 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
603 let mut iter = iter.assume_init();
604 iter.fixup();
605 iter.seek_min();
606 f(self, &mut iter)
607 }
608 }
609
610 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
616 where
617 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
618 {
619 unsafe {
621 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
622 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
623 let mut iter = iter.assume_init();
624 iter.fixup();
625 iter.seek_min();
626 f(self, &mut iter)
627 }
628 }
629
630 pub fn seek_max<F>(&mut self, f: F)
636 where
637 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
638 {
639 unsafe {
641 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
642 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
643 let mut iter = iter.assume_init();
644 iter.fixup();
645 iter.seek_max();
646 f(self, &mut iter)
647 }
648 }
649
650 pub fn seek_max_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
656 where
657 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
658 {
659 unsafe {
661 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
662 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
663 let mut iter = iter.assume_init();
664 iter.fixup();
665 iter.seek_max();
666 f(self, &mut iter)
667 }
668 }
669
670 pub fn seek<F>(&mut self, op: &str, key: K, f: F)
676 where
677 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
678 {
679 unsafe {
681 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
682 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
683 let mut iter = iter.assume_init();
684 iter.fixup();
685 iter.seek(op, key);
686 f(self, &mut iter)
687 }
688 }
689
690 pub fn seek_result<R, F>(&mut self, op: &str, key: K, f: F) -> Result<R, RaxError>
696 where
697 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
698 {
699 unsafe {
701 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
702 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
703 let mut iter = iter.assume_init();
704 iter.fixup();
705 iter.seek(op, key);
706 f(self, &mut iter)
707 }
708 }
709
710 pub fn iter<F>(&mut self, f: F)
716 where
717 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>),
718 {
719 unsafe {
721 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
722 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
723 let mut iter = iter.assume_init();
724 iter.fixup();
725 f(self, &mut iter)
726 }
727 }
728
729 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
735 where
736 F: Fn(&mut RaxMap<K, V>, &mut RaxIterator<K, V>) -> Result<R, RaxError>,
737 {
738 unsafe {
740 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
741 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
742 let mut iter = iter.assume_init();
743 iter.fixup();
744 f(self, &mut iter)
745 }
746 }
747}
748
749pub struct RaxSet<K: RaxKey> {
795 rax: *mut rax,
796 _marker: std::marker::PhantomData<K>,
797}
798
799impl<K: RaxKey> Drop for RaxSet<K> {
800 fn drop(&mut self) {
801 unsafe { raxFree(self.rax) }
803 }
804}
805
806unsafe impl<K: RaxKey + Send> Send for RaxSet<K> {}
809
810unsafe impl<K: RaxKey + Sync> Sync for RaxSet<K> {}
813
814impl<K: RaxKey> Default for RaxSet<K> {
815 fn default() -> Self {
816 Self::new()
817 }
818}
819
820impl<K: RaxKey> RaxSet<K> {
822 pub fn new() -> RaxSet<K> {
828 Self::try_new().expect("raxNew: out of memory")
829 }
830
831 pub fn try_new() -> Result<RaxSet<K>, RaxError> {
835 let ptr = unsafe { raxNew() };
838
839 if ptr.is_null() {
840 return Err(RaxError::OutOfMemory());
841 }
842
843 Ok(RaxSet {
844 rax: ptr,
845 _marker: std::marker::PhantomData,
846 })
847 }
848
849 pub fn len(&self) -> u64 {
851 unsafe { raxSize(self.rax) }
852 }
853
854 pub fn size(&self) -> u64 {
856 unsafe { raxSize(self.rax) }
857 }
858
859 pub fn show(&self) {
861 unsafe { raxShow(self.rax) }
862 }
863
864 pub fn is_empty(&self) -> bool {
866 self.len() == 0
867 }
868
869 pub fn insert(&mut self, key: K) -> Result<bool, RaxError> {
872 unsafe {
873 let k = key.encode();
877 let (ptr, len) = k.to_buf();
878
879 let r = raxTryInsert(
880 self.rax,
881 ptr,
886 len,
887 std::ptr::null_mut(),
888 std::ptr::null_mut(),
889 );
890
891 if r == 0 {
892 if Errno::last() == Errno::ENOMEM {
893 Err(RaxError::OutOfMemory())
894 } else {
895 Ok(false)
896 }
897 } else {
898 Ok(true)
899 }
900 }
901 }
902
903 pub fn remove(&mut self, key: K) -> bool {
904 unsafe {
905 let k = key.encode();
906 let (ptr, len) = k.to_buf();
907
908 let r = raxRemove(self.rax, ptr, len, &mut std::ptr::null_mut());
909
910 r == 1
911 }
912 }
913
914 pub fn exists(&self, key: K) -> bool {
916 unsafe {
917 let k = key.encode();
918 let (ptr, len) = k.to_buf();
919
920 let value = raxFind(self.rax, ptr, len);
921
922 value != raxNotFound
923 }
924 }
925
926 pub fn seek_min<F>(&mut self, f: F)
932 where
933 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>),
934 {
935 unsafe {
937 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
938 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
939 let mut iter = iter.assume_init();
940 iter.fixup();
941 iter.seek_min();
942 f(self, &mut iter)
943 }
944 }
945
946 pub fn seek_min_result<R, F>(&mut self, f: F) -> Result<R, RaxError>
952 where
953 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
954 {
955 unsafe {
957 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
958 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
959 let mut iter = iter.assume_init();
960 iter.fixup();
961 iter.seek_min();
962 f(self, &mut iter)
963 }
964 }
965
966 pub fn seek_max<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_max();
982 f(self, &mut iter)
983 }
984 }
985
986 pub fn seek_max_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_max();
1002 f(self, &mut iter)
1003 }
1004 }
1005
1006 pub fn seek<F>(&mut self, op: &str, key: K, 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(op, key);
1022 f(self, &mut iter)
1023 }
1024 }
1025
1026 pub fn seek_result<R, F>(&mut self, op: &str, key: K, 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(op, key);
1042 f(self, &mut iter)
1043 }
1044 }
1045
1046 pub fn iter<F>(&mut self, 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 f(self, &mut iter)
1062 }
1063 }
1064
1065 pub fn iter_result<F, R>(&mut self, f: F) -> Result<R, RaxError>
1071 where
1072 F: Fn(&mut RaxSet<K>, &mut RaxIterator<K, usize>) -> Result<R, RaxError>,
1073 {
1074 unsafe {
1076 let mut iter = MaybeUninit::<RaxIterator<K, usize>>::uninit();
1077 raxStart(iter.as_mut_ptr() as *mut raxIterator, self.rax);
1078 let mut iter = iter.assume_init();
1079 iter.fixup();
1080 f(self, &mut iter)
1081 }
1082 }
1083}
1084
1085pub trait RaxKey<RHS = Self>: Clone + Default + std::fmt::Debug {
1180 type Output: RaxKey;
1181
1182 fn encode(self) -> Self::Output;
1183
1184 fn to_buf(&self) -> (*const u8, usize);
1185
1186 unsafe fn from_buf(ptr: *const u8, len: usize) -> RHS;
1190}
1191
1192impl RaxKey for f32 {
1193 type Output = u32;
1194
1195 fn encode(self) -> Self::Output {
1196 self.to_bits().to_be()
1198 }
1199
1200 fn to_buf(&self) -> (*const u8, usize) {
1201 (
1203 self as *const _ as *const u8,
1204 std::mem::size_of::<Self::Output>(),
1205 )
1206 }
1207
1208 unsafe fn from_buf(ptr: *const u8, len: usize) -> f32 {
1209 assert_eq!(len, std::mem::size_of::<f32>());
1210 if len != size_of::<Self::Output>() {
1211 return Self::default();
1212 }
1213 unsafe {
1214 f32::from_bits(u32::from_be(
1216 *(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut u32),
1217 ))
1218 }
1219 }
1220}
1221
1222impl RaxKey for f64 {
1223 type Output = u64;
1224
1225 fn encode(self) -> Self::Output {
1226 self.to_bits().to_be()
1228 }
1229
1230 fn to_buf(&self) -> (*const u8, usize) {
1231 (self as *const _ as *const u8, size_of::<Self::Output>())
1233 }
1234
1235 unsafe fn from_buf(ptr: *const u8, len: usize) -> f64 {
1236 assert_eq!(len, std::mem::size_of::<f64>());
1237 if len != size_of::<Self::Output>() {
1238 return Self::default();
1239 }
1240 unsafe {
1241 f64::from_bits(u64::from_be(
1243 *(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u64),
1244 ))
1245 }
1246 }
1247}
1248
1249impl RaxKey for isize {
1250 type Output = isize;
1251
1252 fn encode(self) -> Self::Output {
1253 self.to_be()
1254 }
1255
1256 fn to_buf(&self) -> (*const u8, usize) {
1257 (self as *const _ as *const u8, size_of::<Self::Output>())
1258 }
1259
1260 unsafe fn from_buf(ptr: *const u8, len: usize) -> isize {
1261 assert_eq!(len, std::mem::size_of::<isize>());
1262 if len != size_of::<Self::Output>() {
1263 return Self::default();
1264 }
1265 unsafe { isize::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut isize)) }
1266 }
1267}
1268
1269impl RaxKey for usize {
1270 type Output = usize;
1271
1272 fn encode(self) -> Self::Output {
1273 self.to_be()
1274 }
1275
1276 fn to_buf(&self) -> (*const u8, usize) {
1277 (
1278 self as *const _ as *const u8,
1279 std::mem::size_of::<Self::Output>(),
1280 )
1281 }
1282
1283 unsafe fn from_buf(ptr: *const u8, len: usize) -> usize {
1284 assert_eq!(len, std::mem::size_of::<usize>());
1285 if len != size_of::<Self::Output>() {
1286 return Self::default();
1287 }
1288 unsafe {
1289 usize::from_be(*(ptr as *mut [u8; std::mem::size_of::<Self::Output>()] as *mut usize))
1290 }
1291 }
1292}
1293
1294impl RaxKey for i16 {
1295 type Output = i16;
1296
1297 fn encode(self) -> Self::Output {
1298 self.to_be()
1299 }
1300
1301 fn to_buf(&self) -> (*const u8, usize) {
1302 (self as *const _ as *const u8, size_of::<Self::Output>())
1303 }
1304
1305 unsafe fn from_buf(ptr: *const u8, len: usize) -> Self {
1306 if len != size_of::<Self::Output>() {
1307 return Self::default();
1308 }
1309 unsafe { i16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i16)) }
1310 }
1311}
1312
1313impl RaxKey for u16 {
1314 type Output = u16;
1315
1316 fn encode(self) -> Self::Output {
1317 self.to_be()
1318 }
1319
1320 fn to_buf(&self) -> (*const u8, usize) {
1321 (self as *const _ as *const u8, size_of::<Self::Output>())
1322 }
1323
1324 unsafe fn from_buf(ptr: *const u8, len: usize) -> u16 {
1325 assert_eq!(len, std::mem::size_of::<u16>());
1326 if len != size_of::<Self::Output>() {
1327 return Self::default();
1328 }
1329 unsafe { u16::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u16)) }
1330 }
1331}
1332
1333impl RaxKey for i32 {
1334 type Output = i32;
1335
1336 fn encode(self) -> Self::Output {
1337 self.to_be()
1338 }
1339
1340 fn to_buf(&self) -> (*const u8, usize) {
1341 (self as *const _ as *const u8, size_of::<Self::Output>())
1342 }
1343
1344 unsafe fn from_buf(ptr: *const u8, len: usize) -> i32 {
1345 assert_eq!(len, std::mem::size_of::<i32>());
1346 if len != size_of::<Self::Output>() {
1347 return Self::default();
1348 }
1349 unsafe { i32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i32)) }
1350 }
1351}
1352
1353impl RaxKey for u32 {
1354 type Output = u32;
1355
1356 fn encode(self) -> Self::Output {
1357 self.to_be()
1358 }
1359
1360 fn to_buf(&self) -> (*const u8, usize) {
1361 (self as *const _ as *const u8, size_of::<Self::Output>())
1362 }
1363
1364 unsafe fn from_buf(ptr: *const u8, len: usize) -> u32 {
1365 assert_eq!(len, std::mem::size_of::<u32>());
1366 if len != size_of::<Self::Output>() {
1367 return Self::default();
1368 }
1369 unsafe { u32::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u32)) }
1370 }
1371}
1372
1373impl RaxKey for i64 {
1374 type Output = i64;
1375
1376 fn encode(self) -> Self::Output {
1377 self.to_be()
1378 }
1379
1380 fn to_buf(&self) -> (*const u8, usize) {
1381 (self as *const _ as *const u8, size_of::<Self::Output>())
1382 }
1383
1384 unsafe fn from_buf(ptr: *const u8, len: usize) -> i64 {
1385 assert_eq!(len, std::mem::size_of::<i64>());
1386 if len != size_of::<Self::Output>() {
1387 return Self::default();
1388 }
1389 unsafe { i64::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i64)) }
1390 }
1391}
1392
1393impl RaxKey for u64 {
1394 type Output = u64;
1395
1396 fn encode(self) -> Self::Output {
1397 self.to_be()
1398 }
1399
1400 fn to_buf(&self) -> (*const u8, usize) {
1401 (self as *const _ as *const u8, size_of::<Self::Output>())
1402 }
1403
1404 unsafe fn from_buf(ptr: *const u8, len: usize) -> u64 {
1405 assert_eq!(len, std::mem::size_of::<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 fn encode(self) -> Self::Output {
1417 self.to_be()
1418 }
1419
1420 fn to_buf(&self) -> (*const u8, usize) {
1421 (self as *const _ as *const u8, size_of::<Self::Output>())
1422 }
1423
1424 unsafe fn from_buf(ptr: *const u8, len: usize) -> i128 {
1425 assert_eq!(len, std::mem::size_of::<i128>());
1426 if len != size_of::<Self::Output>() {
1427 return Self::default();
1428 }
1429 unsafe { i128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut i128)) }
1430 }
1431}
1432
1433impl RaxKey for u128 {
1434 type Output = u128;
1435
1436 fn encode(self) -> Self::Output {
1437 self.to_be()
1438 }
1439
1440 fn to_buf(&self) -> (*const u8, usize) {
1441 (self as *const _ as *const u8, size_of::<Self::Output>())
1442 }
1443
1444 unsafe fn from_buf(ptr: *const u8, len: usize) -> u128 {
1445 assert_eq!(len, std::mem::size_of::<u128>());
1446 if len != size_of::<Self::Output>() {
1447 return Self::default();
1448 }
1449 unsafe { u128::from_be(*(ptr as *mut [u8; size_of::<Self::Output>()] as *mut u128)) }
1450 }
1451}
1452
1453impl RaxKey for Vec<u8> {
1454 type Output = Vec<u8>;
1455
1456 fn encode(self) -> Vec<u8> {
1457 self
1458 }
1459
1460 fn to_buf(&self) -> (*const u8, usize) {
1461 (self.as_ptr(), self.len())
1462 }
1463
1464 unsafe fn from_buf(ptr: *const u8, len: usize) -> Vec<u8> {
1465 unsafe { std::slice::from_raw_parts(ptr, len).to_vec() }
1466 }
1467}
1468
1469impl<'a> RaxKey for &'a [u8] {
1470 type Output = &'a [u8];
1471
1472 fn encode(self) -> &'a [u8] {
1473 self
1474 }
1475
1476 fn to_buf(&self) -> (*const u8, usize) {
1477 (self.as_ptr(), self.len())
1478 }
1479
1480 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a [u8] {
1481 unsafe { std::slice::from_raw_parts(ptr, len) }
1482 }
1483}
1484
1485impl<'a> RaxKey for &'a str {
1502 type Output = &'a str;
1503
1504 fn encode(self) -> Self::Output {
1505 self
1506 }
1507
1508 fn to_buf(&self) -> (*const u8, usize) {
1509 ((*self).as_ptr(), self.len())
1510 }
1511
1512 unsafe fn from_buf(ptr: *const u8, len: usize) -> &'a str {
1513 unsafe { std::str::from_utf8(std::slice::from_raw_parts(ptr, len)).unwrap_or_default() }
1514 }
1515}
1516
1517#[repr(C)]
1518pub struct RaxIterator<K: RaxKey, V> {
1519 pub flags: libc::c_int,
1520 pub rt: *mut rax,
1521 pub key: *mut u8,
1522 pub data: *mut libc::c_void,
1523 pub key_len: libc::size_t,
1524 pub key_max: libc::size_t,
1525 pub key_static_string: [u8; 128],
1526 pub node: *mut raxNode,
1527 pub stack: raxStack,
1528 pub node_cb: Option<raxNodeCallback>,
1529 _marker: std::marker::PhantomData<(K, V)>,
1530}
1531
1532impl<K: RaxKey, V> Drop for RaxIterator<K, V> {
1534 fn drop(&mut self) {
1535 unsafe {
1536 if self.key_max == RAX_ITER_STATIC_LEN as usize {
1538 self.key = self.key_static_string.as_mut_ptr();
1539 }
1540
1541 if self.stack.maxitems == RAX_STACK_STATIC_ITEMS as usize {
1543 self.stack.stack = self.stack.static_items.as_mut_ptr();
1544 }
1545
1546 raxStop(&raw mut *self as *mut raxIterator);
1547 }
1548 }
1549}
1550
1551impl<K: RaxKey, V: 'static> Iterator for RaxIterator<K, V> {
1553 type Item = (K, Option<&'static V>);
1554
1555 fn next(&mut self) -> Option<<Self as Iterator>::Item> {
1556 unsafe {
1557 if raxNext(&raw mut *self as *mut raxIterator) == 1 {
1558 let data: *mut libc::c_void = self.data;
1559 if data.is_null() {
1560 None
1561 } else {
1562 let val = data as *const V;
1563 if val.is_null() {
1564 Some((self.key(), None))
1565 } else {
1566 Some((self.key(), Some(&*val)))
1567 }
1568 }
1569 } else {
1570 None
1571 }
1572 }
1573 }
1574}
1575
1576impl<K: RaxKey, V: 'static> DoubleEndedIterator for RaxIterator<K, V> {
1578 fn next_back(&mut self) -> Option<<Self as Iterator>::Item> {
1579 unsafe {
1580 if raxPrev(&raw mut *self as *mut raxIterator) == 1 {
1581 let data: *mut libc::c_void = self.data;
1582 if data.is_null() {
1583 None
1584 } else {
1585 let val = data as *const V;
1586 if val.is_null() {
1587 Some((self.key(), None))
1588 } else {
1589 Some((self.key(), Some(&*val)))
1590 }
1591 }
1592 } else {
1593 None
1594 }
1595 }
1596 }
1597}
1598
1599impl<K: RaxKey, V> RaxIterator<K, V> {
1601 pub fn new(r: RaxMap<K, V>) -> RaxIterator<K, V> {
1603 unsafe {
1605 let mut iter = MaybeUninit::<RaxIterator<K, V>>::uninit();
1606 raxStart(iter.as_mut_ptr() as *mut raxIterator, r.rax);
1607 let mut iter = iter.assume_init();
1608 iter.fixup();
1609 iter
1610 }
1611 }
1612
1613 pub fn print_ptr(&self) {
1614 println!("ptr = {:p}", self);
1615 println!("ptr = {:p}", self as *const _ as *const raxIterator);
1616 }
1617
1618 pub fn seek_min(&mut self) -> bool {
1619 unsafe {
1620 if raxSeek(
1621 &raw mut *self as *mut raxIterator,
1622 BEGIN.as_ptr(),
1623 std::ptr::null(),
1624 0,
1625 ) == 1
1626 {
1627 self.forward()
1628 } else {
1629 false
1630 }
1631 }
1632 }
1633
1634 pub fn seek_max(&mut self) -> bool {
1635 unsafe {
1636 if raxSeek(
1637 &raw mut *self as *mut raxIterator,
1638 END.as_ptr(),
1639 std::ptr::null(),
1640 0,
1641 ) == 1
1642 {
1643 self.back()
1644 } else {
1645 false
1646 }
1647 }
1648 }
1649
1650 pub fn back(&mut self) -> bool {
1651 unsafe { raxPrev(&raw mut *self as *mut raxIterator) == 1 }
1652 }
1653
1654 pub fn forward(&mut self) -> bool {
1655 unsafe { raxNext(&raw mut *self as *mut raxIterator) == 1 }
1656 }
1657
1658 pub fn key(&self) -> K {
1660 unsafe { K::from_buf(self.key, self.key_len) }
1661 }
1662
1663 pub fn value(&self) -> Option<&V> {
1665 unsafe {
1666 let data: *mut libc::c_void = self.data;
1667 if data.is_null() {
1668 None
1669 } else {
1670 Some(&*(data as *const V))
1671 }
1672 }
1673 }
1674
1675 pub fn lesser(&mut self, key: K) -> bool {
1676 self.seek(LESSER, key)
1677 }
1678
1679 pub fn lesser_equal(&mut self, key: K) -> bool {
1680 self.seek(LESSER_EQUAL, key)
1681 }
1682
1683 pub fn greater(&mut self, key: K) -> bool {
1684 self.seek(GREATER, key)
1685 }
1686
1687 pub fn greater_equal(&mut self, key: K) -> bool {
1688 self.seek(GREATER_EQUAL, key)
1689 }
1690
1691 pub fn seek(&mut self, op: &str, key: K) -> bool {
1692 unsafe {
1693 let k = key.encode();
1694 let (p, len) = k.to_buf();
1695 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len) == 1
1696 && self.flags & RAX_ITER_EOF != 0
1697 }
1698 }
1699
1700 pub fn seek_raw(&mut self, op: &str, key: K) -> i32 {
1701 unsafe {
1702 let k = key.encode();
1703 let (p, len) = k.to_buf();
1704 raxSeek(&raw mut *self as *mut raxIterator, op.as_ptr(), p, len)
1705 }
1706 }
1707
1708 pub fn seek_bytes(&mut self, op: &str, ele: &[u8]) -> bool {
1709 unsafe {
1710 raxSeek(
1711 &raw mut *self as *mut raxIterator,
1712 op.as_ptr(),
1713 ele.as_ptr(),
1714 ele.len() as libc::size_t,
1715 ) == 1
1716 }
1717 }
1718
1719 pub fn eof(&self) -> bool {
1724 self.flags & RAX_ITER_EOF != 0
1725 }
1726
1727 pub fn fixup(&mut self) {
1729 self.key = self.key_static_string.as_mut_ptr();
1730 self.stack.stack = self.stack.static_items.as_mut_ptr();
1731 }
1732}
1733
1734impl fmt::Display for RaxError {
1735 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1736 match *self {
1737 RaxError::Generic(ref err) => write!(f, "{err}"),
1738 RaxError::OutOfMemory() => write!(f, "out of memory"),
1739 }
1740 }
1741}
1742
1743impl error::Error for RaxError {
1744 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
1745 match *self {
1746 RaxError::Generic(ref err) => Some(err),
1751 RaxError::OutOfMemory() => Some(self),
1752 }
1753 }
1754}
1755
1756#[derive(Debug)]
1757pub struct GenericError {
1758 message: String,
1759}
1760
1761impl GenericError {
1762 pub fn new(message: &str) -> GenericError {
1763 GenericError {
1764 message: String::from(message),
1765 }
1766 }
1767}
1768
1769impl fmt::Display for GenericError {
1770 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1771 write!(f, "Store error: {}", self.message)
1772 }
1773}
1774
1775impl error::Error for GenericError {}
1776
1777#[repr(C)]
1778pub struct rax;
1779
1780#[repr(C)]
1781pub struct raxNode;
1782
1783#[repr(C)]
1784pub struct raxStack {
1785 stack: *mut *mut libc::c_void,
1786 items: libc::size_t,
1787 maxitems: libc::size_t,
1788 static_items: [*mut libc::c_void; 32],
1789 oom: libc::c_int,
1790}
1791
1792#[repr(C)]
1793pub struct raxIterator;
1794
1795#[allow(non_snake_case)]
1796#[allow(non_camel_case_types)]
1797extern "C" fn RaxFreeWithCallbackWrapper<V>(v: *mut libc::c_void) {
1798 unsafe {
1799 drop(Box::from_raw(v as *mut V));
1801 }
1802}
1803
1804#[allow(non_camel_case_types)]
1805type raxNodeCallback = extern "C" fn(v: *mut libc::c_void);
1806
1807type RaxFreeCallback = extern "C" fn(v: *mut libc::c_void);
1808
1809#[allow(improper_ctypes)]
1810#[allow(non_snake_case)]
1811#[allow(non_camel_case_types)]
1812#[link(name = "rax", kind = "static")]
1813extern "C" {
1814 pub static raxNotFound: *mut u8;
1815
1816 pub static mut rax_malloc: extern "C" fn(size: libc::size_t) -> *mut u8;
1817 pub static mut rax_realloc:
1818 extern "C" fn(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8;
1819 pub static mut rax_free: extern "C" fn(ptr: *mut libc::c_void);
1820
1821 pub fn raxIteratorSize() -> libc::c_int;
1822
1823 pub fn raxNew() -> *mut rax;
1824
1825 pub fn raxFree(rax: *mut rax);
1826
1827 pub fn raxFreeWithCallback(rax: *mut rax, callback: RaxFreeCallback);
1828
1829 pub fn raxInsert(
1830 rax: *mut rax,
1831 s: *const u8,
1832 len: libc::size_t,
1833 data: *const u8,
1834 old: &mut *mut u8,
1835 ) -> libc::c_int;
1836
1837 pub fn raxTryInsert(
1838 rax: *mut rax,
1839 s: *const u8,
1840 len: libc::size_t,
1841 data: *const u8,
1842 old: *mut *mut u8,
1843 ) -> libc::c_int;
1844
1845 pub fn raxRemove(
1846 rax: *mut rax,
1847 s: *const u8,
1848 len: libc::size_t,
1849 old: &mut *mut u8,
1850 ) -> libc::c_int;
1851
1852 pub fn raxFind(rax: *mut rax, s: *const u8, len: libc::size_t) -> *mut u8;
1853
1854 pub fn raxIteratorNew(rt: *mut rax) -> *mut raxIterator;
1855
1856 pub fn raxStart(it: *mut raxIterator, rt: *mut rax);
1857
1858 pub fn raxSeek(
1859 it: *mut raxIterator,
1860 op: *const u8,
1861 ele: *const u8,
1862 len: libc::size_t,
1863 ) -> libc::c_int;
1864
1865 pub fn raxNext(it: *mut raxIterator) -> libc::c_int;
1866
1867 pub fn raxPrev(it: *mut raxIterator) -> libc::c_int;
1868
1869 pub fn raxRandomWalk(it: *mut raxIterator, steps: libc::size_t) -> libc::c_int;
1870
1871 pub fn raxCompare(
1872 it: *mut raxIterator,
1873 op: *const u8,
1874 key: *mut u8,
1875 key_len: libc::size_t,
1876 ) -> libc::c_int;
1877
1878 pub fn raxStop(it: *mut raxIterator);
1879
1880 pub fn raxEOF(it: *mut raxIterator) -> libc::c_int;
1881
1882 pub fn raxShow(rax: *mut rax);
1883
1884 pub fn raxSize(rax: *mut rax) -> u64;
1885}
1886
1887#[cfg(test)]
1888mod tests {
1889 extern crate test;
1890 use std::{
1891 self,
1892 default::Default,
1893 fmt,
1894 time::{Duration, Instant},
1895 };
1896
1897 use super::*;
1898
1899 extern "C" fn rax_malloc_hook(size: libc::size_t) -> *mut u8 {
1900 unsafe {
1901 println!("malloc");
1902 libc::malloc(size) as *mut u8
1903 }
1904 }
1905
1906 extern "C" fn rax_realloc_hook(ptr: *mut libc::c_void, size: libc::size_t) -> *mut u8 {
1907 unsafe {
1908 println!("realloc");
1909 libc::realloc(ptr, size) as *mut u8
1910 }
1911 }
1912
1913 extern "C" fn rax_free_hook(ptr: *mut libc::c_void) {
1914 unsafe {
1915 println!("free");
1916 libc::free(ptr)
1917 }
1918 }
1919
1920 pub struct MyMsg<'a>(&'a str);
1921
1922 impl<'a> Drop for MyMsg<'a> {
1923 fn drop(&mut self) {
1924 println!("dropped -> {}", self.0);
1925 }
1926 }
1927
1928 #[derive(Clone, Copy)]
1929 pub struct Stopwatch {
1930 start_time: Option<Instant>,
1931 elapsed: Duration,
1932 }
1933
1934 impl Default for Stopwatch {
1935 fn default() -> Stopwatch {
1936 Stopwatch {
1937 start_time: None,
1938 elapsed: Duration::from_secs(0),
1939 }
1940 }
1941 }
1942
1943 impl fmt::Display for Stopwatch {
1944 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1945 return write!(f, "{}ms", self.elapsed_ms());
1946 }
1947 }
1948
1949 #[expect(unused)]
1950 impl Stopwatch {
1951 pub fn new() -> Stopwatch {
1952 let sw: Stopwatch = Default::default();
1953 return sw;
1954 }
1955 pub fn start_new() -> Stopwatch {
1956 let mut sw = Stopwatch::new();
1957 sw.start();
1958 return sw;
1959 }
1960
1961 pub fn start(&mut self) {
1962 self.start_time = Some(Instant::now());
1963 }
1964 pub fn stop(&mut self) {
1965 self.elapsed = self.elapsed();
1966 self.start_time = None;
1967 }
1968 pub fn reset(&mut self) {
1969 self.elapsed = Duration::from_secs(0);
1970 self.start_time = None;
1971 }
1972 pub fn restart(&mut self) {
1973 self.reset();
1974 self.start();
1975 }
1976
1977 pub fn is_running(&self) -> bool {
1978 return self.start_time.is_some();
1979 }
1980
1981 pub fn elapsed(&self) -> Duration {
1982 match self.start_time {
1983 Some(t1) => {
1984 return t1.elapsed() + self.elapsed;
1985 }
1986 None => {
1987 return self.elapsed;
1988 }
1989 }
1990 }
1991 pub fn elapsed_ms(&self) -> i64 {
1992 let dur = self.elapsed();
1993 return (dur.as_secs() * 1000 + (dur.subsec_nanos() / 1000000) as u64) as i64;
1994 }
1995 }
1996
1997 #[test]
1998 fn bench() {
1999 let ops = 1000000;
2000 println!("{} operations per function", ops);
2001
2002 for _ in 0..2 {
2003 println!();
2004 println!("Gets...");
2005 {
2006 let r = &mut RaxSet::<u64>::new();
2007 for x in 0..2000 {
2008 r.insert(x).expect("whoops!");
2009 }
2010
2011 let sw = Stopwatch::start_new();
2012 for _po in 0..ops {
2013 r.exists(1601);
2014 }
2015
2016 println!("RaxSet::get {}ms", sw.elapsed_ms());
2017 }
2018 {
2019 let r = &mut RaxMap::<u64, &str>::new();
2020 for x in 0..2000 {
2021 r.insert_null(x).expect("whoops!");
2022 }
2023
2024 match r.find(1601) {
2025 Some(v) => println!("{}", v),
2026 None => {}
2027 }
2028
2029 let sw = Stopwatch::start_new();
2030
2031 for _po in 0..ops {
2032 r.find(1601);
2033 }
2034
2035 println!("RaxMap::get {}ms", sw.elapsed_ms());
2036 }
2037
2038 {
2039 let r = &mut RaxMap::<u64, &str>::new();
2040 for x in 0..2000 {
2041 r.insert_null(x).expect("whoops!");
2042 }
2043 let sw = Stopwatch::start_new();
2044
2045 for _po in 0..ops {
2046 r.iter(|_, iter| {
2047 iter.seek(EQUAL, 1601);
2048 });
2049 }
2050
2051 println!("RaxCursor:seek {}ms", sw.elapsed_ms());
2052 }
2053 {
2054 let r = &mut std::collections::HashSet::<u64>::new();
2055 for x in 0..2000 {
2056 r.insert(x);
2057 }
2058
2059 let sw = Stopwatch::start_new();
2060
2061 let xx = 300;
2062 for _po in 0..ops {
2063 r.get(&xx);
2064 }
2065
2066 println!("HashSet::get {}ms", sw.elapsed_ms());
2067 }
2068 {
2069 let r = &mut std::collections::HashMap::<u64, &str>::new();
2070 for x in 0..2000 {
2071 r.insert(x, "");
2072 }
2073
2074 let sw = Stopwatch::start_new();
2075
2076 let xx = 300;
2077 for _po in 0..ops {
2078 r.get(&xx);
2079 }
2080
2081 println!("HashMap::get {}ms", sw.elapsed_ms());
2082 }
2083 {
2084 let r = &mut std::collections::BTreeSet::<u64>::new();
2085 for x in 0..2000 {
2086 r.insert(x);
2087 }
2088
2089 let sw = Stopwatch::start_new();
2090
2091 let xx = 300;
2092 for _po in 0..ops {
2093 r.get(&xx);
2094 }
2095
2096 println!("BTreeSet::get {}ms", sw.elapsed_ms());
2097 }
2098 {
2099 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2100 for x in 0..2000 {
2101 r.insert(x, "");
2102 }
2103
2104 let sw = Stopwatch::start_new();
2105
2106 let xx = 300;
2107 for _po in 0..ops {
2108 r.get(&xx);
2109 }
2110
2111 println!("BTreeMap::get {}ms", sw.elapsed_ms());
2112 }
2113
2114 println!();
2115 println!("Inserts...");
2116 {
2117 let r = &mut RaxMap::<u64, &str>::new();
2118 let sw = Stopwatch::start_new();
2119
2120 for x in 0..ops {
2121 r.insert(x, Box::new("")).expect("whoops!");
2122 }
2123
2124 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2125 }
2126
2127 {
2128 let r = &mut RaxSet::<u64>::new();
2129 let sw = Stopwatch::start_new();
2130
2131 for x in 0..ops {
2132 r.insert(x).expect("whoops!");
2133 }
2134
2135 println!("RaxSet::insert {}ms", sw.elapsed_ms());
2136 }
2137
2138 {
2139 let r = &mut std::collections::BTreeSet::<u64>::new();
2140 let sw = Stopwatch::start_new();
2141
2142 for x in 0..ops {
2143 r.insert(x);
2144 }
2145
2146 println!("BTreeSet::insert {}ms", sw.elapsed_ms());
2147 }
2148 {
2149 let r = &mut std::collections::BTreeMap::<u64, &str>::new();
2150 let sw = Stopwatch::start_new();
2151
2152 for x in 0..ops {
2153 r.insert(x, "");
2154 }
2155
2156 println!("BTreeMap::insert {}ms", sw.elapsed_ms());
2157 }
2158
2159 {
2160 let r = &mut std::collections::HashMap::<u64, &str>::new();
2161 let sw = Stopwatch::start_new();
2162
2163 for x in 0..ops {
2164 r.insert(x, "");
2165 }
2166
2167 println!("HashMap::insert {}ms", sw.elapsed_ms());
2168 }
2169 }
2170 }
2171
2172 #[test]
2173 fn bench_rax_find() {
2174 for _ in 0..10 {
2175 let r = &mut RaxMap::<u64, &str>::new();
2176 for x in 0..2000 {
2177 r.insert_null(x).expect("whoops!");
2178 }
2179
2180 match r.find(1601) {
2181 Some(v) => println!("{}", v),
2182 None => {}
2183 }
2184
2185 let sw = Stopwatch::start_new();
2186
2187 for _po in 0..1000000 {
2188 r.find(1601);
2189 }
2190
2191 println!("Thing took {}ms", sw.elapsed_ms());
2192 }
2193 }
2194
2195 #[test]
2196 fn bench_rax_cur_find() {
2197 for _ in 0..10 {
2198 let r = &mut RaxMap::<u64, &str>::new();
2199 for x in 0..2000 {
2200 r.insert_null(x).expect("whoops!");
2201 }
2202
2203 match r.find(1601) {
2204 Some(v) => println!("{}", v),
2205 None => {}
2206 }
2207
2208 let sw = Stopwatch::start_new();
2209
2210 for _po in 0..1000000 {
2211 r.iter(|_, iter| {
2212 iter.seek(EQUAL, 1601);
2213 });
2214 }
2215
2216 println!("RaxMap::cursor_find {}ms", sw.elapsed_ms());
2217 }
2218 }
2219
2220 #[test]
2221 fn bench_rax_insert() {
2222 for _ in 0..10 {
2223 let r = &mut RaxMap::<u64, &str>::new();
2224 let sw = Stopwatch::start_new();
2226
2227 for x in 0..1000000 {
2228 r.insert(x, Box::new("")).expect("whoops!");
2229 }
2230
2231 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2232 println!("Size {}", r.size());
2233 }
2234 }
2235
2236 #[test]
2237 fn bench_rax_insert_show() {
2238 let r = &mut RaxMap::<u64, &str>::new();
2239 let sw = Stopwatch::start_new();
2241
2242 for x in 0..100 {
2243 r.insert(x, Box::new("")).expect("whoops!");
2244 }
2245
2246 r.show();
2247 println!("RaxMap::insert {}ms", sw.elapsed_ms());
2248 assert_eq!(r.size(), 100);
2249 }
2250
2251 #[test]
2252 fn bench_rax_replace() {
2253 let ops = 1000000;
2254 for _ in 0..2 {
2255 let r = &mut RaxMap::<u64, &str>::new();
2256 for x in 0..ops {
2258 r.insert(x, Box::new("")).expect("whoops!");
2259 }
2260
2261 let sw = Stopwatch::start_new();
2262
2263 for x in 0..ops {
2264 r.insert(x, Box::new("")).expect("whoops!");
2266 }
2267
2268 println!("RaxMap::replace {}ms", sw.elapsed_ms());
2269 assert_eq!(r.size(), ops);
2270 }
2271 }
2272
2273 #[test]
2274 fn key_str() {
2275 unsafe {
2276 set_allocator(rax_malloc_hook, rax_realloc_hook, rax_free_hook);
2277 }
2278
2279 let mut r = RaxMap::<&str, MyMsg>::new();
2280
2281 let key = "hello-way";
2282
2283 r.insert(key, Box::new(MyMsg("world 80"))).expect("whoops!");
2284 r.insert("hello-war", Box::new(MyMsg("world 80")))
2285 .expect("whoops!");
2286
2287 r.insert("hello-wares", Box::new(MyMsg("world 80")))
2288 .expect("whoops!");
2289 r.insert("hello", Box::new(MyMsg("world 100")))
2290 .expect("whoops!");
2291
2292 {
2293 match r.find("hello") {
2294 Some(v) => println!("Found {}", v.0),
2295 None => println!("Not Found"),
2296 }
2297 }
2298
2299 r.show();
2300
2301 r.iter(|_, iter| {
2302 if !iter.seek_min() {
2303 return;
2304 }
2305 while iter.forward() {
2306 println!("{}", iter.key());
2307 }
2308 if !iter.seek_max() {
2309 return;
2310 }
2311 while iter.back() {
2312 println!("{}", iter.key());
2313 }
2314 });
2315 }
2316
2317 #[test]
2318 fn key_f64() {
2319 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<f64, MyMsg>>());
2320
2321 let mut r = RaxMap::<f64, MyMsg>::new();
2322
2323 r.insert(100.01, Box::new(MyMsg("world 100")))
2324 .expect("whoops!");
2325 r.insert(80.20, Box::new(MyMsg("world 80")))
2326 .expect("whoops!");
2327 r.insert(100.00, Box::new(MyMsg("world 200")))
2328 .expect("whoops!");
2329 r.insert(99.10, Box::new(MyMsg("world 1")))
2330 .expect("whoops!");
2331
2332 r.show();
2333
2334 r.iter(|_, iter| {
2335 iter.seek_min();
2339 while iter.forward() {
2340 println!("{}", iter.key());
2341 }
2342 iter.seek_max();
2343 while iter.back() {
2344 println!("{}", iter.key());
2345 }
2346 });
2347 }
2348
2349 #[test]
2350 fn key_u64() {
2351 println!("sizeof(Rax) {}", std::mem::size_of::<RaxMap<u64, MyMsg>>());
2352
2353 let mut r = RaxMap::<u64, MyMsg>::new();
2354
2355 r.insert(100, Box::new(MyMsg("world 100")))
2356 .expect("whoops!");
2357 r.insert(80, Box::new(MyMsg("world 80"))).expect("whoops!");
2358 r.insert(200, Box::new(MyMsg("world 200")))
2359 .expect("whoops!");
2360 r.insert(1, Box::new(MyMsg("world 1"))).expect("whoops!");
2361
2362 r.show();
2363
2364 r.seek_min(|_, it| {
2400 for (key, value) in it.rev() {
2401 println!("Key Len = {}", key);
2402 println!("Data = {}", value.unwrap().0);
2403 }
2404 });
2405
2406 }
2442}