use std::collections::BTreeMap;
mod scratch;
mod spill;
pub use scratch::Scratch;
pub use spill::{GraphSectionsSpill, PackedFragment};
use crate::ids::Digest128;
use crate::packed::{self, PackedBuilder};
use crate::postings::{BLOCK_ENTRIES, PostingCursor, PostingLayout, PostingList, PostingsBuilder};
use crate::segment::{
Alignment, ErrorKind, KeySpace, KnownSection, Requirement, SectionHandle, SectionId,
SectionKind, SectionSpec, Segment, SegmentError, SegmentWriter,
};
use crate::table::{LookupTable, LookupTableBuilder, UnitLocation, UnitTable, UnitTableBuilder};
const UNITS: SectionKind = SectionKind::new(0x0300);
const DATA: SectionKind = SectionKind::new(0x0301);
const INDEX: SectionKind = SectionKind::new(0x0302);
const TERM_LOOKUP: SectionKind = SectionKind::new(0x0303);
const TERM_POSTINGS: SectionKind = SectionKind::new(0x0304);
const VERSION: u16 = 4;
pub const SECTIONS_VERSION: u16 = VERSION;
const SLICE_DATA: SectionKind = SectionKind::new(0x0305);
const SLICE_INDEX: SectionKind = SectionKind::new(0x0306);
const SLICE_VERSION: u16 = 1;
const UNIT_KEY_SPACE: KeySpace = KeySpace::new(0);
pub const KNOWN: [KnownSection; 5] = [
KnownSection {
kind: UNITS,
version: VERSION,
},
KnownSection {
kind: DATA,
version: VERSION,
},
KnownSection {
kind: INDEX,
version: VERSION,
},
KnownSection {
kind: TERM_LOOKUP,
version: VERSION,
},
KnownSection {
kind: TERM_POSTINGS,
version: VERSION,
},
];
pub const KNOWN_OPTIONAL: [KnownSection; 2] = [
KnownSection {
kind: SLICE_DATA,
version: SLICE_VERSION,
},
KnownSection {
kind: SLICE_INDEX,
version: SLICE_VERSION,
},
];
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct FragmentKey(Digest128);
crate::heap_bytes_none!(FragmentKey);
impl FragmentKey {
#[must_use]
pub const fn from_digest(digest: Digest128) -> Self {
Self(digest)
}
#[must_use]
pub const fn digest(&self) -> Digest128 {
self.0
}
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum TermKind {
CallTarget,
ReferenceName,
SymbolName,
Language,
BindingKey,
ResolutionKey,
DispatchKey,
SiteKey,
FactSubject,
MethodName,
GoRequired,
}
impl TermKind {
const ALL: [Self; 11] = [
Self::CallTarget,
Self::ReferenceName,
Self::SymbolName,
Self::Language,
Self::BindingKey,
Self::ResolutionKey,
Self::DispatchKey,
Self::SiteKey,
Self::FactSubject,
Self::MethodName,
Self::GoRequired,
];
const fn key_space(self) -> KeySpace {
KeySpace::new(match self {
Self::CallTarget => 1,
Self::ReferenceName => 2,
Self::SymbolName => 3,
Self::Language => 4,
Self::BindingKey => 5,
Self::ResolutionKey => 6,
Self::DispatchKey => 7,
Self::SiteKey => 8,
Self::FactSubject => 9,
Self::MethodName => 10,
Self::GoRequired => 11,
})
}
}
fn term_hash(term: &[u8]) -> u64 {
let digest = Digest128::of(term);
let bytes = digest.as_bytes();
u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
])
}
fn layout() -> PostingLayout {
PostingLayout::new(&[])
}
const MIN_POSTING_BLOCK_LEN: u64 = 12;
fn fits(list: PostingList, section_len: u64) -> bool {
let needed = u64::from(list.count).div_ceil(BLOCK_ENTRIES as u64) * MIN_POSTING_BLOCK_LEN;
list.offset
.checked_add(needed)
.is_some_and(|end| end <= section_len)
}
type PendingFragment = (Vec<u8>, Vec<u8>, Vec<(TermKind, u64)>);
#[derive(Debug, Default)]
pub struct GraphSectionsBuilder {
fragments: BTreeMap<FragmentKey, PendingFragment>,
}
impl crate::heap::HeapBytes for GraphSectionsBuilder {
fn heap_bytes(&self, _seen: &mut crate::heap::Seen) -> usize {
let entry = std::mem::size_of::<FragmentKey>() + std::mem::size_of::<PendingFragment>();
crate::heap::btree_bytes(self.fragments.len(), entry)
+ self
.fragments
.values()
.map(|(bytes, slice, terms)| {
bytes.capacity()
+ slice.capacity()
+ terms.capacity() * std::mem::size_of::<(TermKind, u64)>()
})
.sum::<usize>()
}
}
impl GraphSectionsBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn add<'t>(
&mut self,
key: FragmentKey,
bytes: Vec<u8>,
terms: impl IntoIterator<Item = (TermKind, &'t [u8])>,
) {
self.add_with_slice(key, bytes, Vec::new(), terms);
}
pub fn add_with_slice<'t>(
&mut self,
key: FragmentKey,
bytes: Vec<u8>,
slice: Vec<u8>,
terms: impl IntoIterator<Item = (TermKind, &'t [u8])>,
) {
self.fragments.entry(key).or_insert_with(|| {
let mut hashed = terms
.into_iter()
.map(|(kind, term)| (kind, term_hash(term)))
.collect::<Vec<_>>();
hashed.sort_unstable();
hashed.dedup();
(bytes, slice, hashed)
});
}
#[must_use]
pub fn len(&self) -> usize {
self.fragments.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.fragments.is_empty()
}
pub fn retain(&mut self, mut keep: impl FnMut(FragmentKey) -> bool) {
self.fragments.retain(|key, _| keep(*key));
}
pub fn write(self, writer: &mut SegmentWriter) -> Result<(), SegmentError> {
let mut table = UnitTableBuilder::new(Digest128::LEN);
let mut data = PackedBuilder::with_capacity(self.fragments.len());
let mut slices = PackedBuilder::with_capacity(self.fragments.len());
let mut lists = BTreeMap::<(TermKind, u64), Vec<u32>>::new();
for (key, (bytes, slice, terms)) in self.fragments {
let ordinal = table.push(key.0.as_bytes(), UnitLocation { offset: 0, len: 0 });
data.push(&bytes);
slices.push(&slice);
for term in terms {
lists.entry(term).or_default().push(ordinal);
}
}
let (table, units) = table.finish();
writer.write_section(spec(UNITS, UNIT_KEY_SPACE), &table, units)?;
let (data, index) = data.finish();
writer.write_section(spec(DATA, UNIT_KEY_SPACE), &data, units)?;
writer.write_section(spec(INDEX, UNIT_KEY_SPACE), &index, units)?;
let (slices, slice_index) = slices.finish();
writer.write_section(slice_spec(SLICE_DATA), &slices, units)?;
writer.write_section(slice_spec(SLICE_INDEX), &slice_index, units)?;
for kind in TermKind::ALL {
let mut postings = PostingsBuilder::new(layout());
let mut lookup = LookupTableBuilder::new();
for ((_, hash), ordinals) in lists.range((kind, 0)..=(kind, u64::MAX)) {
lookup.push(*hash, postings.add_list(ordinals, &[]));
}
let (lookup, terms) = lookup.finish();
writer.write_section(spec(TERM_LOOKUP, kind.key_space()), &lookup, terms)?;
let (postings, entries) = postings.finish();
writer.write_section(spec(TERM_POSTINGS, kind.key_space()), &postings, entries)?;
}
Ok(())
}
}
fn spec(kind: SectionKind, key_space: KeySpace) -> SectionSpec {
SectionSpec {
id: SectionId::new(kind, key_space),
version: VERSION,
alignment: Alignment::Word,
requirement: Requirement::Required,
}
}
fn slice_spec(kind: SectionKind) -> SectionSpec {
SectionSpec {
id: SectionId::new(kind, UNIT_KEY_SPACE),
version: SLICE_VERSION,
alignment: Alignment::Word,
requirement: Requirement::Optional,
}
}
pub fn write_folded(
writer: &mut SegmentWriter,
sources: &[GraphSegment<'_>],
units: &[(FragmentKey, usize, u32)],
) -> Result<(), SegmentError> {
let mut renumbered = sources
.iter()
.map(|source| vec![crate::fold::NOT_COPIED; source.len() as usize])
.collect::<Vec<_>>();
let mut table = UnitTableBuilder::new(Digest128::LEN);
for (key, source, ordinal) in units {
let new = table.push(key.0.as_bytes(), UnitLocation { offset: 0, len: 0 });
renumbered[*source][*ordinal as usize] = new;
}
let (table, count) = table.finish();
writer.begin_section(spec(DATA, UNIT_KEY_SPACE))?;
let mut data = packed::PackedCopy::with_capacity(units.len());
for (_, source, ordinal) in units {
let source = &sources[*source];
data.push(
writer,
&packed::read_stored(source.segment, source.data, source.index, *ordinal)?,
)?;
}
writer.end_section(count)?;
writer.write_section(spec(INDEX, UNIT_KEY_SPACE), &data.finish(), count)?;
writer.begin_section(slice_spec(SLICE_DATA))?;
let mut slices = packed::PackedCopy::with_capacity(units.len());
for (_, source, ordinal) in units {
let source = &sources[*source];
let slice = match source.slices {
Some((data, index)) => packed::read_stored(source.segment, data, index, *ordinal)?,
None => packed::StoredUnit::EMPTY,
};
slices.push(writer, &slice)?;
}
writer.end_section(count)?;
writer.write_section(slice_spec(SLICE_INDEX), &slices.finish(), count)?;
writer.write_section(spec(UNITS, UNIT_KEY_SPACE), &table, count)?;
for kind in TermKind::ALL {
let postings = sources
.iter()
.zip(&renumbered)
.map(|(source, renumbered)| {
let (_, lookup, postings) = source
.terms
.iter()
.find(|(each, ..)| *each == kind)
.expect("every term kind has its sections");
crate::fold::PostingSource {
segment: source.segment,
lookup: LookupTable::reopen(source.segment, lookup.section()),
postings: *postings,
renumbered,
}
})
.collect::<Vec<_>>();
crate::fold::write_postings(
writer,
spec(TERM_POSTINGS, kind.key_space()),
spec(TERM_LOOKUP, kind.key_space()),
&layout(),
&postings,
)?;
}
Ok(())
}
#[derive(Debug)]
pub struct GraphSegment<'s> {
segment: &'s Segment,
units: UnitTable<'s>,
data: SectionHandle,
index: SectionHandle,
slices: Option<(SectionHandle, SectionHandle)>,
terms: Vec<(TermKind, LookupTable<'s>, SectionHandle)>,
}
impl<'s> GraphSegment<'s> {
pub fn open(segment: &'s Segment) -> Result<Option<Self>, SegmentError> {
let section = |kind, key_space| segment.section(SectionId::new(kind, key_space));
let mut handles = vec![
section(UNITS, UNIT_KEY_SPACE),
section(DATA, UNIT_KEY_SPACE),
section(INDEX, UNIT_KEY_SPACE),
];
for kind in TermKind::ALL {
handles.push(section(TERM_LOOKUP, kind.key_space()));
handles.push(section(TERM_POSTINGS, kind.key_space()));
}
if handles.iter().all(Option::is_none) {
return Ok(None);
}
let Some(handles) = handles.into_iter().collect::<Option<Vec<_>>>() else {
return Err(malformed(segment, "a segment has only some graph sections"));
};
let units = UnitTable::open(segment, handles[0])?;
if segment.info(handles[2]).len != u64::from(units.len()) * packed::INDEX_ENTRY_LEN as u64 {
return Err(malformed(
segment,
"the fragment index does not match the unit table",
));
}
let mut terms = Vec::with_capacity(TermKind::ALL.len());
let (pairs, _) = handles[3..].as_chunks::<2>();
for (kind, [lookup, postings]) in TermKind::ALL.into_iter().zip(pairs) {
terms.push((kind, LookupTable::open(segment, *lookup)?, *postings));
}
let slices = match (
section(SLICE_DATA, UNIT_KEY_SPACE),
section(SLICE_INDEX, UNIT_KEY_SPACE),
) {
(None, None) => None,
(Some(data), Some(index)) => {
if segment.info(index).len
!= u64::from(units.len()) * packed::INDEX_ENTRY_LEN as u64
{
return Err(malformed(
segment,
"the slice index does not match the unit table",
));
}
Some((data, index))
}
_ => {
return Err(malformed(
segment,
"a segment has only one of the slice sections",
));
}
};
Ok(Some(Self {
segment,
units,
data: handles[1],
index: handles[2],
slices,
terms,
}))
}
#[must_use]
pub fn len(&self) -> u32 {
self.units.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.units.is_empty()
}
pub fn find(&self, key: FragmentKey) -> Result<Option<u32>, SegmentError> {
Ok(self
.units
.get(key.0.as_bytes())?
.map(|(ordinal, _)| ordinal))
}
pub fn key(&self, ordinal: u32) -> Result<FragmentKey, SegmentError> {
let (key, _) = self.units.entry(ordinal)?;
let bytes = <[u8; Digest128::LEN]>::try_from(key.as_slice())
.map_err(|_| malformed(self.segment, "a fragment key has the wrong width"))?;
Ok(FragmentKey(Digest128::from_bytes(bytes)))
}
pub fn fragment(&self, ordinal: u32) -> Result<Vec<u8>, SegmentError> {
packed::read(self.segment, self.data, self.index, ordinal)
}
pub fn slice(&self, ordinal: u32) -> Result<Option<Vec<u8>>, SegmentError> {
let Some((data, index)) = self.slices else {
return Ok(None);
};
let bytes = packed::read(self.segment, data, index, ordinal)?;
Ok((!bytes.is_empty()).then_some(bytes))
}
pub fn candidates(&self, kind: TermKind, term: &[u8]) -> Result<Vec<u32>, SegmentError> {
let (_, lookup, postings) = self
.terms
.iter()
.find(|(each, ..)| *each == kind)
.expect("every term kind has its sections");
let Some(list) = lookup.get(term_hash(term))? else {
return Ok(Vec::new());
};
if !fits(list, self.segment.info(*postings).len) {
return Err(malformed(
self.segment,
"a term's posting count needs more bytes than its section holds",
));
}
let mut cursor = PostingCursor::new(self.segment, *postings, layout(), list);
let mut ordinals = Vec::with_capacity(list.count as usize);
while let Some(block) = cursor.next_block()? {
ordinals.extend_from_slice(&block.ordinals);
}
Ok(ordinals)
}
}
fn malformed(segment: &Segment, reason: &'static str) -> SegmentError {
SegmentError::new(segment.path(), ErrorKind::Malformed(reason))
}
crate::heap_bytes_none!(TermKind);
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::Arc;
use super::*;
use crate::cache::BlockCache;
use crate::ids::{FamilyId, SegmentId, WriterIncarnation};
use crate::segment::{BLOCK_LEN, SegmentMeta};
fn key(n: u8) -> FragmentKey {
FragmentKey(Digest128::of(&[n]))
}
fn family() -> FamilyId {
FamilyId::from_digest(Digest128::of(b"repo"))
}
fn create(path: &Path) -> SegmentWriter {
SegmentWriter::create(
path,
SegmentMeta {
family: family(),
segment: SegmentId::new(1),
incarnation: WriterIncarnation::new(1),
created_unix_ms: 0,
},
)
.unwrap()
}
fn open(path: &Path) -> Segment {
let known = KNOWN
.iter()
.chain(&KNOWN_OPTIONAL)
.copied()
.collect::<Vec<_>>();
Segment::open(
path,
family(),
&known,
Arc::new(BlockCache::new(16 * BLOCK_LEN)),
)
.unwrap()
}
fn write(path: &Path, builder: Option<GraphSectionsBuilder>) -> Segment {
let mut writer = create(path);
if let Some(builder) = builder {
builder.write(&mut writer).unwrap();
}
writer.finish().unwrap();
open(path)
}
#[test]
fn streamed_sections_equal_buffered_with_ordering_and_leave_out() {
use crate::family::Family;
use crate::spill::{Config, WriteGuard};
let dir = tempfile::tempdir().unwrap();
let store = Family::open(&dir.path().join("store"), family()).unwrap();
let workspace = scratch::for_test(&store.dir().join("builds"));
let scratch = workspace.path().to_path_buf();
let mut config = Config::new(128 * 1024);
config.buffer_bytes = 1024;
config.fan_in = 2;
let mut streamed =
GraphSectionsSpill::new(workspace, config, WriteGuard::new(|| Ok(()))).unwrap();
let mut buffered = GraphSectionsBuilder::new();
for n in (0..100u8).rev() {
let bytes = vec![n; 16000 + usize::from(n)];
let slice = if n % 2 == 0 { vec![n; 1000] } else { vec![] };
let terms = TermKind::ALL
.into_iter()
.flat_map(|kind| {
[
(kind, b"shared".as_slice()),
(kind, bytes.as_slice()),
(kind, bytes.as_slice()),
]
})
.collect::<Vec<_>>();
streamed
.add(
key(n),
PackedFragment::new(&bytes, &slice, terms.iter().copied()),
)
.unwrap();
buffered.add_with_slice(key(n), bytes.clone(), slice.clone(), terms.iter().copied());
streamed
.add(
key(n),
PackedFragment::new(
b"wrong",
b"wrong",
[(TermKind::CallTarget, b"wrong".as_slice())],
),
)
.unwrap();
}
streamed.retain(|fragment| fragment != key(19));
buffered.retain(|fragment| fragment != key(19));
let expected = write(&dir.path().join("buffered"), Some(buffered));
let path = dir.path().join("streamed");
let mut writer = create(&path);
streamed.write(&mut writer).unwrap();
writer.finish().unwrap();
assert!(
scratch.exists(),
"the spill leaves its folder to the build workspace, which is deleted after publication"
);
assert_eq!(
std::fs::read(dir.path().join("buffered")).unwrap(),
std::fs::read(&path).unwrap(),
"identical metadata produces byte-identical segments"
);
let actual = open(&path);
actual.verify().unwrap();
assert_eq!(expected.sections().count(), actual.sections().count());
for (section, info) in expected.sections() {
let other = actual.section(info.id).unwrap();
assert_eq!(info.item_count, actual.info(other).item_count);
assert_eq!(
expected.read_range(section, 0..info.len).unwrap(),
actual.read_range(other, 0..info.len).unwrap(),
"section {:?}",
info.id
);
}
let graph = GraphSegment::open(&actual).unwrap().unwrap();
assert!(graph.find(key(19)).unwrap().is_none());
assert!(
graph
.candidates(TermKind::CallTarget, b"wrong")
.unwrap()
.is_empty()
);
}
#[test]
fn streamed_output_refuses_disk_floor_and_keeps_its_folder_on_error() {
use crate::family::Family;
use crate::spill::{Config, WriteGuard};
use std::sync::atomic::{AtomicBool, Ordering};
let dir = tempfile::tempdir().unwrap();
let store = Family::open(&dir.path().join("store"), family()).unwrap();
let workspace = scratch::for_test(&store.dir().join("builds"));
let scratch = workspace.path().to_path_buf();
let low = Arc::new(AtomicBool::new(false));
let check = low.clone();
let guard = WriteGuard::new(move || {
if check.load(Ordering::Relaxed) {
Err(std::io::Error::other("disk floor"))
} else {
Ok(())
}
});
let mut spill = GraphSectionsSpill::new(workspace, Config::new(1 << 20), guard).unwrap();
low.store(true, Ordering::Relaxed);
assert!(
spill
.add(key(1), PackedFragment::new(b"data", b"slice", []))
.unwrap_err()
.to_string()
.contains("disk floor")
);
assert!(
!scratch.join("fragments-00000000000000000000.bin").exists(),
"a refused append must not create a fragment range"
);
drop(spill);
assert!(
scratch.exists(),
"a disk-floor pause leaves the build's work for the workspace's owner to delete"
);
}
fn write_forged(path: &Path, list: PostingList) -> Segment {
let mut writer = create(path);
let mut table = UnitTableBuilder::new(Digest128::LEN);
table.push(key(1).0.as_bytes(), UnitLocation { offset: 0, len: 0 });
let (table, units) = table.finish();
writer
.write_section(spec(UNITS, UNIT_KEY_SPACE), &table, units)
.unwrap();
let mut data = PackedBuilder::with_capacity(1);
data.push(b"one");
let (data, index) = data.finish();
writer
.write_section(spec(DATA, UNIT_KEY_SPACE), &data, units)
.unwrap();
writer
.write_section(spec(INDEX, UNIT_KEY_SPACE), &index, units)
.unwrap();
for kind in TermKind::ALL {
let mut postings = PostingsBuilder::new(layout());
let mut lookup = LookupTableBuilder::new();
if kind == TermKind::CallTarget {
postings.add_list(&[0], &[]);
lookup.push(term_hash(b"t"), list);
}
let (lookup, terms) = lookup.finish();
writer
.write_section(spec(TERM_LOOKUP, kind.key_space()), &lookup, terms)
.unwrap();
let (postings, entries) = postings.finish();
writer
.write_section(spec(TERM_POSTINGS, kind.key_space()), &postings, entries)
.unwrap();
}
writer.finish().unwrap();
open(path)
}
#[test]
fn fragments_and_terms_round_trip() {
let dir = tempfile::tempdir().unwrap();
let mut builder = GraphSectionsBuilder::new();
let repeated = b"abcabcabc".repeat(100);
builder.add(
key(1),
repeated.clone(),
[
(TermKind::CallTarget, b"lib.rs\0run".as_slice()),
(TermKind::Language, b"rust".as_slice()),
],
);
builder.add_with_slice(
key(2),
b"two".to_vec(),
b"slice of two".to_vec(),
[
(TermKind::CallTarget, b"lib.rs\0run".as_slice()),
(TermKind::ReferenceName, b"run".as_slice()),
(TermKind::Language, b"rust".as_slice()),
],
);
builder.add(key(3), Vec::new(), []);
let path = dir.path().join("graph.seg");
let segment = write(&path, Some(builder));
let graph = GraphSegment::open(&segment).unwrap().unwrap();
assert_eq!(graph.len(), 3);
let one = graph.find(key(1)).unwrap().unwrap();
let two = graph.find(key(2)).unwrap().unwrap();
let three = graph.find(key(3)).unwrap().unwrap();
assert_eq!(graph.key(one).unwrap(), key(1));
assert_eq!(graph.fragment(one).unwrap(), repeated);
assert_eq!(graph.fragment(two).unwrap(), b"two");
assert!(graph.fragment(three).unwrap().is_empty());
assert_eq!(
graph.slice(two).unwrap().as_deref(),
Some(&b"slice of two"[..])
);
assert_eq!(graph.slice(one).unwrap(), None);
assert_eq!(graph.slice(three).unwrap(), None);
let older = Segment::open(
&path,
family(),
&KNOWN,
Arc::new(BlockCache::new(16 * BLOCK_LEN)),
)
.unwrap();
let older = GraphSegment::open(&older).unwrap().unwrap();
assert_eq!(older.fragment(two).unwrap(), b"two");
assert_eq!(older.slice(two).unwrap(), None);
let mut both = vec![one, two];
both.sort_unstable();
assert_eq!(
graph
.candidates(TermKind::CallTarget, b"lib.rs\0run")
.unwrap(),
both
);
assert_eq!(graph.candidates(TermKind::Language, b"rust").unwrap(), both);
assert_eq!(
graph.candidates(TermKind::ReferenceName, b"run").unwrap(),
vec![two]
);
assert!(
graph
.candidates(TermKind::SymbolName, b"run")
.unwrap()
.is_empty()
);
assert!(
graph
.candidates(TermKind::CallTarget, b"lib.rs\0other")
.unwrap()
.is_empty()
);
}
#[test]
fn a_segment_without_graph_sections_has_no_graph() {
let dir = tempfile::tempdir().unwrap();
let segment = write(&dir.path().join("empty.seg"), None);
assert!(GraphSegment::open(&segment).unwrap().is_none());
}
#[test]
fn a_posting_count_its_section_cannot_hold_is_refused_before_reading() {
let dir = tempfile::tempdir().unwrap();
let segment = write_forged(
&dir.path().join("honest.seg"),
PostingList {
offset: 0,
count: 1,
},
);
let graph = GraphSegment::open(&segment).unwrap().unwrap();
assert_eq!(graph.candidates(TermKind::CallTarget, b"t").unwrap(), [0]);
assert_eq!(graph.slice(0).unwrap(), None);
for (name, list) in [
(
"huge",
PostingList {
offset: 0,
count: u32::MAX,
},
),
(
"two blocks",
PostingList {
offset: 0,
count: u32::try_from(BLOCK_ENTRIES).unwrap() + 1,
},
),
(
"overflow",
PostingList {
offset: u64::MAX - 4,
count: 1,
},
),
] {
let segment = write_forged(&dir.path().join(format!("{name}.seg")), list);
let graph = GraphSegment::open(&segment).unwrap().unwrap();
let error = graph.candidates(TermKind::CallTarget, b"t").unwrap_err();
assert!(
matches!(
error.kind(),
ErrorKind::Malformed(
"a term's posting count needs more bytes than its section holds"
)
),
"{name}: {error}"
);
assert!(error.is_corruption(), "{name}");
}
}
#[test]
fn the_smallest_block_is_the_bound_the_count_check_assumes() {
let mut postings = PostingsBuilder::new(layout());
let list = postings.add_list(&[7; BLOCK_ENTRIES], &[]);
let (bytes, _) = postings.finish();
assert_eq!(bytes.len() as u64, MIN_POSTING_BLOCK_LEN);
assert!(fits(list, MIN_POSTING_BLOCK_LEN));
assert!(!fits(list, MIN_POSTING_BLOCK_LEN - 1));
}
}