1use std::borrow::Cow;
61use std::cmp::Ordering::Equal;
62use std::cmp::Ordering::Greater;
63use std::cmp::Ordering::Less;
64use std::fmt;
65use std::fmt::Debug;
66use std::fmt::Formatter;
67use std::fs;
68use std::fs::File;
69use std::hash::Hasher;
70use std::io;
71use std::io::Read;
72use std::io::Seek;
73use std::io::SeekFrom;
74use std::io::Write;
75use std::mem::size_of;
76use std::ops::Bound;
77use std::ops::Bound::Excluded;
78use std::ops::Bound::Included;
79use std::ops::Bound::Unbounded;
80use std::ops::Deref;
81use std::ops::RangeBounds;
82use std::path::Path;
83use std::path::PathBuf;
84use std::sync::Arc;
85use std::sync::atomic::AtomicBool;
86use std::sync::atomic::AtomicU64;
87use std::sync::atomic::AtomicUsize;
88use std::sync::atomic::Ordering::AcqRel;
89use std::sync::atomic::Ordering::Acquire;
90use std::sync::atomic::Ordering::Relaxed;
91use std::sync::atomic::Ordering::Release;
92use std::time::Instant;
93
94use byteorder::ByteOrder;
95use byteorder::LittleEndian;
96use byteorder::ReadBytesExt;
97use byteorder::WriteBytesExt;
98use minibytes::Bytes;
99use tracing::debug_span;
100use twox_hash::XxHash64;
101use vlqencoding::VLQDecodeAt;
102use vlqencoding::VLQEncode;
103
104use crate::base16::Base16Iter;
105use crate::base16::base16_to_base256;
106use crate::base16::single_hex_to_base16;
107use crate::config;
108use crate::errors::IoResultExt;
109use crate::errors::ResultExt;
110use crate::lock::ScopedFileLock;
111use crate::metrics::Counter;
112use crate::utils;
113use crate::utils::mmap_bytes;
114use crate::utils::xxhash;
115use crate::utils::xxhash32;
116
117static INDEX_WRITE_MS: Counter = Counter::new_counter("indexedlog.index.write_ms");
118static INDEX_CHECKSUM_CHUNKS_HASHED: Counter =
119 Counter::new_counter("indexedlog.index.checksum_chunks_hashed");
120static INDEX_VERIFIED_CACHE_CHUNKS_LOADED: Counter =
121 Counter::new_counter("indexedlog.index.verified_cache_chunks_loaded");
122static INDEX_VERIFIED_CACHE_SAVES: Counter =
123 Counter::new_counter("indexedlog.index.verified_cache_saves");
124
125const VERIFIED_CACHE_MAGIC: &[u8; 8] = b"ilogvrf1";
136const VERIFIED_CACHE_HEADER_LEN: usize = 8 + 8 + 4 + 8 + 8;
137const VERIFIED_CACHE_SUFFIX: &str = ".verified";
138const VERIFIED_CACHE_SAVE_THRESHOLD: usize = 16;
141
142#[derive(Clone, PartialEq, Default)]
145struct MemRadix {
146 pub offsets: [Offset; 16],
147 pub link_offset: LinkOffset,
148}
149
150#[derive(Clone, PartialEq)]
151struct MemLeaf {
152 pub key_offset: Offset,
153 pub link_offset: LinkOffset,
154}
155
156#[derive(Clone, PartialEq)]
157struct MemKey {
158 pub key: Box<[u8]>, }
160
161#[derive(Clone, PartialEq)]
162struct MemExtKey {
163 pub start: u64,
164 pub len: u64,
165}
166
167#[derive(Clone, PartialEq)]
168struct MemLink {
169 pub value: u64,
170 pub next_link_offset: LinkOffset,
171 pub unused: bool,
172}
173
174#[derive(Clone, PartialEq)]
175struct MemRoot {
176 pub radix_offset: RadixOffset,
177 pub meta: Box<[u8]>,
178}
179
180struct MemChecksum {
187 start: u64,
192
193 end: u64,
197
198 chain_len: u32,
201
202 chunk_size_logarithm: u32,
205
206 xxhash_list: Vec<u64>,
225
226 checked: Vec<AtomicU64>,
231
232 cache_dirty: AtomicUsize,
235
236 cache_save_failed: AtomicBool,
239}
240
241fn read_vlq_reverse(buf: &[u8], end_offset: usize) -> io::Result<(u64, usize)> {
244 let mut int_buf = Vec::new();
245 for i in (0..end_offset).rev() {
246 int_buf.push(buf[i]);
247 if buf[i] <= 127 {
248 break;
249 }
250 }
251 let (value, vlq_size) = int_buf.read_vlq_at(0)?;
252 assert_eq!(vlq_size, int_buf.len());
253 Ok((value, vlq_size))
254}
255
256const DIRTY_OFFSET: u64 = 1u64 << 63;
259
260const TYPE_HEAD: u8 = 0;
261const TYPE_ROOT: u8 = 1;
262const TYPE_RADIX: u8 = 2;
263const TYPE_LEAF: u8 = 3;
264const TYPE_LINK: u8 = 4;
265const TYPE_KEY: u8 = 5;
266const TYPE_EXT_KEY: u8 = 6;
267const TYPE_INLINE_LEAF: u8 = 7;
268const TYPE_CHECKSUM: u8 = 8;
269
270const TYPE_BITS: usize = 3;
272
273const TYPE_BYTES: usize = 1;
275const RADIX_FLAG_BYTES: usize = 1;
276const RADIX_BITMAP_BYTES: usize = 2;
277
278const RADIX_FLAG_USE_64BIT: u8 = 1;
280const RADIX_FLAG_HAVE_LINK: u8 = 1 << 7;
281
282#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
284pub struct Offset(u64);
285
286#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
290struct RadixOffset(Offset);
291#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
292struct LeafOffset(Offset);
293
294#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
298pub struct LinkOffset(Offset);
299#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
300struct KeyOffset(Offset);
301#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
302struct ExtKeyOffset(Offset);
303#[derive(Copy, Clone, PartialEq, PartialOrd, Default)]
304struct ChecksumOffset(Offset);
305
306#[derive(Copy, Clone)]
307enum TypedOffset {
308 Radix(RadixOffset),
309 Leaf(LeafOffset),
310 Link(LinkOffset),
311 Key(KeyOffset),
312 ExtKey(ExtKeyOffset),
313 Checksum(ChecksumOffset),
314}
315
316impl Offset {
317 #[inline]
320 fn from_disk(index: impl IndexBuf, value: u64) -> crate::Result<Self> {
321 if value >= DIRTY_OFFSET {
322 Err(index.corruption(format!("illegal disk offset {value}")))
323 } else {
324 Ok(Offset(value))
325 }
326 }
327
328 #[inline]
331 fn to_disk(self, offset_map: &OffsetMap) -> u64 {
332 offset_map.get(self)
333 }
334
335 fn to_typed(self, index: impl IndexBuf) -> crate::Result<TypedOffset> {
337 let type_int = self.type_int(&index)?;
338 match type_int {
339 TYPE_RADIX => Ok(TypedOffset::Radix(RadixOffset(self))),
340 TYPE_LEAF => Ok(TypedOffset::Leaf(LeafOffset(self))),
341 TYPE_LINK => Ok(TypedOffset::Link(LinkOffset(self))),
342 TYPE_KEY => Ok(TypedOffset::Key(KeyOffset(self))),
343 TYPE_EXT_KEY => Ok(TypedOffset::ExtKey(ExtKeyOffset(self))),
344 TYPE_INLINE_LEAF => Ok(TypedOffset::Leaf(LeafOffset(self))),
346 TYPE_CHECKSUM => Ok(TypedOffset::Checksum(ChecksumOffset(self))),
347 _ => Err(index.corruption(format!("type {type_int} is unsupported"))),
348 }
349 }
350
351 fn type_int(self, index: impl IndexBuf) -> crate::Result<u8> {
353 let buf = index.buf();
354 if self.is_null() {
355 Err(index.corruption("invalid read from null"))
356 } else if self.is_dirty() {
357 Ok(((self.0 - DIRTY_OFFSET) & ((1 << TYPE_BITS) - 1)) as u8)
358 } else {
359 index.verify_checksum(self.0, TYPE_BYTES as u64)?;
360 match buf.get(self.0 as usize) {
361 Some(x) => Ok(*x),
362 _ => Err(index.range_error(self.0 as usize, 1)),
363 }
364 }
365 }
366
367 fn to_optional_typed(self, buf: &[u8]) -> Option<TypedOffset> {
371 if self.is_null() {
372 return None;
373 }
374 let type_int = if self.is_dirty() {
375 Some(((self.0 - DIRTY_OFFSET) & ((1 << TYPE_BITS) - 1)) as u8)
376 } else {
377 buf.get(self.0 as usize).cloned()
378 };
379 match type_int {
380 Some(TYPE_RADIX) => Some(TypedOffset::Radix(RadixOffset(self))),
381 Some(TYPE_LEAF) => Some(TypedOffset::Leaf(LeafOffset(self))),
382 Some(TYPE_LINK) => Some(TypedOffset::Link(LinkOffset(self))),
383 Some(TYPE_KEY) => Some(TypedOffset::Key(KeyOffset(self))),
384 Some(TYPE_EXT_KEY) => Some(TypedOffset::ExtKey(ExtKeyOffset(self))),
385 Some(TYPE_INLINE_LEAF) => Some(TypedOffset::Leaf(LeafOffset(self))),
387 Some(TYPE_CHECKSUM) => Some(TypedOffset::Checksum(ChecksumOffset(self))),
388 _ => None,
389 }
390 }
391
392 #[inline]
394 fn is_null(self) -> bool {
395 self.0 == 0
396 }
397
398 #[inline]
400 fn is_dirty(self) -> bool {
401 self.0 >= DIRTY_OFFSET
402 }
403
404 fn null() -> Self {
405 Self(0)
406 }
407}
408
409trait TypedOffsetMethods: Sized {
411 #[inline]
412 fn dirty_index(self) -> usize {
413 debug_assert!(self.to_offset().is_dirty());
414 ((self.to_offset().0 - DIRTY_OFFSET) >> TYPE_BITS) as usize
415 }
416
417 #[inline]
418 fn from_offset(offset: Offset, index: impl IndexBuf) -> crate::Result<Self> {
419 if offset.is_null() {
420 Ok(Self::from_offset_unchecked(offset))
421 } else {
422 let type_int = offset.type_int(&index)?;
423 if type_int == Self::type_int() {
424 Ok(Self::from_offset_unchecked(offset))
425 } else {
426 Err(index.corruption(format!("inconsistent type at {offset:?}")))
427 }
428 }
429 }
430
431 #[inline]
432 fn from_dirty_index(index: usize) -> Self {
433 Self::from_offset_unchecked(Offset(
434 (((index as u64) << TYPE_BITS) | Self::type_int() as u64) + DIRTY_OFFSET,
435 ))
436 }
437
438 fn type_int() -> u8;
439
440 fn from_offset_unchecked(offset: Offset) -> Self;
441
442 fn to_offset(&self) -> Offset;
443}
444
445impl_offset!(RadixOffset, TYPE_RADIX, "Radix");
446impl_offset!(LeafOffset, TYPE_LEAF, "Leaf");
447impl_offset!(LinkOffset, TYPE_LINK, "Link");
448impl_offset!(KeyOffset, TYPE_KEY, "Key");
449impl_offset!(ExtKeyOffset, TYPE_EXT_KEY, "ExtKey");
450impl_offset!(ChecksumOffset, TYPE_CHECKSUM, "Checksum");
451
452impl RadixOffset {
453 #[inline]
455 fn link_offset(self, index: &Index) -> crate::Result<LinkOffset> {
456 if self.is_dirty() {
457 Ok(index.dirty_radixes[self.dirty_index()].link_offset)
458 } else {
459 let flag_start = TYPE_BYTES + usize::from(self);
460 let flag = *index
461 .buf
462 .get(flag_start)
463 .ok_or_else(|| index.range_error(flag_start, 1))?;
464 index.verify_checksum(
465 flag_start as u64,
466 (RADIX_FLAG_BYTES + RADIX_BITMAP_BYTES) as u64,
467 )?;
468
469 if Self::parse_have_link_from_flag(flag) {
470 let bitmap_start = flag_start + RADIX_FLAG_BYTES;
471 let bitmap = Self::read_bitmap_unchecked(index, bitmap_start)?;
472 let int_size = Self::parse_int_size_from_flag(flag);
473 let link_offset =
474 bitmap_start + RADIX_BITMAP_BYTES + bitmap.count_ones() as usize * int_size;
475 index.verify_checksum(link_offset as u64, int_size as u64)?;
476 let raw_offset = Self::read_raw_int_unchecked(index, int_size, link_offset)?;
477 Ok(LinkOffset::from_offset(
478 Offset::from_disk(index, raw_offset)?,
479 index,
480 )?)
481 } else {
482 Ok(LinkOffset::default())
483 }
484 }
485 }
486
487 #[inline]
490 fn child(self, index: &Index, i: u8) -> crate::Result<Offset> {
491 assert!(i < 16);
493 if self.is_dirty() {
494 Ok(index.dirty_radixes[self.dirty_index()].offsets[i as usize])
495 } else {
496 let flag_start = TYPE_BYTES + usize::from(self);
497 let bitmap_start = flag_start + RADIX_FLAG_BYTES;
498 let bitmap = Self::read_bitmap_unchecked(index, bitmap_start)?;
501 let has_child = (1u16 << i) & bitmap != 0;
502 if has_child {
503 let flag = *index
504 .buf
505 .get(flag_start)
506 .ok_or_else(|| index.range_error(flag_start, 1))?;
507 let int_size = Self::parse_int_size_from_flag(flag);
508 let skip_child_count = (((1u16 << i) - 1) & bitmap).count_ones() as usize;
509 let child_offset = bitmap_start + RADIX_BITMAP_BYTES + skip_child_count * int_size;
510 index.verify_checksum(
511 flag_start as u64,
512 (child_offset + int_size - flag_start) as u64,
513 )?;
514 let raw_offset = Self::read_raw_int_unchecked(index, int_size, child_offset)?;
515 Ok(Offset::from_disk(index, raw_offset)?)
516 } else {
517 index.verify_checksum(bitmap_start as u64, RADIX_BITMAP_BYTES as u64)?;
518 Ok(Offset::default())
519 }
520 }
521 }
522
523 #[inline]
526 fn copy(self, index: &mut Index) -> crate::Result<RadixOffset> {
527 if self.is_dirty() {
528 Ok(self)
529 } else {
530 let entry = MemRadix::read_from(index, u64::from(self))?;
531 let len = index.dirty_radixes.len();
532 index.dirty_radixes.push(entry);
533 Ok(RadixOffset::from_dirty_index(len))
534 }
535 }
536
537 #[inline]
539 fn set_child(self, index: &mut Index, i: u8, value: Offset) {
540 assert!(i < 16);
541 if self.is_dirty() {
542 index.dirty_radixes[self.dirty_index()].offsets[i as usize] = value;
543 } else {
544 panic!("bug: set_child called on immutable radix entry");
545 }
546 }
547
548 #[inline]
550 fn set_link(self, index: &mut Index, value: LinkOffset) {
551 if self.is_dirty() {
552 index.dirty_radixes[self.dirty_index()].link_offset = value;
553 } else {
554 panic!("bug: set_link called on immutable radix entry");
555 }
556 }
557
558 fn set_all_to_null(self, index: &mut Index) {
561 if self.is_dirty() {
562 index.dirty_radixes[self.dirty_index()] = MemRadix::default();
563 } else {
564 panic!("bug: set_all_to_null called on immutable radix entry");
565 }
566 }
567
568 #[inline]
570 fn create(index: &mut Index, radix: MemRadix) -> RadixOffset {
571 let len = index.dirty_radixes.len();
572 index.dirty_radixes.push(radix);
573 RadixOffset::from_dirty_index(len)
574 }
575
576 #[inline]
578 fn parse_have_link_from_flag(flag: u8) -> bool {
579 flag & RADIX_FLAG_HAVE_LINK != 0
580 }
581
582 #[inline]
584 fn parse_int_size_from_flag(flag: u8) -> usize {
585 if flag & RADIX_FLAG_USE_64BIT == 0 {
586 size_of::<u32>()
587 } else {
588 size_of::<u64>()
589 }
590 }
591
592 #[inline]
594 fn read_bitmap_unchecked(index: &Index, bitmap_offset: usize) -> crate::Result<u16> {
595 debug_assert_eq!(RADIX_BITMAP_BYTES, size_of::<u16>());
596 let buf = &index.buf;
597 buf.get(bitmap_offset..bitmap_offset + RADIX_BITMAP_BYTES)
598 .map(LittleEndian::read_u16)
599 .ok_or_else(|| {
600 crate::Error::corruption(
601 &index.path,
602 format!("cannot read radix bitmap at {bitmap_offset}"),
603 )
604 })
605 }
606
607 #[inline]
609 fn read_raw_int_unchecked(index: &Index, int_size: usize, offset: usize) -> crate::Result<u64> {
610 let buf = &index.buf;
611 let result = match int_size {
612 4 => buf
613 .get(offset..offset + 4)
614 .map(|buf| LittleEndian::read_u32(buf) as u64),
615 8 => buf.get(offset..offset + 8).map(LittleEndian::read_u64),
616 _ => unreachable!(),
617 };
618 result.ok_or_else(|| {
619 crate::Error::corruption(
620 &index.path,
621 format!("cannot read {int_size}-byte int at {offset}"),
622 )
623 })
624 }
625}
626
627fn extract_key_content(index: &Index, key_offset: Offset) -> crate::Result<&[u8]> {
629 let typed_offset = key_offset.to_typed(index)?;
630 match typed_offset {
631 TypedOffset::Key(x) => Ok(x.key_content(index)?),
632 TypedOffset::ExtKey(x) => Ok(x.key_content(index)?),
633 _ => Err(index.corruption(format!("unexpected key type at {}", key_offset.0))),
634 }
635}
636
637impl LeafOffset {
638 #[inline]
640 fn key_and_link_offset(self, index: &Index) -> crate::Result<(&[u8], LinkOffset)> {
641 if self.is_dirty() {
642 let e = &index.dirty_leafs[self.dirty_index()];
643 let key_content = extract_key_content(index, e.key_offset)?;
644 Ok((key_content, e.link_offset))
645 } else {
646 let (key_content, raw_link_offset) = match index.buf[usize::from(self)] {
647 TYPE_INLINE_LEAF => {
648 let raw_key_offset = u64::from(self) + TYPE_BYTES as u64;
649 let key_offset = ExtKeyOffset::from_offset(
651 Offset::from_disk(index, raw_key_offset)?,
652 index,
653 )?;
654 let (key_content, key_entry_size) =
656 key_offset.key_content_and_entry_size_unchecked(index)?;
657 let key_entry_size = key_entry_size.unwrap();
658 let raw_link_offset = raw_key_offset + key_entry_size as u64;
659 index.verify_checksum(u64::from(self), raw_link_offset - u64::from(self))?;
660 (key_content, raw_link_offset)
661 }
662 TYPE_LEAF => {
663 let (raw_key_offset, vlq_len): (u64, _) = index
664 .buf
665 .read_vlq_at(usize::from(self) + TYPE_BYTES)
666 .context(
667 index.path(),
668 "cannot read key_offset in LeafOffset::key_and_link_offset",
669 )
670 .corruption()?;
671 let key_offset = Offset::from_disk(index, raw_key_offset)?;
672 let key_content = extract_key_content(index, key_offset)?;
673 let (raw_link_offset, vlq_len2) = index
674 .buf
675 .read_vlq_at(usize::from(self) + TYPE_BYTES + vlq_len)
676 .context(
677 index.path(),
678 "cannot read link_offset in LeafOffset::key_and_link_offset",
679 )
680 .corruption()?;
681 index.verify_checksum(
682 u64::from(self),
683 (TYPE_BYTES + vlq_len + vlq_len2) as u64,
684 )?;
685 (key_content, raw_link_offset)
686 }
687 type_int => {
691 return Err(index.corruption(format!(
692 "unexpected type {} at {} for a leaf entry",
693 type_int,
694 u64::from(self)
695 )));
696 }
697 };
698 let link_offset =
699 LinkOffset::from_offset(Offset::from_disk(index, raw_link_offset)?, index)?;
700 Ok((key_content, link_offset))
701 }
702 }
703
704 #[inline]
706 fn create(index: &mut Index, link_offset: LinkOffset, key_offset: Offset) -> LeafOffset {
707 debug_assert!(!key_offset.is_null());
708 let len = index.dirty_leafs.len();
709 index.dirty_leafs.push(MemLeaf {
710 link_offset,
711 key_offset,
712 });
713 LeafOffset::from_dirty_index(len)
714 }
715
716 #[inline]
722 fn set_link(self, index: &mut Index, link_offset: LinkOffset) -> crate::Result<LeafOffset> {
723 if self.is_dirty() {
724 index.dirty_leafs[self.dirty_index()].link_offset = link_offset;
725 Ok(self)
726 } else {
727 let entry = MemLeaf::read_from(index, u64::from(self))?;
728 Ok(Self::create(index, link_offset, entry.key_offset))
729 }
730 }
731
732 fn mark_unused(self, index: &mut Index) {
735 if self.is_dirty() {
736 let key_offset = index.dirty_leafs[self.dirty_index()].key_offset;
737 match key_offset.to_typed(&*index) {
738 Ok(TypedOffset::Key(x)) => x.mark_unused(index),
739 Ok(TypedOffset::ExtKey(x)) => x.mark_unused(index),
740 _ => {}
741 };
742 index.dirty_leafs[self.dirty_index()].mark_unused()
743 }
744 }
745}
746
747pub struct LeafValueIter<'a> {
749 index: &'a Index,
750 offset: LinkOffset,
751 errored: bool,
752}
753
754impl<'a> Iterator for LeafValueIter<'a> {
755 type Item = crate::Result<u64>;
756
757 fn next(&mut self) -> Option<Self::Item> {
758 if self.offset.is_null() || self.errored {
759 None
760 } else {
761 match self.offset.value_and_next(self.index) {
762 Ok((value, next)) => {
763 self.offset = next;
764 Some(Ok(value))
765 }
766 Err(e) => {
767 self.errored = true;
768 Some(Err(e))
769 }
770 }
771 }
772 }
773}
774
775impl<'a> LeafValueIter<'a> {
776 pub fn is_empty(&self) -> bool {
777 self.offset.is_null()
778 }
779}
780
781pub struct RangeIter<'a> {
784 index: &'a Index,
785
786 front_stack: Vec<IterState>,
788
789 back_stack: Vec<IterState>,
791
792 completed: bool,
794}
795
796impl<'a> RangeIter<'a> {
797 fn new(index: &'a Index, front_stack: Vec<IterState>, back_stack: Vec<IterState>) -> Self {
798 assert!(!front_stack.is_empty());
799 assert!(!back_stack.is_empty());
800 Self {
801 completed: front_stack.last() == back_stack.last(),
802 index,
803 front_stack,
804 back_stack,
805 }
806 }
807
808 fn key(stack: &[IterState], index: &Index) -> crate::Result<Vec<u8>> {
810 let mut prefix = Vec::with_capacity(stack.len() - 1);
813 for frame in stack.iter().take(stack.len() - 1).cloned() {
814 prefix.push(match frame {
815 IterState::RadixChild(_, child) if child < 16 => child,
817 _ => unreachable!("bug: malicious iterator state"),
818 })
819 }
820 if prefix.len() & 1 == 1 {
821 Err(index.corruption("unexpected odd-length key"))
823 } else {
824 Ok(base16_to_base256(&prefix))
825 }
826 }
827
828 fn step(
830 index: &'a Index,
831 stack: &mut Vec<IterState>,
832 towards: Side,
833 exclusive: IterState,
834 ) -> Option<crate::Result<(Cow<'a, [u8]>, LinkOffset)>> {
835 loop {
836 let state = match stack.pop().unwrap().step(towards) {
837 None => continue,
839 Some(state) => state,
840 };
841
842 if state == exclusive {
843 return None;
845 }
846
847 stack.push(state);
849
850 return match state {
851 IterState::RadixChild(radix, child) => match radix.child(index, child) {
852 Ok(next_offset) if next_offset.is_null() => continue,
853 Ok(next_offset) => match next_offset.to_typed(index) {
854 Ok(TypedOffset::Radix(next_radix)) => {
855 stack.push(match towards {
856 Front => IterState::RadixEnd(next_radix),
857 Back => IterState::RadixStart(next_radix),
858 });
859 continue;
860 }
861 Ok(TypedOffset::Leaf(next_leaf)) => {
862 stack.push(match towards {
863 Front => IterState::LeafEnd(next_leaf),
864 Back => IterState::LeafStart(next_leaf),
865 });
866 continue;
867 }
868 Ok(_) => Some(Err(index.corruption("unexpected type during iteration"))),
869 Err(err) => Some(Err(err)),
870 },
871 Err(err) => Some(Err(err)),
872 },
873 IterState::RadixLeaf(radix) => match radix.link_offset(index) {
874 Ok(link_offset) if link_offset.is_null() => continue,
875 Ok(link_offset) => match Self::key(stack, index) {
876 Ok(key) => Some(Ok((Cow::Owned(key), link_offset))),
877 Err(err) => Some(Err(err)),
878 },
879 Err(err) => Some(Err(err)),
880 },
881 IterState::Leaf(leaf) => match leaf.key_and_link_offset(index) {
882 Ok((key, link_offset)) => Some(Ok((Cow::Borrowed(key), link_offset))),
883 Err(err) => Some(Err(err)),
884 },
885 IterState::RadixEnd(_)
886 | IterState::RadixStart(_)
887 | IterState::LeafStart(_)
888 | IterState::LeafEnd(_) => {
889 continue;
890 }
891 };
892 }
893 }
894}
895
896impl<'a> Iterator for RangeIter<'a> {
897 type Item = crate::Result<(Cow<'a, [u8]>, LinkOffset)>;
898
899 fn next(&mut self) -> Option<Self::Item> {
901 if self.completed {
902 return None;
903 }
904 let exclusive = self.back_stack.last().cloned().unwrap();
905 let result = Self::step(self.index, &mut self.front_stack, Back, exclusive);
906 match result {
907 Some(Err(_)) | None => self.completed = true,
908 _ => {}
909 }
910 result
911 }
912}
913
914impl<'a> DoubleEndedIterator for RangeIter<'a> {
915 fn next_back(&mut self) -> Option<Self::Item> {
918 if self.completed {
919 return None;
920 }
921 let exclusive = self.front_stack.last().cloned().unwrap();
922 let result = Self::step(self.index, &mut self.back_stack, Front, exclusive);
923 match result {
924 Some(Err(_)) | None => self.completed = true,
925 _ => {}
926 }
927 result
928 }
929}
930
931impl LinkOffset {
932 pub fn values(self, index: &Index) -> LeafValueIter<'_> {
934 LeafValueIter {
935 errored: false,
936 index,
937 offset: self,
938 }
939 }
940
941 #[inline]
943 fn value_and_next(self, index: &Index) -> crate::Result<(u64, LinkOffset)> {
944 if self.is_dirty() {
945 let e = &index.dirty_links[self.dirty_index()];
946 Ok((e.value, e.next_link_offset))
947 } else {
948 let (value, vlq_len) = index
949 .buf
950 .read_vlq_at(usize::from(self) + TYPE_BYTES)
951 .context(
952 index.path(),
953 "cannot read link_value in LinkOffset::value_and_next",
954 )
955 .corruption()?;
956 let (next_link, vlq_len2) = index
957 .buf
958 .read_vlq_at(usize::from(self) + TYPE_BYTES + vlq_len)
959 .context(
960 index.path(),
961 "cannot read next_link_offset in LinkOffset::value_and_next",
962 )
963 .corruption()?;
964 index.verify_checksum(u64::from(self), (TYPE_BYTES + vlq_len + vlq_len2) as u64)?;
965 let next_link = LinkOffset::from_offset(Offset::from_disk(index, next_link)?, index)?;
966 Ok((value, next_link))
967 }
968 }
969
970 fn create(self, index: &mut Index, value: u64) -> LinkOffset {
973 let new_link = MemLink {
974 value,
975 next_link_offset: self,
976 unused: false,
977 };
978 let len = index.dirty_links.len();
979 index.dirty_links.push(new_link);
980 LinkOffset::from_dirty_index(len)
981 }
982}
983
984impl KeyOffset {
985 #[inline]
987 fn key_content(self, index: &Index) -> crate::Result<&[u8]> {
988 if self.is_dirty() {
989 Ok(&index.dirty_keys[self.dirty_index()].key[..])
990 } else {
991 let (key_len, vlq_len): (usize, _) = index
992 .buf
993 .read_vlq_at(usize::from(self) + TYPE_BYTES)
994 .context(
995 index.path(),
996 "cannot read key_len in KeyOffset::key_content",
997 )
998 .corruption()?;
999 let start = usize::from(self) + TYPE_BYTES + vlq_len;
1000 let end = start + key_len;
1001 index.verify_checksum(u64::from(self), end as u64 - u64::from(self))?;
1002 if end > index.buf.len() {
1003 Err(index.range_error(start, end - start))
1004 } else {
1005 Ok(&index.buf[start..end])
1006 }
1007 }
1008 }
1009
1010 #[inline]
1012 fn create(index: &mut Index, key: &[u8]) -> KeyOffset {
1013 debug_assert!(!key.is_empty());
1014 let len = index.dirty_keys.len();
1015 index.dirty_keys.push(MemKey {
1016 key: Vec::from(key).into_boxed_slice(),
1017 });
1018 KeyOffset::from_dirty_index(len)
1019 }
1020
1021 fn mark_unused(self, index: &mut Index) {
1024 if self.is_dirty() {
1025 index.dirty_keys[self.dirty_index()].mark_unused();
1026 }
1027 }
1028}
1029
1030impl ExtKeyOffset {
1031 #[inline]
1033 fn key_content(self, index: &Index) -> crate::Result<&[u8]> {
1034 let (key_content, entry_size) = self.key_content_and_entry_size_unchecked(index)?;
1035 if let Some(entry_size) = entry_size {
1036 index.verify_checksum(u64::from(self), entry_size as u64)?;
1037 }
1038 Ok(key_content)
1039 }
1040
1041 #[inline]
1043 fn key_content_and_entry_size_unchecked(
1044 self,
1045 index: &Index,
1046 ) -> crate::Result<(&[u8], Option<usize>)> {
1047 let (start, len, entry_size) = if self.is_dirty() {
1048 let e = &index.dirty_ext_keys[self.dirty_index()];
1049 (e.start, e.len, None)
1050 } else {
1051 let (start, vlq_len1): (u64, _) = index
1052 .buf
1053 .read_vlq_at(usize::from(self) + TYPE_BYTES)
1054 .context(
1055 index.path(),
1056 "cannot read ext_key_start in ExtKeyOffset::key_content",
1057 )
1058 .corruption()?;
1059 let (len, vlq_len2): (u64, _) = index
1060 .buf
1061 .read_vlq_at(usize::from(self) + TYPE_BYTES + vlq_len1)
1062 .context(
1063 index.path(),
1064 "cannot read ext_key_len in ExtKeyOffset::key_content",
1065 )
1066 .corruption()?;
1067 (start, len, Some(TYPE_BYTES + vlq_len1 + vlq_len2))
1068 };
1069 let key_buf = index.key_buf.as_ref();
1070 let key_content = match key_buf.slice(start, len) {
1071 Some(k) => k,
1072 None => {
1073 return Err(index.corruption(format!(
1074 "key buffer is invalid when reading referred keys at {start}"
1075 )));
1076 }
1077 };
1078 Ok((key_content, entry_size))
1079 }
1080
1081 #[inline]
1083 fn create(index: &mut Index, start: u64, len: u64) -> ExtKeyOffset {
1084 debug_assert!(len > 0);
1085 let i = index.dirty_ext_keys.len();
1086 index.dirty_ext_keys.push(MemExtKey { start, len });
1087 ExtKeyOffset::from_dirty_index(i)
1088 }
1089
1090 fn mark_unused(self, index: &mut Index) {
1093 if self.is_dirty() {
1094 index.dirty_ext_keys[self.dirty_index()].mark_unused();
1095 }
1096 }
1097}
1098
1099fn check_type(index: impl IndexBuf, offset: usize, expected: u8) -> crate::Result<()> {
1101 let typeint = *(index
1102 .buf()
1103 .get(offset)
1104 .ok_or_else(|| index.range_error(offset, 1))?);
1105 if typeint != expected {
1106 Err(index.corruption(format!(
1107 "type mismatch at offset {offset} expected {expected} but got {typeint}"
1108 )))
1109 } else {
1110 Ok(())
1111 }
1112}
1113
1114impl MemRadix {
1115 fn read_from(index: &Index, offset: u64) -> crate::Result<Self> {
1116 let buf = &index.buf;
1117 let offset = offset as usize;
1118 let mut pos = 0;
1119
1120 check_type(index, offset, TYPE_RADIX)?;
1122 pos += TYPE_BYTES;
1123
1124 let flag = *buf
1125 .get(offset + pos)
1126 .ok_or_else(|| index.range_error(offset + pos, 1))?;
1127 pos += RADIX_FLAG_BYTES;
1128
1129 let bitmap = RadixOffset::read_bitmap_unchecked(index, offset + pos)?;
1130 pos += RADIX_BITMAP_BYTES;
1131
1132 let int_size = RadixOffset::parse_int_size_from_flag(flag);
1133
1134 let mut offsets = [Offset::default(); 16];
1135 for (i, o) in offsets.iter_mut().enumerate() {
1136 if (bitmap >> i) & 1 == 1 {
1137 *o = Offset::from_disk(
1138 index,
1139 RadixOffset::read_raw_int_unchecked(index, int_size, offset + pos)?,
1140 )?;
1141 pos += int_size;
1142 }
1143 }
1144
1145 let link_offset = if RadixOffset::parse_have_link_from_flag(flag) {
1146 let raw_offset = RadixOffset::read_raw_int_unchecked(index, int_size, offset + pos)?;
1147 pos += int_size;
1148 LinkOffset::from_offset(Offset::from_disk(index, raw_offset)?, index)?
1149 } else {
1150 LinkOffset::default()
1151 };
1152
1153 index.verify_checksum(offset as u64, pos as u64)?;
1154
1155 Ok(MemRadix {
1156 offsets,
1157 link_offset,
1158 })
1159 }
1160
1161 fn write_to<W: Write>(&self, writer: &mut W, offset_map: &OffsetMap) -> io::Result<()> {
1162 let mut flag = 0;
1164 let mut bitmap = 0;
1165 let u32_max = u32::MAX as u64;
1166
1167 let link_offset = if !self.link_offset.is_null() {
1168 flag |= RADIX_FLAG_HAVE_LINK;
1169 let link_offset = self.link_offset.to_disk(offset_map);
1170 if link_offset > u32_max {
1171 flag |= RADIX_FLAG_USE_64BIT;
1172 }
1173 link_offset
1174 } else {
1175 0
1176 };
1177
1178 let mut child_offsets = [0u64; 16];
1179 for (i, child_offset) in self.offsets.iter().enumerate() {
1180 if !child_offset.is_null() {
1181 bitmap |= 1u16 << i;
1182 let child_offset = child_offset.to_disk(offset_map);
1183 if child_offset > u32_max {
1184 flag |= RADIX_FLAG_USE_64BIT;
1185 }
1186 child_offsets[i] = child_offset;
1187 }
1188 }
1189
1190 writer.write_all(&[TYPE_RADIX, flag])?;
1192 writer.write_u16::<LittleEndian>(bitmap)?;
1193
1194 if flag & RADIX_FLAG_USE_64BIT != 0 {
1195 for &child_offset in child_offsets.iter() {
1196 if child_offset > 0 {
1197 writer.write_u64::<LittleEndian>(child_offset)?;
1198 }
1199 }
1200 if link_offset > 0 {
1201 writer.write_u64::<LittleEndian>(link_offset)?;
1202 }
1203 } else {
1204 for &child_offset in child_offsets.iter() {
1205 if child_offset > 0 {
1206 writer.write_u32::<LittleEndian>(child_offset as u32)?;
1207 }
1208 }
1209 if link_offset > 0 {
1210 writer.write_u32::<LittleEndian>(link_offset as u32)?;
1211 }
1212 }
1213 Ok(())
1214 }
1215}
1216
1217impl MemLeaf {
1218 fn read_from(index: &Index, offset: u64) -> crate::Result<Self> {
1219 let buf = &index.buf;
1220 let offset = offset as usize;
1221 match buf.get(offset) {
1222 Some(&TYPE_INLINE_LEAF) => {
1223 let key_offset = offset + TYPE_BYTES;
1224 let offset = key_offset + TYPE_BYTES;
1226 let (_key_start, vlq_len): (u64, _) = buf
1227 .read_vlq_at(offset)
1228 .context(index.path(), "cannot read key_start in MemLeaf::read_from")
1229 .corruption()?;
1230 let offset = offset + vlq_len;
1231 let (_key_len, vlq_len): (u64, _) = buf
1232 .read_vlq_at(offset)
1233 .context(index.path(), "cannot read key_len in MemLeaf::read_from")
1234 .corruption()?;
1235 let offset = offset + vlq_len;
1236 let key_offset = Offset::from_disk(index, key_offset as u64)?;
1238 let link_offset =
1239 LinkOffset::from_offset(Offset::from_disk(index, offset as u64)?, index)?;
1240 Ok(MemLeaf {
1241 key_offset,
1242 link_offset,
1243 })
1244 }
1245 Some(&TYPE_LEAF) => {
1246 let (key_offset, len1) = buf
1247 .read_vlq_at(offset + TYPE_BYTES)
1248 .context(index.path(), "cannot read key_offset in MemLeaf::read_from")
1249 .corruption()?;
1250 let key_offset = Offset::from_disk(index, key_offset)?;
1251 let (link_offset, len2) = buf
1252 .read_vlq_at(offset + TYPE_BYTES + len1)
1253 .context(
1254 index.path(),
1255 "cannot read link_offset in MemLeaf::read_from",
1256 )
1257 .corruption()?;
1258 let link_offset =
1259 LinkOffset::from_offset(Offset::from_disk(index, link_offset)?, index)?;
1260 index.verify_checksum(offset as u64, (TYPE_BYTES + len1 + len2) as u64)?;
1261 Ok(MemLeaf {
1262 key_offset,
1263 link_offset,
1264 })
1265 }
1266 _ => Err(index.range_error(offset, 1)),
1267 }
1268 }
1269
1270 fn maybe_write_inline_to(
1276 &self,
1277 writer: &mut Vec<u8>,
1278 buf: &[u8],
1279 buf_offset: u64,
1280 dirty_ext_keys: &mut [MemExtKey],
1281 dirty_links: &mut [MemLink],
1282 offset_map: &mut OffsetMap,
1283 ) -> crate::Result<bool> {
1284 debug_assert!(!self.is_unused());
1285
1286 let are_dependencies_dirty = self.key_offset.is_dirty() && self.link_offset.is_dirty();
1294
1295 if are_dependencies_dirty {
1296 if let Some(TypedOffset::ExtKey(key_offset)) = self.key_offset.to_optional_typed(buf) {
1299 let ext_key_index = key_offset.dirty_index();
1300 let link_index = self.link_offset.dirty_index();
1301 let ext_key = dirty_ext_keys.get_mut(ext_key_index).unwrap();
1302 let link = dirty_links.get_mut(link_index).unwrap();
1303
1304 let next_link_offset = link.next_link_offset;
1305 if next_link_offset.is_dirty()
1306 && offset_map.link_map[next_link_offset.dirty_index()] == 0
1307 {
1308 return Ok(false);
1310 }
1311
1312 writer.write_all(&[TYPE_INLINE_LEAF]).infallible()?;
1314
1315 let offset = buf.len() as u64 + buf_offset;
1317 offset_map.ext_key_map[ext_key_index] = offset;
1318 ext_key.write_to(writer, offset_map).infallible()?;
1319
1320 let offset = buf.len() as u64 + buf_offset;
1322 offset_map.link_map[ext_key_index] = offset;
1323 link.write_to(writer, offset_map).infallible()?;
1324
1325 ext_key.mark_unused();
1326 link.mark_unused();
1327
1328 Ok(true)
1329 } else {
1330 Ok(false)
1332 }
1333 } else {
1334 Ok(false)
1335 }
1336 }
1337
1338 fn write_noninline_to<W: Write>(
1340 &self,
1341 writer: &mut W,
1342 offset_map: &OffsetMap,
1343 ) -> io::Result<()> {
1344 debug_assert!(!self.is_unused());
1345 writer.write_all(&[TYPE_LEAF])?;
1346 writer.write_vlq(self.key_offset.to_disk(offset_map))?;
1347 writer.write_vlq(self.link_offset.to_disk(offset_map))?;
1348 Ok(())
1349 }
1350
1351 fn mark_unused(&mut self) {
1353 self.key_offset = Offset::default();
1354 }
1355
1356 #[inline]
1357 fn is_unused(&self) -> bool {
1358 self.key_offset.is_null()
1359 }
1360}
1361
1362impl MemLink {
1363 fn read_from(index: impl IndexBuf, offset: u64) -> crate::Result<Self> {
1364 let buf = index.buf();
1365 let offset = offset as usize;
1366 check_type(&index, offset, TYPE_LINK)?;
1367 let (value, len1) = buf
1368 .read_vlq_at(offset + 1)
1369 .context(index.path(), "cannot read link_value in MemLink::read_from")
1370 .corruption()?;
1371 let (next_link_offset, len2) = buf
1372 .read_vlq_at(offset + TYPE_BYTES + len1)
1373 .context(
1374 index.path(),
1375 "cannot read next_link_offset in MemLink::read_from",
1376 )
1377 .corruption()?;
1378 let next_link_offset =
1379 LinkOffset::from_offset(Offset::from_disk(&index, next_link_offset)?, &index)?;
1380 index.verify_checksum(offset as u64, (TYPE_BYTES + len1 + len2) as u64)?;
1381 Ok(MemLink {
1382 value,
1383 next_link_offset,
1384 unused: false,
1385 })
1386 }
1387
1388 fn write_to<W: Write>(&self, writer: &mut W, offset_map: &OffsetMap) -> io::Result<()> {
1389 writer.write_all(&[TYPE_LINK])?;
1390 writer.write_vlq(self.value)?;
1391 writer.write_vlq(self.next_link_offset.to_disk(offset_map))?;
1392 Ok(())
1393 }
1394
1395 fn mark_unused(&mut self) {
1397 self.unused = true;
1398 }
1399
1400 #[inline]
1401 fn is_unused(&self) -> bool {
1402 self.unused
1403 }
1404}
1405
1406impl MemKey {
1407 fn read_from(index: impl IndexBuf, offset: u64) -> crate::Result<Self> {
1408 let buf = index.buf();
1409 let offset = offset as usize;
1410 check_type(&index, offset, TYPE_KEY)?;
1411 let (key_len, len): (usize, _) = buf
1412 .read_vlq_at(offset + 1)
1413 .context(index.path(), "cannot read key_len in MemKey::read_from")
1414 .corruption()?;
1415 let key = Vec::from(
1416 buf.get(offset + TYPE_BYTES + len..offset + TYPE_BYTES + len + key_len)
1417 .ok_or_else(|| index.range_error(offset + TYPE_BYTES + len, key_len))?,
1418 )
1419 .into_boxed_slice();
1420 index.verify_checksum(offset as u64, (TYPE_BYTES + len + key_len) as u64)?;
1421 Ok(MemKey { key })
1422 }
1423
1424 fn write_to<W: Write>(&self, writer: &mut W, _: &OffsetMap) -> io::Result<()> {
1425 writer.write_all(&[TYPE_KEY])?;
1426 writer.write_vlq(self.key.len())?;
1427 writer.write_all(&self.key)?;
1428 Ok(())
1429 }
1430
1431 fn mark_unused(&mut self) {
1433 self.key = Vec::new().into_boxed_slice();
1434 }
1435
1436 #[inline]
1437 fn is_unused(&self) -> bool {
1438 self.key.is_empty()
1439 }
1440}
1441
1442impl MemExtKey {
1443 fn read_from(index: impl IndexBuf, offset: u64) -> crate::Result<Self> {
1444 let buf = index.buf();
1445 let offset = offset as usize;
1446 check_type(&index, offset, TYPE_EXT_KEY)?;
1447 let (start, vlq_len1) = buf
1448 .read_vlq_at(offset + TYPE_BYTES)
1449 .context(
1450 index.path(),
1451 "cannot read ext_key_start in MemExtKey::read_from",
1452 )
1453 .corruption()?;
1454 let (len, vlq_len2) = buf
1455 .read_vlq_at(offset + TYPE_BYTES + vlq_len1)
1456 .context(
1457 index.path(),
1458 "cannot read ext_key_len in MemExtKey::read_from",
1459 )
1460 .corruption()?;
1461 index.verify_checksum(offset as u64, (TYPE_BYTES + vlq_len1 + vlq_len2) as u64)?;
1462 Ok(MemExtKey { start, len })
1463 }
1464
1465 fn write_to<W: Write>(&self, writer: &mut W, _: &OffsetMap) -> io::Result<()> {
1466 writer.write_all(&[TYPE_EXT_KEY])?;
1467 writer.write_vlq(self.start)?;
1468 writer.write_vlq(self.len)?;
1469 Ok(())
1470 }
1471
1472 fn mark_unused(&mut self) {
1474 self.len = 0;
1475 }
1476
1477 #[inline]
1478 fn is_unused(&self) -> bool {
1479 self.len == 0
1480 }
1481}
1482
1483impl MemRoot {
1484 fn read_from(index: impl IndexBuf, offset: u64) -> crate::Result<(Self, usize)> {
1485 let offset = offset as usize;
1486 let mut cur = offset;
1487 check_type(&index, offset, TYPE_ROOT)?;
1488 cur += TYPE_BYTES;
1489
1490 let (radix_offset, vlq_len) = index
1491 .buf()
1492 .read_vlq_at(cur)
1493 .context(index.path(), "cannot read radix_offset")
1494 .corruption()?;
1495 cur += vlq_len;
1496
1497 let radix_offset =
1498 RadixOffset::from_offset(Offset::from_disk(&index, radix_offset)?, &index)?;
1499
1500 let (meta_len, vlq_len): (usize, _) = index
1501 .buf()
1502 .read_vlq_at(cur)
1503 .context(index.path(), "cannot read meta_len")
1504 .corruption()?;
1505 cur += vlq_len;
1506
1507 let meta = index
1508 .buf()
1509 .get(cur..cur + meta_len)
1510 .ok_or_else(|| index.range_error(cur, meta_len))?;
1511 cur += meta_len;
1512
1513 index.verify_checksum(offset as u64, (cur - offset) as u64)?;
1514 Ok((
1515 MemRoot {
1516 radix_offset,
1517 meta: meta.to_vec().into_boxed_slice(),
1518 },
1519 cur - offset,
1520 ))
1521 }
1522
1523 fn write_to<W: Write>(&self, writer: &mut W, offset_map: &OffsetMap) -> io::Result<usize> {
1524 let mut buf = Vec::with_capacity(16);
1525 buf.write_all(&[TYPE_ROOT])?;
1526 buf.write_vlq(self.radix_offset.to_disk(offset_map))?;
1527 buf.write_vlq(self.meta.len())?;
1528 buf.write_all(&self.meta)?;
1529 let len = buf.len();
1530 writer.write_all(&buf)?;
1531 Ok(len)
1532 }
1533}
1534
1535impl MemChecksum {
1536 fn read_from(index: &impl IndexBuf, start_offset: u64) -> crate::Result<(Self, usize)> {
1537 let span = debug_span!("Checksum::read", offset = start_offset, chain_len = 0);
1538 let _entered = span.enter();
1539 let mut result = Self::default();
1540 let mut size: usize = 0;
1541 let buf_len = index.buf().len();
1542
1543 let mut offset = start_offset as usize;
1544 while offset > 0 {
1545 let mut cur: usize = offset;
1546
1547 check_type(index, cur, TYPE_CHECKSUM)?;
1548 cur += TYPE_BYTES;
1549
1550 let (previous_offset, vlq_len): (u64, _) = index
1551 .buf()
1552 .read_vlq_at(cur)
1553 .context(index.path(), "cannot read previous_checksum_offset")
1554 .corruption()?;
1555 cur += vlq_len;
1556
1557 if previous_offset >= offset as u64 {
1561 return Err(crate::Error::corruption(
1562 index.path(),
1563 format!("invalid previous_checksum_offset {previous_offset} at {offset}"),
1564 ));
1565 }
1566
1567 let (chunk_size_logarithm, vlq_len): (u32, _) = index
1568 .buf()
1569 .read_vlq_at(cur)
1570 .context(index.path(), "cannot read chunk_size_logarithm")
1571 .corruption()?;
1572
1573 if chunk_size_logarithm > 31 {
1574 return Err(crate::Error::corruption(
1575 index.path(),
1576 format!("invalid chunk_size_logarithm {chunk_size_logarithm} at {cur}"),
1577 ));
1578 }
1579 cur += vlq_len;
1580
1581 let chunk_size = 1usize << chunk_size_logarithm;
1582 let chunk_needed = offset.div_ceil(chunk_size);
1583
1584 if chunk_needed > buf_len / 8 {
1590 return Err(crate::Error::corruption(
1591 index.path(),
1592 format!(
1593 "checksum at {offset} needs {chunk_needed} chunks, too many for index length {buf_len}"
1594 ),
1595 ));
1596 }
1597
1598 let is_initial_checksum = start_offset == offset as u64;
1599
1600 if is_initial_checksum {
1602 result.set_chunk_size_logarithm(index.buf(), chunk_size_logarithm)?;
1603
1604 result.xxhash_list.resize(chunk_needed, 0);
1605 result.start = previous_offset;
1606 result.end = offset as u64;
1607
1608 let checked_needed = result.xxhash_list.len().div_ceil(64);
1609 result.checked.resize_with(checked_needed, Default::default);
1610 } else if chunk_needed > result.xxhash_list.len() {
1611 return Err(crate::Error::corruption(
1615 index.path(),
1616 format!(
1617 "checksum at {offset} covers {chunk_needed} chunks, more than {} of the initial checksum",
1618 result.xxhash_list.len()
1619 ),
1620 ));
1621 }
1622 result.chain_len = result.chain_len.saturating_add(1);
1623
1624 let start_chunk_index = (previous_offset >> chunk_size_logarithm) as usize;
1634
1635 let hash_count = chunk_needed.saturating_sub(start_chunk_index);
1639 let entry_end = cur + hash_count * 8 + size_of::<u32>();
1640 if entry_end > buf_len {
1641 return Err(index.range_error(cur, entry_end - cur));
1642 }
1643
1644 for i in start_chunk_index..chunk_needed {
1645 let incomplete_chunk = !offset.is_multiple_of(chunk_size) && i == chunk_needed - 1;
1646
1647 if is_initial_checksum || !incomplete_chunk {
1651 result.xxhash_list[i] = (&index.buf()[cur..])
1652 .read_u64::<LittleEndian>()
1653 .context(index.path(), "cannot read xxhash for checksum")?;
1654 }
1655 cur += 8;
1656 }
1657
1658 let xx32_read = (&index.buf()[cur..])
1660 .read_u32::<LittleEndian>()
1661 .context(index.path(), "cannot read xxhash32 for checksum")?;
1662 let xx32_self = xxhash32(&index.buf()[offset..cur]);
1663 if xx32_read != xx32_self {
1664 return Err(crate::Error::corruption(
1665 index.path(),
1666 format!(
1667 "checksum at {offset} fails integrity check ({xx32_read} != {xx32_self})"
1668 ),
1669 ));
1670 }
1671 cur += 4;
1672
1673 if is_initial_checksum {
1674 size = cur - offset;
1675 }
1676
1677 offset = previous_offset as usize;
1678 }
1679 span.record("chain_len", result.chain_len);
1680
1681 Ok((result, size))
1682 }
1683
1684 fn update(
1688 &mut self,
1689 old_buf: &[u8],
1690 file: &mut File,
1691 file_len: u64,
1692 append_buf: &[u8],
1693 ) -> io::Result<()> {
1694 let start_chunk_index = (self.end >> self.chunk_size_logarithm) as usize;
1695 let start_chunk_offset = (start_chunk_index as u64) << self.chunk_size_logarithm;
1696
1697 let old_end = (old_buf.len() as u64).min(self.end);
1699 if old_end > start_chunk_offset {
1700 self.check_range(old_buf, start_chunk_offset, old_end - start_chunk_offset)?;
1701 }
1702
1703 let new_total_len = file_len + append_buf.len() as u64;
1704 let chunk_size = 1u64 << self.chunk_size_logarithm;
1705 let chunk_needed = ((new_total_len + chunk_size - 1) >> self.chunk_size_logarithm) as usize;
1706 self.xxhash_list.resize(chunk_needed, 0);
1707
1708 if self.end > file_len {
1709 return Err(io::Error::new(
1710 io::ErrorKind::UnexpectedEof,
1711 "unexpected truncation",
1712 ));
1713 }
1714
1715 let file_buf = {
1736 let mut file_buf = vec![0; (file_len - start_chunk_offset) as usize];
1737 file.seek(SeekFrom::Start(start_chunk_offset))?;
1738 file.read_exact(&mut file_buf)?;
1739 file_buf
1740 };
1741
1742 for i in start_chunk_index..self.xxhash_list.len() {
1743 let start = (i as u64) << self.chunk_size_logarithm;
1744 let end = (start + chunk_size).min(new_total_len);
1745 let mut xx = XxHash64::default();
1746 let file_buf_start = ((start - start_chunk_offset) as usize).min(file_buf.len());
1748 let file_buf_end = ((end - start_chunk_offset) as usize).min(file_buf.len());
1749 xx.write(&file_buf[file_buf_start..file_buf_end]);
1750 let append_buf_start = (start.max(file_len) - file_len) as usize;
1752 let append_buf_end = (end.max(file_len) - file_len) as usize;
1753 xx.write(&append_buf[append_buf_start..append_buf_end]);
1754 self.xxhash_list[i] = xx.finish();
1755 }
1756
1757 if (self.start >> self.chunk_size_logarithm) != (self.end >> self.chunk_size_logarithm) {
1781 self.start = self.end;
1782 }
1783 self.end = new_total_len;
1784
1785 Ok(())
1786 }
1787
1788 fn flatten(&mut self) {
1791 self.start = 0;
1792 self.chain_len = 1;
1793 }
1794
1795 fn write_to<W: Write>(&self, writer: &mut W, _offset_map: &OffsetMap) -> io::Result<usize> {
1796 let mut buf = Vec::with_capacity(16);
1797 buf.write_all(&[TYPE_CHECKSUM])?;
1798 buf.write_vlq(self.start)?;
1799 buf.write_vlq(self.chunk_size_logarithm)?;
1801 for &xx in self.xxhash_list_to_write() {
1802 buf.write_u64::<LittleEndian>(xx)?;
1803 }
1804 let xx32 = xxhash32(&buf);
1805 buf.write_u32::<LittleEndian>(xx32)?;
1806 writer.write_all(&buf)?;
1807 Ok(buf.len())
1808 }
1809
1810 fn xxhash_list_to_write(&self) -> &[u64] {
1813 let start_chunk_index = (self.start >> self.chunk_size_logarithm) as usize;
1816 &self.xxhash_list[start_chunk_index..]
1817 }
1818
1819 fn set_chunk_size_logarithm(
1821 &mut self,
1822 _buf: &[u8],
1823 chunk_size_logarithm: u32,
1824 ) -> crate::Result<()> {
1825 if self.xxhash_list.is_empty() {
1827 self.chunk_size_logarithm = chunk_size_logarithm;
1828 }
1829 Ok(())
1831 }
1832
1833 #[inline]
1838 fn check_range(&self, buf: &[u8], offset: u64, length: u64) -> io::Result<()> {
1839 if length == 0 || !self.is_enabled() {
1840 return Ok(());
1841 }
1842
1843 if offset + length > self.end {
1845 return checksum_error(self, offset, length);
1846 }
1847
1848 let start = (offset >> self.chunk_size_logarithm) as usize;
1850 let end = ((offset + length - 1) >> self.chunk_size_logarithm) as usize;
1851 if !(start..=end).all(|i| self.check_chunk(buf, i)) {
1852 return checksum_error(self, offset, length);
1853 }
1854 Ok(())
1855 }
1856
1857 #[inline]
1859 fn check_chunk(&self, buf: &[u8], index: usize) -> bool {
1860 debug_assert!(index < self.xxhash_list.len());
1861 let bit = 1 << (index % 64);
1862 let checked = &self.checked[index / 64];
1863 if (checked.load(Acquire) & bit) == bit {
1864 true
1865 } else {
1866 let start = index << self.chunk_size_logarithm;
1867 let end = (self.end as usize).min((index + 1) << self.chunk_size_logarithm);
1868 if start == end {
1869 return true;
1870 }
1871 let hash = xxhash(&buf[start..end]);
1872 INDEX_CHECKSUM_CHUNKS_HASHED.add(1);
1873 if hash == self.xxhash_list[index] {
1874 let first_time = checked.fetch_or(bit, AcqRel) & bit == 0;
1875 if first_time && index < self.complete_chunk_count() {
1876 self.cache_dirty.fetch_add(1, Relaxed);
1877 }
1878 true
1879 } else {
1880 false
1881 }
1882 }
1883 }
1884
1885 #[inline]
1886 fn is_enabled(&self) -> bool {
1887 self.end > 0
1888 }
1889
1890 #[inline]
1891 fn is_chunk_checked(&self, index: usize) -> bool {
1892 self.checked[index / 64].load(Acquire) & (1 << (index % 64)) != 0
1893 }
1894
1895 fn complete_chunk_count(&self) -> usize {
1898 (self.end >> self.chunk_size_logarithm) as usize
1899 }
1900
1901 fn verified_cache_key(&self, count: usize) -> u64 {
1905 let mut xx = XxHash64::default();
1906 for hash in &self.xxhash_list[..count] {
1907 xx.write(&hash.to_le_bytes());
1908 }
1909 xx.finish()
1910 }
1911
1912 fn serialize_verified_cache(&self, boot_id: u64) -> Vec<u8> {
1913 let count = self.complete_chunk_count();
1914 let words = count.div_ceil(64);
1915 let mut buf = Vec::with_capacity(VERIFIED_CACHE_HEADER_LEN + words * 8 + 4);
1916 buf.extend_from_slice(VERIFIED_CACHE_MAGIC);
1917 buf.write_u64::<LittleEndian>(boot_id).unwrap();
1918 buf.write_u32::<LittleEndian>(self.chunk_size_logarithm)
1919 .unwrap();
1920 buf.write_u64::<LittleEndian>(count as u64).unwrap();
1921 buf.write_u64::<LittleEndian>(self.verified_cache_key(count))
1922 .unwrap();
1923 for (i, word) in self.checked.iter().take(words).enumerate() {
1924 let bits = word.load(Acquire) & complete_chunk_mask(count, i);
1925 buf.write_u64::<LittleEndian>(bits).unwrap();
1926 }
1927 let xx32 = xxhash32(&buf);
1928 buf.write_u32::<LittleEndian>(xx32).unwrap();
1929 buf
1930 }
1931
1932 fn apply_verified_cache(&self, data: &[u8], boot_id: u64) -> Option<usize> {
1936 if data.len() < VERIFIED_CACHE_HEADER_LEN + 4 || !data.starts_with(VERIFIED_CACHE_MAGIC) {
1937 return None;
1938 }
1939 let (body, xx32) = data.split_at(data.len() - 4);
1940 if LittleEndian::read_u32(xx32) != xxhash32(body) {
1941 return None;
1942 }
1943 let mut cur = &body[VERIFIED_CACHE_MAGIC.len()..];
1944 let cached_boot_id = cur.read_u64::<LittleEndian>().ok()?;
1945 let chunk_size_logarithm = cur.read_u32::<LittleEndian>().ok()?;
1946 let count = cur.read_u64::<LittleEndian>().ok()? as usize;
1947 let key = cur.read_u64::<LittleEndian>().ok()?;
1948 let words = count.div_ceil(64);
1949 if cached_boot_id != boot_id
1950 || chunk_size_logarithm != self.chunk_size_logarithm
1951 || count > self.complete_chunk_count()
1952 || cur.len() != words * 8
1953 || key != self.verified_cache_key(count)
1954 {
1955 return None;
1956 }
1957 let mut loaded = 0;
1958 for (i, word) in self.checked.iter().take(words).enumerate() {
1959 let bits = cur.read_u64::<LittleEndian>().ok()? & complete_chunk_mask(count, i);
1960 let old = word.fetch_or(bits, AcqRel);
1961 loaded += (bits & !old).count_ones() as usize;
1962 }
1963 Some(loaded)
1964 }
1965
1966 fn inherit_verified(&self, old: &MemChecksum) {
1970 let count = self.complete_chunk_count().min(old.complete_chunk_count());
1971 if self.chunk_size_logarithm != old.chunk_size_logarithm
1972 || self.xxhash_list[..count] != old.xxhash_list[..count]
1973 {
1974 return;
1975 }
1976 for (i, (word, old_word)) in self.checked.iter().zip(&old.checked).enumerate() {
1977 let bits = old_word.load(Acquire) & complete_chunk_mask(count, i);
1978 if bits != 0 {
1979 word.fetch_or(bits, AcqRel);
1980 }
1981 }
1982 self.cache_dirty
1983 .fetch_add(old.cache_dirty.load(Relaxed), Relaxed);
1984 if old.cache_save_failed.load(Acquire) {
1985 self.cache_save_failed.store(true, Release);
1986 }
1987 }
1988
1989 #[cfg(test)]
1990 fn verified_chunk_count(&self) -> usize {
1991 (0..self.complete_chunk_count())
1992 .filter(|&i| self.is_chunk_checked(i))
1993 .count()
1994 }
1995}
1996
1997fn complete_chunk_mask(count: usize, i: usize) -> u64 {
1999 let start = i * 64;
2000 if count >= start + 64 {
2001 u64::MAX
2002 } else if count <= start {
2003 0
2004 } else {
2005 (1u64 << (count - start)) - 1
2006 }
2007}
2008
2009fn write_reversed_vlq(mut writer: impl Write, value: usize) -> io::Result<()> {
2010 let mut reversed_vlq = Vec::new();
2011 reversed_vlq.write_vlq(value)?;
2012 reversed_vlq.reverse();
2013 writer.write_all(&reversed_vlq)?;
2014 Ok(())
2015}
2016
2017impl Clone for MemChecksum {
2018 fn clone(&self) -> Self {
2019 Self {
2020 start: self.start,
2021 end: self.end,
2022 chain_len: self.chain_len,
2023 chunk_size_logarithm: self.chunk_size_logarithm,
2024 xxhash_list: self.xxhash_list.clone(),
2025 checked: self
2026 .checked
2027 .iter()
2028 .map(|c| c.load(Relaxed))
2029 .map(AtomicU64::new)
2030 .collect(),
2031 cache_dirty: AtomicUsize::new(0),
2034 cache_save_failed: AtomicBool::new(self.cache_save_failed.load(Relaxed)),
2035 }
2036 }
2037}
2038
2039impl Default for MemChecksum {
2040 fn default() -> Self {
2041 Self {
2042 start: 0,
2043 end: 0,
2044 chain_len: 0,
2045 chunk_size_logarithm: 20, xxhash_list: Vec::new(),
2047 checked: Vec::new(),
2048 cache_dirty: AtomicUsize::new(0),
2049 cache_save_failed: AtomicBool::new(false),
2050 }
2051 }
2052}
2053
2054#[derive(Default)]
2055struct OffsetMap {
2056 radix_len: usize,
2057 radix_map: Vec<u64>,
2058 leaf_map: Vec<u64>,
2059 link_map: Vec<u64>,
2060 key_map: Vec<u64>,
2061 ext_key_map: Vec<u64>,
2062}
2063
2064struct SimpleIndexBuf<'a>(&'a [u8], &'a Path);
2067
2068impl<'a> IndexBuf for SimpleIndexBuf<'a> {
2069 fn buf(&self) -> &[u8] {
2070 self.0
2071 }
2072 fn verify_checksum(&self, _start: u64, _length: u64) -> crate::Result<()> {
2073 Ok(())
2074 }
2075 fn path(&self) -> &Path {
2076 self.1
2077 }
2078}
2079
2080impl OffsetMap {
2081 fn empty_for_index(index: &Index) -> OffsetMap {
2082 let radix_len = index.dirty_radixes.len();
2083 OffsetMap {
2084 radix_len,
2085 radix_map: vec![0; radix_len],
2086 leaf_map: vec![0; index.dirty_leafs.len()],
2087 link_map: vec![0; index.dirty_links.len()],
2088 key_map: vec![0; index.dirty_keys.len()],
2089 ext_key_map: vec![0; index.dirty_ext_keys.len()],
2090 }
2091 }
2092
2093 #[inline]
2094 fn get(&self, offset: Offset) -> u64 {
2095 if offset.is_dirty() {
2096 let dummy = SimpleIndexBuf(b"", Path::new("<dummy>"));
2097 let result = match offset.to_typed(dummy).unwrap() {
2098 TypedOffset::Radix(x) => self.radix_map[self.radix_len - 1 - x.dirty_index()],
2101 TypedOffset::Leaf(x) => self.leaf_map[x.dirty_index()],
2102 TypedOffset::Link(x) => self.link_map[x.dirty_index()],
2103 TypedOffset::Key(x) => self.key_map[x.dirty_index()],
2104 TypedOffset::ExtKey(x) => self.ext_key_map[x.dirty_index()],
2105 TypedOffset::Checksum(_) => {
2106 panic!("bug: ChecksumOffset shouldn't be used in OffsetMap::get")
2107 }
2108 };
2109 debug_assert!(result > 0);
2111 result
2112 } else {
2113 offset.0
2115 }
2116 }
2117}
2118
2119#[derive(Clone, Copy)]
2121enum Side {
2122 Front,
2123 Back,
2124}
2125use Side::Back;
2126use Side::Front;
2127
2128#[derive(Clone, Copy, PartialEq, Debug)]
2130enum IterState {
2131 RadixChild(RadixOffset, u8),
2134
2135 RadixLeaf(RadixOffset),
2137
2138 Leaf(LeafOffset),
2140
2141 RadixStart(RadixOffset),
2145 RadixEnd(RadixOffset),
2146 LeafStart(LeafOffset),
2147 LeafEnd(LeafOffset),
2148}
2149
2150impl IterState {
2151 fn next(self) -> Option<Self> {
2154 match self {
2155 IterState::RadixChild(radix, 15) => Some(IterState::RadixEnd(radix)),
2156 IterState::RadixChild(radix, i) => Some(IterState::RadixChild(radix, i + 1)),
2157 IterState::RadixStart(radix) => Some(IterState::RadixLeaf(radix)),
2158 IterState::RadixLeaf(radix) => Some(IterState::RadixChild(radix, 0)),
2159 IterState::LeafStart(leaf) => Some(IterState::Leaf(leaf)),
2160 IterState::Leaf(leaf) => Some(IterState::LeafEnd(leaf)),
2161 _ => None,
2162 }
2163 }
2164
2165 fn prev(self) -> Option<Self> {
2168 match self {
2169 IterState::RadixChild(radix, 0) => Some(IterState::RadixLeaf(radix)),
2170 IterState::RadixChild(radix, i) => Some(IterState::RadixChild(radix, i - 1)),
2171 IterState::RadixEnd(radix) => Some(IterState::RadixChild(radix, 15)),
2172 IterState::RadixLeaf(radix) => Some(IterState::RadixStart(radix)),
2173 IterState::LeafEnd(leaf) => Some(IterState::Leaf(leaf)),
2174 IterState::Leaf(leaf) => Some(IterState::LeafStart(leaf)),
2175 _ => None,
2176 }
2177 }
2178
2179 fn step(self, towards: Side) -> Option<Self> {
2181 match towards {
2182 Front => self.prev(),
2183 Back => self.next(),
2184 }
2185 }
2186}
2187
2188pub struct Index {
2197 file: Option<File>,
2199
2200 pub(crate) buf: Bytes,
2203
2204 pub(crate) path: PathBuf,
2207
2208 checksum_enabled: bool,
2210 checksum_max_chain_len: u32,
2211 verified_cache: bool,
2212 fsync: bool,
2213 write: Option<bool>,
2214
2215 clean_root: MemRoot,
2217
2218 dirty_root: MemRoot,
2220 dirty_radixes: Vec<MemRadix>,
2221 dirty_leafs: Vec<MemLeaf>,
2222 dirty_links: Vec<MemLink>,
2223 dirty_keys: Vec<MemKey>,
2224 dirty_ext_keys: Vec<MemExtKey>,
2225
2226 checksum: MemChecksum,
2227
2228 pub(crate) key_buf: Arc<dyn ReadonlyBuffer + Send + Sync>,
2231
2232 #[cfg(test)]
2234 fail_on_flush: u16,
2235}
2236
2237pub trait ReadonlyBuffer {
2242 fn slice(&self, start: u64, len: u64) -> Option<&[u8]>;
2244}
2245
2246impl<T: AsRef<[u8]>> ReadonlyBuffer for T {
2247 #[inline]
2248 fn slice(&self, start: u64, len: u64) -> Option<&[u8]> {
2249 self.as_ref().get(start as usize..(start + len) as usize)
2250 }
2251}
2252
2253pub enum InsertKey<'a> {
2255 Embed(&'a [u8]),
2257
2258 Reference((u64, u64)),
2260}
2261
2262#[derive(Clone)]
2268pub struct OpenOptions {
2269 checksum_max_chain_len: u32,
2270 checksum_chunk_size_logarithm: u32,
2271 checksum_enabled: bool,
2272 verified_cache: bool,
2273 fsync: bool,
2274 len: Option<u64>,
2275 write: Option<bool>,
2276 key_buf: Option<Arc<dyn ReadonlyBuffer + Send + Sync>>,
2277}
2278
2279impl OpenOptions {
2280 #[allow(clippy::new_without_default)]
2281 pub fn new() -> OpenOptions {
2290 OpenOptions {
2291 checksum_max_chain_len: config::INDEX_CHECKSUM_MAX_CHAIN_LEN.load(Acquire),
2292 checksum_chunk_size_logarithm: 20,
2293 checksum_enabled: true,
2294 verified_cache: config::INDEX_VERIFIED_CACHE.load(Acquire),
2295 fsync: false,
2296 len: None,
2297 write: None,
2298 key_buf: None,
2299 }
2300 }
2301
2302 pub fn checksum_max_chain_len(&mut self, len: u32) -> &mut Self {
2309 self.checksum_max_chain_len = len;
2310 self
2311 }
2312
2313 pub fn checksum_chunk_size_logarithm(
2315 &mut self,
2316 checksum_chunk_size_logarithm: u32,
2317 ) -> &mut Self {
2318 self.checksum_chunk_size_logarithm = checksum_chunk_size_logarithm;
2319 self
2320 }
2321
2322 pub fn checksum_enabled(&mut self, checksum_enabled: bool) -> &mut Self {
2324 self.checksum_enabled = checksum_enabled;
2325 self
2326 }
2327
2328 pub fn verified_cache(&mut self, enabled: bool) -> &mut Self {
2331 self.verified_cache = enabled;
2332 self
2333 }
2334
2335 pub fn fsync(&mut self, fsync: bool) -> &mut Self {
2340 self.fsync = fsync;
2341 self
2342 }
2343
2344 pub fn write(&mut self, value: Option<bool>) -> &mut Self {
2353 self.write = value;
2354 self
2355 }
2356
2357 pub fn logical_len(&mut self, len: Option<u64>) -> &mut Self {
2367 self.len = len;
2368 self
2369 }
2370
2371 pub fn key_buf(&mut self, buf: Option<Arc<dyn ReadonlyBuffer + Send + Sync>>) -> &mut Self {
2376 self.key_buf = buf;
2377 self
2378 }
2379
2380 pub fn open<P: AsRef<Path>>(&self, path: P) -> crate::Result<Index> {
2386 let path = path.as_ref();
2387 let result: crate::Result<_> = (|| {
2388 let span = debug_span!("Index::open", path = path.to_string_lossy().as_ref());
2389 let _guard = span.enter();
2390
2391 let mut open_options = self.clone();
2392 let open_result = if self.write == Some(false) {
2393 fs::OpenOptions::new().read(true).open(path)
2394 } else {
2395 fs::OpenOptions::new()
2396 .read(true)
2397 .create(true)
2398 .append(true)
2399 .open(path)
2400 };
2401 let mut file = match self.write {
2402 Some(write) => open_result.context(
2403 path,
2404 if write {
2405 "cannot open Index with read-write mode"
2406 } else {
2407 "cannot open Index with read-only mode"
2408 },
2409 )?,
2410 None => {
2411 match open_result {
2413 Err(_) => {
2414 open_options.write = Some(false);
2415 fs::OpenOptions::new()
2416 .read(true)
2417 .open(path)
2418 .context(path, "cannot open Index with read-only mode")?
2419 }
2420 Ok(file) => file,
2421 }
2422 }
2423 };
2424
2425 let bytes = {
2426 match self.len {
2427 None => {
2428 let lock = ScopedFileLock::new(&mut file, false)
2430 .context(path, "cannot lock Log to read file length")?;
2431 mmap_bytes(lock.as_ref(), None).context(path, "cannot mmap")?
2432 }
2433 Some(len) => {
2434 mmap_bytes(&file, Some(len)).context(path, "cannot mmap")?
2436 }
2437 }
2438 };
2439
2440 let (dirty_radixes, clean_root, mut checksum) = if bytes.is_empty() {
2441 let radix_offset = RadixOffset::from_dirty_index(0);
2444 let _ = utils::fix_perm_file(&file, false);
2445 let meta = Default::default();
2446 let root = MemRoot { radix_offset, meta };
2447 let checksum = MemChecksum::default();
2448 (vec![MemRadix::default()], root, checksum)
2449 } else {
2450 let end = bytes.len();
2451 let (root, mut checksum) = read_root_checksum_at_end(path, &bytes, end)?;
2452 if !self.checksum_enabled {
2453 checksum = MemChecksum::default();
2454 }
2455 (vec![], root, checksum)
2456 };
2457
2458 checksum.set_chunk_size_logarithm(&bytes, self.checksum_chunk_size_logarithm)?;
2459 let key_buf = self.key_buf.clone();
2460 let dirty_root = clean_root.clone();
2461
2462 let index = Index {
2463 file: Some(file),
2464 buf: bytes,
2465 path: path.to_path_buf(),
2466 checksum_enabled: open_options.checksum_enabled,
2469 checksum_max_chain_len: open_options.checksum_max_chain_len,
2470 verified_cache: open_options.verified_cache,
2471 fsync: open_options.fsync,
2472 write: open_options.write,
2473 clean_root,
2474 dirty_root,
2475 checksum,
2476 dirty_radixes,
2477 dirty_links: vec![],
2478 dirty_leafs: vec![],
2479 dirty_keys: vec![],
2480 dirty_ext_keys: vec![],
2481 key_buf: key_buf.unwrap_or_else(|| Arc::new(&b""[..])),
2482 #[cfg(test)]
2483 fail_on_flush: 0,
2484 };
2485 index.load_verified_cache();
2486
2487 Ok(index)
2488 })();
2489 result.context(|| format!("in index::OpenOptions::open({path:?})"))
2490 }
2491
2492 pub fn create_in_memory(&self) -> crate::Result<Index> {
2495 let result: crate::Result<_> = (|| {
2496 let buf = Bytes::new();
2497 let dirty_radixes = vec![MemRadix::default()];
2498 let clean_root = {
2499 let radix_offset = RadixOffset::from_dirty_index(0);
2500 let meta = Default::default();
2501 MemRoot { radix_offset, meta }
2502 };
2503 let key_buf = self.key_buf.clone();
2504 let dirty_root = clean_root.clone();
2505 let mut checksum = MemChecksum::default();
2506 checksum.set_chunk_size_logarithm(&buf, self.checksum_chunk_size_logarithm)?;
2507
2508 Ok(Index {
2509 file: None,
2510 buf,
2511 path: PathBuf::new(),
2512 checksum_enabled: self.checksum_enabled,
2513 checksum_max_chain_len: self.checksum_max_chain_len,
2514 verified_cache: self.verified_cache,
2515 fsync: self.fsync,
2516 write: self.write,
2517 clean_root,
2518 dirty_root,
2519 checksum,
2520 dirty_radixes,
2521 dirty_links: vec![],
2522 dirty_leafs: vec![],
2523 dirty_keys: vec![],
2524 dirty_ext_keys: vec![],
2525 key_buf: key_buf.unwrap_or_else(|| Arc::new(&b""[..])),
2526 #[cfg(test)]
2527 fail_on_flush: 0,
2528 })
2529 })();
2530 result.context("in index::OpenOptions::create_in_memory")
2531 }
2532}
2533
2534fn read_root_checksum_at_end(
2536 path: &Path,
2537 bytes: &[u8],
2538 end: usize,
2539) -> crate::Result<(MemRoot, MemChecksum)> {
2540 let buf = SimpleIndexBuf(bytes, path);
2547 let (root_checksum_size, vlq_size) =
2550 read_vlq_reverse(bytes, end).context(path, "cannot read len(root+checksum)")?;
2551
2552 check_type(&buf, 0, TYPE_HEAD)?;
2554
2555 if end < root_checksum_size as usize + vlq_size {
2556 return Err(crate::Error::corruption(
2557 path,
2558 format!("data corrupted at {end} (invalid size: {root_checksum_size})"),
2559 ));
2560 }
2561
2562 let root_offset = end - root_checksum_size as usize - vlq_size;
2563 let (root, root_size) = MemRoot::read_from(&buf, root_offset as u64)?;
2564
2565 let checksum = if root_offset + root_size + vlq_size == end {
2566 MemChecksum::default()
2568 } else {
2569 let (checksum, _checksum_len) =
2570 MemChecksum::read_from(&buf, (root_offset + root_size) as u64)?;
2571
2572 checksum
2582 .check_range(bytes, root_offset as u64, root_size as u64)
2583 .context(path, "failed to verify Root entry")?;
2584 checksum
2585 };
2586
2587 Ok((root, checksum))
2588}
2589
2590impl fmt::Debug for OpenOptions {
2591 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2592 write!(f, "OpenOptions {{ ")?;
2593 write!(
2594 f,
2595 "checksum_chunk_size_logarithm: {}, ",
2596 self.checksum_chunk_size_logarithm
2597 )?;
2598 write!(f, "fsync: {}, ", self.fsync)?;
2599 write!(f, "len: {:?}, ", self.len)?;
2600 write!(f, "write: {:?}, ", self.write)?;
2601 let key_buf_desc = match self.key_buf {
2602 Some(ref _buf) => "Some(_)",
2603 None => "None",
2604 };
2605 write!(f, "key_buf: {key_buf_desc} }}")?;
2606 Ok(())
2607 }
2608}
2609
2610trait IndexBuf {
2615 fn buf(&self) -> &[u8];
2616 fn path(&self) -> &Path;
2617
2618 fn verify_checksum(&self, start: u64, length: u64) -> crate::Result<()>;
2620
2621 #[inline(never)]
2622 fn range_error(&self, start: usize, length: usize) -> crate::Error {
2623 self.corruption(format!(
2624 "byte range {}..{} is unavailable",
2625 start,
2626 start + length
2627 ))
2628 }
2629
2630 #[inline(never)]
2631 fn corruption(&self, message: impl ToString) -> crate::Error {
2632 crate::Error::corruption(self.path(), message)
2633 }
2634}
2635
2636impl<T: IndexBuf> IndexBuf for &T {
2637 fn buf(&self) -> &[u8] {
2638 T::buf(self)
2639 }
2640 fn verify_checksum(&self, start: u64, length: u64) -> crate::Result<()> {
2641 T::verify_checksum(self, start, length)
2642 }
2643 fn path(&self) -> &Path {
2644 T::path(self)
2645 }
2646}
2647
2648impl Drop for Index {
2649 fn drop(&mut self) {
2650 if self.checksum.cache_dirty.load(Relaxed) > 0 {
2651 self.save_verified_cache();
2652 }
2653 }
2654}
2655
2656impl IndexBuf for Index {
2657 fn buf(&self) -> &[u8] {
2658 &self.buf
2659 }
2660 fn verify_checksum(&self, offset: u64, length: u64) -> crate::Result<()> {
2661 self.checksum
2662 .check_range(&self.buf, offset, length)
2663 .context(&self.path, || format!("Index path = {:?}", self.path))?;
2664 if self.checksum.cache_dirty.load(Relaxed) >= VERIFIED_CACHE_SAVE_THRESHOLD {
2665 self.save_verified_cache();
2666 }
2667 Ok(())
2668 }
2669 fn path(&self) -> &Path {
2670 &self.path
2671 }
2672}
2673
2674#[inline(never)]
2679fn checksum_error(checksum: &MemChecksum, offset: u64, length: u64) -> io::Result<()> {
2680 Err(io::Error::new(
2681 io::ErrorKind::InvalidData,
2682 format!(
2683 "range {}..{} failed checksum check ({:?})",
2684 offset,
2685 offset + length,
2686 checksum,
2687 ),
2688 ))
2689}
2690
2691impl Index {
2692 pub fn try_clone(&self) -> crate::Result<Self> {
2694 self.try_clone_internal(true)
2695 .context("in Index::try_clone")
2696 .context(|| format!(" Index.path = {:?}", self.path))
2697 }
2698
2699 pub fn try_clone_without_dirty(&self) -> crate::Result<Self> {
2704 self.try_clone_internal(false)
2705 .context("in Index::try_clone_without_dirty")
2706 .context(|| format!(" Index.path = {:?}", self.path))
2707 }
2708
2709 pub(crate) fn try_clone_internal(&self, copy_dirty: bool) -> crate::Result<Index> {
2710 let file = match &self.file {
2711 Some(f) => Some(f.try_clone().context(self.path(), "cannot duplicate")?),
2712 None => None,
2713 };
2714
2715 let index = if copy_dirty {
2716 Index {
2717 file,
2718 buf: self.buf.clone(),
2719 path: self.path.clone(),
2720 checksum_enabled: self.checksum_enabled,
2721 checksum_max_chain_len: self.checksum_max_chain_len,
2722 verified_cache: self.verified_cache,
2723 fsync: self.fsync,
2724 write: self.write,
2725 clean_root: self.clean_root.clone(),
2726 dirty_root: self.dirty_root.clone(),
2727 checksum: self.checksum.clone(),
2728 dirty_keys: self.dirty_keys.clone(),
2729 dirty_ext_keys: self.dirty_ext_keys.clone(),
2730 dirty_leafs: self.dirty_leafs.clone(),
2731 dirty_links: self.dirty_links.clone(),
2732 dirty_radixes: self.dirty_radixes.clone(),
2733 key_buf: self.key_buf.clone(),
2734 #[cfg(test)]
2735 fail_on_flush: self.fail_on_flush,
2736 }
2737 } else {
2738 Index {
2739 file,
2740 buf: self.buf.clone(),
2741 path: self.path.clone(),
2742 checksum_enabled: self.checksum_enabled,
2743 checksum_max_chain_len: self.checksum_max_chain_len,
2744 verified_cache: self.verified_cache,
2745 fsync: self.fsync,
2746 write: self.write,
2747 clean_root: self.clean_root.clone(),
2748 dirty_root: self.clean_root.clone(),
2749 checksum: self.checksum.clone(),
2750 dirty_keys: Vec::new(),
2751 dirty_ext_keys: Vec::new(),
2752 dirty_leafs: Vec::new(),
2753 dirty_links: Vec::new(),
2754 dirty_radixes: if self.clean_root.radix_offset.is_dirty() {
2755 vec![MemRadix::default()]
2757 } else {
2758 Vec::new()
2759 },
2760 key_buf: self.key_buf.clone(),
2761 #[cfg(test)]
2762 fail_on_flush: self.fail_on_flush,
2763 }
2764 };
2765
2766 Ok(index)
2767 }
2768
2769 pub fn get_meta(&self) -> &[u8] {
2772 &self.dirty_root.meta
2773 }
2774
2775 pub fn get_original_meta(&self) -> &[u8] {
2779 &self.clean_root.meta
2780 }
2781
2782 pub fn set_meta<B: AsRef<[u8]>>(&mut self, meta: B) {
2785 self.dirty_root.meta = meta.as_ref().to_vec().into_boxed_slice()
2786 }
2787
2788 pub fn clear_dirty(&mut self) {
2791 self.dirty_root = self.clean_root.clone();
2792 self.dirty_radixes.clear();
2793 if self.dirty_root.radix_offset.is_dirty() {
2794 assert_eq!(
2798 self.dirty_root.radix_offset,
2799 RadixOffset::from_dirty_index(0)
2800 );
2801 self.dirty_radixes.push(MemRadix::default());
2802 }
2803 self.dirty_leafs.clear();
2804 self.dirty_links.clear();
2805 self.dirty_keys.clear();
2806 self.dirty_ext_keys.clear();
2807 }
2808
2809 pub fn flush(&mut self) -> crate::Result<u64> {
2839 let result: crate::Result<_> = (|| {
2840 let span = debug_span!("Index::flush", path = self.path.to_string_lossy().as_ref());
2841 let _guard = span.enter();
2842
2843 if self.write == Some(false) {
2844 return Err(crate::Error::path(
2845 self.path(),
2846 "cannot flush: Index opened with read-only mode",
2847 ));
2848 }
2849 if self.file.is_none() {
2850 return Ok(0);
2861 }
2862
2863 let old_len = self.buf.len() as u64;
2864 let mut new_len = old_len;
2865 if self.dirty_root == self.clean_root && !self.dirty_root.radix_offset.is_dirty() {
2866 return Ok(new_len);
2868 }
2869
2870 {
2872 let mut offset_map = OffsetMap::empty_for_index(self);
2873 let estimated_dirty_bytes = self.dirty_links.len() * 50;
2874 let mut lock = ScopedFileLock::new(self.file.as_mut().unwrap(), true)
2875 .context(&self.path, "cannot lock")?;
2876 let len = lock
2877 .as_mut()
2878 .seek(SeekFrom::End(0))
2879 .context(&self.path, "cannot seek to end")?;
2880
2881 test_only_fail_point!(self.fail_on_flush == 1);
2882 if len < old_len {
2883 let message = format!(
2884 "on-disk index is unexpectedly smaller ({len} bytes) than its previous version ({old_len} bytes)"
2885 );
2886 let err = crate::Error::path(&self.path, message);
2891 return Err(err);
2892 }
2893
2894 let mut buf = Vec::with_capacity(estimated_dirty_bytes);
2895
2896 if len == 0 {
2901 buf.write_all(&[TYPE_HEAD]).infallible()?;
2902 }
2903
2904 for (i, entry) in self.dirty_keys.iter().enumerate() {
2905 if !entry.is_unused() {
2906 let offset = buf.len() as u64 + len;
2907 offset_map.key_map[i] = offset;
2908 entry.write_to(&mut buf, &offset_map).infallible()?;
2909 };
2910 }
2911
2912 for i in 0..self.dirty_leafs.len() {
2914 let entry = self.dirty_leafs.get_mut(i).unwrap();
2915 let offset = buf.len() as u64 + len;
2916 if !entry.is_unused()
2917 && entry.maybe_write_inline_to(
2918 &mut buf,
2919 &self.buf,
2920 len,
2921 &mut self.dirty_ext_keys,
2922 &mut self.dirty_links,
2923 &mut offset_map,
2924 )?
2925 {
2926 offset_map.leaf_map[i] = offset;
2927 entry.mark_unused();
2928 }
2929 }
2930
2931 for (i, entry) in self.dirty_ext_keys.iter().enumerate() {
2932 if !entry.is_unused() {
2933 let offset = buf.len() as u64 + len;
2934 offset_map.ext_key_map[i] = offset;
2935 entry.write_to(&mut buf, &offset_map).infallible()?;
2936 }
2937 }
2938
2939 for (i, entry) in self.dirty_links.iter().enumerate() {
2940 if !entry.is_unused() {
2941 let offset = buf.len() as u64 + len;
2942 offset_map.link_map[i] = offset;
2943 entry.write_to(&mut buf, &offset_map).infallible()?;
2944 }
2945 }
2946
2947 for (i, entry) in self.dirty_leafs.iter().enumerate() {
2949 if !entry.is_unused() {
2950 let offset = buf.len() as u64 + len;
2951 offset_map.leaf_map[i] = offset;
2952 entry
2953 .write_noninline_to(&mut buf, &offset_map)
2954 .infallible()?;
2955 }
2956 }
2957
2958 for (i, entry) in self.dirty_radixes.iter().rev().enumerate() {
2960 let offset = buf.len() as u64 + len;
2961 entry.write_to(&mut buf, &offset_map).infallible()?;
2962 offset_map.radix_map[i] = offset;
2963 }
2964
2965 let root_len = self
2967 .dirty_root
2968 .write_to(&mut buf, &offset_map)
2969 .infallible()?;
2970
2971 let mut new_checksum = self.checksum.clone();
2973
2974 test_only_fail_point!(self.fail_on_flush == 2);
2975 let checksum_len = if self.checksum_enabled {
2976 new_checksum
2977 .update(&self.buf, lock.as_mut(), len, &buf)
2978 .context(&self.path, "cannot read and update checksum")?;
2979 if self.checksum_max_chain_len > 0
2981 && new_checksum.chain_len >= self.checksum_max_chain_len
2982 {
2983 new_checksum.flatten();
2984 }
2985 new_checksum.write_to(&mut buf, &offset_map).infallible()?
2986 } else {
2987 assert!(!self.checksum.is_enabled());
2988 0
2989 };
2990 write_reversed_vlq(&mut buf, root_len + checksum_len).infallible()?;
2991
2992 new_len = buf.len() as u64 + len;
2993
2994 test_only_fail_point!(self.fail_on_flush == 3);
2995 let start = Instant::now();
2996 lock.as_mut()
2997 .seek(SeekFrom::Start(len))
2998 .context(&self.path, "cannot seek")?;
2999
3000 test_only_fail_point!(self.fail_on_flush == 4);
3001 lock.as_mut()
3002 .write_all(&buf)
3003 .context(&self.path, "cannot write new data to index")?;
3004
3005 test_only_fail_point!(self.fail_on_flush == 5);
3006 if self.fsync || config::get_global_fsync() {
3007 lock.as_mut()
3008 .sync_all()
3009 .context(&self.path, "cannot sync")?;
3010 }
3011 INDEX_WRITE_MS.add(start.elapsed().as_millis() as usize);
3012
3013 test_only_fail_point!(self.fail_on_flush == 6);
3015 let bytes = mmap_bytes(lock.as_ref(), None).context(&self.path, "cannot mmap")?;
3016
3017 let this = SimpleIndexBuf(&bytes, &self.path);
3018
3019 test_only_fail_point!(self.fail_on_flush == 7);
3022 if bytes.len() as u64 != new_len {
3023 return Err(this.corruption("file changed unexpectedly"));
3024 }
3025
3026 test_only_fail_point!(self.fail_on_flush == 8);
3028 let (root, checksum) =
3029 read_root_checksum_at_end(&self.path, &bytes, new_len as usize)?;
3030
3031 debug_assert_eq!(checksum.end, new_checksum.end);
3035 debug_assert_eq!(&checksum.xxhash_list, &new_checksum.xxhash_list);
3036 checksum.inherit_verified(&self.checksum);
3037 self.checksum = checksum;
3038 self.clean_root = root;
3039 self.buf = bytes;
3040 }
3041
3042 self.clear_dirty();
3045
3046 if cfg!(all(debug_assertions, test)) {
3047 self.verify()
3048 .expect("sync() should not break checksum check");
3049 }
3050
3051 Ok(new_len)
3052 })();
3053 result
3054 .context("in Index::flush")
3055 .context(|| format!(" Index.path = {:?}", self.path))
3056 }
3057
3058 pub fn get<K: AsRef<[u8]>>(&self, key: &K) -> crate::Result<LinkOffset> {
3063 let result: crate::Result<_> = (|| {
3064 let mut offset: Offset = self.dirty_root.radix_offset.into();
3065 let mut iter = Base16Iter::from_base256(key);
3066
3067 while !offset.is_null() {
3068 match offset.to_typed(self)? {
3070 TypedOffset::Radix(radix) => {
3071 match iter.next() {
3072 None => {
3073 return radix.link_offset(self);
3075 }
3076 Some(x) => {
3077 offset = radix.child(self, x)?;
3079 }
3080 }
3081 }
3082 TypedOffset::Leaf(leaf) => {
3083 let (stored_key, link_offset) = leaf.key_and_link_offset(self)?;
3085 if stored_key == key.as_ref() {
3086 return Ok(link_offset);
3087 } else {
3088 return Ok(LinkOffset::default());
3089 }
3090 }
3091 _ => return Err(self.corruption("unexpected type during key lookup")),
3092 }
3093 }
3094
3095 Ok(LinkOffset::default())
3097 })();
3098
3099 result
3100 .context(|| format!("in Index::get({:?})", key.as_ref()))
3101 .context(|| format!(" Index.path = {:?}", self.path))
3102 }
3103
3104 pub fn scan_prefix_base16(
3107 &self,
3108 mut base16: impl Iterator<Item = u8>,
3109 ) -> crate::Result<RangeIter<'_>> {
3110 let mut offset: Offset = self.dirty_root.radix_offset.into();
3111 let mut front_stack = Vec::<IterState>::new();
3112
3113 while !offset.is_null() {
3114 match offset.to_typed(self)? {
3116 TypedOffset::Radix(radix) => {
3117 match base16.next() {
3118 None => {
3119 let start = IterState::RadixStart(radix);
3120 let end = IterState::RadixEnd(radix);
3121 front_stack.push(start);
3122 let mut back_stack = front_stack.clone();
3123 *back_stack.last_mut().unwrap() = end;
3124 return Ok(RangeIter::new(self, front_stack, back_stack));
3125 }
3126 Some(x) => {
3127 front_stack.push(IterState::RadixChild(radix, x));
3129 offset = radix.child(self, x)?;
3130 }
3131 }
3132 }
3133 TypedOffset::Leaf(leaf) => {
3134 let eq = {
3136 let (stored_key, _link_offset) = leaf.key_and_link_offset(self)?;
3137 let remaining: Vec<u8> = base16.collect();
3139 Base16Iter::from_base256(&stored_key)
3140 .skip(front_stack.len())
3141 .take(remaining.len())
3142 .eq(remaining.iter().cloned())
3143 };
3144 if eq {
3145 let start = IterState::LeafStart(leaf);
3146 let end = IterState::LeafEnd(leaf);
3147 front_stack.push(start);
3148 let mut back_stack = front_stack.clone();
3149 *back_stack.last_mut().unwrap() = end;
3150 return Ok(RangeIter::new(self, front_stack, back_stack));
3151 } else {
3152 return Ok(RangeIter::new(self, front_stack.clone(), front_stack));
3153 };
3154 }
3155 _ => return Err(self.corruption("unexpected type during prefix scan")),
3156 }
3157 }
3158
3159 Ok(RangeIter::new(self, front_stack.clone(), front_stack))
3161 }
3162
3163 pub fn scan_prefix<B: AsRef<[u8]>>(&self, prefix: B) -> crate::Result<RangeIter<'_>> {
3166 self.scan_prefix_base16(Base16Iter::from_base256(&prefix))
3167 .context(|| format!("in Index::scan_prefix({:?})", prefix.as_ref()))
3168 .context(|| format!(" Index.path = {:?}", self.path))
3169 }
3170
3171 pub fn scan_prefix_hex<B: AsRef<[u8]>>(&self, prefix: B) -> crate::Result<RangeIter<'_>> {
3174 let base16 = prefix.as_ref().iter().cloned().map(single_hex_to_base16);
3176 self.scan_prefix_base16(base16)
3177 .context(|| format!("in Index::scan_prefix_hex({:?})", prefix.as_ref()))
3178 .context(|| format!(" Index.path = {:?}", self.path))
3179 }
3180
3181 pub fn range<'a>(&self, range: impl RangeBounds<&'a [u8]>) -> crate::Result<RangeIter<'_>> {
3186 let is_empty_range = match (range.start_bound(), range.end_bound()) {
3187 (Included(start), Included(end)) => start > end,
3188 (Included(start), Excluded(end)) => start > end,
3189 (Excluded(start), Included(end)) => start > end,
3190 (Excluded(start), Excluded(end)) => start >= end,
3191 (Unbounded, _) | (_, Unbounded) => false,
3192 };
3193
3194 if is_empty_range {
3195 panic!("range start is greater than range end");
3197 }
3198
3199 let result: crate::Result<_> = (|| {
3200 let front_stack = self.iter_stack_by_bound(range.start_bound(), Front)?;
3201 let back_stack = self.iter_stack_by_bound(range.end_bound(), Back)?;
3202 Ok(RangeIter::new(self, front_stack, back_stack))
3203 })();
3204
3205 result
3206 .context(|| {
3207 format!(
3208 "in Index::range({:?} to {:?})",
3209 range.start_bound(),
3210 range.end_bound()
3211 )
3212 })
3213 .context(|| format!(" Index.path = {:?}", self.path))
3214 }
3215
3216 pub fn insert<K: AsRef<[u8]>>(&mut self, key: &K, value: u64) -> crate::Result<()> {
3220 self.insert_advanced(InsertKey::Embed(key.as_ref()), InsertValue::Prepend(value))
3221 .context(|| format!("in Index::insert(key={:?}, value={})", key.as_ref(), value))
3222 .context(|| format!(" Index.path = {:?}", self.path))
3223 }
3224
3225 pub fn remove(&mut self, key: impl AsRef<[u8]>) -> crate::Result<()> {
3227 let key = key.as_ref();
3232 self.insert_advanced(InsertKey::Embed(key), InsertValue::Tombstone)
3233 .context(|| format!("in Index::remove(key={key:?})"))
3234 .context(|| format!(" Index.path = {:?}", self.path))
3235 }
3236
3237 pub fn remove_prefix(&mut self, prefix: impl AsRef<[u8]>) -> crate::Result<()> {
3239 let prefix = prefix.as_ref();
3242 self.insert_advanced(InsertKey::Embed(prefix), InsertValue::TombstonePrefix)
3243 .context(|| format!("in Index::remove_prefix(prefix={prefix:?})"))
3244 .context(|| format!(" Index.path = {:?}", self.path))
3245 }
3246
3247 pub fn insert_advanced(&mut self, key: InsertKey, value: InsertValue) -> crate::Result<()> {
3258 let mut offset: Offset = self.dirty_root.radix_offset.into();
3259 let mut step = 0;
3260 let (key, key_buf_offset) = match key {
3261 InsertKey::Embed(k) => (k, None),
3262 InsertKey::Reference((start, len)) => {
3263 let key = match self.key_buf.as_ref().slice(start, len) {
3264 Some(k) => k,
3265 None => {
3266 return Err(
3267 self.corruption("key buffer is invalid when inserting referred keys")
3268 );
3269 }
3270 };
3271 let detached_key = unsafe { &*(key as *const [u8]) };
3275 (detached_key, Some((start, len)))
3276 }
3277 };
3278 let mut iter = Base16Iter::from_base256(&key);
3279
3280 let mut last_radix = RadixOffset::default();
3281 let mut last_child = 0u8;
3282
3283 loop {
3284 match offset.to_typed(&*self)? {
3285 TypedOffset::Radix(radix) => {
3286 let radix = radix.copy(self)?;
3288 offset = radix.into();
3289
3290 if step == 0 {
3291 self.dirty_root.radix_offset = radix;
3292 } else {
3293 last_radix.set_child(self, last_child, offset);
3294 }
3295
3296 last_radix = radix;
3297
3298 match iter.next() {
3299 None => {
3300 let old_link_offset = radix.link_offset(self)?;
3303 let new_link_offset = match value {
3304 InsertValue::Prepend(value) => old_link_offset.create(self, value),
3305 InsertValue::PrependReplace(value, link_offset) => {
3306 link_offset.create(self, value)
3307 }
3308 InsertValue::Tombstone => LinkOffset::default(),
3309 InsertValue::TombstonePrefix => {
3310 radix.set_all_to_null(self);
3311 return Ok(());
3312 }
3313 };
3314 radix.set_link(self, new_link_offset);
3315 return Ok(());
3316 }
3317 Some(x) => {
3318 let next_offset = radix.child(self, x)?;
3319 if next_offset.is_null() {
3320 let new_link_offset = match value {
3323 InsertValue::Prepend(value) => {
3324 LinkOffset::default().create(self, value)
3325 }
3326 InsertValue::PrependReplace(value, link_offset) => {
3327 link_offset.create(self, value)
3328 }
3329 InsertValue::Tombstone | InsertValue::TombstonePrefix => {
3330 radix.set_child(self, x, Offset::null());
3332 return Ok(());
3333 }
3334 };
3335 let key_offset = self.create_key(key, key_buf_offset);
3336 let leaf_offset =
3337 LeafOffset::create(self, new_link_offset, key_offset);
3338 radix.set_child(self, x, leaf_offset.into());
3339 return Ok(());
3340 } else {
3341 offset = next_offset;
3342 last_child = x;
3343 }
3344 }
3345 }
3346 }
3347 TypedOffset::Leaf(leaf) => {
3348 let (old_key, old_link_offset) = {
3349 let (old_key, link_offset) = leaf.key_and_link_offset(self)?;
3350 let detached_key = unsafe { &*(old_key as *const [u8]) };
3356 (detached_key, link_offset)
3357 };
3358 let matched = if let InsertValue::TombstonePrefix = value {
3359 old_key.get(..key.len()) == Some(key)
3361 } else {
3362 old_key == key
3363 };
3364 if matched {
3365 let new_link_offset = match value {
3368 InsertValue::Prepend(value) => old_link_offset.create(self, value),
3369 InsertValue::PrependReplace(value, link_offset) => {
3370 link_offset.create(self, value)
3371 }
3372 InsertValue::Tombstone | InsertValue::TombstonePrefix => {
3373 last_radix.set_child(self, last_child, Offset::null());
3375 return Ok(());
3376 }
3377 };
3378 let new_leaf_offset = leaf.set_link(self, new_link_offset)?;
3379 last_radix.set_child(self, last_child, new_leaf_offset.into());
3380 } else {
3381 let new_link_offset = match value {
3383 InsertValue::Prepend(value) => {
3384 LinkOffset::default().create(self, value)
3385 }
3386 InsertValue::PrependReplace(value, link_offset) => {
3387 link_offset.create(self, value)
3388 }
3389 InsertValue::Tombstone | InsertValue::TombstonePrefix => return Ok(()),
3390 };
3391 self.split_leaf(
3392 leaf,
3393 old_key,
3394 key.as_ref(),
3395 key_buf_offset,
3396 step,
3397 last_radix,
3398 last_child,
3399 old_link_offset,
3400 new_link_offset,
3401 )?;
3402 }
3403 return Ok(());
3404 }
3405 _ => return Err(self.corruption("unexpected type during insertion")),
3406 }
3407
3408 step += 1;
3409 }
3410 }
3411
3412 pub fn slice_to_bytes(&self, slice: &[u8]) -> Bytes {
3415 self.buf.slice_to_bytes(slice)
3416 }
3417
3418 pub fn verify(&self) -> crate::Result<()> {
3420 self.verify_checksum(0, self.checksum.end)
3421 }
3422
3423 fn verified_cache_path(&self) -> Option<PathBuf> {
3425 if !self.verified_cache || self.file.is_none() || !self.checksum.is_enabled() {
3426 return None;
3427 }
3428 let mut name = self.path.file_name()?.to_os_string();
3429 name.push(VERIFIED_CACHE_SUFFIX);
3430 Some(self.path.with_file_name(name))
3431 }
3432
3433 fn load_verified_cache(&self) {
3443 let (Some(path), Some(boot_id)) = (self.verified_cache_path(), utils::boot_id()) else {
3444 return;
3445 };
3446 let Ok(data) = utils::atomic_read(&path) else {
3447 return;
3448 };
3449 if let Some(loaded) = self.checksum.apply_verified_cache(&data, boot_id) {
3450 INDEX_VERIFIED_CACHE_CHUNKS_LOADED.add(loaded);
3451 }
3452 }
3453
3454 fn save_verified_cache(&self) {
3458 let (Some(path), Some(boot_id)) = (self.verified_cache_path(), utils::boot_id()) else {
3459 return;
3460 };
3461 if self.checksum.cache_save_failed.load(Acquire) {
3462 return;
3463 }
3464 self.checksum.cache_dirty.store(0, Relaxed);
3467 if let Ok(data) = utils::atomic_read(&path) {
3468 let _ = self.checksum.apply_verified_cache(&data, boot_id);
3469 }
3470 let data = self.checksum.serialize_verified_cache(boot_id);
3471 match utils::atomic_write(&path, data, false) {
3472 Ok(()) => INDEX_VERIFIED_CACHE_SAVES.add(1),
3473 Err(err) => {
3474 tracing::debug!(?path, ?err, "cannot write verified-chunk cache");
3475 self.checksum.cache_save_failed.store(true, Release);
3476 }
3477 }
3478 }
3479
3480 fn iter_stack_by_bound(
3485 &self,
3486 bound: Bound<&&[u8]>,
3487 side: Side,
3488 ) -> crate::Result<Vec<IterState>> {
3489 let root_radix = self.dirty_root.radix_offset;
3490 let (inclusive, mut base16iter) = match bound {
3491 Unbounded => {
3492 return Ok(match side {
3493 Front => vec![IterState::RadixStart(root_radix)],
3494 Back => vec![IterState::RadixEnd(root_radix)],
3495 });
3496 }
3497 Included(ref key) => (true, Base16Iter::from_base256(key)),
3498 Excluded(ref key) => (false, Base16Iter::from_base256(key)),
3499 };
3500
3501 let mut offset: Offset = root_radix.into();
3502 let mut stack = Vec::<IterState>::new();
3503
3504 while !offset.is_null() {
3505 match offset.to_typed(self)? {
3506 TypedOffset::Radix(radix) => match base16iter.next() {
3507 None => {
3508 let state = IterState::RadixLeaf(radix);
3510 let state = if inclusive {
3511 state.step(side).unwrap()
3512 } else {
3513 state
3514 };
3515 stack.push(state);
3516 return Ok(stack);
3517 }
3518 Some(x) => {
3519 stack.push(IterState::RadixChild(radix, x));
3521 offset = radix.child(self, x)?;
3522 }
3523 },
3524 TypedOffset::Leaf(leaf) => {
3525 let stored_cmp_key = {
3526 let (stored_key, _link_offset) = leaf.key_and_link_offset(self)?;
3527 Base16Iter::from_base256(&stored_key)
3528 .skip(stack.len())
3529 .cmp(base16iter)
3530 };
3531 let state = IterState::Leaf(leaf);
3532 let state = match (stored_cmp_key, side, inclusive) {
3533 (Equal, _, true) | (Less, Back, _) | (Greater, Front, _) => {
3534 state.step(side).unwrap()
3535 }
3536 (Equal, _, false) | (Greater, Back, _) | (Less, Front, _) => state,
3537 };
3538 stack.push(state);
3539 return Ok(stack);
3540 }
3541 _ => return Err(self.corruption("unexpected type following prefix")),
3542 }
3543 }
3544
3545 Ok(stack)
3548 }
3549
3550 #[allow(clippy::too_many_arguments)]
3551 #[inline]
3555 fn split_leaf(
3556 &mut self,
3557 old_leaf_offset: LeafOffset,
3558 old_key: &[u8],
3559 new_key: &[u8],
3560 key_buf_offset: Option<(u64, u64)>,
3561 step: usize,
3562 radix_offset: RadixOffset,
3563 child: u8,
3564 old_link_offset: LinkOffset,
3565 new_link_offset: LinkOffset,
3566 ) -> crate::Result<()> {
3567 let mut old_iter = Base16Iter::from_base256(&old_key).skip(step);
3615 let mut new_iter = Base16Iter::from_base256(&new_key).skip(step);
3616
3617 let mut last_radix_offset = radix_offset;
3618 let mut last_radix_child = child;
3619
3620 let mut completed = false;
3621
3622 loop {
3623 let b1 = old_iter.next();
3624 let b2 = new_iter.next();
3625
3626 let mut radix = MemRadix::default();
3627
3628 if let Some(b1) = b1 {
3629 radix.offsets[b1 as usize] = old_leaf_offset.into();
3632 } else {
3633 old_leaf_offset.mark_unused(self);
3636 radix.link_offset = old_link_offset;
3637 }
3638
3639 match b2 {
3640 None => {
3641 radix.link_offset = new_link_offset;
3643 completed = true;
3644 }
3645 Some(b2v) if b1 != b2 => {
3646 let new_key_offset = self.create_key(new_key, key_buf_offset);
3648 let new_leaf_offset = LeafOffset::create(self, new_link_offset, new_key_offset);
3649 radix.offsets[b2v as usize] = new_leaf_offset.into();
3650 completed = true;
3651 }
3652 _ => {}
3653 }
3654
3655 let offset = RadixOffset::create(self, radix);
3657 last_radix_offset.set_child(self, last_radix_child, offset.into());
3658
3659 if completed {
3660 break;
3661 }
3662
3663 debug_assert!(b1 == b2);
3664 last_radix_offset = offset;
3665 last_radix_child = b2.unwrap();
3666 }
3667
3668 Ok(())
3669 }
3670
3671 #[inline]
3673 fn create_key(&mut self, key: &[u8], key_buf_offset: Option<(u64, u64)>) -> Offset {
3674 match key_buf_offset {
3675 None => KeyOffset::create(self, key).into(),
3676 Some((start, len)) => ExtKeyOffset::create(self, start, len).into(),
3677 }
3678 }
3679}
3680
3681#[derive(Copy, Clone)]
3683pub enum InsertValue {
3684 Prepend(u64),
3686
3687 PrependReplace(u64, LinkOffset),
3689
3690 Tombstone,
3692
3693 TombstonePrefix,
3696}
3697
3698impl Debug for Offset {
3700 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3701 if self.is_null() {
3702 write!(f, "None")
3703 } else if self.is_dirty() {
3704 let path = Path::new("<dummy>");
3705 let dummy = SimpleIndexBuf(b"", path);
3706 match self.to_typed(dummy).unwrap() {
3707 TypedOffset::Radix(x) => x.fmt(f),
3708 TypedOffset::Leaf(x) => x.fmt(f),
3709 TypedOffset::Link(x) => x.fmt(f),
3710 TypedOffset::Key(x) => x.fmt(f),
3711 TypedOffset::ExtKey(x) => x.fmt(f),
3712 TypedOffset::Checksum(x) => x.fmt(f),
3713 }
3714 } else {
3715 write!(f, "Disk[{}]", self.0)
3716 }
3717 }
3718}
3719
3720impl Debug for MemRadix {
3721 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3722 write!(f, "Radix {{ link: {:?}", self.link_offset)?;
3723 for (i, v) in self.offsets.iter().cloned().enumerate() {
3724 if !v.is_null() {
3725 write!(f, ", {i}: {v:?}")?;
3726 }
3727 }
3728 write!(f, " }}")
3729 }
3730}
3731
3732impl Debug for MemLeaf {
3733 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3734 if self.is_unused() {
3735 write!(f, "Leaf (unused)")
3736 } else {
3737 write!(
3738 f,
3739 "Leaf {{ key: {:?}, link: {:?} }}",
3740 self.key_offset, self.link_offset
3741 )
3742 }
3743 }
3744}
3745
3746impl Debug for MemLink {
3747 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3748 write!(
3749 f,
3750 "Link {{ value: {}, next: {:?} }}",
3751 self.value, self.next_link_offset
3752 )
3753 }
3754}
3755
3756impl Debug for MemKey {
3757 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3758 if self.is_unused() {
3759 write!(f, "Key (unused)")
3760 } else {
3761 write!(f, "Key {{ key:")?;
3762 for byte in self.key.iter() {
3763 write!(f, " {byte:X}")?;
3764 }
3765 write!(f, " }}")
3766 }
3767 }
3768}
3769
3770impl Debug for MemExtKey {
3771 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3772 if self.is_unused() {
3773 write!(f, "ExtKey (unused)")
3774 } else {
3775 write!(f, "ExtKey {{ start: {}, len: {} }}", self.start, self.len)
3776 }
3777 }
3778}
3779
3780impl Debug for MemRoot {
3781 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3782 if self.meta.is_empty() {
3783 write!(f, "Root {{ radix: {:?} }}", self.radix_offset)
3784 } else {
3785 write!(
3786 f,
3787 "Root {{ radix: {:?}, meta: {:?} }}",
3788 self.radix_offset, self.meta
3789 )
3790 }
3791 }
3792}
3793impl Debug for MemChecksum {
3794 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3795 write!(
3796 f,
3797 "Checksum {{ start: {}, end: {}, chunk_size_logarithm: {}, checksums.len(): {} }}",
3798 self.start,
3799 self.end,
3800 self.chunk_size_logarithm,
3801 self.xxhash_list_to_write().len(),
3802 )
3803 }
3804}
3805
3806impl Debug for Index {
3807 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
3808 writeln!(
3809 f,
3810 "Index {{ len: {}, root: {:?} }}",
3811 self.buf.len(),
3812 self.dirty_root.radix_offset
3813 )?;
3814
3815 let offset_map = OffsetMap::default();
3817 let mut buf = Vec::with_capacity(self.buf.len());
3818 buf.push(TYPE_HEAD);
3819 let mut root_offset = 0;
3820 loop {
3821 let i = buf.len();
3822 if i >= self.buf.len() {
3823 break;
3824 }
3825 write!(f, "Disk[{i}]: ")?;
3826 let type_int = self.buf[i];
3827 let i = i as u64;
3828 match type_int {
3829 TYPE_RADIX => {
3830 let e = MemRadix::read_from(self, i).expect("read");
3831 e.write_to(&mut buf, &offset_map).expect("write");
3832 writeln!(f, "{e:?}")?;
3833 }
3834 TYPE_LEAF => {
3835 let e = MemLeaf::read_from(self, i).expect("read");
3836 e.write_noninline_to(&mut buf, &offset_map).expect("write");
3837 writeln!(f, "{e:?}")?;
3838 }
3839 TYPE_INLINE_LEAF => {
3840 let e = MemLeaf::read_from(self, i).expect("read");
3841 writeln!(f, "Inline{e:?}")?;
3842 buf.push(TYPE_INLINE_LEAF);
3844 }
3845 TYPE_LINK => {
3846 let e = MemLink::read_from(self, i).unwrap();
3847 e.write_to(&mut buf, &offset_map).expect("write");
3848 writeln!(f, "{e:?}")?;
3849 }
3850 TYPE_KEY => {
3851 let e = MemKey::read_from(self, i).expect("read");
3852 e.write_to(&mut buf, &offset_map).expect("write");
3853 writeln!(f, "{e:?}")?;
3854 }
3855 TYPE_EXT_KEY => {
3856 let e = MemExtKey::read_from(self, i).expect("read");
3857 e.write_to(&mut buf, &offset_map).expect("write");
3858 writeln!(f, "{e:?}")?;
3859 }
3860 TYPE_ROOT => {
3861 root_offset = i as usize;
3862 let e = MemRoot::read_from(self, i).expect("read").0;
3863 e.write_to(&mut buf, &offset_map).expect("write");
3864 if self.buf.get(buf.len()) != Some(&TYPE_CHECKSUM)
3868 || MemChecksum::read_from(&self, buf.len() as u64).is_err()
3869 {
3870 let root_len = buf.len() - root_offset;
3871 write_reversed_vlq(&mut buf, root_len).expect("write");
3872 }
3873 writeln!(f, "{e:?}")?;
3874 }
3875 TYPE_CHECKSUM => {
3876 let e = MemChecksum::read_from(&self, i).expect("read").0;
3877 e.write_to(&mut buf, &offset_map).expect("write");
3878 let root_checksum_len = buf.len() - root_offset;
3879 let vlq_start = buf.len();
3880 write_reversed_vlq(&mut buf, root_checksum_len).expect("write");
3881 let vlq_end = buf.len();
3882 debug_assert_eq!(
3883 &buf[vlq_start..vlq_end],
3884 &self.buf[vlq_start..vlq_end],
3885 "reversed vlq should match (root+checksum len: {root_checksum_len})"
3886 );
3887 writeln!(f, "{e:?}")?;
3888 }
3889 _ => {
3890 writeln!(f, "Broken Data!")?;
3891 break;
3892 }
3893 }
3894 }
3895
3896 if buf.len() > 1 && self.buf[..] != buf[..] {
3897 debug_assert_eq!(&self.buf[..], &buf[..]);
3898 return writeln!(f, "Inconsistent Data!");
3899 }
3900
3901 for (i, e) in self.dirty_radixes.iter().enumerate() {
3903 write!(f, "Radix[{i}]: ")?;
3904 writeln!(f, "{e:?}")?;
3905 }
3906
3907 for (i, e) in self.dirty_leafs.iter().enumerate() {
3908 write!(f, "Leaf[{i}]: ")?;
3909 writeln!(f, "{e:?}")?;
3910 }
3911
3912 for (i, e) in self.dirty_links.iter().enumerate() {
3913 write!(f, "Link[{i}]: ")?;
3914 writeln!(f, "{e:?}")?;
3915 }
3916
3917 for (i, e) in self.dirty_keys.iter().enumerate() {
3918 write!(f, "Key[{i}]: ")?;
3919 writeln!(f, "{e:?}")?;
3920 }
3921
3922 for (i, e) in self.dirty_ext_keys.iter().enumerate() {
3923 writeln!(f, "ExtKey[{i}]: {e:?}")?;
3924 }
3925
3926 Ok(())
3927 }
3928}
3929
3930#[cfg(test)]
3931mod tests {
3932 use std::collections::BTreeSet;
3933 use std::collections::HashMap;
3934 use std::fs::File;
3935 use std::sync::mpsc;
3936 use std::thread;
3937 use std::time::Duration;
3938
3939 use quickcheck::quickcheck;
3940 use tempfile::tempdir;
3941
3942 use super::InsertValue::PrependReplace;
3943 use super::*;
3944
3945 fn open_opts() -> OpenOptions {
3946 let mut opts = OpenOptions::new();
3947 opts.checksum_chunk_size_logarithm(4);
3948 opts
3949 }
3950
3951 fn in_memory_index() -> Index {
3952 OpenOptions::new().create_in_memory().unwrap()
3953 }
3954
3955 #[test]
3959 fn test_leaf_offset_at_non_leaf_entry() {
3960 let dir = tempdir().unwrap();
3961 let mut index = open_opts().open(dir.path().join("a")).unwrap();
3962 index.insert(b"ab", 1).unwrap();
3963 index.flush().unwrap();
3964 let index = open_opts().open(dir.path().join("a")).unwrap();
3965 let radix: Offset = index.dirty_root.radix_offset.into();
3967 assert!(!radix.is_dirty());
3968 let leaf = LeafOffset::from_offset_unchecked(radix);
3969 let err = leaf.key_and_link_offset(&index).unwrap_err();
3970 assert!(err.is_corruption(), "{err:?}");
3971 assert!(err.to_string().contains("for a leaf entry"), "{err}");
3972 }
3973
3974 #[test]
3975 fn test_scan_prefix() {
3976 let dir = tempdir().unwrap();
3977 let mut index = open_opts().open(dir.path().join("a")).unwrap();
3978 let keys: Vec<&[u8]> = vec![b"01", b"02", b"03", b"031", b"0410", b"042", b"05000"];
3979 for (i, key) in keys.iter().enumerate() {
3980 index.insert(key, i as u64).unwrap();
3981 }
3982
3983 let scan_keys = |prefix: &[u8]| -> Vec<Vec<u8>> {
3985 let iter = index.scan_prefix(prefix).unwrap();
3986 iter_to_keys(&index, &keys, &iter)
3987 };
3988
3989 assert_eq!(scan_keys(b"01"), vec![b"01"]);
3990 assert!(scan_keys(b"010").is_empty());
3991 assert_eq!(scan_keys(b"02"), vec![b"02"]);
3992 assert!(scan_keys(b"020").is_empty());
3993 assert_eq!(scan_keys(b"03"), vec![&b"03"[..], b"031"]);
3994 assert_eq!(scan_keys(b"031"), vec![b"031"]);
3995 assert!(scan_keys(b"032").is_empty());
3996 assert_eq!(scan_keys(b"04"), vec![&b"0410"[..], b"042"]);
3997 assert_eq!(scan_keys(b"041"), vec![b"0410"]);
3998 assert_eq!(scan_keys(b"0410"), vec![b"0410"]);
3999 assert!(scan_keys(b"04101").is_empty());
4000 assert!(scan_keys(b"0412").is_empty());
4001 assert_eq!(scan_keys(b"042"), vec![b"042"]);
4002 assert!(scan_keys(b"0421").is_empty());
4003 assert_eq!(scan_keys(b"05"), vec![b"05000"]);
4004 assert_eq!(scan_keys(b"0500"), vec![b"05000"]);
4005 assert_eq!(scan_keys(b"05000"), vec![b"05000"]);
4006 assert!(scan_keys(b"051").is_empty());
4007 assert_eq!(scan_keys(b"0"), keys);
4008 assert_eq!(scan_keys(b""), keys);
4009 assert!(scan_keys(b"1").is_empty());
4010
4011 assert_eq!(index.scan_prefix_hex(b"30").unwrap().count(), keys.len());
4013 assert_eq!(index.scan_prefix_hex(b"3").unwrap().count(), keys.len());
4014 assert_eq!(index.scan_prefix_hex(b"31").unwrap().count(), 0);
4015 }
4016
4017 #[test]
4018 fn test_remove() {
4019 let dir = tempdir().unwrap();
4020 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4021
4022 let text = format!("{index:?}");
4024 index.remove("").unwrap();
4025 index.remove("a").unwrap();
4026 assert_eq!(text, format!("{index:?}"));
4027
4028 index.insert(b"abc", 42).unwrap();
4029 index.insert(b"abc", 43).unwrap();
4030 index.insert(b"abxyz", 44).unwrap();
4031 index.flush().unwrap();
4032
4033 assert_eq!(index.range(..).unwrap().count(), 2);
4035 index.remove(b"abxyz").unwrap();
4036 assert_eq!(index.range(..).unwrap().count(), 1);
4037 index.remove(b"abc").unwrap();
4038 assert_eq!(index.range(..).unwrap().count(), 0);
4039
4040 let text = format!("{index:?}");
4042 index.remove("").unwrap();
4043 index.remove("a").unwrap();
4044 index.remove("ab").unwrap();
4045 index.remove("abc").unwrap();
4046 index.remove("abcd").unwrap();
4047 index.remove("abcde").unwrap();
4048 index.remove("abcx").unwrap();
4049 index.remove("abcxyz").unwrap();
4050 index.remove("abcxyzz").unwrap();
4051 assert_eq!(text, format!("{index:?}"));
4052
4053 index.flush().unwrap();
4055 let index = open_opts().open(dir.path().join("a")).expect("open");
4056 assert_eq!(index.range(..).unwrap().count(), 0);
4057 }
4058
4059 #[test]
4060 fn test_remove_recursive() {
4061 let dir = tempdir().unwrap();
4062 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4063 index.insert(b"abc", 42).unwrap();
4064 index.insert(b"abc", 42).unwrap();
4065 index.insert(b"abxyz1", 42).unwrap();
4066 index.insert(b"abxyz2", 42).unwrap();
4067 index.insert(b"abxyz33333", 42).unwrap();
4068 index.insert(b"abxyz44444", 42).unwrap();
4069 index.insert(b"aby", 42).unwrap();
4070 index.flush().unwrap();
4071
4072 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4073 let mut n = index.range(..).unwrap().count();
4074 index.remove_prefix(b"abxyz33333333333").unwrap(); assert_eq!(index.range(..).unwrap().count(), n);
4076
4077 index.remove_prefix(b"abxyz33333").unwrap(); n -= 1; assert_eq!(index.range(..).unwrap().count(), n);
4080
4081 index.remove_prefix(b"abxyz4").unwrap(); n -= 1; assert_eq!(index.range(..).unwrap().count(), n);
4084
4085 index.remove_prefix(b"ab").unwrap(); n -= 4; assert_eq!(index.range(..).unwrap().count(), n);
4088
4089 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4090 index.remove_prefix(b"").unwrap(); assert_eq!(index.range(..).unwrap().count(), 0);
4092 }
4093
4094 #[test]
4095 fn test_distinct_one_byte_keys() {
4096 let dir = tempdir().unwrap();
4097 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4098 assert_eq!(
4099 format!("{index:?}"),
4100 "Index { len: 0, root: Radix[0] }\n\
4101 Radix[0]: Radix { link: None }\n"
4102 );
4103
4104 index.insert(&[], 55).expect("update");
4105 assert_eq!(
4106 format!("{index:?}"),
4107 r#"Index { len: 0, root: Radix[0] }
4108Radix[0]: Radix { link: Link[0] }
4109Link[0]: Link { value: 55, next: None }
4110"#
4111 );
4112
4113 index.insert(&[0x12], 77).expect("update");
4114 assert_eq!(
4115 format!("{index:?}"),
4116 r#"Index { len: 0, root: Radix[0] }
4117Radix[0]: Radix { link: Link[0], 1: Leaf[0] }
4118Leaf[0]: Leaf { key: Key[0], link: Link[1] }
4119Link[0]: Link { value: 55, next: None }
4120Link[1]: Link { value: 77, next: None }
4121Key[0]: Key { key: 12 }
4122"#
4123 );
4124
4125 let link = index.get(&[0x12]).expect("get");
4126 index
4127 .insert_advanced(InsertKey::Embed(&[0x34]), PrependReplace(99, link))
4128 .expect("update");
4129 assert_eq!(
4130 format!("{index:?}"),
4131 r#"Index { len: 0, root: Radix[0] }
4132Radix[0]: Radix { link: Link[0], 1: Leaf[0], 3: Leaf[1] }
4133Leaf[0]: Leaf { key: Key[0], link: Link[1] }
4134Leaf[1]: Leaf { key: Key[1], link: Link[2] }
4135Link[0]: Link { value: 55, next: None }
4136Link[1]: Link { value: 77, next: None }
4137Link[2]: Link { value: 99, next: Link[1] }
4138Key[0]: Key { key: 12 }
4139Key[1]: Key { key: 34 }
4140"#
4141 );
4142 }
4143
4144 #[test]
4145 fn test_distinct_one_byte_keys_flush() {
4146 let dir = tempdir().unwrap();
4147 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4148
4149 assert_eq!(index.flush().expect("flush"), 24);
4151 assert_eq!(
4152 format!("{index:?}"),
4153 r#"Index { len: 24, root: Disk[1] }
4154Disk[1]: Radix { link: None }
4155Disk[5]: Root { radix: Disk[1] }
4156Disk[8]: Checksum { start: 0, end: 8, chunk_size_logarithm: 4, checksums.len(): 1 }
4157"#
4158 );
4159
4160 index.insert(&[], 55).expect("update");
4162 index.insert(&[0x12], 77).expect("update");
4163 assert_eq!(
4164 format!("{index:?}"),
4165 r#"Index { len: 24, root: Radix[0] }
4166Disk[1]: Radix { link: None }
4167Disk[5]: Root { radix: Disk[1] }
4168Disk[8]: Checksum { start: 0, end: 8, chunk_size_logarithm: 4, checksums.len(): 1 }
4169Radix[0]: Radix { link: Link[0], 1: Leaf[0] }
4170Leaf[0]: Leaf { key: Key[0], link: Link[1] }
4171Link[0]: Link { value: 55, next: None }
4172Link[1]: Link { value: 77, next: None }
4173Key[0]: Key { key: 12 }
4174"#
4175 );
4176
4177 let link = index.get(&[0x12]).expect("get");
4179 index
4180 .insert_advanced(InsertKey::Embed(&[0x34]), PrependReplace(99, link))
4181 .expect("update");
4182 index.flush().expect("flush");
4183 assert_eq!(
4184 format!("{index:?}"),
4185 r#"Index { len: 104, root: Disk[45] }
4186Disk[1]: Radix { link: None }
4187Disk[5]: Root { radix: Disk[1] }
4188Disk[8]: Checksum { start: 0, end: 8, chunk_size_logarithm: 4, checksums.len(): 1 }
4189Disk[24]: Key { key: 12 }
4190Disk[27]: Key { key: 34 }
4191Disk[30]: Link { value: 55, next: None }
4192Disk[33]: Link { value: 77, next: None }
4193Disk[36]: Link { value: 99, next: Disk[33] }
4194Disk[39]: Leaf { key: Disk[24], link: Disk[33] }
4195Disk[42]: Leaf { key: Disk[27], link: Disk[36] }
4196Disk[45]: Radix { link: Disk[30], 1: Disk[39], 3: Disk[42] }
4197Disk[61]: Root { radix: Disk[45] }
4198Disk[64]: Checksum { start: 0, end: 64, chunk_size_logarithm: 4, checksums.len(): 4 }
4199"#
4200 );
4201 }
4202
4203 #[test]
4204 fn test_leaf_split() {
4205 let dir = tempdir().unwrap();
4206 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4207
4208 index.insert(&[0x12, 0x34], 5).expect("insert");
4210 assert_eq!(
4211 format!("{index:?}"),
4212 r#"Index { len: 0, root: Radix[0] }
4213Radix[0]: Radix { link: None, 1: Leaf[0] }
4214Leaf[0]: Leaf { key: Key[0], link: Link[0] }
4215Link[0]: Link { value: 5, next: None }
4216Key[0]: Key { key: 12 34 }
4217"#
4218 );
4219 index.insert(&[0x12, 0x78], 7).expect("insert");
4220 assert_eq!(
4221 format!("{index:?}"),
4222 r#"Index { len: 0, root: Radix[0] }
4223Radix[0]: Radix { link: None, 1: Radix[1] }
4224Radix[1]: Radix { link: None, 2: Radix[2] }
4225Radix[2]: Radix { link: None, 3: Leaf[0], 7: Leaf[1] }
4226Leaf[0]: Leaf { key: Key[0], link: Link[0] }
4227Leaf[1]: Leaf { key: Key[1], link: Link[1] }
4228Link[0]: Link { value: 5, next: None }
4229Link[1]: Link { value: 7, next: None }
4230Key[0]: Key { key: 12 34 }
4231Key[1]: Key { key: 12 78 }
4232"#
4233 );
4234
4235 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4237 index.insert(&[0x12, 0x34], 5).expect("insert");
4238 index.insert(&[0x12], 7).expect("insert");
4239 assert_eq!(
4240 format!("{index:?}"),
4241 r#"Index { len: 0, root: Radix[0] }
4242Radix[0]: Radix { link: None, 1: Radix[1] }
4243Radix[1]: Radix { link: None, 2: Radix[2] }
4244Radix[2]: Radix { link: Link[1], 3: Leaf[0] }
4245Leaf[0]: Leaf { key: Key[0], link: Link[0] }
4246Link[0]: Link { value: 5, next: None }
4247Link[1]: Link { value: 7, next: None }
4248Key[0]: Key { key: 12 34 }
4249"#
4250 );
4251
4252 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4254 index.insert(&[0x12], 5).expect("insert");
4255 index.insert(&[0x12, 0x78], 7).expect("insert");
4256 assert_eq!(
4257 format!("{index:?}"),
4258 r#"Index { len: 0, root: Radix[0] }
4259Radix[0]: Radix { link: None, 1: Radix[1] }
4260Radix[1]: Radix { link: None, 2: Radix[2] }
4261Radix[2]: Radix { link: Link[0], 7: Leaf[1] }
4262Leaf[0]: Leaf (unused)
4263Leaf[1]: Leaf { key: Key[1], link: Link[1] }
4264Link[0]: Link { value: 5, next: None }
4265Link[1]: Link { value: 7, next: None }
4266Key[0]: Key (unused)
4267Key[1]: Key { key: 12 78 }
4268"#
4269 );
4270
4271 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4273 index.insert(&[0x12], 5).expect("insert");
4274 index.insert(&[0x12], 7).expect("insert");
4275 assert_eq!(
4276 format!("{index:?}"),
4277 r#"Index { len: 0, root: Radix[0] }
4278Radix[0]: Radix { link: None, 1: Leaf[0] }
4279Leaf[0]: Leaf { key: Key[0], link: Link[1] }
4280Link[0]: Link { value: 5, next: None }
4281Link[1]: Link { value: 7, next: Link[0] }
4282Key[0]: Key { key: 12 }
4283"#
4284 );
4285 }
4286
4287 #[test]
4288 fn test_leaf_split_flush() {
4289 let dir = tempdir().unwrap();
4292 let mut index = open_opts().open(dir.path().join("1")).expect("open");
4293
4294 index.insert(&[0x12, 0x34], 5).expect("insert");
4296 index.flush().expect("flush");
4297 assert_eq!(
4298 format!("{index:?}"),
4299 r#"Index { len: 46, root: Disk[11] }
4300Disk[1]: Key { key: 12 34 }
4301Disk[5]: Link { value: 5, next: None }
4302Disk[8]: Leaf { key: Disk[1], link: Disk[5] }
4303Disk[11]: Radix { link: None, 1: Disk[8] }
4304Disk[19]: Root { radix: Disk[11] }
4305Disk[22]: Checksum { start: 0, end: 22, chunk_size_logarithm: 4, checksums.len(): 2 }
4306"#
4307 );
4308 index.insert(&[0x12, 0x78], 7).expect("insert");
4309 assert_eq!(
4310 format!("{index:?}"),
4311 r#"Index { len: 46, root: Radix[0] }
4312Disk[1]: Key { key: 12 34 }
4313Disk[5]: Link { value: 5, next: None }
4314Disk[8]: Leaf { key: Disk[1], link: Disk[5] }
4315Disk[11]: Radix { link: None, 1: Disk[8] }
4316Disk[19]: Root { radix: Disk[11] }
4317Disk[22]: Checksum { start: 0, end: 22, chunk_size_logarithm: 4, checksums.len(): 2 }
4318Radix[0]: Radix { link: None, 1: Radix[1] }
4319Radix[1]: Radix { link: None, 2: Radix[2] }
4320Radix[2]: Radix { link: None, 3: Disk[8], 7: Leaf[0] }
4321Leaf[0]: Leaf { key: Key[0], link: Link[0] }
4322Link[0]: Link { value: 7, next: None }
4323Key[0]: Key { key: 12 78 }
4324"#
4325 );
4326
4327 let mut index = open_opts().open(dir.path().join("2")).expect("open");
4329 index.insert(&[0x12, 0x34], 5).expect("insert");
4330 index.flush().expect("flush");
4331 index.insert(&[0x12], 7).expect("insert");
4332 assert_eq!(
4333 format!("{index:?}"),
4334 r#"Index { len: 46, root: Radix[0] }
4335Disk[1]: Key { key: 12 34 }
4336Disk[5]: Link { value: 5, next: None }
4337Disk[8]: Leaf { key: Disk[1], link: Disk[5] }
4338Disk[11]: Radix { link: None, 1: Disk[8] }
4339Disk[19]: Root { radix: Disk[11] }
4340Disk[22]: Checksum { start: 0, end: 22, chunk_size_logarithm: 4, checksums.len(): 2 }
4341Radix[0]: Radix { link: None, 1: Radix[1] }
4342Radix[1]: Radix { link: None, 2: Radix[2] }
4343Radix[2]: Radix { link: Link[0], 3: Disk[8] }
4344Link[0]: Link { value: 7, next: None }
4345"#
4346 );
4347
4348 let mut index = open_opts().open(dir.path().join("3a")).expect("open");
4351 index.insert(&[0x12], 5).expect("insert");
4352 index.insert(&[0x12, 0x78], 7).expect("insert");
4353 index.flush().expect("flush");
4354 assert_eq!(
4355 format!("{index:?}"),
4356 r#"Index { len: 77, root: Disk[34] }
4357Disk[1]: Key { key: 12 78 }
4358Disk[5]: Link { value: 5, next: None }
4359Disk[8]: Link { value: 7, next: None }
4360Disk[11]: Leaf { key: Disk[1], link: Disk[8] }
4361Disk[14]: Radix { link: Disk[5], 7: Disk[11] }
4362Disk[26]: Radix { link: None, 2: Disk[14] }
4363Disk[34]: Radix { link: None, 1: Disk[26] }
4364Disk[42]: Root { radix: Disk[34] }
4365Disk[45]: Checksum { start: 0, end: 45, chunk_size_logarithm: 4, checksums.len(): 3 }
4366"#
4367 );
4368
4369 let mut index = open_opts().open(dir.path().join("3b")).expect("open");
4371 index.insert(&[0x12], 5).expect("insert");
4372 index.flush().expect("flush");
4373 index.insert(&[0x12, 0x78], 7).expect("insert");
4374 assert_eq!(
4375 format!("{index:?}"),
4376 r#"Index { len: 45, root: Radix[0] }
4377Disk[1]: Key { key: 12 }
4378Disk[4]: Link { value: 5, next: None }
4379Disk[7]: Leaf { key: Disk[1], link: Disk[4] }
4380Disk[10]: Radix { link: None, 1: Disk[7] }
4381Disk[18]: Root { radix: Disk[10] }
4382Disk[21]: Checksum { start: 0, end: 21, chunk_size_logarithm: 4, checksums.len(): 2 }
4383Radix[0]: Radix { link: None, 1: Radix[1] }
4384Radix[1]: Radix { link: None, 2: Radix[2] }
4385Radix[2]: Radix { link: Disk[4], 7: Leaf[0] }
4386Leaf[0]: Leaf { key: Key[0], link: Link[0] }
4387Link[0]: Link { value: 7, next: None }
4388Key[0]: Key { key: 12 78 }
4389"#
4390 );
4391
4392 let mut index = open_opts().open(dir.path().join("4")).expect("open");
4394 index.insert(&[0x12], 5).expect("insert");
4395 index.flush().expect("flush");
4396 index.insert(&[0x12], 7).expect("insert");
4397 assert_eq!(
4398 format!("{index:?}"),
4399 r#"Index { len: 45, root: Radix[0] }
4400Disk[1]: Key { key: 12 }
4401Disk[4]: Link { value: 5, next: None }
4402Disk[7]: Leaf { key: Disk[1], link: Disk[4] }
4403Disk[10]: Radix { link: None, 1: Disk[7] }
4404Disk[18]: Root { radix: Disk[10] }
4405Disk[21]: Checksum { start: 0, end: 21, chunk_size_logarithm: 4, checksums.len(): 2 }
4406Radix[0]: Radix { link: None, 1: Leaf[0] }
4407Leaf[0]: Leaf { key: Disk[1], link: Link[0] }
4408Link[0]: Link { value: 7, next: Disk[4] }
4409"#
4410 );
4411 }
4412
4413 #[test]
4414 fn test_external_keys() {
4415 let buf = Arc::new(vec![0x12u8, 0x34, 0x56, 0x78, 0x9a, 0xbc]);
4416 let dir = tempdir().unwrap();
4417 let mut index = open_opts()
4418 .key_buf(Some(buf))
4419 .open(dir.path().join("a"))
4420 .expect("open");
4421 index
4422 .insert_advanced(InsertKey::Reference((1, 2)), InsertValue::Prepend(55))
4423 .expect("insert");
4424 index.flush().expect("flush");
4425 index
4426 .insert_advanced(InsertKey::Reference((1, 3)), InsertValue::Prepend(77))
4427 .expect("insert");
4428 assert_eq!(
4429 format!("{index:?}"),
4430 r#"Index { len: 43, root: Radix[0] }
4431Disk[1]: InlineLeaf { key: Disk[2], link: Disk[5] }
4432Disk[2]: ExtKey { start: 1, len: 2 }
4433Disk[5]: Link { value: 55, next: None }
4434Disk[8]: Radix { link: None, 3: Disk[1] }
4435Disk[16]: Root { radix: Disk[8] }
4436Disk[19]: Checksum { start: 0, end: 19, chunk_size_logarithm: 4, checksums.len(): 2 }
4437Radix[0]: Radix { link: None, 3: Radix[1] }
4438Radix[1]: Radix { link: None, 4: Radix[2] }
4439Radix[2]: Radix { link: None, 5: Radix[3] }
4440Radix[3]: Radix { link: None, 6: Radix[4] }
4441Radix[4]: Radix { link: Disk[5], 7: Leaf[0] }
4442Leaf[0]: Leaf { key: ExtKey[0], link: Link[0] }
4443Link[0]: Link { value: 77, next: None }
4444ExtKey[0]: ExtKey { start: 1, len: 3 }
4445"#
4446 );
4447 }
4448
4449 #[test]
4450 fn test_inline_leafs() {
4451 let buf = Arc::new(vec![0x12u8, 0x34, 0x56, 0x78, 0x9a, 0xbc]);
4452 let dir = tempdir().unwrap();
4453 let mut index = open_opts()
4454 .key_buf(Some(buf))
4455 .open(dir.path().join("a"))
4456 .expect("open");
4457
4458 index
4460 .insert_advanced(InsertKey::Reference((1, 1)), InsertValue::Prepend(55))
4461 .unwrap();
4462 index.flush().expect("flush");
4463
4464 index
4466 .insert_advanced(InsertKey::Reference((2, 1)), InsertValue::Prepend(77))
4467 .unwrap();
4468 index.flush().expect("flush");
4469
4470 index
4472 .insert_advanced(InsertKey::Reference((2, 1)), InsertValue::Prepend(88))
4473 .unwrap();
4474 index.flush().expect("flush");
4475
4476 index
4479 .insert_advanced(InsertKey::Reference((3, 1)), InsertValue::Prepend(99))
4480 .unwrap();
4481 index
4482 .insert_advanced(InsertKey::Reference((3, 1)), InsertValue::Prepend(100))
4483 .unwrap();
4484 index.flush().expect("flush");
4485
4486 assert_eq!(
4487 format!("{index:?}"),
4488 r#"Index { len: 257, root: Disk[181] }
4489Disk[1]: InlineLeaf { key: Disk[2], link: Disk[5] }
4490Disk[2]: ExtKey { start: 1, len: 1 }
4491Disk[5]: Link { value: 55, next: None }
4492Disk[8]: Radix { link: None, 3: Disk[1] }
4493Disk[16]: Root { radix: Disk[8] }
4494Disk[19]: Checksum { start: 0, end: 19, chunk_size_logarithm: 4, checksums.len(): 2 }
4495Disk[43]: InlineLeaf { key: Disk[44], link: Disk[47] }
4496Disk[44]: ExtKey { start: 2, len: 1 }
4497Disk[47]: Link { value: 77, next: None }
4498Disk[50]: Radix { link: None, 3: Disk[1], 5: Disk[43] }
4499Disk[62]: Root { radix: Disk[50] }
4500Disk[65]: Checksum { start: 19, end: 65, chunk_size_logarithm: 4, checksums.len(): 4 }
4501Disk[105]: Link { value: 88, next: Disk[47] }
4502Disk[108]: Leaf { key: Disk[44], link: Disk[105] }
4503Disk[111]: Radix { link: None, 3: Disk[1], 5: Disk[108] }
4504Disk[123]: Root { radix: Disk[111] }
4505Disk[126]: Checksum { start: 65, end: 126, chunk_size_logarithm: 4, checksums.len(): 4 }
4506Disk[166]: ExtKey { start: 3, len: 1 }
4507Disk[169]: Link { value: 99, next: None }
4508Disk[172]: Link { value: 100, next: Disk[169] }
4509Disk[176]: Leaf { key: Disk[166], link: Disk[172] }
4510Disk[181]: Radix { link: None, 3: Disk[1], 5: Disk[108], 7: Disk[176] }
4511Disk[197]: Root { radix: Disk[181] }
4512Disk[201]: Checksum { start: 126, end: 201, chunk_size_logarithm: 4, checksums.len(): 6 }
4513"#
4514 )
4515 }
4516
4517 #[test]
4518 fn test_clone() {
4519 let dir = tempdir().unwrap();
4520 let mut index = open_opts().open(dir.path().join("a")).expect("open");
4521
4522 assert_eq!(
4524 format!("{:?}", index.try_clone().unwrap()),
4525 format!("{:?}", index)
4526 );
4527 assert_eq!(
4528 format!("{:?}", index.try_clone_without_dirty().unwrap()),
4529 format!("{:?}", index)
4530 );
4531
4532 index.insert(&[], 55).expect("insert");
4534 index.insert(&[0x12], 77).expect("insert");
4535 index.flush().expect("flush");
4536 index.insert(&[0x15], 99).expect("insert");
4537
4538 let mut index2 = index.try_clone().expect("clone");
4539 assert_eq!(format!("{index:?}"), format!("{:?}", index2));
4540
4541 let index2clean = index.try_clone_without_dirty().unwrap();
4543 index2.clear_dirty();
4544 assert_eq!(format!("{index2:?}"), format!("{:?}", index2clean));
4545
4546 let mut index3 = open_opts()
4548 .checksum_chunk_size_logarithm(0)
4549 .create_in_memory()
4550 .unwrap();
4551 let index4 = index3.try_clone().unwrap();
4552 assert_eq!(format!("{index3:?}"), format!("{:?}", index4));
4553
4554 index3.insert(&[0x15], 99).expect("insert");
4555 let index4 = index3.try_clone().unwrap();
4556 assert_eq!(format!("{index3:?}"), format!("{:?}", index4));
4557 }
4558
4559 #[test]
4560 fn test_open_options_write() {
4561 let dir = tempdir().unwrap();
4562 let mut index = OpenOptions::new().open(dir.path().join("a")).expect("open");
4563 index.insert(&[0x12], 77).expect("insert");
4564 index.flush().expect("flush");
4565
4566 OpenOptions::new()
4567 .write(Some(false))
4568 .open(dir.path().join("b"))
4569 .expect_err("open"); let mut index = OpenOptions::new()
4572 .write(Some(false))
4573 .open(dir.path().join("a"))
4574 .expect("open");
4575 index.flush().expect_err("cannot flush read-only index");
4576 }
4577
4578 #[test]
4579 fn test_linked_list_values() {
4580 let dir = tempdir().unwrap();
4581 let mut index = OpenOptions::new().open(dir.path().join("a")).expect("open");
4582 let list = vec![11u64, 17, 19, 31];
4583 for i in list.iter().rev() {
4584 index.insert(&[], *i).expect("insert");
4585 }
4586
4587 let list1: Vec<u64> = index
4588 .get(&[])
4589 .unwrap()
4590 .values(&index)
4591 .map(|v| v.unwrap())
4592 .collect();
4593 assert_eq!(list, list1);
4594
4595 index.flush().expect("flush");
4596 let list2: Vec<u64> = index
4597 .get(&[])
4598 .unwrap()
4599 .values(&index)
4600 .map(|v| v.unwrap())
4601 .collect();
4602 assert_eq!(list, list2);
4603
4604 assert_eq!(index.get(&[1]).unwrap().values(&index).count(), 0);
4606
4607 index.insert(&[], 5).expect("insert");
4609 index.dirty_links[0].next_link_offset = LinkOffset(Offset(1000));
4610 let list_errored: Vec<crate::Result<u64>> =
4613 index.get(&[]).unwrap().values(&index).collect();
4614 assert!(list_errored[list_errored.len() - 1].is_err());
4615 }
4616
4617 #[test]
4618 fn test_checksum_bitflip_1b() {
4619 test_checksum_bitflip_with_size(0);
4620 }
4621
4622 #[test]
4623 fn test_checksum_bitflip_2b() {
4624 test_checksum_bitflip_with_size(1);
4625 }
4626
4627 #[test]
4628 fn test_checksum_bitflip_16b() {
4629 test_checksum_bitflip_with_size(4);
4630 }
4631
4632 #[test]
4633 fn test_checksum_bitflip_1mb() {
4634 test_checksum_bitflip_with_size(20);
4635 }
4636
4637 fn test_checksum_bitflip_with_size(checksum_log_size: u32) {
4638 let dir = tempdir().unwrap();
4639
4640 let keys = if cfg!(debug_assertions) {
4641 vec![vec![0x13], vec![0x17], vec![]]
4643 } else {
4644 vec![
4646 vec![0x12, 0x34],
4647 vec![0x12, 0x78],
4648 vec![0x34, 0x56],
4649 vec![0x34],
4650 vec![0x78],
4651 vec![0x78, 0x9a],
4652 ]
4653 };
4654
4655 let opts = open_opts()
4658 .checksum_chunk_size_logarithm(checksum_log_size)
4659 .verified_cache(false)
4660 .clone();
4661
4662 let bytes = {
4663 let mut index = opts.open(dir.path().join("a")).expect("open");
4664
4665 for (i, key) in keys.iter().enumerate() {
4666 index.insert(key, i as u64).expect("insert");
4667 index.insert(key, (i as u64) << 50).expect("insert");
4668 }
4669 index.flush().expect("flush");
4670
4671 let mut f = File::open(dir.path().join("a")).expect("open");
4673 let mut buf = vec![];
4674 f.read_to_end(&mut buf).expect("read");
4675
4676 if std::env::var("DEBUG").is_ok() {
4679 eprintln!("{index:?}");
4680 }
4681
4682 buf
4683 };
4684
4685 fn is_corrupted(index: &Index, key: &[u8]) -> bool {
4686 let link = index.get(&key);
4687 match link {
4688 Err(_) => true,
4689 Ok(link) => link.values(index).any(|v| v.is_err()),
4690 }
4691 }
4692
4693 for i in 0..(bytes.len() * 8) {
4695 let mut bytes = bytes.clone();
4696 bytes[i / 8] ^= 1u8 << (i % 8);
4697 let mut f = File::create(dir.path().join("a")).expect("create");
4698 f.write_all(&bytes).expect("write");
4699
4700 let index = opts.clone().open(dir.path().join("a"));
4701 let detected = match index {
4702 Err(_) => true,
4703 Ok(index) => {
4704 let range = if cfg!(debug_assertions) { 0 } else { 0x10000 };
4705 (0..range).any(|key_int| {
4706 let key = [(key_int >> 8) as u8, (key_int & 0xff) as u8];
4707 is_corrupted(&index, &key)
4708 }) || (0..0x100).any(|key_int| {
4709 let key = [key_int as u8];
4710 is_corrupted(&index, &key)
4711 }) || is_corrupted(&index, &[])
4712 }
4713 };
4714 assert!(
4715 detected,
4716 "bit flip at byte {} , bit {} is not detected (set DEBUG=1 to see Index dump)",
4717 i / 8,
4718 i % 8,
4719 );
4720 }
4721 }
4722
4723 #[test]
4724 fn test_checksum_toggle() {
4725 let dir = tempdir().unwrap();
4726 let open = |enabled: bool| {
4727 open_opts()
4728 .checksum_enabled(enabled)
4729 .open(dir.path().join("a"))
4730 .expect("open")
4731 };
4732
4733 let mut index = open(false);
4735 index.verify().unwrap();
4736 index.insert(b"abcdefg", 0x1234).unwrap();
4737 index.flush().unwrap();
4738 index.insert(b"bcdefgh", 0x2345).unwrap();
4739 index.flush().unwrap();
4740
4741 let mut index = open(true);
4743 index.verify().unwrap();
4744 index.insert(b"cdefghi", 0x3456).unwrap();
4745 index.flush().unwrap();
4746 index.insert(b"defghij", 0x4567).unwrap();
4747 index.flush().unwrap();
4748
4749 let mut index = open(false);
4751 index.verify().unwrap();
4752 index.insert(b"efghijh", 0x5678).unwrap();
4753 index.flush().unwrap();
4754 index.insert(b"fghijkl", 0x7890).unwrap();
4755 index.flush().unwrap();
4756
4757 assert_eq!(
4758 format!("{index:?}"),
4759 r#"Index { len: 415, root: Disk[402] }
4760Disk[1]: Key { key: 61 62 63 64 65 66 67 }
4761Disk[10]: Link { value: 4660, next: None }
4762Disk[14]: Leaf { key: Disk[1], link: Disk[10] }
4763Disk[17]: Radix { link: None, 6: Disk[14] }
4764Disk[25]: Root { radix: Disk[17] }
4765Disk[29]: Key { key: 62 63 64 65 66 67 68 }
4766Disk[38]: Link { value: 9029, next: None }
4767Disk[42]: Leaf { key: Disk[29], link: Disk[38] }
4768Disk[45]: Radix { link: None, 1: Disk[14], 2: Disk[42] }
4769Disk[57]: Radix { link: None, 6: Disk[45] }
4770Disk[65]: Root { radix: Disk[57] }
4771Disk[69]: Key { key: 63 64 65 66 67 68 69 }
4772Disk[78]: Link { value: 13398, next: None }
4773Disk[82]: Leaf { key: Disk[69], link: Disk[78] }
4774Disk[85]: Radix { link: None, 1: Disk[14], 2: Disk[42], 3: Disk[82] }
4775Disk[101]: Radix { link: None, 6: Disk[85] }
4776Disk[109]: Root { radix: Disk[101] }
4777Disk[112]: Checksum { start: 0, end: 112, chunk_size_logarithm: 4, checksums.len(): 7 }
4778Disk[176]: Key { key: 64 65 66 67 68 69 6A }
4779Disk[185]: Link { value: 17767, next: None }
4780Disk[190]: Leaf { key: Disk[176], link: Disk[185] }
4781Disk[195]: Radix { link: None, 1: Disk[14], 2: Disk[42], 3: Disk[82], 4: Disk[190] }
4782Disk[215]: Radix { link: None, 6: Disk[195] }
4783Disk[223]: Root { radix: Disk[215] }
4784Disk[227]: Checksum { start: 112, end: 227, chunk_size_logarithm: 4, checksums.len(): 8 }
4785Disk[299]: Key { key: 65 66 67 68 69 6A 68 }
4786Disk[308]: Link { value: 22136, next: None }
4787Disk[313]: Leaf { key: Disk[299], link: Disk[308] }
4788Disk[318]: Radix { link: None, 1: Disk[14], 2: Disk[42], 3: Disk[82], 4: Disk[190], 5: Disk[313] }
4789Disk[342]: Radix { link: None, 6: Disk[318] }
4790Disk[350]: Root { radix: Disk[342] }
4791Disk[355]: Key { key: 66 67 68 69 6A 6B 6C }
4792Disk[364]: Link { value: 30864, next: None }
4793Disk[369]: Leaf { key: Disk[355], link: Disk[364] }
4794Disk[374]: Radix { link: None, 1: Disk[14], 2: Disk[42], 3: Disk[82], 4: Disk[190], 5: Disk[313], 6: Disk[369] }
4795Disk[402]: Radix { link: None, 6: Disk[374] }
4796Disk[410]: Root { radix: Disk[402] }
4797"#
4798 );
4799 }
4800
4801 fn set_verified_cache_boot_id(path: &Path, boot_id: u64) {
4803 let mut data = utils::atomic_read(path).unwrap();
4804 let len = data.len();
4805 LittleEndian::write_u64(&mut data[8..16], boot_id);
4806 let xx32 = xxhash32(&data[..len - 4]);
4807 LittleEndian::write_u32(&mut data[len - 4..], xx32);
4808 utils::atomic_write(path, data, false).unwrap();
4809 }
4810
4811 fn flip_bit(path: &Path, offset: u64) {
4812 let mut file = fs::OpenOptions::new()
4813 .read(true)
4814 .write(true)
4815 .open(path)
4816 .unwrap();
4817 let mut byte = [0u8; 1];
4818 file.seek(SeekFrom::Start(offset)).unwrap();
4819 file.read_exact(&mut byte).unwrap();
4820 byte[0] ^= 1;
4821 file.seek(SeekFrom::Start(offset)).unwrap();
4822 file.write_all(&byte).unwrap();
4823 }
4824
4825 #[test]
4826 fn test_verified_cache() {
4827 if utils::boot_id().is_none() {
4828 return;
4830 }
4831 let dir = tempdir().unwrap();
4832 let path = dir.path().join("i");
4833 let cache_path = dir.path().join("i.verified");
4834 let open = || open_opts().verified_cache(true).open(&path).unwrap();
4835 let fill = |index: &mut Index, seed: u8| {
4836 for i in 0..40u8 {
4837 index.insert(&[i ^ seed; 8], i as u64).unwrap();
4838 }
4839 index.flush().unwrap();
4840 };
4841
4842 let mut index = open();
4843 fill(&mut index, 0);
4844 let complete = index.checksum.complete_chunk_count();
4845 assert!(complete > VERIFIED_CACHE_SAVE_THRESHOLD);
4846 assert!(((complete as u64) << 4) < index.checksum.end);
4848 index.verify().unwrap();
4849 drop(index);
4850 let cache = utils::atomic_read(&cache_path).unwrap();
4851
4852 assert_eq!(LittleEndian::read_u64(&cache[20..28]), complete as u64);
4854
4855 let index = open();
4857 assert_eq!(index.checksum.verified_chunk_count(), complete);
4858 drop(index);
4859
4860 let first_complete = complete;
4864 let mut index = open();
4865 fill(&mut index, 1);
4866 assert!(index.checksum.verified_chunk_count() >= complete);
4867 let end = index.checksum.end;
4868 let complete = index.checksum.complete_chunk_count();
4869 drop(index);
4870 let a = open();
4871 let b = open();
4872 let half = end / 2;
4873 a.verify_checksum(0, half).unwrap();
4874 b.verify_checksum(half, end - half).unwrap();
4875 drop(a);
4876 drop(b);
4877 let index = open();
4878 assert_eq!(index.checksum.verified_chunk_count(), complete);
4879 drop(index);
4880
4881 flip_bit(&path, 2);
4884 let index = open();
4885 index.verify().unwrap();
4886 drop(index);
4887 set_verified_cache_boot_id(&cache_path, 42);
4890 let index = open();
4891 assert!(index.checksum.verified_chunk_count() < complete);
4892 assert!(index.verify().is_err());
4893 drop(index);
4894
4895 fs::remove_file(&path).unwrap();
4897 let mut index = open();
4898 fill(&mut index, 0x80);
4899 drop(index);
4900 utils::atomic_write(&cache_path, cache, false).unwrap();
4901 let index = open();
4902 assert!(index.checksum.verified_chunk_count() < first_complete);
4903 index.verify().unwrap();
4904 }
4905
4906 fn show_checksums(index: &Index) -> String {
4907 let debug_str = format!("{index:?}");
4908 debug_str
4909 .lines()
4910 .filter_map(|l| {
4911 if l.contains("Checksum") {
4912 Some(format!("\n {l}"))
4913 } else {
4914 None
4915 }
4916 })
4917 .collect::<Vec<_>>()
4918 .concat()
4919 }
4920
4921 #[test]
4922 fn test_checksum_max_chain_len() {
4923 let t = |max_chain_len: u32| {
4925 let dir = tempdir().unwrap();
4926 let path = dir.path().join("i");
4927 let mut index = open_opts()
4928 .checksum_chunk_size_logarithm(7 )
4929 .checksum_max_chain_len(max_chain_len)
4930 .open(&path)
4931 .unwrap();
4932 for i in 0..10u8 {
4933 let data: Vec<u8> = if i % 2 == 0 { vec![i] } else { vec![i; 100] };
4934 index.insert(&data, 1).unwrap();
4935 index.flush().unwrap();
4936 index.verify().unwrap();
4937 let mut index2 = open_opts()
4939 .checksum_max_chain_len(max_chain_len)
4940 .open(&path)
4941 .unwrap();
4942 index2.verify().unwrap();
4943 if i % 3 == 0 {
4945 index2.insert(&data, 2).unwrap();
4946 index2.flush().unwrap();
4947 }
4948 }
4949 show_checksums(&index)
4950 };
4951
4952 assert_eq!(
4954 t(0),
4955 r#"
4956 Disk[21]: Checksum { start: 0, end: 21, chunk_size_logarithm: 7, checksums.len(): 1 }
4957 Disk[54]: Checksum { start: 0, end: 54, chunk_size_logarithm: 7, checksums.len(): 1 }
4958 Disk[203]: Checksum { start: 0, end: 203, chunk_size_logarithm: 7, checksums.len(): 2 }
4959 Disk[266]: Checksum { start: 203, end: 266, chunk_size_logarithm: 7, checksums.len(): 2 }
4960 Disk[433]: Checksum { start: 266, end: 433, chunk_size_logarithm: 7, checksums.len(): 2 }
4961 Disk[499]: Checksum { start: 433, end: 499, chunk_size_logarithm: 7, checksums.len(): 1 }
4962 Disk[563]: Checksum { start: 433, end: 563, chunk_size_logarithm: 7, checksums.len(): 2 }
4963 Disk[738]: Checksum { start: 563, end: 738, chunk_size_logarithm: 7, checksums.len(): 2 }
4964 Disk[818]: Checksum { start: 738, end: 818, chunk_size_logarithm: 7, checksums.len(): 2 }
4965 Disk[896]: Checksum { start: 818, end: 896, chunk_size_logarithm: 7, checksums.len(): 1 }
4966 Disk[1071]: Checksum { start: 818, end: 1071, chunk_size_logarithm: 7, checksums.len(): 3 }
4967 Disk[1167]: Checksum { start: 1071, end: 1167, chunk_size_logarithm: 7, checksums.len(): 2 }
4968 Disk[1358]: Checksum { start: 1167, end: 1358, chunk_size_logarithm: 7, checksums.len(): 2 }"#
4969 );
4970
4971 assert_eq!(
4973 t(2),
4974 r#"
4975 Disk[21]: Checksum { start: 0, end: 21, chunk_size_logarithm: 7, checksums.len(): 1 }
4976 Disk[54]: Checksum { start: 0, end: 54, chunk_size_logarithm: 7, checksums.len(): 1 }
4977 Disk[203]: Checksum { start: 0, end: 203, chunk_size_logarithm: 7, checksums.len(): 2 }
4978 Disk[266]: Checksum { start: 203, end: 266, chunk_size_logarithm: 7, checksums.len(): 2 }
4979 Disk[433]: Checksum { start: 0, end: 433, chunk_size_logarithm: 7, checksums.len(): 4 }
4980 Disk[514]: Checksum { start: 433, end: 514, chunk_size_logarithm: 7, checksums.len(): 2 }
4981 Disk[586]: Checksum { start: 433, end: 586, chunk_size_logarithm: 7, checksums.len(): 2 }
4982 Disk[761]: Checksum { start: 0, end: 761, chunk_size_logarithm: 7, checksums.len(): 6 }
4983 Disk[872]: Checksum { start: 761, end: 872, chunk_size_logarithm: 7, checksums.len(): 2 }
4984 Disk[950]: Checksum { start: 0, end: 950, chunk_size_logarithm: 7, checksums.len(): 8 }
4985 Disk[1180]: Checksum { start: 0, end: 1180, chunk_size_logarithm: 7, checksums.len(): 10 }
4986 Disk[1331]: Checksum { start: 1180, end: 1331, chunk_size_logarithm: 7, checksums.len(): 2 }
4987 Disk[1522]: Checksum { start: 0, end: 1522, chunk_size_logarithm: 7, checksums.len(): 12 }"#
4988 );
4989
4990 assert_eq!(
4992 t(1),
4993 r#"
4994 Disk[21]: Checksum { start: 0, end: 21, chunk_size_logarithm: 7, checksums.len(): 1 }
4995 Disk[54]: Checksum { start: 0, end: 54, chunk_size_logarithm: 7, checksums.len(): 1 }
4996 Disk[203]: Checksum { start: 0, end: 203, chunk_size_logarithm: 7, checksums.len(): 2 }
4997 Disk[266]: Checksum { start: 0, end: 266, chunk_size_logarithm: 7, checksums.len(): 3 }
4998 Disk[440]: Checksum { start: 0, end: 440, chunk_size_logarithm: 7, checksums.len(): 4 }
4999 Disk[521]: Checksum { start: 0, end: 521, chunk_size_logarithm: 7, checksums.len(): 5 }
5000 Disk[616]: Checksum { start: 0, end: 616, chunk_size_logarithm: 7, checksums.len(): 5 }
5001 Disk[814]: Checksum { start: 0, end: 814, chunk_size_logarithm: 7, checksums.len(): 7 }
5002 Disk[933]: Checksum { start: 0, end: 933, chunk_size_logarithm: 7, checksums.len(): 8 }
5003 Disk[1058]: Checksum { start: 0, end: 1058, chunk_size_logarithm: 7, checksums.len(): 9 }
5004 Disk[1296]: Checksum { start: 0, end: 1296, chunk_size_logarithm: 7, checksums.len(): 11 }
5005 Disk[1455]: Checksum { start: 0, end: 1455, chunk_size_logarithm: 7, checksums.len(): 12 }
5006 Disk[1725]: Checksum { start: 0, end: 1725, chunk_size_logarithm: 7, checksums.len(): 14 }"#
5007 );
5008 }
5009
5010 fn checksum_entry(
5013 previous_offset: u64,
5014 chunk_size_logarithm: u32,
5015 hash_count: usize,
5016 ) -> Vec<u8> {
5017 let mut buf = vec![TYPE_CHECKSUM];
5018 buf.write_vlq(previous_offset).unwrap();
5019 buf.write_vlq(chunk_size_logarithm).unwrap();
5020 for _ in 0..hash_count {
5021 buf.write_u64::<LittleEndian>(0).unwrap();
5022 }
5023 let xx32 = xxhash32(&buf);
5024 buf.write_u32::<LittleEndian>(xx32).unwrap();
5025 buf
5026 }
5027
5028 fn index_buf(len: usize, entries: &[(usize, Vec<u8>)]) -> Vec<u8> {
5031 let mut buf = vec![0u8; len];
5032 for (offset, entry) in entries {
5033 buf[*offset..*offset + entry.len()].copy_from_slice(entry);
5034 }
5035 buf
5036 }
5037
5038 fn read_checksum(buf: &[u8], offset: u64) -> crate::Result<MemChecksum> {
5039 let index = SimpleIndexBuf(buf, Path::new("<test>"));
5040 MemChecksum::read_from(&index, offset).map(|(checksum, _size)| checksum)
5041 }
5042
5043 #[test]
5044 fn test_checksum_read_rejects_oversized_chunk_count() {
5045 let buf = index_buf(4096, &[(4000, checksum_entry(0, 0, 0))]);
5048 let err = read_checksum(&buf, 4000).unwrap_err();
5049 assert!(
5050 err.to_string().contains("needs 4000 chunks"),
5051 "unexpected error: {err}"
5052 );
5053 }
5054
5055 #[test]
5056 fn test_checksum_read_rejects_entry_past_end() {
5057 let buf = index_buf(
5061 65536,
5062 &[
5063 (65000, checksum_entry(63542, 8, 6)),
5064 (63542, checksum_entry(0, 8, 0)),
5065 ],
5066 );
5067 let err = read_checksum(&buf, 65000).unwrap_err();
5068 assert!(
5069 err.to_string()
5070 .contains("byte range 63545..65541 is unavailable"),
5071 "unexpected error: {err}"
5072 );
5073 }
5074
5075 #[test]
5076 fn test_checksum_read_rejects_self_referential_chain() {
5077 let buf = index_buf(4096, &[(4000, checksum_entry(4000, 20, 1))]);
5080 let (tx, rx) = mpsc::channel();
5081 thread::spawn(move || {
5082 let _ = tx.send(read_checksum(&buf, 4000).is_err());
5083 });
5084 match rx.recv_timeout(Duration::from_secs(60)) {
5085 Ok(rejected) => assert!(rejected, "self-referential checksum chain was accepted"),
5086 Err(_) => panic!("MemChecksum::read_from did not terminate"),
5087 }
5088 }
5089
5090 #[test]
5091 fn test_checksum_read_rejects_chunk_count_above_initial() {
5092 let buf = index_buf(
5095 4096,
5096 &[
5097 (4000, checksum_entry(3900, 12, 1)),
5098 (3900, checksum_entry(0, 4, 0)),
5099 ],
5100 );
5101 let err = read_checksum(&buf, 4000).unwrap_err();
5102 assert!(
5103 err.to_string().contains("covers 244 chunks"),
5104 "unexpected error: {err}"
5105 );
5106 }
5107
5108 #[test]
5109 fn test_root_meta() {
5110 let dir = tempdir().unwrap();
5111 let mut index = open_opts().open(dir.path().join("a")).expect("open");
5112 assert!(index.get_meta().is_empty());
5113 let meta = vec![200; 4000];
5114 index.set_meta(&meta);
5115 assert_eq!(index.get_meta(), &meta[..]);
5116 index.flush().expect("flush");
5117 let index = open_opts().open(dir.path().join("a")).expect("open");
5118 assert_eq!(index.get_meta(), &meta[..]);
5119 }
5120
5121 impl<'a> RangeIter<'a> {
5122 fn clone_with_index(&self, index: &'a Index) -> Self {
5123 Self {
5124 completed: self.completed,
5125 index,
5126 front_stack: self.front_stack.clone(),
5127 back_stack: self.back_stack.clone(),
5128 }
5129 }
5130 }
5131
5132 fn iter_to_keys(index: &Index, keys: &[&[u8]], iter: &RangeIter) -> Vec<Vec<u8>> {
5136 let it_forward = iter.clone_with_index(index);
5137 let it_backward = iter.clone_with_index(index);
5138 let mut it_both_ends = iter.clone_with_index(index);
5139
5140 let extract = |v: crate::Result<(Cow<'_, [u8]>, LinkOffset)>| -> Vec<u8> {
5141 let (key, link_offset) = v.unwrap();
5142 let key = key.as_ref();
5143 let ids: Vec<u64> = link_offset
5145 .values(index)
5146 .collect::<crate::Result<Vec<u64>>>()
5147 .unwrap();
5148 assert!(ids.len() == 1);
5149 assert_eq!(keys[ids[0] as usize], key);
5150 key.to_vec()
5151 };
5152
5153 let keys_forward: Vec<_> = it_forward.map(extract).collect();
5154 let mut keys_backward: Vec<_> = it_backward.rev().map(extract).collect();
5155 keys_backward.reverse();
5156 assert_eq!(keys_forward, keys_backward);
5157
5158 let mut keys_both_ends = Vec::new();
5160 for i in 0..(keys_forward.len() + 2) {
5161 if let Some(v) = it_both_ends.next() {
5162 keys_both_ends.insert(i, extract(v));
5163 }
5164 if let Some(v) = it_both_ends.next_back() {
5165 keys_both_ends.insert(i + 1, extract(v));
5166 }
5167 }
5168 assert_eq!(keys_forward, keys_both_ends);
5169
5170 keys_forward
5171 }
5172
5173 fn test_range_against_btreeset(tree: BTreeSet<&[u8]>) {
5175 let dir = tempdir().unwrap();
5176 let mut index = open_opts().open(dir.path().join("a")).unwrap();
5177 let keys: Vec<&[u8]> = tree.iter().cloned().collect();
5178 for (i, key) in keys.iter().enumerate() {
5179 index.insert(key, i as u64).unwrap();
5180 }
5181
5182 let range_test = |start: Bound<&[u8]>, end: Bound<&[u8]>| {
5183 let range = (start, end);
5184 let iter = index.range(range).unwrap();
5185 let expected_keys: Vec<Vec<u8>> = tree
5186 .range::<&[u8], _>((start, end))
5187 .map(|v| v.to_vec())
5188 .collect();
5189 let selected_keys: Vec<Vec<u8>> = iter_to_keys(&index, &keys, &iter);
5190 assert_eq!(selected_keys, expected_keys);
5191 };
5192
5193 let mut variant_keys = Vec::new();
5196 for base_key in keys.iter() {
5197 for b in [0x00, 0x77, 0xff] {
5199 let mut key = base_key.to_vec();
5200 key.push(b);
5201 variant_keys.push(key);
5202 }
5203
5204 if !base_key.is_empty() {
5206 let mut key = base_key.to_vec();
5207 let last = *key.last().unwrap();
5208 *key.last_mut().unwrap() = last.wrapping_add(1);
5209 variant_keys.push(key.clone());
5210 *key.last_mut().unwrap() = last.wrapping_sub(1);
5211 variant_keys.push(key.clone());
5212 key.pop();
5213 variant_keys.push(key);
5214 }
5215 }
5216
5217 let variant_keys = variant_keys
5219 .iter()
5220 .map(|v| v.as_ref())
5221 .filter(|k| !tree.contains(k))
5222 .collect::<BTreeSet<&[u8]>>()
5223 .iter()
5224 .cloned()
5225 .collect::<Vec<&[u8]>>();
5226
5227 range_test(Unbounded, Unbounded);
5228
5229 for key1 in keys.iter().chain(variant_keys.iter()) {
5230 range_test(Unbounded, Included(key1));
5231 range_test(Unbounded, Excluded(key1));
5232 range_test(Included(key1), Unbounded);
5233 range_test(Excluded(key1), Unbounded);
5234
5235 for key2 in keys.iter().chain(variant_keys.iter()) {
5236 if key1 < key2 {
5237 range_test(Excluded(key1), Excluded(key2));
5238 }
5239 if key1 <= key2 {
5240 range_test(Excluded(key1), Included(key2));
5241 range_test(Included(key1), Excluded(key2));
5242 range_test(Included(key1), Included(key2));
5243 }
5244 }
5245 }
5246 }
5247
5248 #[test]
5249 fn test_range_example1() {
5250 test_range_against_btreeset(
5251 [
5252 &[0x00, 0x00, 0x00][..],
5253 &[0x10, 0x0d, 0x01],
5254 &[0x10, 0x0e],
5255 &[0x10, 0x0f],
5256 &[0x10, 0x0f, 0xff],
5257 &[0x10, 0x10, 0x01],
5258 &[0x10, 0x11],
5259 &[0xff],
5260 ]
5261 .iter()
5262 .cloned()
5263 .collect(),
5264 );
5265 }
5266
5267 #[test]
5268 fn test_clear_dirty() {
5269 let dir = tempdir().unwrap();
5270 let mut index = open_opts().open(dir.path().join("a")).unwrap();
5271
5272 index.insert(&"foo", 2).unwrap();
5273 assert!(!index.get(&"foo").unwrap().is_null());
5274
5275 index.clear_dirty();
5276 assert!(index.get(&"foo").unwrap().is_null());
5277
5278 index.set_meta(vec![42]);
5279 index.insert(&"foo", 1).unwrap();
5280 index.flush().unwrap();
5281
5282 index.set_meta(vec![43]);
5283 index.insert(&"bar", 2).unwrap();
5284
5285 assert_eq!(index.get_original_meta(), [42]);
5286 index.clear_dirty();
5287
5288 assert_eq!(index.get_meta(), [42]);
5289 assert!(index.get(&"bar").unwrap().is_null());
5290 }
5291
5292 #[test]
5293 fn test_meta_only_flush() {
5294 let dir = tempdir().unwrap();
5295 let mut index = open_opts().open(dir.path().join("a")).unwrap();
5296
5297 index.set_meta(b"foo");
5298 index.flush().unwrap();
5299
5300 let mut index = open_opts().open(dir.path().join("a")).unwrap();
5301 assert_eq!(index.get_meta(), b"foo");
5302
5303 index.set_meta(b"bar");
5304 let len1 = index.flush().unwrap();
5305
5306 let mut index = open_opts().open(dir.path().join("a")).unwrap();
5307 assert_eq!(index.get_meta(), b"bar");
5308 index.set_meta(b"bar");
5309 let len2 = index.flush().unwrap();
5310 assert_eq!(len1, len2);
5311 }
5312
5313 #[test]
5314 fn test_flush_with_replaced_file() {
5315 let dir = tempdir().unwrap();
5316 let path1 = dir.path().join("1");
5317 let path2 = dir.path().join("2");
5318 let mut index1 = open_opts().open(&path1).unwrap();
5319 let mut index2 = open_opts().open(&path2).unwrap();
5320
5321 index1.insert(b"foo1", 1).unwrap();
5322 index1.insert(b"z1", 1).unwrap();
5323 index2.insert(b"foo1", 2).unwrap();
5324 index2.insert(b"z1", 2).unwrap();
5325
5326 let len1 = index1.flush().unwrap();
5327 let len2 = index2.flush().unwrap();
5328
5329 assert_eq!(len1, len2);
5330
5331 index1.insert(b"z1", 3).unwrap();
5333
5334 fs::rename(&path1, path1.with_extension("bak")).unwrap();
5338 fs::rename(&path2, &path1).unwrap();
5339
5340 index1.fail_on_flush = 8;
5342 index1.flush().unwrap_err();
5343 let link_offset = index1.get(b"foo1").expect("lookup");
5344 assert_eq!(link_offset.value_and_next(&index1).unwrap().0, 1);
5346 }
5347
5348 quickcheck! {
5349 fn test_single_value(map: HashMap<Vec<u8>, u64>, flush: bool) -> bool {
5350 let dir = tempdir().unwrap();
5351 let mut index = open_opts().open(dir.path().join("a")).expect("open");
5352
5353 for (key, value) in &map {
5354 index.insert(key, *value).expect("insert");
5355 }
5356
5357 if flush {
5358 let len = index.flush().expect("flush");
5359 index = open_opts().logical_len(len.into()).open(dir.path().join("a")).unwrap();
5360 }
5361
5362 index.verify_against_hashmap(&map)
5363 }
5364
5365 fn test_flush_failure(map: HashMap<Vec<u8>, u64>) -> bool {
5366 let dir = tempdir().unwrap();
5367 let mut index = open_opts().open(dir.path().join("a")).expect("open");
5368
5369 for (key, value) in &map {
5371 if value % 2 == 0 {
5372 index.insert(key, *value).expect("insert");
5373 }
5374 }
5375 index.flush().expect("flush");
5376
5377 let mut should_fail = false;
5379 for (key, value) in &map {
5380 if value % 2 == 1 {
5381 index.insert(key, *value).expect("insert");
5382 should_fail = true;
5383 }
5384 }
5385
5386 (1..=8).all(|flush_failure| {
5387 let mut index = index.try_clone().expect("clone");
5388 index.fail_on_flush = flush_failure;
5389 let old_index_buf_len = index.buf.len();
5390 assert_eq!(index.flush().is_err(), should_fail);
5391 assert_eq!(old_index_buf_len, index.buf.len());
5392
5393 let mut verified = index.verify_against_hashmap(&map);
5395
5396 if !should_fail {
5398 index.fail_on_flush = 0;
5399 index.flush().expect("flush should succeed");
5400 verified &= index.verify_against_hashmap(&map)
5401 }
5402
5403 verified
5404 })
5405 }
5406
5407 fn test_multiple_values(map: HashMap<Vec<u8>, Vec<u64>>) -> bool {
5408 let dir = tempdir().unwrap();
5409 let mut index = open_opts().open(dir.path().join("a")).expect("open");
5410 let mut index_mem = open_opts().checksum_chunk_size_logarithm(20).create_in_memory().unwrap();
5411
5412 for (key, values) in &map {
5413 for value in values.iter().rev() {
5414 index.insert(key, *value).expect("insert");
5415 index_mem.insert(key, *value).expect("insert");
5416 }
5417 if values.is_empty() {
5418 index.flush().expect("flush");
5420 }
5421 }
5422
5423 map.iter().all(|(key, values)| {
5424 let v: Vec<u64> =
5425 index.get(key).unwrap().values(&index).map(|v| v.unwrap()).collect();
5426 let v_mem: Vec<u64> =
5427 index_mem.get(key).unwrap().values(&index_mem).map(|v| v.unwrap()).collect();
5428 v == *values && v_mem == *values
5429 })
5430 }
5431
5432 fn test_range_quickcheck(keys: Vec<Vec<u8>>) -> bool {
5433 let size_limit = if cfg!(debug_assertions) {
5434 4
5435 } else {
5436 16
5437 };
5438 let size = keys.len() % size_limit + 1;
5439 let tree: BTreeSet<&[u8]> = keys.iter().take(size).map(|v| v.as_ref()).collect();
5440 test_range_against_btreeset(tree);
5441 true
5442 }
5443
5444 fn test_deletion(keys_deleted: Vec<(Vec<u8>, bool)>) -> bool {
5445 let mut set = BTreeSet::<Vec<u8>>::new();
5447 let mut index = in_memory_index();
5448 keys_deleted.into_iter().all(|(key, deleted)| {
5449 if deleted {
5450 set.remove(&key);
5451 index.remove(&key).unwrap();
5452 } else {
5453 set.insert(key.clone());
5454 index.insert(&key, 1).unwrap();
5455 }
5456 index
5457 .range(..)
5458 .unwrap()
5459 .map(|s| s.unwrap().0.as_ref().to_vec())
5460 .collect::<Vec<_>>()
5461 == set.iter().cloned().collect::<Vec<_>>()
5462 })
5463 }
5464
5465 fn test_deletion_prefix(keys_deleted: Vec<(Vec<u8>, bool)>) -> bool {
5466 let mut set = BTreeSet::<Vec<u8>>::new();
5467 let mut index = in_memory_index();
5468 keys_deleted.into_iter().all(|(key, deleted)| {
5469 if deleted {
5470 let to_delete = set
5472 .iter()
5473 .filter(|k| k.starts_with(&key))
5474 .cloned()
5475 .collect::<Vec<_>>();
5476 for key in to_delete {
5477 set.remove(&key);
5478 }
5479 index.remove_prefix(&key).unwrap();
5480 } else {
5481 set.insert(key.clone());
5482 index.insert(&key, 1).unwrap();
5483 }
5484 index
5485 .range(..)
5486 .unwrap()
5487 .map(|s| s.unwrap().0.as_ref().to_vec())
5488 .collect::<Vec<_>>()
5489 == set.iter().cloned().collect::<Vec<_>>()
5490 })
5491 }
5492 }
5493
5494 impl Index {
5495 fn verify_against_hashmap(&self, map: &HashMap<Vec<u8>, u64>) -> bool {
5496 let index = self;
5497 map.iter().all(|(key, value)| {
5498 let link_offset = index.get(key).expect("lookup");
5499 assert!(!link_offset.is_null());
5500 link_offset.value_and_next(index).unwrap().0 == *value
5501 })
5502 }
5503 }
5504}