Skip to main content

link_cli/engine/paged/
format.rs

1//! Version-one wire format; independent vectors live in docs/protocol.
2use crate::LinkError;
3
4pub const PAGE_SIZE: usize = 4096;
5pub const CELLS: u64 = 252;
6pub const MAX_PAGES: u64 = ((1_u64 << 53) - 1) / PAGE_SIZE as u64;
7pub const EXTERNAL: u64 = 1 << 63;
8pub const PAYLOAD: u64 = (1 << 56) - 1;
9pub const PAGE_MAGIC: &[u8; 8] = b"LNKDPG01";
10const META_MAGIC: &[u8; 8] = b"LNKDMT01";
11
12pub fn invalid(message: &str) -> LinkError {
13    LinkError::StorageError(format!("invalid native pages: {message}"))
14}
15pub fn u64_at(bytes: &[u8], offset: usize) -> u64 {
16    u64::from_le_bytes(
17        bytes[offset..offset + 8]
18            .try_into()
19            .expect("fixed wire field"),
20    )
21}
22pub fn u32_at(bytes: &[u8], offset: usize) -> u32 {
23    u32::from_le_bytes(
24        bytes[offset..offset + 4]
25            .try_into()
26            .expect("fixed wire field"),
27    )
28}
29pub fn put(bytes: &mut [u8], offset: usize, value: u64) {
30    bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
31}
32pub fn portable(value: u64) -> Result<u64, LinkError> {
33    if value > (1 << 53) - 1 {
34        return Err(invalid("integer exceeds portable range"));
35    }
36    Ok(value)
37}
38pub(super) fn hash(bytes: &[u8], initial: u64) -> u64 {
39    bytes.iter().fold(initial, |sum, byte| {
40        (sum ^ u64::from(*byte)).wrapping_mul(0x100000001b3)
41    })
42}
43pub fn page_hash(bytes: &[u8; PAGE_SIZE]) -> u64 {
44    hash(&bytes[64..], hash(&bytes[..56], 0xcbf29ce484222325))
45}
46
47#[derive(Clone)]
48pub struct Metadata {
49    pub flags: u32,
50    pub identity: [u8; 16],
51    pub generation: u64,
52    pub pages: u64,
53    pub rows: u64,
54    pub records: u64,
55    pub root: u64,
56    pub last_hash: u64,
57}
58impl Metadata {
59    pub fn empty(identity: [u8; 16], flags: u32) -> Self {
60        Self {
61            flags,
62            identity,
63            generation: 0,
64            pages: 0,
65            rows: 0,
66            records: 0,
67            root: 0,
68            last_hash: 0,
69        }
70    }
71    pub fn encode(&self) -> [u8; 128] {
72        let mut bytes = [0; 128];
73        bytes[..8].copy_from_slice(META_MAGIC);
74        bytes[8..12].copy_from_slice(&1_u32.to_le_bytes());
75        bytes[12..16].copy_from_slice(&self.flags.to_le_bytes());
76        bytes[16..32].copy_from_slice(&self.identity);
77        for (index, value) in [
78            self.generation,
79            self.pages,
80            self.rows,
81            self.records,
82            self.root,
83            self.last_hash,
84        ]
85        .into_iter()
86        .enumerate()
87        {
88            put(&mut bytes, 32 + index * 8, value);
89        }
90        let checksum = hash(&bytes[..120], 0xcbf29ce484222325);
91        put(&mut bytes, 120, checksum);
92        bytes
93    }
94    /// Missing/torn decisions have no committed meaning. Checksummed unsupported
95    /// versions/flags are errors, not permission to silently select old state.
96    pub fn decode(bytes: &[u8], flags: u32) -> Result<Option<Self>, LinkError> {
97        if bytes.len() != 128 || hash(&bytes[..120], 0xcbf29ce484222325) != u64_at(bytes, 120) {
98            return Ok(None);
99        }
100        if &bytes[..8] != META_MAGIC || u32_at(bytes, 8) != 1 {
101            return Err(invalid("unsupported metadata version"));
102        }
103        if u32_at(bytes, 12) != flags || bytes[80..120].iter().any(|v| *v != 0) {
104            return Err(invalid("unsupported metadata flags"));
105        }
106        let result = Self {
107            flags,
108            identity: bytes[16..32].try_into().expect("fixed identity"),
109            generation: portable(u64_at(bytes, 32))?,
110            pages: portable(u64_at(bytes, 40))?,
111            rows: portable(u64_at(bytes, 48))?,
112            records: portable(u64_at(bytes, 56))?,
113            root: portable(u64_at(bytes, 64))?,
114            last_hash: u64_at(bytes, 72),
115        };
116        let Self {
117            generation,
118            pages,
119            rows,
120            records,
121            root,
122            last_hash,
123            ..
124        } = result;
125        if pages > MAX_PAGES
126            || generation > pages
127            || rows > pages * CELLS
128            || records > rows
129            || rows < pages
130            || records < generation
131        {
132            return Err(invalid("metadata counts"));
133        }
134        if if pages == 0 {
135            generation != 0 || rows != 0 || records != 0 || root != 0 || last_hash != 0
136        } else {
137            generation == 0 || root <= (pages - 1) * CELLS || root > pages * CELLS
138        } {
139            return Err(invalid("metadata root"));
140        }
141        Ok(Some(result))
142    }
143}