use alloc::collections::BTreeSet;
use crate::err;
use crate::error::Result;
pub const BLOCKS_SIGNATURE: &[u8; 8] = b"XISB0100";
pub const BLOCKS_PREAMBLE_LEN: usize = 16;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct IndexElement {
pub id: u64,
pub position: u64,
pub length: u64,
pub uncompressed_length: u64,
}
impl IndexElement {
pub const SIZE: usize = 40;
pub fn is_free(&self) -> bool {
self.position == 0
}
fn parse(bytes: &[u8]) -> Self {
let read = |offset: usize| {
u64::from_le_bytes(bytes[offset..offset + 8].try_into().expect("checked length"))
};
IndexElement {
id: read(0),
position: read(8),
length: read(16),
uncompressed_length: read(24),
}
}
fn write(&self, out: &mut Vec<u8>) {
out.extend_from_slice(&self.id.to_le_bytes());
out.extend_from_slice(&self.position.to_le_bytes());
out.extend_from_slice(&self.length.to_le_bytes());
out.extend_from_slice(&self.uncompressed_length.to_le_bytes());
out.extend_from_slice(&[0u8; 8]);
}
}
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct BlocksIndex {
pub elements: Vec<IndexElement>,
}
impl BlocksIndex {
pub fn get(&self, id: u64) -> Option<&IndexElement> {
self.elements.iter().find(|e| e.id == id)
}
pub fn occupied(&self) -> impl Iterator<Item = &IndexElement> {
self.elements.iter().filter(|e| !e.is_free())
}
}
const MAX_NODES: usize = 100_000;
pub fn parse_blocks_file(bytes: &[u8]) -> Result<BlocksIndex> {
if bytes.len() < BLOCKS_PREAMBLE_LEN {
return Err(err!(
Truncated,
"a data blocks file needs at least {BLOCKS_PREAMBLE_LEN} bytes, this has {}",
bytes.len()
));
}
if &bytes[..8] != BLOCKS_SIGNATURE {
return Err(err!(
NotXisf,
"expected the signature {:?}, found {:?}",
String::from_utf8_lossy(BLOCKS_SIGNATURE),
String::from_utf8_lossy(&bytes[..8])
));
}
if bytes[8..16] != [0; 8] {
return Err(err!(BadHeader, "the reserved field must be zero"));
}
let max_elements = bytes.len() / IndexElement::SIZE;
let mut elements = Vec::new();
let mut seen: BTreeSet<u64> = BTreeSet::new();
let mut position = BLOCKS_PREAMBLE_LEN as u64;
for _ in 0..MAX_NODES {
if position == 0 {
return Ok(BlocksIndex { elements });
}
if !seen.insert(position) {
return Err(err!(BadHeader, "the block index loops back to position {position}"));
}
let start = usize::try_from(position)
.map_err(|_| err!(Truncated, "an index node lies beyond this platform's range"))?;
let header_end = start
.checked_add(16)
.ok_or_else(|| err!(Truncated, "an index node position overflows"))?;
if header_end > bytes.len() {
return Err(err!(Truncated, "an index node at {start} runs past the end of the file"));
}
let count = u32::from_le_bytes(bytes[start..start + 4].try_into().expect("4 bytes"));
if bytes[start + 4..start + 8] != [0; 4] {
return Err(err!(BadHeader, "an index node's reserved field is not zero"));
}
let next = u64::from_le_bytes(bytes[start + 8..start + 16].try_into().expect("8 bytes"));
let count = count as usize;
let elements_end = count
.checked_mul(IndexElement::SIZE)
.and_then(|n| header_end.checked_add(n))
.ok_or_else(|| err!(Truncated, "an index node declares too many elements"))?;
if elements_end > bytes.len() {
return Err(err!(
Truncated,
"an index node at {start} declares {count} elements, which run past the end"
));
}
if elements.len() + count > max_elements {
return Err(err!(
BadHeader,
"the block index declares more than {max_elements} elements, \
which is more than a file of {} bytes can hold",
bytes.len()
));
}
for i in 0..count {
let at = header_end + i * IndexElement::SIZE;
elements.push(IndexElement::parse(&bytes[at..at + IndexElement::SIZE]));
}
position = next;
}
Err(err!(BadHeader, "the block index has more than {MAX_NODES} nodes"))
}
pub fn read_block_from<R: std::io::Read + std::io::Seek>(
source: &mut R,
file_len: u64,
id: u64,
) -> Result<Option<Vec<u8>>> {
use std::io::SeekFrom;
let mut preamble = [0u8; BLOCKS_PREAMBLE_LEN];
source.seek(SeekFrom::Start(0))?;
source.read_exact(&mut preamble).map_err(|_| {
err!(Truncated, "a data blocks file needs at least {BLOCKS_PREAMBLE_LEN} bytes")
})?;
if &preamble[..8] != BLOCKS_SIGNATURE {
return Err(err!(NotXisf, "not a data blocks file"));
}
if preamble[8..16] != [0; 8] {
return Err(err!(BadHeader, "the reserved field must be zero"));
}
let max_elements = file_len / IndexElement::SIZE as u64;
let mut counted = 0u64;
let mut seen: BTreeSet<u64> = BTreeSet::new();
let mut position = BLOCKS_PREAMBLE_LEN as u64;
for _ in 0..MAX_NODES {
if position == 0 {
return Ok(None);
}
if !seen.insert(position) {
return Err(err!(BadHeader, "the block index loops back to position {position}"));
}
if position.checked_add(16).is_none_or(|end| end > file_len) {
return Err(err!(Truncated, "an index node at {position} runs past the end"));
}
let mut node = [0u8; 16];
source.seek(SeekFrom::Start(position))?;
source.read_exact(&mut node)?;
let count = u32::from_le_bytes(node[..4].try_into().expect("4 bytes")) as u64;
if node[4..8] != [0; 4] {
return Err(err!(BadHeader, "an index node's reserved field is not zero"));
}
let next = u64::from_le_bytes(node[8..16].try_into().expect("8 bytes"));
let elements_end = count
.checked_mul(IndexElement::SIZE as u64)
.and_then(|n| n.checked_add(position + 16))
.ok_or_else(|| err!(Truncated, "an index node declares too many elements"))?;
if elements_end > file_len {
return Err(err!(
Truncated,
"an index node at {position} declares {count} elements, which run past the end"
));
}
counted += count;
if counted > max_elements {
return Err(err!(
BadHeader,
"the block index declares more than {max_elements} elements, \
which is more than a file of {file_len} bytes can hold"
));
}
let mut buffer = vec![0u8; IndexElement::SIZE];
for i in 0..count {
source.seek(SeekFrom::Start(position + 16 + i * IndexElement::SIZE as u64))?;
source.read_exact(&mut buffer)?;
let element = IndexElement::parse(&buffer);
if element.id != id || element.is_free() {
continue;
}
let end = element
.position
.checked_add(element.length)
.ok_or_else(|| err!(Truncated, "block {id}'s position and length overflow"))?;
if end > file_len {
return Err(err!(
Truncated,
"block {id} runs {} bytes past the end of the file",
end - file_len
));
}
let length = usize::try_from(element.length)
.map_err(|_| err!(Unsupported, "block {id} is too large for this platform"))?;
let mut data = vec![0u8; length];
source.seek(SeekFrom::Start(element.position))?;
source.read_exact(&mut data)?;
return Ok(Some(data));
}
position = next;
}
Err(err!(BadHeader, "the block index has more than {MAX_NODES} nodes"))
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct PendingBlock {
pub id: u64,
pub bytes: Vec<u8>,
pub uncompressed_length: Option<u64>,
}
pub fn write_blocks_file(blocks: &[PendingBlock]) -> Result<Vec<u8>> {
let node_size = 16 + blocks.len() * IndexElement::SIZE;
let first_block = BLOCKS_PREAMBLE_LEN
.checked_add(node_size)
.ok_or_else(|| err!(Unsupported, "too many blocks for this platform"))?;
let mut seen: BTreeSet<u64> = BTreeSet::new();
let mut elements = Vec::with_capacity(blocks.len());
let mut position = first_block as u64;
for block in blocks {
let id = block.id;
if !seen.insert(id) {
return Err(err!(InvalidArgument, "two blocks share the identifier {id}"));
}
if block.bytes.is_empty() {
return Err(err!(
InvalidArgument,
"block {id} is empty; a data blocks file holds blocks of one or more bytes"
));
}
elements.push(IndexElement {
id,
position,
length: block.bytes.len() as u64,
uncompressed_length: block.uncompressed_length.unwrap_or(0),
});
position += block.bytes.len() as u64;
}
let mut out =
Vec::with_capacity(first_block + blocks.iter().map(|b| b.bytes.len()).sum::<usize>());
out.extend_from_slice(BLOCKS_SIGNATURE);
out.extend_from_slice(&[0u8; 8]);
out.extend_from_slice(&(blocks.len() as u32).to_le_bytes());
out.extend_from_slice(&[0u8; 4]);
out.extend_from_slice(&0u64.to_le_bytes());
for element in &elements {
element.write(&mut out);
}
for block in blocks {
out.extend_from_slice(&block.bytes);
}
Ok(out)
}
pub fn parse_header_file(bytes: &[u8]) -> Result<crate::header::Header> {
let text = core::str::from_utf8(bytes)
.map_err(|e| err!(BadHeader, "an XISF header file must be UTF-8: {e}"))?;
crate::header::parse(text)
}
#[cfg(test)]
fn plain_block(id: u64, bytes: &[u8]) -> PendingBlock {
PendingBlock { id, bytes: bytes.to_vec(), uncompressed_length: None }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ErrorKind;
fn blocks_file(blocks: &[(u64, &[u8])]) -> Vec<u8> {
let owned: Vec<PendingBlock> = blocks
.iter()
.map(|(id, d)| PendingBlock { id: *id, bytes: d.to_vec(), uncompressed_length: None })
.collect();
write_blocks_file(&owned).expect("write")
}
#[test]
fn an_index_element_records_the_size_before_compression() {
let bytes = write_blocks_file(&[
PendingBlock { id: 1, bytes: vec![0xAA; 40], uncompressed_length: Some(4096) },
PendingBlock { id: 2, bytes: vec![0xBB; 40], uncompressed_length: None },
])
.expect("write");
let index = parse_blocks_file(&bytes).expect("parse");
assert_eq!(index.get(1).unwrap().uncompressed_length, 4096, "compressed block");
assert_eq!(index.get(2).unwrap().uncompressed_length, 0, "uncompressed block");
}
#[test]
fn an_empty_block_cannot_be_placed_in_a_blocks_file() {
let err = write_blocks_file(&[plain_block(1, b"")]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidArgument);
assert!(err.message().contains("empty"), "{}", err.message());
}
#[test]
fn a_blocks_file_round_trips() {
let bytes = blocks_file(&[(1, b"first"), (7, b"second block"), (99, b"third")]);
let index = parse_blocks_file(&bytes).expect("parse");
assert_eq!(index.elements.len(), 3);
assert_eq!(index.get(7).unwrap().length, 12);
assert_eq!(index.get(99).unwrap().length, 5);
assert!(index.get(1234).is_none());
for (id, expected) in [(1u64, &b"first"[..]), (7, b"second block"), (99, b"third")] {
let element = index.get(id).unwrap();
let start = element.position as usize;
let end = start + element.length as usize;
assert_eq!(&bytes[start..end], expected, "block {id} is not where the index says");
}
}
#[test]
fn the_signature_is_xisb_not_xisf() {
let mut bytes = blocks_file(&[(1, b"x")]);
bytes[3] = b'F'; assert_eq!(parse_blocks_file(&bytes).unwrap_err().kind(), ErrorKind::NotXisf);
}
#[test]
fn free_elements_are_recognised_and_skipped() {
let mut bytes = Vec::new();
bytes.extend_from_slice(BLOCKS_SIGNATURE);
bytes.extend_from_slice(&[0u8; 8]);
bytes.extend_from_slice(&2u32.to_le_bytes());
bytes.extend_from_slice(&[0u8; 4]);
bytes.extend_from_slice(&0u64.to_le_bytes());
IndexElement { id: 1, position: 0, length: 0, uncompressed_length: 0 }.write(&mut bytes);
let data_at = (16 + 16 + 2 * IndexElement::SIZE) as u64;
IndexElement { id: 2, position: data_at, length: 3, uncompressed_length: 0 }
.write(&mut bytes);
bytes.extend_from_slice(b"abc");
let index = parse_blocks_file(&bytes).expect("parse");
assert_eq!(index.elements.len(), 2);
assert!(index.get(1).unwrap().is_free());
assert_eq!(index.occupied().count(), 1, "the free element should be skipped");
}
#[test]
fn a_cyclic_index_is_refused_rather_than_followed() {
let mut bytes = Vec::new();
bytes.extend_from_slice(BLOCKS_SIGNATURE);
bytes.extend_from_slice(&[0u8; 8]);
bytes.extend_from_slice(&0u32.to_le_bytes());
bytes.extend_from_slice(&[0u8; 4]);
bytes.extend_from_slice(&(BLOCKS_PREAMBLE_LEN as u64).to_le_bytes());
let err = parse_blocks_file(&bytes).unwrap_err();
assert_eq!(err.kind(), ErrorKind::BadHeader);
assert!(err.message().contains("loops"), "{}", err.message());
}
#[test]
fn a_node_pointing_past_the_end_is_refused() {
let mut bytes = Vec::new();
bytes.extend_from_slice(BLOCKS_SIGNATURE);
bytes.extend_from_slice(&[0u8; 8]);
bytes.extend_from_slice(&0u32.to_le_bytes());
bytes.extend_from_slice(&[0u8; 4]);
bytes.extend_from_slice(&1_000_000u64.to_le_bytes());
assert_eq!(parse_blocks_file(&bytes).unwrap_err().kind(), ErrorKind::Truncated);
}
#[test]
fn an_absurd_element_count_is_refused() {
let mut bytes = Vec::new();
bytes.extend_from_slice(BLOCKS_SIGNATURE);
bytes.extend_from_slice(&[0u8; 8]);
bytes.extend_from_slice(&u32::MAX.to_le_bytes());
bytes.extend_from_slice(&[0u8; 4]);
bytes.extend_from_slice(&0u64.to_le_bytes());
assert_eq!(parse_blocks_file(&bytes).unwrap_err().kind(), ErrorKind::Truncated);
}
#[test]
fn truncation_at_every_length_is_an_error_not_a_panic() {
let bytes = blocks_file(&[(1, b"first"), (2, b"second")]);
for n in 0..bytes.len() {
let _ = parse_blocks_file(&bytes[..n]);
}
}
#[test]
fn corruption_of_any_single_byte_never_panics() {
let original = blocks_file(&[(1, b"first"), (2, b"second")]);
for i in 0..original.len().min(200) {
let mut bytes = original.clone();
bytes[i] ^= 0xff;
let _ = parse_blocks_file(&bytes);
}
}
#[test]
fn duplicate_identifiers_are_refused_when_writing() {
let err = write_blocks_file(&[plain_block(1, b"a"), plain_block(1, b"b")]).unwrap_err();
assert_eq!(err.kind(), ErrorKind::InvalidArgument);
}
#[test]
fn an_empty_blocks_file_is_valid() {
let bytes = write_blocks_file(&[]).expect("write");
let index = parse_blocks_file(&bytes).expect("parse");
assert!(index.elements.is_empty());
}
#[test]
fn a_header_file_is_the_header_alone() {
let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<xisf version="1.0"><Image geometry="4:4:1" sampleFormat="UInt8"
location="path(data.xisb)"/></xisf>"#;
let header = parse_header_file(xml.as_bytes()).expect("parse");
assert_eq!(header.images().len(), 1);
let mut monolithic = Vec::from(crate::layout::SIGNATURE);
monolithic.extend_from_slice(&[0u8; 8]);
assert!(parse_header_file(&monolithic).is_err());
}
}