use crate::error::{Error, Result};
use crate::format::common::encoding::TextEncoding;
use crate::limits::MemoryReservation;
use crate::types::Header;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SectionRange {
offset: u64,
len: u64,
}
impl SectionRange {
pub(crate) const fn new(offset: u64, len: u64) -> Self {
Self { offset, len }
}
pub(crate) const fn offset(self) -> u64 {
self.offset
}
pub(crate) fn end(self) -> Result<u64> {
self.offset
.checked_add(self.len)
.ok_or(Error::InvalidFormat("section range end overflow"))
}
}
#[derive(Debug, Clone, Copy)]
pub struct SectionRanges {
pub(crate) header: SectionRange,
pub(crate) keyword_header: SectionRange,
pub(crate) keyword_index: SectionRange,
pub(crate) keyword_blocks: SectionRange,
pub(crate) record_header: SectionRange,
pub(crate) record_index: SectionRange,
pub(crate) record_blocks: SectionRange,
}
impl SectionRanges {
pub(crate) fn verify_contiguous(&self) -> Result<()> {
let ordered = [
("header", self.header),
("keyword header", self.keyword_header),
("keyword index", self.keyword_index),
("keyword blocks", self.keyword_blocks),
("record header", self.record_header),
("record index", self.record_index),
("record blocks", self.record_blocks),
];
let mut expected = ordered[0].0;
let mut cursor = self.header.offset();
for (name, section) in ordered {
if section.offset() != cursor {
return Err(Error::InvalidData(format!(
"{name} section starts at {} but {expected} ended at {cursor}",
section.offset()
)));
}
cursor = section.end()?;
expected = name;
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct KeyBlockDescriptor {
pub entry_count: u64,
pub entry_start_index: u64,
pub first_key: String,
pub last_key: String,
pub comp_offset: u64,
pub comp_size: u64,
pub decomp_size: u64,
}
#[derive(Debug, Clone)]
pub struct RecordBlockDescriptor {
pub comp_offset: u64,
pub comp_size: u64,
pub decomp_offset: u64,
pub decomp_size: u64,
}
pub(crate) fn find_record_block(
blocks: &[RecordBlockDescriptor],
record_offset: u64,
) -> Option<usize> {
let mut left = 0usize;
let mut right = blocks.len();
while left < right {
let mid = (left + right) / 2;
let block = &blocks[mid];
let end = block.decomp_offset.checked_add(block.decomp_size)?;
if record_offset < block.decomp_offset {
right = mid;
} else if record_offset >= end {
left = mid + 1;
} else {
return Some(mid);
}
}
None
}
#[derive(Debug, Clone)]
pub struct DecodedKeyRow {
pub key: String,
pub record_start: u64,
}
pub struct KeyRowContext {
pub encoding: TextEncoding,
pub expected_entries: u64,
pub total_decoded_record_len: u64,
}
pub type DecodeKeyRows = fn(&[u8], &KeyRowContext) -> Result<Vec<DecodedKeyRow>>;
#[derive(Debug, Clone, Copy)]
pub struct WireOperations {
pub decode_key_rows: DecodeKeyRows,
}
#[derive(Debug)]
pub struct RetainedBudget {
header: MemoryReservation,
key_metadata: MemoryReservation,
record_metadata: MemoryReservation,
}
impl RetainedBudget {
pub(crate) const fn new(
header: MemoryReservation,
key_metadata: MemoryReservation,
record_metadata: MemoryReservation,
) -> Self {
Self {
header,
key_metadata,
record_metadata,
}
}
pub(crate) fn metadata_bytes(&self) -> Result<usize> {
self.header
.bytes()
.checked_add(self.key_metadata.bytes())
.and_then(|bytes| bytes.checked_add(self.record_metadata.bytes()))
.ok_or(Error::InvalidFormat("metadata memory accounting overflow"))
}
}
#[derive(Debug)]
pub struct ValidatedLayout {
pub header: Header,
pub key_encoding: TextEncoding,
pub record_encoding: Option<TextEncoding>,
pub sections: SectionRanges,
pub total_entries: u64,
pub total_decoded_record_len: u64,
pub key_blocks: Box<[KeyBlockDescriptor]>,
pub record_blocks: Box<[RecordBlockDescriptor]>,
pub wire: WireOperations,
pub retained: RetainedBudget,
}
impl ValidatedLayout {
pub(crate) fn verify(&self) -> Result<()> {
self.sections.verify_contiguous()?;
let mut expected_start = 0u64;
for block in &self.key_blocks {
if block.entry_start_index != expected_start {
return Err(Error::InvalidData(format!(
"key block starts at ordinal {} but {expected_start} was expected",
block.entry_start_index
)));
}
expected_start = block
.entry_start_index
.checked_add(block.entry_count)
.ok_or(Error::InvalidFormat("keyword entry count overflow"))?;
}
if expected_start != self.total_entries {
return Err(Error::InvalidData(format!(
"key blocks cover {expected_start} entries but {} were declared",
self.total_entries
)));
}
let mut expected_offset = 0u64;
for block in &self.record_blocks {
if block.decomp_offset != expected_offset {
return Err(Error::InvalidData(format!(
"record block starts at {} but {expected_offset} was expected",
block.decomp_offset
)));
}
expected_offset = block
.decomp_offset
.checked_add(block.decomp_size)
.ok_or(Error::InvalidFormat("record block offset overflow"))?;
}
if expected_offset != self.total_decoded_record_len {
return Err(Error::InvalidData(format!(
"record blocks cover {expected_offset} bytes but {} were declared",
self.total_decoded_record_len
)));
}
Ok(())
}
}