mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:22:39 +00:00
sqlite: extract shared page-size, B-tree header, local-payload, and signed-int helpers (#2694)
* sqlite: extract shared page-size, B-tree header, and signed-int helpers (#778) * sqlite: remove duplicate test block in wire.rs * sqlite: cover Error Display and truncated/invalid page-header branches
This commit is contained in:
@@ -57,6 +57,20 @@ pub enum Error {
|
||||
TruncatedVarint,
|
||||
/// The serial type is reserved and has no defined field width.
|
||||
ReservedSerialType(u64),
|
||||
/// The decoded database page size is not a power of two in `512..=65_536`.
|
||||
InvalidPageSize(u32),
|
||||
/// The usable page size (`page_size - reserved`) is below 480 bytes.
|
||||
UsablePageSizeTooSmall(u32),
|
||||
/// A B-tree page ended before its header or cell-pointer array completed.
|
||||
TruncatedPage,
|
||||
/// The B-tree page type byte is not a table or index interior/leaf page.
|
||||
UnsupportedBtreePageType(u8),
|
||||
/// A cell pointer falls outside `[pointers_end, usable)`.
|
||||
InvalidCellPointer { offset: usize, min: usize, usable: usize },
|
||||
/// The requested cell index is outside the page's cell count.
|
||||
CellIndexOutOfBounds { index: usize, cells: usize },
|
||||
/// A signed big-endian integer slice is empty or wider than 8 bytes.
|
||||
InvalidIntegerWidth(usize),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@@ -64,6 +78,13 @@ impl fmt::Display for Error {
|
||||
match self {
|
||||
Self::TruncatedVarint => f.write_str("truncated SQLite varint"),
|
||||
Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"),
|
||||
Self::InvalidPageSize(size) => write!(f, "invalid SQLite page size {size}"),
|
||||
Self::UsablePageSizeTooSmall(usable) => write!(f, "usable SQLite page size {usable} is too small"),
|
||||
Self::TruncatedPage => f.write_str("truncated SQLite B-tree page"),
|
||||
Self::UnsupportedBtreePageType(kind) => write!(f, "unsupported SQLite B-tree page type 0x{kind:02x}"),
|
||||
Self::InvalidCellPointer { offset, min, usable } => write!(f, "invalid SQLite cell pointer {offset} outside {min}..{usable}"),
|
||||
Self::CellIndexOutOfBounds { index, cells } => write!(f, "SQLite cell index {index} out of bounds for {cells} cells"),
|
||||
Self::InvalidIntegerWidth(width) => write!(f, "invalid SQLite signed integer width {width}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,3 +146,137 @@ pub const fn serial_type_len(serial_type: u64) -> Result<u64, Error> {
|
||||
_ => Ok((serial_type - 12) / 2),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a raw big-endian 16-bit SQLite header page size (`1` represents `65_536`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::InvalidPageSize`] when the decoded size is not a power of two in `512..=65_536`.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_sqlite::page_size_from_raw;
|
||||
///
|
||||
/// assert_eq!(page_size_from_raw(1), Ok(65_536));
|
||||
/// assert_eq!(page_size_from_raw(4096), Ok(4096));
|
||||
/// ```
|
||||
pub const fn page_size_from_raw(raw: u16) -> Result<u32, Error> {
|
||||
let size = if raw == 1 { 65_536 } else { raw as u32 };
|
||||
if size < 512 || !size.is_power_of_two() { Err(Error::InvalidPageSize(size)) } else { Ok(size) }
|
||||
}
|
||||
|
||||
/// Compute the usable byte count of a SQLite page after subtracting `reserved` trailing bytes.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::UsablePageSizeTooSmall`] when `page_size - reserved < 480`.
|
||||
pub const fn usable_page_size(page_size: u32, reserved: u8) -> Result<u32, Error> {
|
||||
let Some(usable) = page_size.checked_sub(reserved as u32) else {
|
||||
return Err(Error::UsablePageSizeTooSmall(0));
|
||||
};
|
||||
if usable < 480 { Err(Error::UsablePageSizeTooSmall(usable)) } else { Ok(usable) }
|
||||
}
|
||||
|
||||
/// Decode a 1..=8-byte big-endian signed two's-complement integer into `i64`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::InvalidIntegerWidth`] if `bytes` is empty or longer than 8 bytes.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_sqlite::decode_signed_be_int;
|
||||
///
|
||||
/// assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607));
|
||||
/// ```
|
||||
pub fn decode_signed_be_int(bytes: &[u8]) -> Result<i64, Error> {
|
||||
let Some(&first) = bytes.first() else {
|
||||
return Err(Error::InvalidIntegerWidth(0));
|
||||
};
|
||||
if bytes.len() > 8 {
|
||||
return Err(Error::InvalidIntegerWidth(bytes.len()));
|
||||
}
|
||||
let mut value: i64 = if first & 0x80 != 0 { -1 } else { 0 };
|
||||
for &byte in bytes {
|
||||
value = (value << 8) | i64::from(byte);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// Parsed B-tree page header and cell-pointer array bounds within a usable page slice.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct BtreePageHeader {
|
||||
/// B-tree page type (`0x02`, `0x05`, `0x0a`, or `0x0d`).
|
||||
pub kind: u8,
|
||||
/// Offset where the B-tree page header starts (`100` on page 1, `0` otherwise).
|
||||
pub header_offset: usize,
|
||||
/// Number of cells declared in the B-tree header.
|
||||
pub cells: usize,
|
||||
/// Start offset of the 2-byte big-endian cell-pointer array.
|
||||
pub pointers_offset: usize,
|
||||
/// Exclusive end offset of the cell-pointer array.
|
||||
pub pointers_end: usize,
|
||||
}
|
||||
|
||||
/// Parse and bounds-check the B-tree page header and cell-pointer array on `usable_page`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::TruncatedPage`] if the page ends before the header or pointer array, or
|
||||
/// [`Error::UnsupportedBtreePageType`] if the page type byte is not `0x02`, `0x05`, `0x0a`, or `0x0d`.
|
||||
pub fn parse_btree_page_header(usable_page: &[u8], is_page_one: bool) -> Result<BtreePageHeader, Error> {
|
||||
let header_offset = if is_page_one { 100 } else { 0 };
|
||||
let Some(&kind) = usable_page.get(header_offset) else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
let header_size = match kind {
|
||||
0x05 | 0x02 => 12,
|
||||
0x0d | 0x0a => 8,
|
||||
_ => return Err(Error::UnsupportedBtreePageType(kind)),
|
||||
};
|
||||
let Some(cells_bytes) = header_offset
|
||||
.checked_add(3)
|
||||
.and_then(|start| start.checked_add(2).and_then(|end| usable_page.get(start..end)))
|
||||
.and_then(|slice| <[u8; 2]>::try_from(slice).ok())
|
||||
else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
let cells = usize::from(u16::from_be_bytes(cells_bytes));
|
||||
let Some(pointers_offset) = header_offset.checked_add(header_size) else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
let Some(pointers_bytes) = cells.checked_mul(2) else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
let Some(pointers_end) = pointers_offset.checked_add(pointers_bytes) else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
if pointers_end > usable_page.len() {
|
||||
return Err(Error::TruncatedPage);
|
||||
}
|
||||
Ok(BtreePageHeader { kind, header_offset, cells, pointers_offset, pointers_end })
|
||||
}
|
||||
|
||||
/// Read and bounds-check the `index`-th cell offset from a parsed [`BtreePageHeader`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::CellIndexOutOfBounds`] when `index >= header.cells`, [`Error::TruncatedPage`]
|
||||
/// if the pointer slot is out of bounds, or [`Error::InvalidCellPointer`] if the pointer lies
|
||||
/// outside `[header.pointers_end, usable_page.len())`.
|
||||
pub fn btree_cell_offset(usable_page: &[u8], header: &BtreePageHeader, index: usize) -> Result<usize, Error> {
|
||||
if index >= header.cells {
|
||||
return Err(Error::CellIndexOutOfBounds { index, cells: header.cells });
|
||||
}
|
||||
let Some(bytes) = index
|
||||
.checked_mul(2)
|
||||
.and_then(|off| header.pointers_offset.checked_add(off))
|
||||
.and_then(|ptr| ptr.checked_add(2).and_then(|end| usable_page.get(ptr..end)))
|
||||
.and_then(|slice| <[u8; 2]>::try_from(slice).ok())
|
||||
else {
|
||||
return Err(Error::TruncatedPage);
|
||||
};
|
||||
let offset = usize::from(u16::from_be_bytes(bytes));
|
||||
if offset < header.pointers_end || offset >= usable_page.len() {
|
||||
return Err(Error::InvalidCellPointer { offset, min: header.pointers_end, usable: usable_page.len() });
|
||||
}
|
||||
Ok(offset)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
use craft_sqlite::{Error, PayloadKind, local_payload_len, read_varint, serial_type_len};
|
||||
use craft_sqlite::{
|
||||
BtreePageHeader, Error, PayloadKind, btree_cell_offset, decode_signed_be_int, local_payload_len, page_size_from_raw, parse_btree_page_header,
|
||||
read_varint, serial_type_len, usable_page_size,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn local_payload_preserves_inline_and_overflow_boundaries() {
|
||||
@@ -119,3 +122,77 @@ fn variable_serial_type_widths_are_portable() {
|
||||
assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_size_and_usable_validation() {
|
||||
assert_eq!(page_size_from_raw(512), Ok(512));
|
||||
assert_eq!(page_size_from_raw(4096), Ok(4096));
|
||||
assert_eq!(page_size_from_raw(1), Ok(65_536));
|
||||
assert_eq!(page_size_from_raw(0), Err(Error::InvalidPageSize(0)));
|
||||
assert_eq!(page_size_from_raw(256), Err(Error::InvalidPageSize(256)));
|
||||
assert_eq!(page_size_from_raw(1000), Err(Error::InvalidPageSize(1000)));
|
||||
|
||||
assert_eq!(usable_page_size(512, 32), Ok(480));
|
||||
assert_eq!(usable_page_size(512, 33), Err(Error::UsablePageSizeTooSmall(479)));
|
||||
assert_eq!(usable_page_size(100, 150), Err(Error::UsablePageSizeTooSmall(0)));
|
||||
assert_eq!(usable_page_size(512, 0), Ok(512));
|
||||
|
||||
for err in [
|
||||
Error::InvalidPageSize(0),
|
||||
Error::UsablePageSizeTooSmall(479),
|
||||
Error::TruncatedPage,
|
||||
Error::UnsupportedBtreePageType(0x01),
|
||||
Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 },
|
||||
Error::CellIndexOutOfBounds { index: 1, cells: 1 },
|
||||
Error::InvalidIntegerWidth(0),
|
||||
] {
|
||||
assert!(!err.to_string().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_be_integers_decode_with_sign_extension() {
|
||||
assert_eq!(decode_signed_be_int(&[0x7f]), Ok(127));
|
||||
assert_eq!(decode_signed_be_int(&[0x80]), Ok(-128));
|
||||
assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x01]), Ok(-8_388_607));
|
||||
assert_eq!(decode_signed_be_int(&[0xff, 0xff, 0xff, 0xff, 0xff, 0xfe]), Ok(-2));
|
||||
assert_eq!(decode_signed_be_int(&[0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Ok(i64::MAX));
|
||||
assert_eq!(decode_signed_be_int(&[0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), Ok(i64::MIN));
|
||||
assert_eq!(decode_signed_be_int(&[]), Err(Error::InvalidIntegerWidth(0)));
|
||||
assert_eq!(decode_signed_be_int(&[0; 9]), Err(Error::InvalidIntegerWidth(9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn btree_page_header_and_cell_pointer_bounds() {
|
||||
let mut page = [0u8; 512];
|
||||
page[100] = 0x0d;
|
||||
page[103..105].copy_from_slice(&1u16.to_be_bytes());
|
||||
page[108..110].copy_from_slice(&400u16.to_be_bytes());
|
||||
|
||||
let hdr = parse_btree_page_header(&page, true).unwrap();
|
||||
assert_eq!(hdr, BtreePageHeader { kind: 0x0d, header_offset: 100, cells: 1, pointers_offset: 108, pointers_end: 110 });
|
||||
assert_eq!(btree_cell_offset(&page, &hdr, 0), Ok(400));
|
||||
assert_eq!(btree_cell_offset(&page, &hdr, 1), Err(Error::CellIndexOutOfBounds { index: 1, cells: 1 }));
|
||||
|
||||
// Pointer inside header/pointer array is rejected.
|
||||
page[108..110].copy_from_slice(&109u16.to_be_bytes());
|
||||
assert_eq!(btree_cell_offset(&page, &hdr, 0), Err(Error::InvalidCellPointer { offset: 109, min: 110, usable: 512 }));
|
||||
|
||||
// Unsupported page kind and truncated pages are rejected.
|
||||
page[0] = 0x01;
|
||||
assert_eq!(parse_btree_page_header(&page, false), Err(Error::UnsupportedBtreePageType(0x01)));
|
||||
assert_eq!(parse_btree_page_header(&[], false), Err(Error::TruncatedPage));
|
||||
assert_eq!(parse_btree_page_header(&[0x0d, 0, 0, 0], false), Err(Error::TruncatedPage));
|
||||
|
||||
// Interior page with pointer array exceeding usable page is rejected.
|
||||
page[0] = 0x05;
|
||||
page[3..5].copy_from_slice(&300u16.to_be_bytes());
|
||||
assert_eq!(parse_btree_page_header(&page, false), Err(Error::TruncatedPage));
|
||||
|
||||
// Cell pointer >= usable is rejected.
|
||||
page[0] = 0x0d;
|
||||
page[3..5].copy_from_slice(&1u16.to_be_bytes());
|
||||
page[8..10].copy_from_slice(&512u16.to_be_bytes());
|
||||
let small_hdr = parse_btree_page_header(&page, false).unwrap();
|
||||
assert_eq!(btree_cell_offset(&page, &small_hdr, 0), Err(Error::InvalidCellPointer { offset: 512, min: 10, usable: 512 }));
|
||||
}
|
||||
|
||||
@@ -21,7 +21,18 @@ The scalar values other than the updated label agreed across every view. Both pi
|
||||
|
||||
## Candidate shared boundary
|
||||
|
||||
Start with bounded varint decoding and serial-type widths over borrowed bytes. The reader sources already have independently implemented versions of these mechanics. Before adopting a helper, add boundary fixtures for ninth-byte varints, failed reads and offset handling, reserved serial types, and truncated values. Both readers assemble overflow data, but their caps and treatment of partial data need separate parity evidence before that code moves. [LightCraft reader](https://github.com/storytold/lightcraft/blob/78b575658a61d17bd392b4b81b64c92c8beecbac/crates/engine/src/lightroom_sqlite.rs) · [Craft Anything reader](https://github.com/storytold/craft-anything/blob/df2270904c36d6904883ba4442fb80fb383ed350/crates/formats/src/sqlite.rs)
|
||||
Shared wire mechanics in `craft-sqlite` (`crates/sqlite/src/lib.rs`) cover only the parts that genuinely match across both readers:
|
||||
- `read_varint` — bounded 1..=9-byte SQLite varint decoding
|
||||
- `serial_type_len` — SQLite record serial-type body width (refusing reserved codes 10 and 11)
|
||||
- `local_payload_len` and `PayloadKind` (#2696) — SQLite B-tree local payload formula (`TableLeaf` and `Index`) before overflow spilling
|
||||
- `page_size_from_raw` and `usable_page_size` — 16-bit header page-size decoding (`1` -> `65_536`, power of two in `512..=65_536`) and `usable >= 480` validation
|
||||
- `parse_btree_page_header` and `btree_cell_offset` — B-tree page header (`0x02`/`0x05`/`0x0a`/`0x0d`) and cell-pointer array bounds within a usable page
|
||||
- `decode_signed_be_int` — 1..=8-byte big-endian signed integer decoding
|
||||
|
||||
### Intentional app-specific differences (kept local)
|
||||
- **WAL & snapshot policy:** LightCraft (`lightroom_catalog.rs` + `lightroom_sqlite.rs`) validates the `-wal` checksum chain and overlays the committed prefix onto the main image (including multi-commit growth, shrink over a larger main file, and page-1 header/schema overrides). Craft Anything (`crates/formats/src/sqlite.rs`) inspects the main database file only and discloses `wal_mode` / `db_size_pages` mismatches in `overview().integrity_notes` (and `-wal` sidecar presence in `database_tools.rs`).
|
||||
- **Error & truncation policy:** LightCraft is strict for catalog import (errors on reserved serial types, non-finite `f64`, invalid UTF-8/UTF-16, or truncated payloads/pages). Craft Anything is best-effort for inspection (`CellValue::NotRead`, `CellValue::PartialBlob`, lossy/capped `MAX_TEXT` / `4096`-byte `CellValue::Text { truncated: true, .. }`, SHA-256 blob digests).
|
||||
- **Schema & table support:** LightCraft handles table B-trees (`0x05`/`0x0d`) and Lightroom `sqlite_schema` / `rowid` alias resolution. Craft Anything additionally inspects index B-trees (`0x02`/`0x0a`), `WITHOUT ROWID` tables, `STRICT` affinities (including `Affinity::Real` promotion), `GENERATED` columns, and `DEFAULT` column fill.
|
||||
|
||||
Keep snapshot selection and caller validation with the Lightroom importer. Keep schema defaults, pagination, text previews and BLOB presentation with Craft Anything. Coordinate a consumer change against the current catalog bounds and old-row default work. [LightCraft #3674](https://github.com/storytold/lightcraft/pull/3674) · [Craft Anything #1349](https://github.com/storytold/craft-anything/pull/1349)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user