use sha2::{Digest, Sha256};
use crate::sqlite::Position;
use crate::{Error, ErrorKind, Result};
pub(crate) const MAGIC: &[u8; 8] = b"TSLOG001";
const FIXED: usize = 1 + 8 + 8 + 16 + 16 + 4 + 4 + 4;
const CHECK: usize = 16;
const LARGEST: usize = 1 << 30;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Kind {
Commit = 0,
Begin = 1,
Gap = 2,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Point {
pub(crate) sequence: u64,
pub(crate) epoch: u64,
pub(crate) check: [u8; CHECK],
}
#[derive(Debug)]
pub(crate) struct Entry<'a> {
pub(crate) kind: Kind,
pub(crate) sequence: u64,
pub(crate) epoch: u64,
pub(crate) previous: [u8; CHECK],
pub(crate) check: [u8; CHECK],
pub(crate) position: Position,
pub(crate) page_size: u32,
pub(crate) size: u32,
pub(crate) pages: Vec<(u32, &'a [u8])>,
}
impl Entry<'_> {
pub(crate) fn point(&self) -> Point {
Point { sequence: self.sequence, epoch: self.epoch, check: self.check }
}
pub(crate) fn follows(&self, point: &Point) -> bool {
self.sequence == point.sequence + 1 && self.previous == point.check && self.epoch >= point.epoch
}
}
pub(crate) struct Head {
pub(crate) kind: Kind,
pub(crate) sequence: u64,
pub(crate) epoch: u64,
pub(crate) previous: [u8; CHECK],
pub(crate) position: Position,
pub(crate) page_size: u32,
pub(crate) size: u32,
}
pub(crate) fn encode(head: &Head, pages: &[(u32, &[u8])]) -> (Vec<u8>, [u8; CHECK]) {
let pages_bytes: usize = pages.iter().map(|(_, page)| 4 + page.len()).sum();
let mut bytes = Vec::with_capacity(4 + FIXED + pages_bytes + CHECK);
bytes.extend_from_slice(&u32::try_from(FIXED + pages_bytes).unwrap_or(u32::MAX).to_le_bytes());
bytes.push(head.kind as u8);
bytes.extend_from_slice(&head.sequence.to_le_bytes());
bytes.extend_from_slice(&head.epoch.to_le_bytes());
bytes.extend_from_slice(&head.previous);
let Position { checkpoints, salts: [first, second], frame } = head.position;
for word in [checkpoints, first, second, frame, head.page_size, head.size] {
bytes.extend_from_slice(&word.to_le_bytes());
}
bytes.extend_from_slice(&u32::try_from(pages.len()).unwrap_or(u32::MAX).to_le_bytes());
for (number, page) in pages {
bytes.extend_from_slice(&number.to_le_bytes());
bytes.extend_from_slice(page);
}
let check = check_of(&bytes[4..]);
bytes.extend_from_slice(&check);
(bytes, check)
}
pub(crate) fn decode(bytes: &[u8]) -> Result<Option<(Entry<'_>, usize)>> {
let Some(length) = bytes.get(..4) else {
return Ok(None);
};
let length = u32::from_le_bytes(length.try_into().expect("four bytes")) as usize;
if !(FIXED..=LARGEST).contains(&length) {
return Err(corrupt("an entry's length is outside what an entry may be"));
}
let Some(body) = bytes.get(4..4 + length) else {
return Ok(None);
};
let Some(check) = bytes.get(4 + length..4 + length + CHECK) else {
return Ok(None);
};
if check_of(body) != check {
return Err(corrupt("an entry's check is not its body's"));
}
Ok(Some((parse(body, check.try_into().expect("sixteen bytes"))?, 4 + length + CHECK)))
}
pub(crate) fn torn(rest: &[u8]) -> bool {
let end = rest.get(..4).map_or(rest.len(), |length| {
let length = u32::from_le_bytes(length.try_into().expect("four bytes")) as usize;
if (FIXED..=LARGEST).contains(&length) { (4 + length + CHECK).min(rest.len()) } else { 0 }
});
rest[end..].iter().all(|&byte| byte == 0)
}
fn parse(body: &[u8], check: [u8; CHECK]) -> Result<Entry<'_>> {
let mut at = Cursor { bytes: body, at: 0 };
let kind = match at.byte() {
0 => Kind::Commit,
1 => Kind::Begin,
2 => Kind::Gap,
_ => return Err(corrupt("an entry's kind is none the log writes")),
};
let sequence = at.long();
let epoch = at.long();
let previous = at.check();
let position = Position { checkpoints: at.word(), salts: [at.word(), at.word()], frame: at.word() };
let page_size = at.word();
let size = at.word();
let count = at.word() as usize;
if body.len() - FIXED != count * (4 + page_size as usize) {
return Err(corrupt("an entry's pages do not fill its body"));
}
let pages = (0..count).map(|_| (at.word(), at.take(page_size as usize))).collect();
Ok(Entry { kind, sequence, epoch, previous, check, position, page_size, size, pages })
}
fn check_of(body: &[u8]) -> [u8; CHECK] {
let digest = Sha256::digest(body);
digest[..CHECK].try_into().expect("a digest is longer than a check")
}
fn corrupt(what: &str) -> Error {
Error::new(ErrorKind::Corrupt, what)
}
struct Cursor<'a> {
bytes: &'a [u8],
at: usize,
}
impl<'a> Cursor<'a> {
fn take(&mut self, n: usize) -> &'a [u8] {
let taken = &self.bytes[self.at..self.at + n];
self.at += n;
taken
}
fn byte(&mut self) -> u8 {
self.take(1)[0]
}
fn word(&mut self) -> u32 {
u32::from_le_bytes(self.take(4).try_into().expect("four bytes"))
}
fn long(&mut self) -> u64 {
u64::from_le_bytes(self.take(8).try_into().expect("eight bytes"))
}
fn check(&mut self) -> [u8; CHECK] {
self.take(CHECK).try_into().expect("sixteen bytes")
}
}