Skip to main content

fsqlite_types/
lib.rs

1#![cfg_attr(
2    all(
3        feature = "nightly-simd",
4        target_arch = "x86_64",
5        not(target_arch = "wasm32")
6    ),
7    feature(portable_simd)
8)]
9
10pub mod cx;
11pub mod ecs;
12pub mod encoding;
13pub mod eprocess;
14pub mod flags;
15pub mod glossary;
16pub mod limits;
17pub mod obligation;
18pub mod opcode;
19pub mod qsbr;
20pub mod record;
21pub mod record_coder_pacbayes;
22pub mod serial_type;
23pub mod sync_primitives;
24pub mod value;
25
26pub use cx::Cx;
27pub use ecs::{
28    ObjectId, PayloadHash, SYMBOL_RECORD_MAGIC, SYMBOL_RECORD_VERSION, SymbolReadPath,
29    SymbolRecord, SymbolRecordError, SymbolRecordFlags, SystematicLayoutError,
30    layout_systematic_run, reconstruct_systematic_happy_path, recover_object_with_fallback,
31    source_symbol_count, validate_systematic_run,
32};
33pub use eprocess::{
34    EProcessConfig, EProcessDecision, EProcessOracle, EProcessSignal, EProcessSnapshot,
35    EProcessTelemetryBridge,
36};
37pub use glossary::{
38    ArcCache, BtreeRef, Budget, COMMIT_MARKER_RECORD_V1_SIZE, ColumnIdx, CommitCapsule,
39    CommitMarker, CommitProof, CommitSeq, DecodeProof, DependencyEdge, EpochId, IdempotencyKey,
40    IndexId, IntentFootprint, IntentLog, IntentOp, IntentOpKind, OTI_WIRE_SIZE, OperatingMode, Oti,
41    Outcome, PageHistory, PageVersion, RangeKey, ReadWitness, RebaseBinaryOp, RebaseExpr,
42    RebaseUnaryOp, Region, RemoteCap, RootManifest, RowId, RowIdAllocator, RowIdExhausted,
43    RowIdMode, Saga, SchemaEpoch, SemanticKeyKind, SemanticKeyRef, Snapshot, StructuralEffects,
44    SymbolAuthMasterKeyCap, SymbolValidityWindow, TableId, TxnEpoch, TxnId, TxnSlot, TxnToken,
45    VersionPointer, WitnessIndexSegment, WitnessKey, WriteWitness,
46};
47pub use value::{SmallText, SqliteValue};
48
49use std::fmt;
50use std::num::NonZeroU32;
51use std::sync::atomic::{AtomicU64, Ordering};
52use std::sync::{Arc, OnceLock};
53
54/// A page number in the database file.
55///
56/// Page numbers are 1-based (page 0 does not exist). Page 1 is the database
57/// header page. The maximum page count is `u32::MAX - 1` (4,294,967,294).
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59#[repr(transparent)]
60pub struct PageNumber(NonZeroU32);
61
62impl PageNumber {
63    /// Page 1 is the database header page containing the file header and the
64    /// schema table root.
65    pub const ONE: Self = Self(NonZeroU32::MIN);
66
67    /// Create a new page number from a raw u32.
68    ///
69    /// Returns `None` if `n` is 0 (page 0 does not exist in SQLite) or
70    /// `u32::MAX` (outside SQLite's maximum page count).
71    #[inline]
72    pub const fn new(n: u32) -> Option<Self> {
73        if n == u32::MAX {
74            None
75        } else {
76            match NonZeroU32::new(n) {
77                Some(v) => Some(Self(v)),
78                None => None,
79            }
80        }
81    }
82
83    /// Get the raw u32 value.
84    #[inline]
85    pub const fn get(self) -> u32 {
86        self.0.get()
87    }
88}
89
90impl fmt::Display for PageNumber {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "{}", self.0)
93    }
94}
95
96impl serde::Serialize for PageNumber {
97    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
98    where
99        S: serde::Serializer,
100    {
101        serializer.serialize_u32(self.get())
102    }
103}
104
105impl<'de> serde::Deserialize<'de> for PageNumber {
106    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
107    where
108        D: serde::Deserializer<'de>,
109    {
110        let raw = <u32 as serde::Deserialize>::deserialize(deserializer)?;
111        Self::new(raw).ok_or_else(|| {
112            serde::de::Error::invalid_value(
113                serde::de::Unexpected::Unsigned(u64::from(raw)),
114                &"a SQLite page number in 1..=4294967294",
115            )
116        })
117    }
118}
119
120impl TryFrom<u32> for PageNumber {
121    type Error = InvalidPageNumber;
122
123    fn try_from(value: u32) -> Result<Self, Self::Error> {
124        Self::new(value).ok_or(InvalidPageNumber)
125    }
126}
127
128/// Fast identity hasher for `PageNumber` keys in lock/commit tables.
129///
130/// Page numbers are already well-distributed u32 values, so we skip
131/// hashing entirely and use the raw value directly.
132#[derive(Default)]
133pub struct PageNumberHasher(u64);
134
135impl std::hash::Hasher for PageNumberHasher {
136    fn write(&mut self, _: &[u8]) {
137        // PageNumber's Hash impl calls write_u32 (via NonZeroU32). If this
138        // method is reached, the hasher is being misused with a non-u32 key.
139        debug_assert!(false, "PageNumberHasher only supports write_u32");
140    }
141
142    fn write_u32(&mut self, n: u32) {
143        self.0 = u64::from(n);
144    }
145
146    fn finish(&self) -> u64 {
147        self.0
148    }
149}
150
151/// BuildHasher for `PageNumberHasher`.
152pub type PageNumberBuildHasher = std::hash::BuildHasherDefault<PageNumberHasher>;
153
154/// GF(256) addition (`+`) for bytes (XOR).
155#[must_use]
156pub const fn gf256_add_byte(lhs: u8, rhs: u8) -> u8 {
157    lhs ^ rhs
158}
159
160/// Scalar GF(256) multiply with irreducible polynomial `0x11d`.
161///
162/// This is the core algebraic primitive used for RaptorQ encoding and
163/// XOR-delta compression (§3.2.1).
164#[must_use]
165pub fn gf256_mul_byte(mut a: u8, mut b: u8) -> u8 {
166    let mut out = 0_u8;
167    while b != 0 {
168        if (b & 1) != 0 {
169            out ^= a;
170        }
171        let carry = (a & 0x80) != 0;
172        a <<= 1;
173        if carry {
174            a ^= 0x1D;
175        }
176        b >>= 1;
177    }
178    out
179}
180
181/// Multiplicative inverse in GF(256) (`None` for zero).
182#[must_use]
183pub fn gf256_inverse_byte(value: u8) -> Option<u8> {
184    if value == 0 {
185        return None;
186    }
187    for candidate in 1u16..=255 {
188        let inv = u8::try_from(candidate).expect("candidate in 1..=255 always fits u8");
189        if gf256_mul_byte(value, inv) == 1 {
190            return Some(inv);
191        }
192    }
193    None
194}
195
196/// SQLite page categories relevant to merge safety policy.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
198pub enum MergePageKind {
199    /// Interior table b-tree page (0x05).
200    BtreeInteriorTable,
201    /// Leaf table b-tree page (0x0D).
202    BtreeLeafTable,
203    /// Interior index b-tree page (0x02).
204    BtreeInteriorIndex,
205    /// Leaf index b-tree page (0x0A).
206    BtreeLeafIndex,
207    /// Overflow page.
208    Overflow,
209    /// Freelist trunk/leaf page.
210    Freelist,
211    /// Pointer-map page.
212    PointerMap,
213    /// Opaque/non-SQLite-structured page.
214    Opaque,
215}
216
217impl MergePageKind {
218    /// Whether this page has SQLite-internal pointer semantics.
219    #[must_use]
220    pub const fn is_sqlite_structured(self) -> bool {
221        !matches!(self, Self::Opaque)
222    }
223
224    /// Classify a raw page image for merge-safety policy checks.
225    #[must_use]
226    pub fn classify(page: &[u8]) -> Self {
227        let Some(first_byte) = page.first().copied() else {
228            return Self::Opaque;
229        };
230        match BTreePageType::from_byte(first_byte) {
231            Some(BTreePageType::LeafTable) => Self::BtreeLeafTable,
232            Some(BTreePageType::InteriorTable) => Self::BtreeInteriorTable,
233            Some(BTreePageType::LeafIndex) => Self::BtreeLeafIndex,
234            Some(BTreePageType::InteriorIndex) => Self::BtreeInteriorIndex,
235            None => Self::Opaque,
236        }
237    }
238}
239
240/// Error returned when attempting to create an out-of-range `PageNumber`.
241#[derive(Debug, Clone, Copy, PartialEq, Eq)]
242pub struct InvalidPageNumber;
243
244impl fmt::Display for InvalidPageNumber {
245    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
246        f.write_str("page number must be in 1..=4294967294")
247    }
248}
249
250impl std::error::Error for InvalidPageNumber {}
251
252/// Database page size in bytes.
253///
254/// Must be a power of two between 512 and 65536 (inclusive). The default is
255/// 4096 bytes, matching SQLite's `SQLITE_DEFAULT_PAGE_SIZE`.
256#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
257pub struct PageSize(u32);
258
259impl PageSize {
260    /// Minimum page size: 512 bytes.
261    pub const MIN: Self = Self(512);
262
263    /// Default page size: 4096 bytes.
264    pub const DEFAULT: Self = Self(limits::DEFAULT_PAGE_SIZE);
265
266    /// Maximum page size: 65536 bytes.
267    pub const MAX: Self = Self(limits::MAX_PAGE_SIZE);
268
269    /// Create a new page size, validating that it is a power of two in
270    /// the range \[512, 65536\].
271    pub const fn new(size: u32) -> Option<Self> {
272        if size < 512 || size > 65536 || !size.is_power_of_two() {
273            None
274        } else {
275            Some(Self(size))
276        }
277    }
278
279    /// Get the raw page size in bytes.
280    #[inline]
281    pub const fn get(self) -> u32 {
282        self.0
283    }
284
285    /// Get the page size as a `usize`.
286    #[inline]
287    pub const fn as_usize(self) -> usize {
288        self.0 as usize
289    }
290
291    /// The usable size of a page (total size minus reserved bytes at the end).
292    ///
293    /// `reserved` is the number of bytes reserved at the end of each page
294    /// for extensions (typically 0, stored at byte offset 20 of the header).
295    #[inline]
296    pub const fn usable(self, reserved: u8) -> u32 {
297        self.0 - reserved as u32
298    }
299}
300
301impl Default for PageSize {
302    fn default() -> Self {
303        Self::DEFAULT
304    }
305}
306
307impl fmt::Display for PageSize {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        write!(f, "{}", self.0)
310    }
311}
312
313/// Raw page data as an owned byte buffer.
314///
315/// The length always matches the database page size.
316/// Fresh pages stay owned until the first clone, then lazily promote to
317/// `Arc<[u8]>` for shared copy-on-write snapshots.
318pub struct PageData {
319    repr: PageDataRepr,
320    image_token: u64,
321}
322
323enum PageDataRepr {
324    /// Single-owner page bytes before the first clone.
325    ///
326    /// The shared `Arc<[u8]>` snapshot is created lazily on the first clone so
327    /// freshly written pages do not pay refcount costs until they are actually
328    /// shared across snapshots or layers.
329    Owned {
330        bytes: Vec<u8>,
331        shared: OnceLock<Arc<[u8]>>,
332    },
333    /// Shared immutable bytes after the page has been cloned.
334    Shared(Arc<[u8]>),
335}
336
337impl Clone for PageData {
338    fn clone(&self) -> Self {
339        match &self.repr {
340            PageDataRepr::Owned { bytes, shared } => {
341                let shared = Arc::clone(
342                    shared.get_or_init(|| Arc::<[u8]>::from(bytes.clone().into_boxed_slice())),
343                );
344                Self {
345                    repr: PageDataRepr::Shared(shared),
346                    image_token: self.image_token,
347                }
348            }
349            PageDataRepr::Shared(bytes) => Self {
350                repr: PageDataRepr::Shared(Arc::clone(bytes)),
351                image_token: self.image_token,
352            },
353        }
354    }
355}
356
357impl PartialEq for PageData {
358    fn eq(&self, other: &Self) -> bool {
359        self.as_bytes() == other.as_bytes()
360    }
361}
362
363impl Eq for PageData {}
364
365impl PageDataRepr {
366    #[inline]
367    fn as_bytes(&self) -> &[u8] {
368        match self {
369            Self::Owned { bytes, .. } => bytes.as_slice(),
370            Self::Shared(bytes) => bytes.as_ref(),
371        }
372    }
373}
374
375impl PageData {
376    fn next_image_token() -> u64 {
377        static NEXT_IMAGE_TOKEN: AtomicU64 = AtomicU64::new(1);
378        NEXT_IMAGE_TOKEN.fetch_add(1, Ordering::Relaxed).max(1)
379    }
380
381    fn bump_image_token(&mut self) {
382        self.image_token = Self::next_image_token();
383    }
384
385    fn invalidate_owned_snapshot_cache_if_needed(&mut self) {
386        let reset_owned_snapshot_cache = matches!(
387            &self.repr,
388            PageDataRepr::Owned { shared, .. } if shared.get().is_some()
389        );
390        if reset_owned_snapshot_cache {
391            let bytes = match std::mem::replace(
392                &mut self.repr,
393                PageDataRepr::Owned {
394                    bytes: Vec::new(),
395                    shared: OnceLock::new(),
396                },
397            ) {
398                PageDataRepr::Owned { bytes, .. } => bytes,
399                PageDataRepr::Shared(_) => {
400                    unreachable!("owned snapshot cache reset should only run for owned pages")
401                }
402            };
403            self.repr = PageDataRepr::Owned {
404                bytes,
405                shared: OnceLock::new(),
406            };
407        }
408    }
409
410    /// Create a zero-filled page of the given size.
411    pub fn zeroed(size: PageSize) -> Self {
412        Self::from_vec(vec![0u8; size.as_usize()])
413    }
414
415    /// Create from existing bytes. The caller must ensure the length matches
416    /// the page size.
417    pub fn from_vec(data: Vec<u8>) -> Self {
418        Self {
419            repr: PageDataRepr::Owned {
420                bytes: data,
421                shared: OnceLock::new(),
422            },
423            image_token: Self::next_image_token(),
424        }
425    }
426
427    /// Create from an already shared immutable page snapshot.
428    #[must_use]
429    pub fn from_shared(bytes: Arc<[u8]>) -> Self {
430        Self {
431            repr: PageDataRepr::Shared(bytes),
432            image_token: Self::next_image_token(),
433        }
434    }
435
436    /// Get the page data as a byte slice.
437    #[inline]
438    pub fn as_bytes(&self) -> &[u8] {
439        self.repr.as_bytes()
440    }
441
442    /// Cheap identity for this exact immutable page image.
443    ///
444    /// Clones preserve the token because they expose identical bytes. Any
445    /// mutable access assigns a fresh token before returning the mutable slice,
446    /// so caches can key on `(page_no, image_token)` instead of re-hashing the
447    /// whole page to detect page-image changes.
448    #[inline]
449    #[must_use]
450    pub fn image_token(&self) -> u64 {
451        self.image_token
452    }
453
454    /// Get the page data as a mutable byte slice.
455    ///
456    /// This performs a clone if the data is shared (Copy-On-Write).
457    #[inline]
458    pub fn as_bytes_mut(&mut self) -> &mut [u8] {
459        self.invalidate_owned_snapshot_cache_if_needed();
460        self.bump_image_token();
461        match &mut self.repr {
462            PageDataRepr::Owned { bytes, .. } => bytes.as_mut_slice(),
463            PageDataRepr::Shared(bytes) => Arc::make_mut(bytes),
464        }
465    }
466
467    /// Returns `true` when this page is backed by single-owner `Owned` bytes
468    /// whose shared-snapshot cache has not yet been materialised.
469    ///
470    /// Callers can use this as a cheap probe before mutating via
471    /// `as_bytes_mut`: a `true` result guarantees that the subsequent mutable
472    /// borrow will NOT trigger a copy-on-write clone (`Arc::make_mut`) and
473    /// thus stays allocation-free.
474    #[inline]
475    #[must_use]
476    pub fn is_single_owner_owned(&self) -> bool {
477        matches!(
478            &self.repr,
479            PageDataRepr::Owned { shared, .. } if shared.get().is_none()
480        )
481    }
482
483    /// Extend an owned page buffer with zero bytes in place.
484    ///
485    /// Returns `true` when the underlying representation stayed owned and was
486    /// extended without promoting/cloning through a shared snapshot.
487    pub fn try_zero_extend_owned_to(&mut self, new_len: usize) -> bool {
488        self.invalidate_owned_snapshot_cache_if_needed();
489        match &mut self.repr {
490            PageDataRepr::Owned { bytes, .. } => {
491                if bytes.len() > new_len {
492                    return false;
493                }
494                if bytes.len() < new_len {
495                    self.image_token = Self::next_image_token();
496                    bytes.resize(new_len, 0);
497                }
498                true
499            }
500            PageDataRepr::Shared(_) => false,
501        }
502    }
503
504    /// Get the length in bytes.
505    #[inline]
506    pub fn len(&self) -> usize {
507        self.as_bytes().len()
508    }
509
510    /// Returns true if the page data is empty (should never be true for valid pages).
511    #[inline]
512    pub fn is_empty(&self) -> bool {
513        self.as_bytes().is_empty()
514    }
515
516    /// Consume self and return the inner `Vec<u8>`.
517    ///
518    /// If the data is shared, this clones into a new Vec.
519    pub fn into_vec(self) -> Vec<u8> {
520        match self.repr {
521            PageDataRepr::Owned { bytes, .. } => bytes,
522            PageDataRepr::Shared(bytes) => bytes.as_ref().to_vec(),
523        }
524    }
525}
526
527impl fmt::Debug for PageData {
528    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529        f.debug_struct("PageData")
530            .field("len", &self.len())
531            .finish()
532    }
533}
534
535impl AsRef<[u8]> for PageData {
536    fn as_ref(&self) -> &[u8] {
537        self.as_bytes()
538    }
539}
540
541impl AsMut<[u8]> for PageData {
542    fn as_mut(&mut self) -> &mut [u8] {
543        self.as_bytes_mut()
544    }
545}
546
547/// SQLite type affinity, used for column type resolution.
548///
549/// See <https://www.sqlite.org/datatype3.html#type_affinity>.
550#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
551#[repr(u8)]
552pub enum TypeAffinity {
553    /// Column prefers integer storage. Includes INTEGER, INT, TINYINT, etc.
554    Integer = b'D',
555    /// Column prefers text storage. Includes TEXT, VARCHAR, CLOB.
556    Text = b'B',
557    /// Column has no preference. Includes BLOB or no type specified.
558    Blob = b'A',
559    /// Column prefers real (float) storage. Includes REAL, DOUBLE, FLOAT.
560    Real = b'E',
561    /// Column prefers numeric storage. Includes NUMERIC, DECIMAL, BOOLEAN,
562    /// DATE, DATETIME.
563    Numeric = b'C',
564}
565
566impl TypeAffinity {
567    /// Determine the type affinity for a declared column type name.
568    ///
569    /// Uses SQLite's first-match rule (§3.1 of datatype3.html):
570    /// 1. Contains "INT" → INTEGER
571    /// 2. Contains "CHAR", "CLOB", or "TEXT" → TEXT
572    /// 3. Contains "BLOB" or is empty → BLOB
573    /// 4. Contains "REAL", "FLOA", or "DOUB" → REAL
574    /// 5. Otherwise → NUMERIC
575    pub fn from_type_name(type_name: &str) -> Self {
576        let upper = type_name.to_ascii_uppercase();
577
578        if upper.contains("INT") {
579            Self::Integer
580        } else if upper.contains("CHAR") || upper.contains("CLOB") || upper.contains("TEXT") {
581            Self::Text
582        } else if upper.is_empty() || upper.contains("BLOB") {
583            Self::Blob
584        } else if upper.contains("REAL") || upper.contains("FLOA") || upper.contains("DOUB") {
585            Self::Real
586        } else {
587            Self::Numeric
588        }
589    }
590
591    /// Determine the affinity to apply for a comparison between two operands.
592    ///
593    /// Returns `Some(affinity)` if one side needs coercion, `None` if no
594    /// coercion is needed. The returned affinity should be applied to the
595    /// operand that needs conversion.
596    ///
597    /// Rules (§3.2 of datatype3.html):
598    /// - If one operand is INTEGER/REAL/NUMERIC and the other is TEXT/BLOB,
599    ///   apply numeric affinity to the TEXT/BLOB side.
600    /// - If one operand is TEXT and the other is BLOB (no numeric involved),
601    ///   apply TEXT affinity to the BLOB side.
602    /// - Same affinity or both BLOB → no coercion.
603    pub fn comparison_affinity(left: Self, right: Self) -> Option<Self> {
604        if left == right {
605            return None;
606        }
607
608        let is_numeric = |a: Self| matches!(a, Self::Integer | Self::Real | Self::Numeric);
609
610        // Rule 1: numeric vs TEXT/BLOB → apply numeric affinity
611        if is_numeric(left) && matches!(right, Self::Text | Self::Blob) {
612            return Some(Self::Numeric);
613        }
614        if is_numeric(right) && matches!(left, Self::Text | Self::Blob) {
615            return Some(Self::Numeric);
616        }
617
618        // Rule 2: TEXT vs BLOB → apply TEXT affinity to BLOB side
619        if (left == Self::Text && right == Self::Blob)
620            || (left == Self::Blob && right == Self::Text)
621        {
622            return Some(Self::Text);
623        }
624
625        // Rule 3: no coercion
626        None
627    }
628}
629
630/// SQLite affinity attached to an expression for comparison purposes.
631///
632/// This deliberately distinguishes an expression with no affinity (for
633/// example, a literal or most computed expressions) from an expression with
634/// genuine [`TypeAffinity::Blob`] affinity. Although both cases avoid storage
635/// conversion in many comparisons, they combine differently with the other
636/// operand's affinity under SQLite's comparison rules.
637#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
638pub enum ExprAffinity {
639    /// The expression has no affinity.
640    None,
641    /// The expression carries the specified SQLite type affinity.
642    Affinity(TypeAffinity),
643}
644
645/// Affinity encoded on a SQLite comparison operation.
646///
647/// The discriminants match SQLite's comparison-affinity codes, including
648/// `@` (`0x40`) for no affinity. Keeping `None` distinct from `Blob` is
649/// essential: a no-affinity literal paired with a TEXT column selects TEXT,
650/// while two declared TEXT/BLOB operands select BLOB (raw) comparison.
651#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
652#[repr(u8)]
653pub enum ComparisonAffinity {
654    /// No comparison affinity (`SQLITE_AFF_NONE`, `@`).
655    None = b'@',
656    /// Raw/BLOB comparison affinity (`SQLITE_AFF_BLOB`, `A`).
657    Blob = b'A',
658    /// TEXT comparison affinity (`SQLITE_AFF_TEXT`, `B`).
659    Text = b'B',
660    /// NUMERIC comparison affinity (`SQLITE_AFF_NUMERIC`, `C`).
661    Numeric = b'C',
662    /// INTEGER comparison affinity (`SQLITE_AFF_INTEGER`, `D`).
663    Integer = b'D',
664    /// REAL comparison affinity (`SQLITE_AFF_REAL`, `E`).
665    Real = b'E',
666}
667
668impl ComparisonAffinity {
669    /// Combine two expression affinities using SQLite's comparison rules.
670    ///
671    /// If neither operand has affinity, the comparison has no affinity. If
672    /// exactly one operand has affinity, that exact affinity is preserved. If
673    /// both operands have affinity, any numeric-class operand selects NUMERIC;
674    /// otherwise the comparison uses BLOB affinity and keeps runtime storage
675    /// classes unchanged.
676    #[must_use]
677    pub const fn from_operands(left: ExprAffinity, right: ExprAffinity) -> Self {
678        match (left, right) {
679            (ExprAffinity::None, ExprAffinity::None) => Self::None,
680            (ExprAffinity::Affinity(affinity), ExprAffinity::None)
681            | (ExprAffinity::None, ExprAffinity::Affinity(affinity)) => match affinity {
682                TypeAffinity::Blob => Self::Blob,
683                TypeAffinity::Text => Self::Text,
684                TypeAffinity::Numeric => Self::Numeric,
685                TypeAffinity::Integer => Self::Integer,
686                TypeAffinity::Real => Self::Real,
687            },
688            (ExprAffinity::Affinity(left), ExprAffinity::Affinity(right)) => {
689                if matches!(
690                    left,
691                    TypeAffinity::Numeric | TypeAffinity::Integer | TypeAffinity::Real
692                ) || matches!(
693                    right,
694                    TypeAffinity::Numeric | TypeAffinity::Integer | TypeAffinity::Real
695                ) {
696                    Self::Numeric
697                } else {
698                    Self::Blob
699                }
700            }
701        }
702    }
703}
704
705/// The five fundamental SQLite storage classes.
706///
707/// Every value stored in SQLite belongs to exactly one of these classes.
708/// See <https://www.sqlite.org/datatype3.html>.
709#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
710#[repr(u8)]
711pub enum StorageClass {
712    /// SQL NULL.
713    Null = 1,
714    /// A signed 64-bit integer.
715    Integer = 2,
716    /// An IEEE 754 64-bit float.
717    Real = 3,
718    /// A UTF-8 text string.
719    Text = 4,
720    /// A binary large object.
721    Blob = 5,
722}
723
724impl fmt::Display for StorageClass {
725    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
726        match self {
727            Self::Null => f.write_str("NULL"),
728            Self::Integer => f.write_str("INTEGER"),
729            Self::Real => f.write_str("REAL"),
730            Self::Text => f.write_str("TEXT"),
731            Self::Blob => f.write_str("BLOB"),
732        }
733    }
734}
735
736/// Column types valid in STRICT tables.
737///
738/// STRICT tables enforce that every non-NULL value stored in a column matches
739/// the declared type. See <https://www.sqlite.org/stricttables.html>.
740#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
741pub enum StrictColumnType {
742    /// Only INTEGER storage class (and NULL).
743    Integer,
744    /// REAL storage class; integers are implicitly converted to REAL (and NULL).
745    Real,
746    /// Only TEXT storage class (and NULL).
747    Text,
748    /// Only BLOB storage class (and NULL).
749    Blob,
750    /// Any storage class accepted without coercion.
751    Any,
752}
753
754impl StrictColumnType {
755    /// Parse a STRICT column type from a type name string.
756    ///
757    /// Returns `None` if the type name is not a valid STRICT type.
758    /// Valid STRICT types: INT, INTEGER, REAL, TEXT, BLOB, ANY.
759    pub fn from_type_name(name: &str) -> Option<Self> {
760        match name.to_ascii_uppercase().as_str() {
761            "INT" | "INTEGER" => Some(Self::Integer),
762            "REAL" => Some(Self::Real),
763            "TEXT" => Some(Self::Text),
764            "BLOB" => Some(Self::Blob),
765            "ANY" => Some(Self::Any),
766            _ => None,
767        }
768    }
769}
770
771/// Error returned when a value violates a STRICT table column type constraint.
772#[derive(Debug, Clone, PartialEq, Eq)]
773pub struct StrictTypeError {
774    /// The expected strict column type.
775    pub expected: StrictColumnType,
776    /// The actual storage class of the value.
777    pub actual: StorageClass,
778}
779
780impl fmt::Display for StrictTypeError {
781    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
782        write!(
783            f,
784            "cannot store {} value in {:?} column",
785            self.actual, self.expected
786        )
787    }
788}
789
790/// Encoding used for text in the database.
791#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
792#[repr(u8)]
793pub enum TextEncoding {
794    /// UTF-8 encoding (the most common).
795    #[default]
796    Utf8 = 1,
797    /// UTF-16le (little-endian).
798    Utf16le = 2,
799    /// UTF-16be (big-endian).
800    Utf16be = 3,
801}
802
803impl TextEncoding {
804    /// Whether the v0.2 runtime can safely interpret and write this encoding.
805    ///
806    /// Header parsing remains format-complete for all three SQLite encoding
807    /// values so callers can distinguish valid-but-unsupported databases from
808    /// malformed headers. Runtime admission is deliberately narrower until the
809    /// value and collation layers preserve UTF-16 text bytes end to end.
810    #[must_use]
811    pub const fn is_runtime_supported(self) -> bool {
812        matches!(self, Self::Utf8)
813    }
814
815    /// Whether this encoding is supported for READ-ONLY access (bd-bld9w.3).
816    ///
817    /// UTF-8 plus UTF-16LE/BE: the record-decode layer decodes UTF-16 TEXT to
818    /// canonical UTF-8 end to end, so reading a UTF-16 database is safe. Writing
819    /// one is NOT yet supported (the record-encode path is not wired into
820    /// `MakeRecord`), so callers must still reject mutations on a database whose
821    /// encoding is not [`Self::is_runtime_supported`].
822    #[must_use]
823    pub const fn is_read_supported(self) -> bool {
824        matches!(self, Self::Utf8 | Self::Utf16le | Self::Utf16be)
825    }
826}
827
828/// Journal mode for the database connection.
829#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
830pub enum JournalMode {
831    /// Delete the rollback journal after each transaction.
832    #[default]
833    Delete,
834    /// Truncate the rollback journal to zero length.
835    Truncate,
836    /// Persist the rollback journal (don't delete, just zero the header).
837    Persist,
838    /// Store rollback journal in memory only.
839    Memory,
840    /// Write-ahead logging.
841    Wal,
842    /// Completely disable the rollback journal.
843    Off,
844}
845
846/// Synchronous mode for database writes.
847#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
848#[repr(u8)]
849pub enum SynchronousMode {
850    /// No syncs at all. Maximum speed, minimum safety.
851    Off = 0,
852    /// Sync at critical moments. Good balance.
853    Normal = 1,
854    /// Sync after each write. Maximum safety.
855    #[default]
856    Full = 2,
857    /// Like Full, but also sync the directory after creating files.
858    Extra = 3,
859}
860
861/// Lock level for database file locking (SQLite's five-state lock).
862#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
863#[repr(u8)]
864pub enum LockLevel {
865    /// No lock held.
866    #[default]
867    None = 0,
868    /// Shared lock (reading).
869    Shared = 1,
870    /// Reserved lock (intending to write).
871    Reserved = 2,
872    /// Pending lock (waiting for shared locks to clear).
873    Pending = 3,
874    /// Exclusive lock (writing).
875    Exclusive = 4,
876}
877
878/// WAL checkpoint mode.
879#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
880#[repr(u8)]
881pub enum CheckpointMode {
882    /// Checkpoint as many frames as possible without waiting.
883    Passive = 0,
884    /// Block until all frames are checkpointed.
885    Full = 1,
886    /// Like Full, then truncate the WAL file.
887    Restart = 2,
888    /// Like Restart, then truncate WAL to zero bytes.
889    Truncate = 3,
890}
891
892/// The 100-byte database file header layout.
893///
894/// This struct represents the parsed content of the first 100 bytes of a
895/// SQLite database file.
896#[derive(Debug, Clone, PartialEq, Eq)]
897pub struct DatabaseHeader {
898    /// Page size in bytes (stored as big-endian u16 at offset 16; value 1 means 65536).
899    pub page_size: PageSize,
900    /// File format write version (1 = legacy, 2 = WAL).
901    pub write_version: u8,
902    /// File format read version (1 = legacy, 2 = WAL).
903    pub read_version: u8,
904    /// Reserved bytes per page (at offset 20).
905    pub reserved_per_page: u8,
906    /// File change counter (at offset 24).
907    pub change_counter: u32,
908    /// Total number of pages in the database file.
909    pub page_count: u32,
910    /// Page number of the first freelist trunk page (0 if none).
911    pub freelist_trunk: u32,
912    /// Total number of freelist pages.
913    pub freelist_count: u32,
914    /// Schema cookie (incremented on schema changes).
915    pub schema_cookie: u32,
916    /// Schema format number (currently 4).
917    pub schema_format: u32,
918    /// Default page cache size (from `PRAGMA default_cache_size`).
919    pub default_cache_size: i32,
920    /// Largest root page number for auto-vacuum/incremental-vacuum (0 if not auto-vacuum).
921    pub largest_root_page: u32,
922    /// Database text encoding (1=UTF8, 2=UTF16le, 3=UTF16be).
923    pub text_encoding: TextEncoding,
924    /// User version (from `PRAGMA user_version`).
925    pub user_version: u32,
926    /// Non-zero for incremental vacuum mode.
927    pub incremental_vacuum: u32,
928    /// Application ID (from `PRAGMA application_id`).
929    pub application_id: u32,
930    /// Version-valid-for number (the change counter value when the version
931    /// number was stored).
932    pub version_valid_for: u32,
933    /// SQLite version number that created the database.
934    pub sqlite_version: u32,
935}
936
937impl Default for DatabaseHeader {
938    fn default() -> Self {
939        Self {
940            page_size: PageSize::DEFAULT,
941            write_version: 1,
942            read_version: 1,
943            reserved_per_page: 0,
944            change_counter: 0,
945            page_count: 0,
946            freelist_trunk: 0,
947            freelist_count: 0,
948            schema_cookie: 0,
949            schema_format: 4,
950            default_cache_size: -2000,
951            largest_root_page: 0,
952            text_encoding: TextEncoding::Utf8,
953            user_version: 0,
954            incremental_vacuum: 0,
955            application_id: 0,
956            version_valid_for: 0,
957            sqlite_version: 0,
958        }
959    }
960}
961
962/// The magic string at the start of every SQLite database file.
963pub const DATABASE_HEADER_MAGIC: &[u8; 16] = b"SQLite format 3\0";
964
965/// Size of the database file header in bytes.
966pub const DATABASE_HEADER_SIZE: usize = 100;
967
968/// Maximum SQLite file format version supported by this codebase.
969///
970/// This corresponds to WAL support (`2`). If the database header's read version exceeds this
971/// value, the database must be refused. If only the write version exceeds this value, the
972/// database may be opened read-only.
973pub const MAX_FILE_FORMAT_VERSION: u8 = 2;
974
975/// SQLite version number written into the database header for FrankenSQLite-created databases.
976///
977/// This matches SQLite 3.52.0 (`3052000`), which is the conformance target for this project.
978pub const FRANKENSQLITE_SQLITE_VERSION_NUMBER: u32 = 3_052_000;
979
980/// SQLite version string for the conformance target.
981///
982/// **Single source of truth for the version string.** All runtime paths
983/// (`sqlite_version()`, `PRAGMA sqlite_version`, harness configs) must use
984/// this constant — never use a bare `"3.52.0"` literal.
985pub const FRANKENSQLITE_SQLITE_VERSION: &str = "3.52.0";
986
987/// Full source ID string returned by `sqlite_source_id()`.
988pub const FRANKENSQLITE_SOURCE_ID: &str = "FrankenSQLite 0.1.0 (compatible with SQLite 3.52.0)";
989
990/// Database file open mode derived from the header's read/write version bytes.
991#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
992pub enum DatabaseOpenMode {
993    /// The database can be opened read-write.
994    ReadWrite,
995    /// The database can only be opened read-only (write version too new).
996    ReadOnly,
997}
998
999/// Errors that can occur while parsing or validating the 100-byte database header.
1000#[derive(Debug, Clone, PartialEq, Eq)]
1001pub enum DatabaseHeaderError {
1002    /// Magic string mismatch at bytes 0..16.
1003    InvalidMagic,
1004    /// Page size encoding was invalid.
1005    InvalidPageSize { raw: u16 },
1006    /// Embedded payload fractions (bytes 21..24) are invalid.
1007    InvalidPayloadFractions { max: u8, min: u8, leaf: u8 },
1008    /// The effective usable page size would be below the minimum allowed by SQLite (480).
1009    UsableSizeTooSmall {
1010        page_size: u32,
1011        reserved_per_page: u8,
1012        usable_size: u32,
1013    },
1014    /// Read file format version is too new to be understood.
1015    UnsupportedReadVersion { read_version: u8, max_supported: u8 },
1016    /// Text encoding field was not 1/2/3.
1017    InvalidTextEncoding { raw: u32 },
1018    /// Schema format number is unsupported.
1019    InvalidSchemaFormat { raw: u32 },
1020}
1021
1022impl fmt::Display for DatabaseHeaderError {
1023    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1024        match self {
1025            Self::InvalidMagic => f.write_str("invalid database header magic"),
1026            Self::InvalidPageSize { raw } => write!(f, "invalid page size encoding: {raw}"),
1027            Self::InvalidPayloadFractions { max, min, leaf } => write!(
1028                f,
1029                "invalid payload fractions: max={max} min={min} leaf={leaf}"
1030            ),
1031            Self::UsableSizeTooSmall {
1032                page_size,
1033                reserved_per_page,
1034                usable_size,
1035            } => write!(
1036                f,
1037                "usable page size too small: page_size={page_size} reserved={reserved_per_page} usable={usable_size}"
1038            ),
1039            Self::UnsupportedReadVersion {
1040                read_version,
1041                max_supported,
1042            } => write!(
1043                f,
1044                "unsupported read format version: read_version={read_version} max_supported={max_supported}"
1045            ),
1046            Self::InvalidTextEncoding { raw } => write!(f, "invalid text encoding: {raw}"),
1047            Self::InvalidSchemaFormat { raw } => write!(f, "invalid schema format: {raw}"),
1048        }
1049    }
1050}
1051
1052impl std::error::Error for DatabaseHeaderError {}
1053
1054impl DatabaseHeader {
1055    /// Parse and validate a 100-byte database header.
1056    pub fn from_bytes(buf: &[u8; DATABASE_HEADER_SIZE]) -> Result<Self, DatabaseHeaderError> {
1057        if &buf[..DATABASE_HEADER_MAGIC.len()] != DATABASE_HEADER_MAGIC {
1058            return Err(DatabaseHeaderError::InvalidMagic);
1059        }
1060
1061        let page_size_raw = encoding::read_u16_be(&buf[16..18]).expect("fixed u16 field");
1062        let page_size_u32 = match page_size_raw {
1063            1 => 65_536,
1064            0 => return Err(DatabaseHeaderError::InvalidPageSize { raw: page_size_raw }),
1065            n => u32::from(n),
1066        };
1067        let page_size = PageSize::new(page_size_u32)
1068            .ok_or(DatabaseHeaderError::InvalidPageSize { raw: page_size_raw })?;
1069
1070        let write_version = buf[18];
1071        let read_version = buf[19];
1072        let reserved_per_page = buf[20];
1073
1074        let max_payload = buf[21];
1075        let min_payload = buf[22];
1076        let leaf_payload = buf[23];
1077        if (max_payload, min_payload, leaf_payload) != (64, 32, 32) {
1078            return Err(DatabaseHeaderError::InvalidPayloadFractions {
1079                max: max_payload,
1080                min: min_payload,
1081                leaf: leaf_payload,
1082            });
1083        }
1084
1085        let usable_size = page_size.usable(reserved_per_page);
1086        if usable_size < 480 {
1087            return Err(DatabaseHeaderError::UsableSizeTooSmall {
1088                page_size: page_size.get(),
1089                reserved_per_page,
1090                usable_size,
1091            });
1092        }
1093
1094        // Read version governs forward compatibility: refuse if too new.
1095        if read_version > MAX_FILE_FORMAT_VERSION {
1096            return Err(DatabaseHeaderError::UnsupportedReadVersion {
1097                read_version,
1098                max_supported: MAX_FILE_FORMAT_VERSION,
1099            });
1100        }
1101
1102        let change_counter = encoding::read_u32_be(&buf[24..28]).expect("fixed u32 field");
1103        let page_count = encoding::read_u32_be(&buf[28..32]).expect("fixed u32 field");
1104        let freelist_trunk = encoding::read_u32_be(&buf[32..36]).expect("fixed u32 field");
1105        let freelist_count = encoding::read_u32_be(&buf[36..40]).expect("fixed u32 field");
1106        let schema_cookie = encoding::read_u32_be(&buf[40..44]).expect("fixed u32 field");
1107        let schema_format = encoding::read_u32_be(&buf[44..48]).expect("fixed u32 field");
1108
1109        // This project intentionally does not support legacy schema formats.
1110        // See README: "What We Deliberately Exclude".
1111        if schema_format != 4 {
1112            return Err(DatabaseHeaderError::InvalidSchemaFormat { raw: schema_format });
1113        }
1114
1115        let default_cache_size = encoding::read_i32_be(&buf[48..52]).expect("fixed i32 field");
1116        let largest_root_page = encoding::read_u32_be(&buf[52..56]).expect("fixed u32 field");
1117
1118        let text_encoding_raw = encoding::read_u32_be(&buf[56..60]).expect("fixed u32 field");
1119        let text_encoding = match text_encoding_raw {
1120            1 => TextEncoding::Utf8,
1121            2 => TextEncoding::Utf16le,
1122            3 => TextEncoding::Utf16be,
1123            _ => {
1124                return Err(DatabaseHeaderError::InvalidTextEncoding {
1125                    raw: text_encoding_raw,
1126                });
1127            }
1128        };
1129
1130        let user_version = encoding::read_u32_be(&buf[60..64]).expect("fixed u32 field");
1131        let incremental_vacuum = encoding::read_u32_be(&buf[64..68]).expect("fixed u32 field");
1132        let application_id = encoding::read_u32_be(&buf[68..72]).expect("fixed u32 field");
1133        let version_valid_for = encoding::read_u32_be(&buf[92..96]).expect("fixed u32 field");
1134        let sqlite_version = encoding::read_u32_be(&buf[96..100]).expect("fixed u32 field");
1135
1136        Ok(Self {
1137            page_size,
1138            write_version,
1139            read_version,
1140            reserved_per_page,
1141            change_counter,
1142            page_count,
1143            freelist_trunk,
1144            freelist_count,
1145            schema_cookie,
1146            schema_format,
1147            default_cache_size,
1148            largest_root_page,
1149            text_encoding,
1150            user_version,
1151            incremental_vacuum,
1152            application_id,
1153            version_valid_for,
1154            sqlite_version,
1155        })
1156    }
1157
1158    /// Compute the open mode implied by the header's read/write version bytes.
1159    pub const fn open_mode(
1160        &self,
1161        max_supported: u8,
1162    ) -> Result<DatabaseOpenMode, DatabaseHeaderError> {
1163        if self.read_version > max_supported {
1164            return Err(DatabaseHeaderError::UnsupportedReadVersion {
1165                read_version: self.read_version,
1166                max_supported,
1167            });
1168        }
1169        if self.write_version > max_supported {
1170            return Ok(DatabaseOpenMode::ReadOnly);
1171        }
1172        Ok(DatabaseOpenMode::ReadWrite)
1173    }
1174
1175    /// Check whether the header-derived database size might be stale.
1176    ///
1177    /// When `version_valid_for != change_counter`, header-derived fields
1178    /// like `page_count` may be stale and should be recomputed from the
1179    /// actual file size. This protects against partial header writes or
1180    /// external modification.
1181    pub const fn is_page_count_stale(&self) -> bool {
1182        self.version_valid_for != self.change_counter
1183    }
1184
1185    /// Compute the page count from the actual file size.
1186    ///
1187    /// This should be used when `is_page_count_stale()` returns true.
1188    /// Returns `None` if the file size is not a multiple of the page size
1189    /// or would exceed `u32::MAX` pages.
1190    #[allow(clippy::cast_possible_truncation)]
1191    pub const fn page_count_from_file_size(&self, file_size: u64) -> Option<u32> {
1192        let ps = self.page_size.get() as u64;
1193        if file_size == 0 || !file_size.is_multiple_of(ps) {
1194            return None;
1195        }
1196        let count = file_size / ps;
1197        if count > u32::MAX as u64 {
1198            return None;
1199        }
1200        Some(count as u32)
1201    }
1202
1203    /// Serialize this header into a 100-byte buffer.
1204    pub fn write_to_bytes(
1205        &self,
1206        out: &mut [u8; DATABASE_HEADER_SIZE],
1207    ) -> Result<(), DatabaseHeaderError> {
1208        // Validate invariants we rely on for interoperability.
1209        if self.schema_format != 4 {
1210            return Err(DatabaseHeaderError::InvalidSchemaFormat {
1211                raw: self.schema_format,
1212            });
1213        }
1214
1215        let usable_size = self.page_size.usable(self.reserved_per_page);
1216        if usable_size < 480 {
1217            return Err(DatabaseHeaderError::UsableSizeTooSmall {
1218                page_size: self.page_size.get(),
1219                reserved_per_page: self.reserved_per_page,
1220                usable_size,
1221            });
1222        }
1223
1224        out.fill(0);
1225        out[..DATABASE_HEADER_MAGIC.len()].copy_from_slice(DATABASE_HEADER_MAGIC);
1226
1227        // Page size (big-endian u16) where 1 encodes 65536.
1228        let page_size_raw = if self.page_size.get() == 65_536 {
1229            1u16
1230        } else {
1231            #[allow(clippy::cast_possible_truncation)]
1232            {
1233                self.page_size.get() as u16
1234            }
1235        };
1236        encoding::write_u16_be(&mut out[16..18], page_size_raw).expect("fixed u16 field");
1237
1238        out[18] = self.write_version;
1239        out[19] = self.read_version;
1240        out[20] = self.reserved_per_page;
1241
1242        // Payload fractions must be 64/32/32.
1243        out[21] = 64;
1244        out[22] = 32;
1245        out[23] = 32;
1246
1247        encoding::write_u32_be(&mut out[24..28], self.change_counter).expect("fixed u32 field");
1248        encoding::write_u32_be(&mut out[28..32], self.page_count).expect("fixed u32 field");
1249        encoding::write_u32_be(&mut out[32..36], self.freelist_trunk).expect("fixed u32 field");
1250        encoding::write_u32_be(&mut out[36..40], self.freelist_count).expect("fixed u32 field");
1251        encoding::write_u32_be(&mut out[40..44], self.schema_cookie).expect("fixed u32 field");
1252        encoding::write_u32_be(&mut out[44..48], self.schema_format).expect("fixed u32 field");
1253        encoding::write_i32_be(&mut out[48..52], self.default_cache_size).expect("fixed i32 field");
1254        encoding::write_u32_be(&mut out[52..56], self.largest_root_page).expect("fixed u32 field");
1255
1256        let text_encoding_u32 = match self.text_encoding {
1257            TextEncoding::Utf8 => 1u32,
1258            TextEncoding::Utf16le => 2u32,
1259            TextEncoding::Utf16be => 3u32,
1260        };
1261        encoding::write_u32_be(&mut out[56..60], text_encoding_u32).expect("fixed u32 field");
1262
1263        encoding::write_u32_be(&mut out[60..64], self.user_version).expect("fixed u32 field");
1264        encoding::write_u32_be(&mut out[64..68], self.incremental_vacuum).expect("fixed u32 field");
1265        encoding::write_u32_be(&mut out[68..72], self.application_id).expect("fixed u32 field");
1266
1267        // Bytes 72..92 are reserved for future expansion. We always write zeros.
1268        encoding::write_u32_be(&mut out[92..96], self.version_valid_for).expect("fixed u32 field");
1269        encoding::write_u32_be(&mut out[96..100], self.sqlite_version).expect("fixed u32 field");
1270
1271        Ok(())
1272    }
1273
1274    /// Serialize this header to bytes.
1275    pub fn to_bytes(&self) -> Result<[u8; DATABASE_HEADER_SIZE], DatabaseHeaderError> {
1276        let mut out = [0u8; DATABASE_HEADER_SIZE];
1277        self.write_to_bytes(&mut out)?;
1278        Ok(out)
1279    }
1280}
1281
1282/// Maximum number of fragmented free bytes allowed on a B-tree page header.
1283pub const BTREE_MAX_FRAGMENTED_FREE_BYTES: u8 = 60;
1284
1285/// Errors that can occur while parsing B-tree page layout structures.
1286#[derive(Debug, Clone, PartialEq, Eq)]
1287pub enum BTreePageError {
1288    /// Page buffer did not match the expected page size.
1289    PageSizeMismatch { expected: usize, actual: usize },
1290    /// Page did not have enough bytes to read the header.
1291    PageTooSmall { usable_size: usize, needed: usize },
1292    /// Unknown B-tree page type byte.
1293    InvalidPageType { raw: u8 },
1294    /// Fragmented free bytes exceeds the maximum allowed.
1295    InvalidFragmentedFreeBytes { raw: u8, max: u8 },
1296    /// Cell content area start offset was invalid for this page.
1297    InvalidCellContentAreaStart {
1298        raw: u16,
1299        decoded: u32,
1300        usable_size: usize,
1301    },
1302    /// Cell content area begins before the end of the cell pointer array.
1303    CellContentAreaOverlapsCellPointers {
1304        cell_content_start: u32,
1305        cell_pointer_array_end: usize,
1306    },
1307    /// Cell pointer array extends past the usable page area.
1308    CellPointerArrayOutOfBounds {
1309        start: usize,
1310        len: usize,
1311        usable_size: usize,
1312    },
1313    /// A cell pointer was invalid.
1314    InvalidCellPointer {
1315        index: usize,
1316        offset: u16,
1317        usable_size: usize,
1318    },
1319    /// Freeblock offset/size was invalid.
1320    InvalidFreeblock {
1321        offset: u16,
1322        size: u16,
1323        usable_size: usize,
1324    },
1325    /// Freeblock list contained a loop.
1326    FreeblockLoop { offset: u16 },
1327    /// Interior page right-most child pointer was invalid.
1328    InvalidRightMostChild { raw: u32 },
1329}
1330
1331impl fmt::Display for BTreePageError {
1332    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1333        match self {
1334            Self::PageSizeMismatch { expected, actual } => write!(
1335                f,
1336                "page size mismatch: expected {expected} bytes, got {actual} bytes"
1337            ),
1338            Self::PageTooSmall {
1339                usable_size,
1340                needed,
1341            } => write!(
1342                f,
1343                "page too small: usable_size={usable_size} needed={needed}"
1344            ),
1345            Self::InvalidPageType { raw } => write!(f, "invalid B-tree page type: {raw:#04x}"),
1346            Self::InvalidFragmentedFreeBytes { raw, max } => {
1347                write!(f, "invalid fragmented free bytes: {raw} (max {max})")
1348            }
1349            Self::InvalidCellContentAreaStart {
1350                raw,
1351                decoded,
1352                usable_size,
1353            } => write!(
1354                f,
1355                "invalid cell content area start: raw={raw} decoded={decoded} usable_size={usable_size}"
1356            ),
1357            Self::CellContentAreaOverlapsCellPointers {
1358                cell_content_start,
1359                cell_pointer_array_end,
1360            } => write!(
1361                f,
1362                "cell content area overlaps cell pointer array: cell_content_start={cell_content_start} cell_pointer_array_end={cell_pointer_array_end}"
1363            ),
1364            Self::CellPointerArrayOutOfBounds {
1365                start,
1366                len,
1367                usable_size,
1368            } => write!(
1369                f,
1370                "cell pointer array out of bounds: start={start} len={len} usable_size={usable_size}"
1371            ),
1372            Self::InvalidCellPointer {
1373                index,
1374                offset,
1375                usable_size,
1376            } => write!(
1377                f,
1378                "invalid cell pointer: index={index} offset={offset} usable_size={usable_size}"
1379            ),
1380            Self::InvalidFreeblock {
1381                offset,
1382                size,
1383                usable_size,
1384            } => write!(
1385                f,
1386                "invalid freeblock: offset={offset} size={size} usable_size={usable_size}"
1387            ),
1388            Self::FreeblockLoop { offset } => write!(f, "freeblock loop at offset {offset}"),
1389            Self::InvalidRightMostChild { raw } => {
1390                write!(f, "invalid right-most child pointer: {raw}")
1391            }
1392        }
1393    }
1394}
1395
1396impl std::error::Error for BTreePageError {}
1397
1398/// Parsed B-tree page header.
1399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1400pub struct BTreePageHeader {
1401    /// Offset within the page where the B-tree page header begins (0 normally, 100 for page 1).
1402    pub header_offset: usize,
1403    /// Page type.
1404    pub page_type: BTreePageType,
1405    /// Offset of the first freeblock in the freeblock list (0 if none).
1406    pub first_freeblock: u16,
1407    /// Number of cells on this page.
1408    pub cell_count: u16,
1409    /// Start of cell content area. A raw value of 0 decodes to 65536.
1410    pub cell_content_start: u32,
1411    /// Count of fragmented free bytes on this page.
1412    pub fragmented_free_bytes: u8,
1413    /// Right-most child page number for interior pages.
1414    pub right_most_child: Option<PageNumber>,
1415}
1416
1417impl BTreePageHeader {
1418    /// Size of the B-tree page header in bytes (8 for leaf, 12 for interior).
1419    pub const fn header_size(self) -> usize {
1420        if self.page_type.is_leaf() { 8 } else { 12 }
1421    }
1422
1423    /// Parse a B-tree page header from a page buffer.
1424    pub fn parse(
1425        page: &[u8],
1426        page_size: PageSize,
1427        reserved_per_page: u8,
1428        is_page1: bool,
1429    ) -> Result<Self, BTreePageError> {
1430        let expected = page_size.as_usize();
1431        if page.len() != expected {
1432            return Err(BTreePageError::PageSizeMismatch {
1433                expected,
1434                actual: page.len(),
1435            });
1436        }
1437
1438        let usable_size = page_size.usable(reserved_per_page) as usize;
1439        let header_offset = if is_page1 { DATABASE_HEADER_SIZE } else { 0 };
1440        let min_needed = header_offset + 8;
1441        if usable_size < min_needed {
1442            return Err(BTreePageError::PageTooSmall {
1443                usable_size,
1444                needed: min_needed,
1445            });
1446        }
1447
1448        let page_type_raw = page[header_offset];
1449        let page_type = BTreePageType::from_byte(page_type_raw)
1450            .ok_or(BTreePageError::InvalidPageType { raw: page_type_raw })?;
1451
1452        let header_size = if page_type.is_leaf() { 8 } else { 12 };
1453        let needed = header_offset + header_size;
1454        if usable_size < needed {
1455            return Err(BTreePageError::PageTooSmall {
1456                usable_size,
1457                needed,
1458            });
1459        }
1460
1461        let first_freeblock =
1462            u16::from_be_bytes([page[header_offset + 1], page[header_offset + 2]]);
1463        let cell_count = u16::from_be_bytes([page[header_offset + 3], page[header_offset + 4]]);
1464        let cell_content_raw =
1465            u16::from_be_bytes([page[header_offset + 5], page[header_offset + 6]]);
1466        let cell_content_start = if cell_content_raw == 0 {
1467            65_536
1468        } else {
1469            u32::from(cell_content_raw)
1470        };
1471        let usable_size_u32 = u32::try_from(usable_size).unwrap_or(u32::MAX);
1472        if cell_content_start > usable_size_u32 {
1473            return Err(BTreePageError::InvalidCellContentAreaStart {
1474                raw: cell_content_raw,
1475                decoded: cell_content_start,
1476                usable_size,
1477            });
1478        }
1479
1480        let fragmented_free_bytes = page[header_offset + 7];
1481        if fragmented_free_bytes > BTREE_MAX_FRAGMENTED_FREE_BYTES {
1482            return Err(BTreePageError::InvalidFragmentedFreeBytes {
1483                raw: fragmented_free_bytes,
1484                max: BTREE_MAX_FRAGMENTED_FREE_BYTES,
1485            });
1486        }
1487
1488        let right_most_child = if page_type.is_interior() {
1489            let raw = u32::from_be_bytes([
1490                page[header_offset + 8],
1491                page[header_offset + 9],
1492                page[header_offset + 10],
1493                page[header_offset + 11],
1494            ]);
1495            let pn = PageNumber::new(raw).ok_or(BTreePageError::InvalidRightMostChild { raw })?;
1496            Some(pn)
1497        } else {
1498            None
1499        };
1500
1501        // Ensure the cell pointer array is within the usable page area.
1502        let ptr_array_start = header_offset + header_size;
1503        let ptr_array_len = usize::from(cell_count) * 2;
1504        if ptr_array_start + ptr_array_len > usable_size {
1505            return Err(BTreePageError::CellPointerArrayOutOfBounds {
1506                start: ptr_array_start,
1507                len: ptr_array_len,
1508                usable_size,
1509            });
1510        }
1511        let ptr_array_end = ptr_array_start + ptr_array_len;
1512        let ptr_array_end_u32 = u32::try_from(ptr_array_end).unwrap_or(u32::MAX);
1513        if cell_content_start < ptr_array_end_u32 {
1514            return Err(BTreePageError::CellContentAreaOverlapsCellPointers {
1515                cell_content_start,
1516                cell_pointer_array_end: ptr_array_end,
1517            });
1518        }
1519
1520        Ok(Self {
1521            header_offset,
1522            page_type,
1523            first_freeblock,
1524            cell_count,
1525            cell_content_start,
1526            fragmented_free_bytes,
1527            right_most_child,
1528        })
1529    }
1530
1531    /// Parse the cell pointer array for this page.
1532    pub fn parse_cell_pointers(
1533        self,
1534        page: &[u8],
1535        page_size: PageSize,
1536        reserved_per_page: u8,
1537    ) -> Result<Vec<u16>, BTreePageError> {
1538        let expected = page_size.as_usize();
1539        if page.len() != expected {
1540            return Err(BTreePageError::PageSizeMismatch {
1541                expected,
1542                actual: page.len(),
1543            });
1544        }
1545
1546        let usable_size = page_size.usable(reserved_per_page) as usize;
1547        let ptr_array_start = self.header_offset + self.header_size();
1548        let ptr_array_len = usize::from(self.cell_count) * 2;
1549        if ptr_array_start + ptr_array_len > usable_size {
1550            return Err(BTreePageError::CellPointerArrayOutOfBounds {
1551                start: ptr_array_start,
1552                len: ptr_array_len,
1553                usable_size,
1554            });
1555        }
1556
1557        let min_cell_offset = ptr_array_start + ptr_array_len;
1558        let mut out = Vec::with_capacity(self.cell_count as usize);
1559        for i in 0..self.cell_count as usize {
1560            let off = ptr_array_start + i * 2;
1561            let cell_off = u16::from_be_bytes([page[off], page[off + 1]]);
1562            let cell_off_usize = usize::from(cell_off);
1563            if cell_off_usize < min_cell_offset
1564                || cell_off_usize < self.cell_content_start as usize
1565                || cell_off_usize >= usable_size
1566            {
1567                return Err(BTreePageError::InvalidCellPointer {
1568                    index: i,
1569                    offset: cell_off,
1570                    usable_size,
1571                });
1572            }
1573            out.push(cell_off);
1574        }
1575        Ok(out)
1576    }
1577
1578    /// Traverse and parse the freeblock list for this page.
1579    pub fn parse_freeblocks(
1580        self,
1581        page: &[u8],
1582        page_size: PageSize,
1583        reserved_per_page: u8,
1584    ) -> Result<Vec<Freeblock>, BTreePageError> {
1585        let expected = page_size.as_usize();
1586        if page.len() != expected {
1587            return Err(BTreePageError::PageSizeMismatch {
1588                expected,
1589                actual: page.len(),
1590            });
1591        }
1592        let usable_size = page_size.usable(reserved_per_page) as usize;
1593
1594        let mut blocks = Vec::new();
1595        let mut seen = std::collections::BTreeSet::new();
1596        let mut offset = self.first_freeblock;
1597        while offset != 0 {
1598            if !seen.insert(offset) {
1599                return Err(BTreePageError::FreeblockLoop { offset });
1600            }
1601
1602            let off = usize::from(offset);
1603            if off < self.cell_content_start as usize {
1604                return Err(BTreePageError::InvalidFreeblock {
1605                    offset,
1606                    size: 0,
1607                    usable_size,
1608                });
1609            }
1610            if off + 4 > usable_size {
1611                return Err(BTreePageError::InvalidFreeblock {
1612                    offset,
1613                    size: 0,
1614                    usable_size,
1615                });
1616            }
1617
1618            let next = u16::from_be_bytes([page[off], page[off + 1]]);
1619            let size = u16::from_be_bytes([page[off + 2], page[off + 3]]);
1620            if size < 4 || off + usize::from(size) > usable_size {
1621                return Err(BTreePageError::InvalidFreeblock {
1622                    offset,
1623                    size,
1624                    usable_size,
1625                });
1626            }
1627
1628            blocks.push(Freeblock { offset, next, size });
1629            offset = next;
1630        }
1631
1632        Ok(blocks)
1633    }
1634
1635    /// Write an empty leaf-table B-tree page header into a buffer.
1636    ///
1637    /// Sets up the 8-byte B-tree page header for an empty leaf table page
1638    /// (type `0x0D`) with zero cells, suitable for `sqlite_master` or any
1639    /// newly created table root page.
1640    ///
1641    /// `header_offset` is the byte offset of the B-tree header within the
1642    /// page buffer.  For page 1 this must be [`DATABASE_HEADER_SIZE`] (100);
1643    /// for every other page it should be 0.
1644    ///
1645    /// `usable_size` equals `page_size − reserved_per_page`.  The cell
1646    /// content area offset is set to this value so that all usable space is
1647    /// available for future cell insertions.
1648    #[allow(clippy::cast_possible_truncation)]
1649    pub fn write_empty_leaf_table(page: &mut [u8], header_offset: usize, usable_size: u32) {
1650        page[header_offset] = BTreePageType::LeafTable as u8; // 0x0D
1651        // first_freeblock = 0 (no freeblocks)
1652        page[header_offset + 1] = 0;
1653        page[header_offset + 2] = 0;
1654        // cell_count = 0
1655        page[header_offset + 3] = 0;
1656        page[header_offset + 4] = 0;
1657        // cell content area offset (0 encodes 65536)
1658        let content_raw = if usable_size >= 65_536 {
1659            0u16
1660        } else {
1661            usable_size as u16
1662        };
1663        page[header_offset + 5..header_offset + 7].copy_from_slice(&content_raw.to_be_bytes());
1664        // fragmented_free_bytes = 0
1665        page[header_offset + 7] = 0;
1666    }
1667
1668    /// Initialize an empty leaf index page (type `0x0A`) with zero cells,
1669    /// suitable for a newly created index root page.
1670    ///
1671    /// `header_offset` is the byte offset of the B-tree header within the
1672    /// page buffer (0 for all non-page-1 pages).
1673    ///
1674    /// `usable_size` equals `page_size − reserved_per_page`.
1675    #[allow(clippy::cast_possible_truncation)]
1676    pub fn write_empty_leaf_index(page: &mut [u8], header_offset: usize, usable_size: u32) {
1677        page[header_offset] = BTreePageType::LeafIndex as u8; // 0x0A
1678        // first_freeblock = 0 (no freeblocks)
1679        page[header_offset + 1] = 0;
1680        page[header_offset + 2] = 0;
1681        // cell_count = 0
1682        page[header_offset + 3] = 0;
1683        page[header_offset + 4] = 0;
1684        // cell content area offset (0 encodes 65536)
1685        let content_raw = if usable_size >= 65_536 {
1686            0u16
1687        } else {
1688            usable_size as u16
1689        };
1690        page[header_offset + 5..header_offset + 7].copy_from_slice(&content_raw.to_be_bytes());
1691        // fragmented_free_bytes = 0
1692        page[header_offset + 7] = 0;
1693    }
1694}
1695
1696/// A freeblock entry in a B-tree page freeblock list.
1697#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1698pub struct Freeblock {
1699    pub offset: u16,
1700    pub next: u16,
1701    pub size: u16,
1702}
1703
1704/// Determine if adding `additional` fragmented bytes would exceed the maximum allowed.
1705pub const fn would_exceed_fragmented_free_bytes(current: u8, additional: u8) -> bool {
1706    current.saturating_add(additional) > BTREE_MAX_FRAGMENTED_FREE_BYTES
1707}
1708
1709/// B-tree page types.
1710#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1711#[repr(u8)]
1712pub enum BTreePageType {
1713    /// Interior index B-tree page.
1714    InteriorIndex = 2,
1715    /// Interior table B-tree page.
1716    InteriorTable = 5,
1717    /// Leaf index B-tree page.
1718    LeafIndex = 10,
1719    /// Leaf table B-tree page.
1720    LeafTable = 13,
1721}
1722
1723impl BTreePageType {
1724    /// Parse from the raw byte value at the start of a B-tree page header.
1725    pub const fn from_byte(b: u8) -> Option<Self> {
1726        match b {
1727            2 => Some(Self::InteriorIndex),
1728            5 => Some(Self::InteriorTable),
1729            10 => Some(Self::LeafIndex),
1730            13 => Some(Self::LeafTable),
1731            _ => None,
1732        }
1733    }
1734
1735    /// Whether this is a leaf page (no children).
1736    pub const fn is_leaf(self) -> bool {
1737        matches!(self, Self::LeafIndex | Self::LeafTable)
1738    }
1739
1740    /// Whether this is an interior (non-leaf) page.
1741    pub const fn is_interior(self) -> bool {
1742        matches!(self, Self::InteriorIndex | Self::InteriorTable)
1743    }
1744
1745    /// Whether this is a table B-tree (INTKEY) page.
1746    pub const fn is_table(self) -> bool {
1747        matches!(self, Self::InteriorTable | Self::LeafTable)
1748    }
1749
1750    /// Whether this is an index B-tree (BLOBKEY) page.
1751    pub const fn is_index(self) -> bool {
1752        matches!(self, Self::InteriorIndex | Self::LeafIndex)
1753    }
1754}
1755
1756#[cfg(test)]
1757mod tests {
1758    use super::*;
1759    use crate::value::SmallText;
1760
1761    #[test]
1762    fn page_number_zero_is_invalid() {
1763        assert!(PageNumber::new(0).is_none());
1764        assert!(PageNumber::try_from(0u32).is_err());
1765    }
1766
1767    #[test]
1768    fn test_page_number_zero_rejected() {
1769        assert!(PageNumber::new(0).is_none());
1770        assert!(PageNumber::try_from(0u32).is_err());
1771    }
1772
1773    #[test]
1774    fn page_number_max_u32_is_invalid() {
1775        assert!(PageNumber::new(u32::MAX).is_none());
1776        assert!(PageNumber::try_from(u32::MAX).is_err());
1777        assert_eq!(
1778            PageNumber::new(u32::MAX - 1)
1779                .expect("SQLite maximum page number should be valid")
1780                .get(),
1781            u32::MAX - 1
1782        );
1783    }
1784
1785    #[test]
1786    fn page_number_serde_preserves_constructor_invariant() {
1787        let max =
1788            PageNumber::new(u32::MAX - 1).expect("SQLite maximum page number should be valid");
1789        let encoded = serde_json::to_string(&max).expect("PageNumber should serialize as a u32");
1790        assert_eq!(encoded, (u32::MAX - 1).to_string());
1791        assert_eq!(
1792            serde_json::from_str::<PageNumber>(&encoded)
1793                .expect("valid serialized PageNumber should decode"),
1794            max
1795        );
1796
1797        let err = serde_json::from_str::<PageNumber>(&u32::MAX.to_string())
1798            .expect_err("serde must reject page numbers outside SQLite's valid range");
1799        assert!(
1800            err.to_string().contains("SQLite page number"),
1801            "unexpected serde error: {err}"
1802        );
1803    }
1804
1805    #[test]
1806    fn page_number_valid() {
1807        let pn = PageNumber::new(1).unwrap();
1808        assert_eq!(pn.get(), 1);
1809        assert_eq!(pn, PageNumber::ONE);
1810
1811        let pn = PageNumber::new(42).unwrap();
1812        assert_eq!(pn.get(), 42);
1813        assert_eq!(pn.to_string(), "42");
1814    }
1815
1816    #[test]
1817    fn page_number_ordering() {
1818        let a = PageNumber::new(1).unwrap();
1819        let b = PageNumber::new(100).unwrap();
1820        assert!(a < b);
1821    }
1822
1823    #[test]
1824    fn page_size_validation() {
1825        assert!(PageSize::new(0).is_none());
1826        assert!(PageSize::new(256).is_none());
1827        assert!(PageSize::new(511).is_none());
1828        assert!(PageSize::new(513).is_none());
1829        assert!(PageSize::new(1000).is_none());
1830        assert!(PageSize::new(131_072).is_none());
1831
1832        assert!(PageSize::new(512).is_some());
1833        assert!(PageSize::new(1024).is_some());
1834        assert!(PageSize::new(4096).is_some());
1835        assert!(PageSize::new(8192).is_some());
1836        assert!(PageSize::new(16384).is_some());
1837        assert!(PageSize::new(32768).is_some());
1838        assert!(PageSize::new(65536).is_some());
1839    }
1840
1841    #[test]
1842    fn page_size_defaults() {
1843        assert_eq!(PageSize::DEFAULT.get(), 4096);
1844        assert_eq!(PageSize::MIN.get(), 512);
1845        assert_eq!(PageSize::MAX.get(), 65536);
1846        assert_eq!(PageSize::default(), PageSize::DEFAULT);
1847    }
1848
1849    #[test]
1850    fn page_data_clone_promotes_owned_bytes_to_shared_snapshot() {
1851        let page = PageData::from_vec(vec![1, 2, 3, 4]);
1852        let PageDataRepr::Owned { shared, .. } = &page.repr else {
1853            panic!("fresh page data should start owned");
1854        };
1855        assert!(
1856            shared.get().is_none(),
1857            "fresh page should not allocate Arc eagerly"
1858        );
1859
1860        let cloned = page.clone();
1861
1862        let PageDataRepr::Owned { shared, .. } = &page.repr else {
1863            panic!("original page should remain in owned mode");
1864        };
1865        assert!(
1866            shared.get().is_some(),
1867            "first clone should materialize a shared snapshot lazily"
1868        );
1869        assert!(
1870            matches!(cloned.repr, PageDataRepr::Shared(_)),
1871            "clone should observe the shared snapshot"
1872        );
1873    }
1874
1875    #[test]
1876    fn page_data_mutation_reuses_owned_bytes_after_snapshot_clone() {
1877        let mut page = PageData::from_vec(vec![9, 8, 7, 6]);
1878        let snapshot = page.clone();
1879
1880        page.as_bytes_mut()[0] = 1;
1881
1882        assert_eq!(snapshot.as_bytes(), &[9, 8, 7, 6]);
1883        assert_eq!(page.as_bytes(), &[1, 8, 7, 6]);
1884        assert!(
1885            matches!(page.repr, PageDataRepr::Owned { .. }),
1886            "mutating the original owner should stay on its owned bytes"
1887        );
1888        let PageDataRepr::Owned { shared, .. } = &page.repr else {
1889            panic!("mutated page should remain in owned mode");
1890        };
1891        assert!(
1892            shared.get().is_none(),
1893            "mutating the original owner must invalidate the stale shared snapshot cache so later clones observe the new bytes"
1894        );
1895    }
1896
1897    #[test]
1898    fn page_data_clone_after_owner_mutation_observes_latest_bytes() {
1899        let mut page = PageData::from_vec(vec![9, 8, 7, 6]);
1900        let first_snapshot = page.clone();
1901
1902        page.as_bytes_mut()[0] = 1;
1903        let second_snapshot = page.clone();
1904
1905        assert_eq!(first_snapshot.as_bytes(), &[9, 8, 7, 6]);
1906        assert_eq!(second_snapshot.as_bytes(), &[1, 8, 7, 6]);
1907        assert_eq!(page.as_bytes(), &[1, 8, 7, 6]);
1908    }
1909
1910    #[test]
1911    fn page_data_image_token_tracks_clone_and_mutation_boundaries() {
1912        let mut page = PageData::from_vec(vec![9, 8, 7, 6]);
1913        let original_token = page.image_token();
1914        let snapshot = page.clone();
1915
1916        assert_eq!(
1917            snapshot.image_token(),
1918            original_token,
1919            "immutable clones must share the same page-image token"
1920        );
1921
1922        page.as_bytes_mut()[0] = 1;
1923        assert_ne!(
1924            page.image_token(),
1925            original_token,
1926            "mutable access must move the owner to a fresh page-image token"
1927        );
1928        assert_eq!(
1929            snapshot.image_token(),
1930            original_token,
1931            "old snapshots retain the old image token"
1932        );
1933
1934        let second_snapshot = page.clone();
1935        assert_eq!(
1936            second_snapshot.image_token(),
1937            page.image_token(),
1938            "new snapshots observe the latest token"
1939        );
1940    }
1941
1942    #[test]
1943    fn page_data_try_zero_extend_owned_to_preserves_owned_bytes_and_invalidates_stale_snapshot() {
1944        let mut page = PageData::from_vec(vec![9, 8, 7, 6]);
1945        let snapshot = page.clone();
1946        let original_token = page.image_token();
1947
1948        assert!(page.try_zero_extend_owned_to(8));
1949        assert_eq!(page.as_bytes(), &[9, 8, 7, 6, 0, 0, 0, 0]);
1950        assert_eq!(snapshot.as_bytes(), &[9, 8, 7, 6]);
1951        assert_ne!(
1952            page.image_token(),
1953            original_token,
1954            "zero extension mutates the page image and must bump the token"
1955        );
1956        assert!(
1957            matches!(page.repr, PageDataRepr::Owned { .. }),
1958            "zero-extending an owned page should stay on the owned representation"
1959        );
1960        let PageDataRepr::Owned { shared, .. } = &page.repr else {
1961            panic!("zero-extended page should remain owned");
1962        };
1963        assert!(
1964            shared.get().is_none(),
1965            "zero-extending must invalidate any stale shared snapshot cache"
1966        );
1967    }
1968
1969    #[test]
1970    fn page_data_try_zero_extend_owned_to_returns_false_for_shared_pages() {
1971        let original = PageData::from_vec(vec![1, 2, 3, 4]);
1972        let mut shared = original.clone();
1973
1974        assert!(!shared.try_zero_extend_owned_to(8));
1975        assert_eq!(shared.as_bytes(), &[1, 2, 3, 4]);
1976    }
1977
1978    fn make_header_for_tests() -> DatabaseHeader {
1979        DatabaseHeader {
1980            page_size: PageSize::DEFAULT,
1981            write_version: 2,
1982            read_version: 2,
1983            reserved_per_page: 0,
1984            change_counter: 7,
1985            page_count: 123,
1986            freelist_trunk: 0,
1987            freelist_count: 0,
1988            schema_cookie: 1,
1989            schema_format: 4,
1990            default_cache_size: -2000,
1991            largest_root_page: 0,
1992            text_encoding: TextEncoding::Utf8,
1993            user_version: 0,
1994            incremental_vacuum: 0,
1995            application_id: 0,
1996            version_valid_for: 7,
1997            sqlite_version: FRANKENSQLITE_SQLITE_VERSION_NUMBER,
1998        }
1999    }
2000
2001    #[test]
2002    fn test_header_magic_validation() {
2003        let hdr = make_header_for_tests();
2004        let mut buf = hdr.to_bytes().unwrap();
2005        let parsed = DatabaseHeader::from_bytes(&buf).unwrap();
2006        assert_eq!(parsed, hdr);
2007
2008        buf[0] = b'X';
2009        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2010        assert!(matches!(err, DatabaseHeaderError::InvalidMagic));
2011    }
2012
2013    #[test]
2014    fn test_header_page_size_encoding() {
2015        // 65536 is encoded as 1.
2016        let mut hdr = make_header_for_tests();
2017        hdr.page_size = PageSize::new(65_536).unwrap();
2018        let buf = hdr.to_bytes().unwrap();
2019        assert_eq!(u16::from_be_bytes([buf[16], buf[17]]), 1);
2020        assert_eq!(
2021            DatabaseHeader::from_bytes(&buf).unwrap().page_size.get(),
2022            65_536
2023        );
2024
2025        // Typical values are stored literally.
2026        for size in [512u32, 1024, 2048, 4096, 8192, 16_384, 32_768] {
2027            hdr.page_size = PageSize::new(size).unwrap();
2028            let buf = hdr.to_bytes().unwrap();
2029            let expected_u16 = u16::try_from(size).unwrap();
2030            assert_eq!(u16::from_be_bytes([buf[16], buf[17]]), expected_u16);
2031            assert_eq!(
2032                DatabaseHeader::from_bytes(&buf).unwrap().page_size.get(),
2033                size
2034            );
2035        }
2036
2037        // Non power-of-two rejected.
2038        let mut buf = make_header_for_tests().to_bytes().unwrap();
2039        buf[16..18].copy_from_slice(&1000u16.to_be_bytes());
2040        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2041        assert!(matches!(err, DatabaseHeaderError::InvalidPageSize { .. }));
2042    }
2043
2044    #[test]
2045    fn test_header_page_size_range() {
2046        let mut buf = make_header_for_tests().to_bytes().unwrap();
2047        buf[16..18].copy_from_slice(&256u16.to_be_bytes());
2048        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2049        assert!(matches!(err, DatabaseHeaderError::InvalidPageSize { .. }));
2050    }
2051
2052    #[test]
2053    fn test_header_write_read_version() {
2054        let mut hdr = make_header_for_tests();
2055
2056        hdr.write_version = 2;
2057        hdr.read_version = 2;
2058        assert_eq!(
2059            hdr.open_mode(MAX_FILE_FORMAT_VERSION).unwrap(),
2060            DatabaseOpenMode::ReadWrite
2061        );
2062
2063        hdr.read_version = 3;
2064        let err = hdr.open_mode(MAX_FILE_FORMAT_VERSION).unwrap_err();
2065        assert!(matches!(
2066            err,
2067            DatabaseHeaderError::UnsupportedReadVersion { .. }
2068        ));
2069
2070        hdr.read_version = 2;
2071        hdr.write_version = 3;
2072        assert_eq!(
2073            hdr.open_mode(MAX_FILE_FORMAT_VERSION).unwrap(),
2074            DatabaseOpenMode::ReadOnly
2075        );
2076    }
2077
2078    #[test]
2079    fn test_header_payload_fractions() {
2080        let mut buf = make_header_for_tests().to_bytes().unwrap();
2081        buf[21] = 65;
2082        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2083        assert!(matches!(
2084            err,
2085            DatabaseHeaderError::InvalidPayloadFractions { .. }
2086        ));
2087    }
2088
2089    #[test]
2090    fn test_header_usable_size_minimum() {
2091        // For 512-byte pages, reserved_per_page must be <= 32 (512-32=480).
2092        let mut buf = make_header_for_tests().to_bytes().unwrap();
2093        buf[16..18].copy_from_slice(&512u16.to_be_bytes());
2094        buf[20] = 33;
2095        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2096        assert!(matches!(
2097            err,
2098            DatabaseHeaderError::UsableSizeTooSmall { .. }
2099        ));
2100
2101        buf[20] = 32;
2102        DatabaseHeader::from_bytes(&buf).unwrap();
2103    }
2104
2105    #[test]
2106    fn test_header_round_trip() {
2107        let hdr = make_header_for_tests();
2108        let buf1 = hdr.to_bytes().unwrap();
2109        let parsed = DatabaseHeader::from_bytes(&buf1).unwrap();
2110        assert_eq!(parsed, hdr);
2111
2112        let buf2 = parsed.to_bytes().unwrap();
2113        assert_eq!(buf1, buf2);
2114    }
2115
2116    #[test]
2117    fn test_btree_page_header_leaf() {
2118        let page_size = PageSize::new(512).unwrap();
2119        let mut page = vec![0u8; page_size.as_usize()];
2120
2121        // Leaf table page.
2122        page[0] = 0x0D;
2123        page[1..3].copy_from_slice(&0u16.to_be_bytes()); // first freeblock
2124        page[3..5].copy_from_slice(&1u16.to_be_bytes()); // 1 cell
2125        page[5..7].copy_from_slice(&400u16.to_be_bytes()); // cell content start
2126        page[7] = 0; // fragmented bytes
2127
2128        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2129        assert!(hdr.page_type.is_leaf());
2130        assert_eq!(hdr.header_size(), 8);
2131    }
2132
2133    #[test]
2134    fn test_btree_page_header_interior() {
2135        let page_size = PageSize::new(512).unwrap();
2136        let mut page = vec![0u8; page_size.as_usize()];
2137
2138        // Interior table page.
2139        page[0] = 0x05;
2140        page[1..3].copy_from_slice(&0u16.to_be_bytes());
2141        page[3..5].copy_from_slice(&0u16.to_be_bytes());
2142        page[5..7].copy_from_slice(&500u16.to_be_bytes());
2143        page[7] = 0;
2144        page[8..12].copy_from_slice(&2u32.to_be_bytes()); // right-most child
2145
2146        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2147        assert!(hdr.page_type.is_interior());
2148        assert_eq!(hdr.header_size(), 12);
2149        assert_eq!(hdr.right_most_child.unwrap().get(), 2);
2150    }
2151
2152    #[test]
2153    fn test_page1_offset_adjustment() {
2154        let page_size = PageSize::new(512).unwrap();
2155        let mut page = vec![0u8; page_size.as_usize()];
2156
2157        // Page 1: B-tree header starts after the 100-byte DB header prefix.
2158        let h = DATABASE_HEADER_SIZE;
2159        page[h] = 0x0D; // leaf table
2160        page[h + 1..h + 3].copy_from_slice(&0u16.to_be_bytes());
2161        page[h + 3..h + 5].copy_from_slice(&1u16.to_be_bytes()); // 1 cell
2162        page[h + 5..h + 7].copy_from_slice(&300u16.to_be_bytes()); // cell content start
2163        page[h + 7] = 0;
2164
2165        // Cell pointer array begins at h+8.
2166        page[h + 8..h + 10].copy_from_slice(&300u16.to_be_bytes());
2167
2168        let hdr = BTreePageHeader::parse(&page, page_size, 0, true).unwrap();
2169        let ptrs = hdr.parse_cell_pointers(&page, page_size, 0).unwrap();
2170        assert_eq!(ptrs, vec![300u16]);
2171    }
2172
2173    #[test]
2174    fn test_cell_pointer_array() {
2175        let page_size = PageSize::new(512).unwrap();
2176        let mut page = vec![0u8; page_size.as_usize()];
2177
2178        page[0] = 0x0D;
2179        page[1..3].copy_from_slice(&0u16.to_be_bytes());
2180        page[3..5].copy_from_slice(&3u16.to_be_bytes()); // 3 cells
2181        page[5..7].copy_from_slice(&300u16.to_be_bytes());
2182        page[7] = 0;
2183        page[8..10].copy_from_slice(&300u16.to_be_bytes());
2184        page[10..12].copy_from_slice(&320u16.to_be_bytes());
2185        page[12..14].copy_from_slice(&340u16.to_be_bytes());
2186
2187        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2188        let ptrs = hdr.parse_cell_pointers(&page, page_size, 0).unwrap();
2189        assert_eq!(ptrs, vec![300u16, 320u16, 340u16]);
2190    }
2191
2192    #[test]
2193    fn test_freeblock_list_traversal() {
2194        let page_size = PageSize::new(512).unwrap();
2195        let mut page = vec![0u8; page_size.as_usize()];
2196
2197        page[0] = 0x0D;
2198        page[1..3].copy_from_slice(&400u16.to_be_bytes()); // first freeblock
2199        page[3..5].copy_from_slice(&0u16.to_be_bytes());
2200        page[5..7].copy_from_slice(&400u16.to_be_bytes());
2201        page[7] = 0;
2202
2203        // freeblock at 400 -> next 420, size 20
2204        page[400..402].copy_from_slice(&420u16.to_be_bytes());
2205        page[402..404].copy_from_slice(&20u16.to_be_bytes());
2206        // freeblock at 420 -> next 0, size 30
2207        page[420..422].copy_from_slice(&0u16.to_be_bytes());
2208        page[422..424].copy_from_slice(&30u16.to_be_bytes());
2209
2210        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2211        let blocks = hdr.parse_freeblocks(&page, page_size, 0).unwrap();
2212        assert_eq!(
2213            blocks,
2214            vec![
2215                Freeblock {
2216                    offset: 400,
2217                    next: 420,
2218                    size: 20
2219                },
2220                Freeblock {
2221                    offset: 420,
2222                    next: 0,
2223                    size: 30
2224                }
2225            ]
2226        );
2227    }
2228
2229    #[test]
2230    fn test_freeblock_min_size() {
2231        let page_size = PageSize::new(512).unwrap();
2232        let mut page = vec![0u8; page_size.as_usize()];
2233
2234        page[0] = 0x0D;
2235        page[1..3].copy_from_slice(&400u16.to_be_bytes());
2236        page[3..5].copy_from_slice(&0u16.to_be_bytes());
2237        page[5..7].copy_from_slice(&400u16.to_be_bytes());
2238        page[7] = 0;
2239
2240        page[400..402].copy_from_slice(&0u16.to_be_bytes());
2241        page[402..404].copy_from_slice(&3u16.to_be_bytes()); // invalid
2242
2243        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2244        let err = hdr.parse_freeblocks(&page, page_size, 0).unwrap_err();
2245        assert!(matches!(err, BTreePageError::InvalidFreeblock { .. }));
2246    }
2247
2248    #[test]
2249    fn test_fragment_defrag_threshold() {
2250        assert!(!would_exceed_fragmented_free_bytes(60, 0));
2251        assert!(would_exceed_fragmented_free_bytes(60, 1));
2252        assert!(would_exceed_fragmented_free_bytes(59, 2));
2253    }
2254
2255    #[test]
2256    fn test_e2e_bd_1a32() {
2257        use std::fs::File;
2258        use std::io::{Read, Seek};
2259        use std::process::Command;
2260        use std::sync::atomic::{AtomicUsize, Ordering};
2261
2262        static COUNTER: AtomicUsize = AtomicUsize::new(0);
2263
2264        // If sqlite3 isn't available in the environment, skip.
2265        if Command::new("sqlite3").arg("--version").output().is_err() {
2266            return;
2267        }
2268
2269        let mut path = std::env::temp_dir();
2270        path.push(format!(
2271            "fsqlite_bd_1a32_{}_{}.sqlite",
2272            std::process::id(),
2273            COUNTER.fetch_add(1, Ordering::Relaxed)
2274        ));
2275
2276        let status = Command::new("sqlite3")
2277            .arg(&path)
2278            .arg("CREATE TABLE t(x); INSERT INTO t VALUES(1);")
2279            .status()
2280            .expect("sqlite3 execution failed");
2281        assert!(status.success());
2282
2283        let mut f = File::open(&path).expect("open temp db");
2284        let mut header_bytes = [0u8; DATABASE_HEADER_SIZE];
2285        f.read_exact(&mut header_bytes).expect("read db header");
2286        let header = DatabaseHeader::from_bytes(&header_bytes).expect("parse db header");
2287        assert_eq!(header.schema_format, 4);
2288        assert_eq!(
2289            header.open_mode(MAX_FILE_FORMAT_VERSION).unwrap(),
2290            DatabaseOpenMode::ReadWrite
2291        );
2292
2293        // Re-serialize the parsed header and verify byte-for-byte equivalence.
2294        let hdr2 = header.to_bytes().expect("serialize header");
2295        assert_eq!(header_bytes, hdr2);
2296
2297        // Parse page 1 B-tree header from the first page.
2298        let page_size = header.page_size;
2299        let mut page1 = vec![0u8; page_size.as_usize()];
2300        f.rewind().expect("rewind");
2301        f.read_exact(&mut page1).expect("read page 1");
2302        let btree_hdr = BTreePageHeader::parse(&page1, page_size, header.reserved_per_page, true)
2303            .expect("parse page1 btree header");
2304        assert_eq!(btree_hdr.header_offset, DATABASE_HEADER_SIZE);
2305    }
2306
2307    #[test]
2308    fn test_varint_signed_cast() {
2309        use crate::serial_type::{read_varint, write_varint};
2310
2311        // Varint-decoded u64 cast to i64 produces correct two's complement for rowids.
2312        let test_cases: &[(u64, i64)] = &[
2313            (0, 0),
2314            (1, 1),
2315            (0x7FFF_FFFF_FFFF_FFFF, i64::MAX),
2316            (u64::MAX, -1),
2317            (0x8000_0000_0000_0000, i64::MIN),
2318        ];
2319        let mut buf = [0u8; 9];
2320        for &(unsigned, expected_signed) in test_cases {
2321            let written = write_varint(&mut buf, unsigned);
2322            let (decoded, consumed) = read_varint(&buf[..written]).unwrap();
2323            assert_eq!(decoded, unsigned);
2324            assert_eq!(consumed, written);
2325            #[allow(clippy::cast_possible_wrap)]
2326            let signed = decoded as i64;
2327            assert_eq!(
2328                signed, expected_signed,
2329                "u64 {unsigned} should cast to i64 {expected_signed}, got {signed}"
2330            );
2331        }
2332    }
2333
2334    #[test]
2335    fn test_reserved_bytes_72_91_zero() {
2336        let hdr = make_header_for_tests();
2337        let buf = hdr.to_bytes().unwrap();
2338        for (i, &byte) in buf.iter().enumerate().take(92).skip(72) {
2339            assert_eq!(byte, 0, "byte {i} should be zero (reserved region)");
2340        }
2341
2342        let mut hdr2 = make_header_for_tests();
2343        hdr2.application_id = 0xDEAD_BEEF;
2344        hdr2.user_version = 42;
2345        let buf2 = hdr2.to_bytes().unwrap();
2346        for (i, &byte) in buf2.iter().enumerate().take(92).skip(72) {
2347            assert_eq!(byte, 0, "byte {i} should be zero even with custom app_id");
2348        }
2349    }
2350
2351    #[test]
2352    fn test_version_valid_for_stale() {
2353        let mut hdr = make_header_for_tests();
2354        hdr.change_counter = 7;
2355        hdr.version_valid_for = 7;
2356        assert!(!hdr.is_page_count_stale());
2357
2358        hdr.version_valid_for = 5;
2359        assert!(hdr.is_page_count_stale());
2360
2361        hdr.page_size = PageSize::new(4096).unwrap();
2362        assert_eq!(hdr.page_count_from_file_size(4096 * 100), Some(100));
2363        assert_eq!(hdr.page_count_from_file_size(4096), Some(1));
2364        assert!(hdr.page_count_from_file_size(5000).is_none());
2365        assert!(hdr.page_count_from_file_size(0).is_none());
2366    }
2367
2368    #[test]
2369    fn test_reserved_space_per_page() {
2370        let mut hdr = make_header_for_tests();
2371        hdr.page_size = PageSize::new(4096).unwrap();
2372        hdr.reserved_per_page = 40;
2373        let usable = hdr.page_size.usable(hdr.reserved_per_page);
2374        assert_eq!(usable, 4056);
2375
2376        let buf = hdr.to_bytes().unwrap();
2377        let parsed = DatabaseHeader::from_bytes(&buf).unwrap();
2378        assert_eq!(parsed.reserved_per_page, 40);
2379        assert_eq!(parsed.page_size.usable(parsed.reserved_per_page), 4056);
2380    }
2381
2382    #[test]
2383    fn test_header_text_encoding_invalid() {
2384        let mut buf = make_header_for_tests().to_bytes().unwrap();
2385        buf[56..60].copy_from_slice(&4u32.to_be_bytes());
2386        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2387        assert!(matches!(
2388            err,
2389            DatabaseHeaderError::InvalidTextEncoding { raw: 4 }
2390        ));
2391
2392        buf[56..60].copy_from_slice(&0u32.to_be_bytes());
2393        let err = DatabaseHeader::from_bytes(&buf).unwrap_err();
2394        assert!(matches!(
2395            err,
2396            DatabaseHeaderError::InvalidTextEncoding { raw: 0 }
2397        ));
2398    }
2399
2400    #[test]
2401    fn test_btree_page_type_classification() {
2402        assert_eq!(
2403            BTreePageType::from_byte(0x02),
2404            Some(BTreePageType::InteriorIndex)
2405        );
2406        assert_eq!(
2407            BTreePageType::from_byte(0x05),
2408            Some(BTreePageType::InteriorTable)
2409        );
2410        assert_eq!(
2411            BTreePageType::from_byte(0x0A),
2412            Some(BTreePageType::LeafIndex)
2413        );
2414        assert_eq!(
2415            BTreePageType::from_byte(0x0D),
2416            Some(BTreePageType::LeafTable)
2417        );
2418
2419        assert!(BTreePageType::from_byte(0x00).is_none());
2420        assert!(BTreePageType::from_byte(0x01).is_none());
2421        assert!(BTreePageType::from_byte(0xFF).is_none());
2422
2423        assert!(BTreePageType::InteriorTable.is_interior());
2424        assert!(BTreePageType::InteriorTable.is_table());
2425        assert!(!BTreePageType::InteriorTable.is_leaf());
2426        assert!(!BTreePageType::InteriorTable.is_index());
2427
2428        assert!(BTreePageType::LeafIndex.is_leaf());
2429        assert!(BTreePageType::LeafIndex.is_index());
2430        assert!(!BTreePageType::LeafIndex.is_interior());
2431        assert!(!BTreePageType::LeafIndex.is_table());
2432    }
2433
2434    #[test]
2435    fn test_invalid_page_type_rejected() {
2436        let page_size = PageSize::new(512).unwrap();
2437        let mut page = vec![0u8; page_size.as_usize()];
2438        page[0] = 0x01;
2439        let err = BTreePageHeader::parse(&page, page_size, 0, false).unwrap_err();
2440        assert!(matches!(err, BTreePageError::InvalidPageType { raw: 0x01 }));
2441    }
2442
2443    #[test]
2444    fn test_freeblock_loop_detected() {
2445        let page_size = PageSize::new(512).unwrap();
2446        let mut page = vec![0u8; page_size.as_usize()];
2447
2448        page[0] = 0x0D;
2449        page[1..3].copy_from_slice(&400u16.to_be_bytes()); // first freeblock
2450        page[3..5].copy_from_slice(&0u16.to_be_bytes()); // 0 cells
2451        // cell_content_start must be <= 400 so freeblocks are valid
2452        page[5..7].copy_from_slice(&300u16.to_be_bytes());
2453        page[7] = 0;
2454
2455        // freeblock at 400 -> next 420, size 20
2456        page[400..402].copy_from_slice(&420u16.to_be_bytes());
2457        page[402..404].copy_from_slice(&20u16.to_be_bytes());
2458        // freeblock at 420 -> next 400 (LOOP), size 20
2459        page[420..422].copy_from_slice(&400u16.to_be_bytes());
2460        page[422..424].copy_from_slice(&20u16.to_be_bytes());
2461
2462        let hdr = BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2463        let err = hdr.parse_freeblocks(&page, page_size, 0).unwrap_err();
2464        assert!(matches!(err, BTreePageError::FreeblockLoop { .. }));
2465    }
2466
2467    #[test]
2468    fn test_fragmented_free_bytes_max() {
2469        let page_size = PageSize::new(512).unwrap();
2470        let mut page = vec![0u8; page_size.as_usize()];
2471
2472        page[0] = 0x0D;
2473        page[5..7].copy_from_slice(&500u16.to_be_bytes()); // valid cell_content_start
2474        page[7] = 61; // exceeds max of 60
2475        let err = BTreePageHeader::parse(&page, page_size, 0, false).unwrap_err();
2476        assert!(matches!(
2477            err,
2478            BTreePageError::InvalidFragmentedFreeBytes { raw: 61, max: 60 }
2479        ));
2480
2481        // 60 is exactly the limit -- should succeed
2482        page[7] = 60;
2483        BTreePageHeader::parse(&page, page_size, 0, false).unwrap();
2484    }
2485
2486    #[test]
2487    fn test_error_variants_distinct_display() {
2488        let errors: Vec<DatabaseHeaderError> = vec![
2489            DatabaseHeaderError::InvalidMagic,
2490            DatabaseHeaderError::InvalidPageSize { raw: 100 },
2491            DatabaseHeaderError::InvalidPayloadFractions {
2492                max: 65,
2493                min: 32,
2494                leaf: 32,
2495            },
2496            DatabaseHeaderError::UsableSizeTooSmall {
2497                page_size: 512,
2498                reserved_per_page: 33,
2499                usable_size: 479,
2500            },
2501            DatabaseHeaderError::UnsupportedReadVersion {
2502                read_version: 3,
2503                max_supported: 2,
2504            },
2505            DatabaseHeaderError::InvalidTextEncoding { raw: 4 },
2506            DatabaseHeaderError::InvalidSchemaFormat { raw: 0 },
2507        ];
2508
2509        let displays: Vec<String> = errors
2510            .iter()
2511            .map(std::string::ToString::to_string)
2512            .collect();
2513        for (i, d) in displays.iter().enumerate() {
2514            assert!(!d.is_empty(), "error variant {i} has empty display");
2515            for (j, d2) in displays.iter().enumerate() {
2516                if i != j {
2517                    assert_ne!(d, d2, "error variants {i} and {j} have identical display");
2518                }
2519            }
2520        }
2521    }
2522
2523    // ── bd-94us §11.11-11.12 sqlite_master + encoding tests ────────────
2524
2525    #[test]
2526    fn test_sqlite_master_page1_root() {
2527        // sqlite_master is always rooted at page 1.
2528        // On creation, page 1 is a table leaf (0x0D) with 0 cells.
2529        let page_size = PageSize::new(4096).unwrap();
2530        let mut page = [0u8; 4096];
2531        // Page 1 has 100-byte database header prefix.
2532        // B-tree header starts at offset 100 for page 1.
2533        page[..16].copy_from_slice(b"SQLite format 3\0");
2534        page[16..18].copy_from_slice(&4096u16.to_be_bytes()); // page size
2535        page[100] = 0x0D; // leaf table page type at header offset
2536        // cell count = 0 at offset 103
2537        page[103..105].copy_from_slice(&0u16.to_be_bytes());
2538        // cell content area start = page_size at offset 105
2539        page[105..107].copy_from_slice(&4096u16.to_be_bytes()); // cell content area at end of page
2540
2541        let page_type = BTreePageType::from_byte(page[100]);
2542        assert_eq!(page_type, Some(BTreePageType::LeafTable));
2543        let hdr = BTreePageHeader::parse(&page, page_size, 0, true).expect("valid leaf header");
2544        assert_eq!(hdr.cell_count, 0, "fresh sqlite_master has 0 rows");
2545    }
2546
2547    #[test]
2548    fn test_sqlite_master_schema_columns() {
2549        // sqlite_master has exactly 5 columns: type, name, tbl_name, rootpage, sql.
2550        let columns = ["type", "name", "tbl_name", "rootpage", "sql"];
2551        assert_eq!(columns.len(), 5);
2552        // Verify the valid type values.
2553        let valid_types = ["table", "index", "view", "trigger"];
2554        assert_eq!(valid_types.len(), 4);
2555    }
2556
2557    #[test]
2558    fn test_encoding_utf8_default() {
2559        // New database defaults to text encoding 1 (UTF-8).
2560        let hdr = DatabaseHeader::default();
2561        assert_eq!(hdr.text_encoding, TextEncoding::Utf8);
2562
2563        let bytes = hdr.to_bytes().expect("encode");
2564        // Header offset 56 stores encoding as big-endian u32.
2565        let enc_raw = u32::from_be_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]);
2566        assert_eq!(enc_raw, 1, "UTF-8 encoding stored as 1 at offset 56");
2567    }
2568
2569    #[test]
2570    fn test_encoding_utf16le() {
2571        let mut hdr = make_header_for_tests();
2572        hdr.text_encoding = TextEncoding::Utf16le;
2573        let bytes = hdr.to_bytes().expect("encode");
2574        let enc_raw = u32::from_be_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]);
2575        assert_eq!(enc_raw, 2, "UTF-16LE encoding stored as 2");
2576
2577        let parsed = DatabaseHeader::from_bytes(&bytes).expect("decode");
2578        assert_eq!(parsed.text_encoding, TextEncoding::Utf16le);
2579    }
2580
2581    #[test]
2582    fn test_encoding_utf16be() {
2583        let mut hdr = make_header_for_tests();
2584        hdr.text_encoding = TextEncoding::Utf16be;
2585        let bytes = hdr.to_bytes().expect("encode");
2586        let enc_raw = u32::from_be_bytes([bytes[56], bytes[57], bytes[58], bytes[59]]);
2587        assert_eq!(enc_raw, 3, "UTF-16BE encoding stored as 3");
2588
2589        let parsed = DatabaseHeader::from_bytes(&bytes).expect("decode");
2590        assert_eq!(parsed.text_encoding, TextEncoding::Utf16be);
2591    }
2592
2593    #[test]
2594    fn test_text_encoding_runtime_support() {
2595        assert!(TextEncoding::Utf8.is_runtime_supported());
2596        assert!(!TextEncoding::Utf16le.is_runtime_supported());
2597        assert!(!TextEncoding::Utf16be.is_runtime_supported());
2598    }
2599
2600    #[test]
2601    fn test_encoding_immutable_after_creation() {
2602        // The generic header codec represents every valid SQLite encoding.
2603        // Runtime admission is a separate policy enforced through
2604        // TextEncoding::is_runtime_supported().
2605        let hdr1 = make_header_for_tests();
2606        assert_eq!(hdr1.text_encoding, TextEncoding::Utf8);
2607        let bytes1 = hdr1.to_bytes().expect("encode");
2608
2609        let mut hdr2 = hdr1;
2610        hdr2.text_encoding = TextEncoding::Utf16le;
2611        let bytes2 = hdr2.to_bytes().expect("encode");
2612
2613        // The encoding field differs in the serialized bytes.
2614        assert_ne!(
2615            bytes1[56..60],
2616            bytes2[56..60],
2617            "different encodings must serialize differently"
2618        );
2619    }
2620
2621    #[test]
2622    fn test_binary_collation_memcmp_utf8() {
2623        // BINARY collation uses memcmp on raw bytes.
2624        // For UTF-8, memcmp produces correct Unicode code point ordering.
2625        let a = "abc";
2626        let b = "abd";
2627        assert!(
2628            a.as_bytes() < b.as_bytes(),
2629            "memcmp ordering for ASCII UTF-8"
2630        );
2631
2632        // Multi-byte UTF-8: 'é' (U+00E9) = [0xC3, 0xA9], 'z' (U+007A) = [0x7A].
2633        // In code point order: 'z' (122) < 'é' (233).
2634        // In byte order: 0x7A < 0xC3, so 'z' < 'é' — same as code point order.
2635        let z = "z";
2636        let e_acute = "é";
2637        assert!(
2638            z.as_bytes() < e_acute.as_bytes(),
2639            "UTF-8 memcmp preserves code point order"
2640        );
2641    }
2642
2643    // ── bd-16ov §12.15-12.16 Type Affinity tests ────────────────────────
2644
2645    #[test]
2646    fn test_affinity_int_keyword() {
2647        assert_eq!(
2648            TypeAffinity::from_type_name("INTEGER"),
2649            TypeAffinity::Integer
2650        );
2651        assert_eq!(TypeAffinity::from_type_name("INT"), TypeAffinity::Integer);
2652        assert_eq!(
2653            TypeAffinity::from_type_name("TINYINT"),
2654            TypeAffinity::Integer
2655        );
2656        assert_eq!(
2657            TypeAffinity::from_type_name("SMALLINT"),
2658            TypeAffinity::Integer
2659        );
2660        assert_eq!(
2661            TypeAffinity::from_type_name("MEDIUMINT"),
2662            TypeAffinity::Integer
2663        );
2664        assert_eq!(
2665            TypeAffinity::from_type_name("BIGINT"),
2666            TypeAffinity::Integer
2667        );
2668        assert_eq!(
2669            TypeAffinity::from_type_name("UNSIGNED BIG INT"),
2670            TypeAffinity::Integer
2671        );
2672        assert_eq!(TypeAffinity::from_type_name("INT2"), TypeAffinity::Integer);
2673        assert_eq!(TypeAffinity::from_type_name("INT8"), TypeAffinity::Integer);
2674    }
2675
2676    #[test]
2677    fn test_affinity_text_keyword() {
2678        assert_eq!(TypeAffinity::from_type_name("TEXT"), TypeAffinity::Text);
2679        assert_eq!(
2680            TypeAffinity::from_type_name("CHARACTER(20)"),
2681            TypeAffinity::Text
2682        );
2683        assert_eq!(
2684            TypeAffinity::from_type_name("VARCHAR(255)"),
2685            TypeAffinity::Text
2686        );
2687        assert_eq!(
2688            TypeAffinity::from_type_name("VARYING CHARACTER(255)"),
2689            TypeAffinity::Text
2690        );
2691        assert_eq!(
2692            TypeAffinity::from_type_name("NCHAR(55)"),
2693            TypeAffinity::Text
2694        );
2695        assert_eq!(
2696            TypeAffinity::from_type_name("NATIVE CHARACTER(70)"),
2697            TypeAffinity::Text
2698        );
2699        assert_eq!(
2700            TypeAffinity::from_type_name("NVARCHAR(100)"),
2701            TypeAffinity::Text
2702        );
2703        assert_eq!(TypeAffinity::from_type_name("CLOB"), TypeAffinity::Text);
2704    }
2705
2706    #[test]
2707    fn test_affinity_blob_keyword() {
2708        assert_eq!(TypeAffinity::from_type_name("BLOB"), TypeAffinity::Blob);
2709        assert_eq!(TypeAffinity::from_type_name("blob"), TypeAffinity::Blob);
2710    }
2711
2712    #[test]
2713    fn test_affinity_empty_type() {
2714        assert_eq!(TypeAffinity::from_type_name(""), TypeAffinity::Blob);
2715    }
2716
2717    #[test]
2718    fn test_affinity_real_keyword() {
2719        assert_eq!(TypeAffinity::from_type_name("REAL"), TypeAffinity::Real);
2720        assert_eq!(TypeAffinity::from_type_name("DOUBLE"), TypeAffinity::Real);
2721        assert_eq!(
2722            TypeAffinity::from_type_name("DOUBLE PRECISION"),
2723            TypeAffinity::Real
2724        );
2725        assert_eq!(TypeAffinity::from_type_name("FLOAT"), TypeAffinity::Real);
2726    }
2727
2728    #[test]
2729    fn test_affinity_numeric_keyword() {
2730        assert_eq!(
2731            TypeAffinity::from_type_name("NUMERIC"),
2732            TypeAffinity::Numeric
2733        );
2734        assert_eq!(
2735            TypeAffinity::from_type_name("DECIMAL(10,5)"),
2736            TypeAffinity::Numeric
2737        );
2738        assert_eq!(
2739            TypeAffinity::from_type_name("BOOLEAN"),
2740            TypeAffinity::Numeric
2741        );
2742        assert_eq!(TypeAffinity::from_type_name("DATE"), TypeAffinity::Numeric);
2743        assert_eq!(
2744            TypeAffinity::from_type_name("DATETIME"),
2745            TypeAffinity::Numeric
2746        );
2747    }
2748
2749    #[test]
2750    fn test_affinity_case_insensitive() {
2751        assert_eq!(
2752            TypeAffinity::from_type_name("integer"),
2753            TypeAffinity::Integer
2754        );
2755        assert_eq!(TypeAffinity::from_type_name("text"), TypeAffinity::Text);
2756        assert_eq!(TypeAffinity::from_type_name("Real"), TypeAffinity::Real);
2757        assert_eq!(
2758            TypeAffinity::from_type_name("Numeric"),
2759            TypeAffinity::Numeric
2760        );
2761    }
2762
2763    #[test]
2764    fn test_affinity_first_match_int_before_char() {
2765        // "CHARINT" contains both "CHAR" and "INT", but "INT" is checked first.
2766        assert_eq!(
2767            TypeAffinity::from_type_name("CHARINT"),
2768            TypeAffinity::Integer
2769        );
2770        // "POINTERFLOAT" contains "INT" so INTEGER wins over REAL.
2771        assert_eq!(
2772            TypeAffinity::from_type_name("POINTERFLOAT"),
2773            TypeAffinity::Integer
2774        );
2775    }
2776
2777    #[test]
2778    fn comparison_affinity_codes_match_sqlite_p5() {
2779        assert_eq!(ComparisonAffinity::None as u8, b'@');
2780        assert_eq!(ComparisonAffinity::Blob as u8, b'A');
2781        assert_eq!(ComparisonAffinity::Text as u8, b'B');
2782        assert_eq!(ComparisonAffinity::Numeric as u8, b'C');
2783        assert_eq!(ComparisonAffinity::Integer as u8, b'D');
2784        assert_eq!(ComparisonAffinity::Real as u8, b'E');
2785    }
2786
2787    #[test]
2788    fn expression_comparison_affinity_has_exhaustive_sqlite_truth_table() {
2789        let operands = [
2790            ExprAffinity::None,
2791            ExprAffinity::Affinity(TypeAffinity::Blob),
2792            ExprAffinity::Affinity(TypeAffinity::Text),
2793            ExprAffinity::Affinity(TypeAffinity::Numeric),
2794            ExprAffinity::Affinity(TypeAffinity::Integer),
2795            ExprAffinity::Affinity(TypeAffinity::Real),
2796        ];
2797        let expected = [
2798            [
2799                ComparisonAffinity::None,
2800                ComparisonAffinity::Blob,
2801                ComparisonAffinity::Text,
2802                ComparisonAffinity::Numeric,
2803                ComparisonAffinity::Integer,
2804                ComparisonAffinity::Real,
2805            ],
2806            [
2807                ComparisonAffinity::Blob,
2808                ComparisonAffinity::Blob,
2809                ComparisonAffinity::Blob,
2810                ComparisonAffinity::Numeric,
2811                ComparisonAffinity::Numeric,
2812                ComparisonAffinity::Numeric,
2813            ],
2814            [
2815                ComparisonAffinity::Text,
2816                ComparisonAffinity::Blob,
2817                ComparisonAffinity::Blob,
2818                ComparisonAffinity::Numeric,
2819                ComparisonAffinity::Numeric,
2820                ComparisonAffinity::Numeric,
2821            ],
2822            [
2823                ComparisonAffinity::Numeric,
2824                ComparisonAffinity::Numeric,
2825                ComparisonAffinity::Numeric,
2826                ComparisonAffinity::Numeric,
2827                ComparisonAffinity::Numeric,
2828                ComparisonAffinity::Numeric,
2829            ],
2830            [
2831                ComparisonAffinity::Integer,
2832                ComparisonAffinity::Numeric,
2833                ComparisonAffinity::Numeric,
2834                ComparisonAffinity::Numeric,
2835                ComparisonAffinity::Numeric,
2836                ComparisonAffinity::Numeric,
2837            ],
2838            [
2839                ComparisonAffinity::Real,
2840                ComparisonAffinity::Numeric,
2841                ComparisonAffinity::Numeric,
2842                ComparisonAffinity::Numeric,
2843                ComparisonAffinity::Numeric,
2844                ComparisonAffinity::Numeric,
2845            ],
2846        ];
2847
2848        assert_eq!(operands.len() * operands.len(), 36);
2849        for (left_index, left) in operands.iter().copied().enumerate() {
2850            for (right_index, right) in operands.iter().copied().enumerate() {
2851                assert_eq!(
2852                    ComparisonAffinity::from_operands(left, right),
2853                    expected[left_index][right_index],
2854                    "unexpected comparison affinity for left={left:?}, right={right:?}",
2855                );
2856            }
2857        }
2858    }
2859
2860    #[test]
2861    fn test_comparison_numeric_vs_text() {
2862        assert_eq!(
2863            TypeAffinity::comparison_affinity(TypeAffinity::Integer, TypeAffinity::Text),
2864            Some(TypeAffinity::Numeric)
2865        );
2866        assert_eq!(
2867            TypeAffinity::comparison_affinity(TypeAffinity::Text, TypeAffinity::Real),
2868            Some(TypeAffinity::Numeric)
2869        );
2870        assert_eq!(
2871            TypeAffinity::comparison_affinity(TypeAffinity::Numeric, TypeAffinity::Blob),
2872            Some(TypeAffinity::Numeric)
2873        );
2874    }
2875
2876    #[test]
2877    fn test_comparison_text_vs_blob() {
2878        assert_eq!(
2879            TypeAffinity::comparison_affinity(TypeAffinity::Text, TypeAffinity::Blob),
2880            Some(TypeAffinity::Text)
2881        );
2882        assert_eq!(
2883            TypeAffinity::comparison_affinity(TypeAffinity::Blob, TypeAffinity::Text),
2884            Some(TypeAffinity::Text)
2885        );
2886    }
2887
2888    #[test]
2889    fn test_comparison_same_affinity_no_coercion() {
2890        assert_eq!(
2891            TypeAffinity::comparison_affinity(TypeAffinity::Integer, TypeAffinity::Integer),
2892            None
2893        );
2894        assert_eq!(
2895            TypeAffinity::comparison_affinity(TypeAffinity::Text, TypeAffinity::Text),
2896            None
2897        );
2898        assert_eq!(
2899            TypeAffinity::comparison_affinity(TypeAffinity::Blob, TypeAffinity::Blob),
2900            None
2901        );
2902    }
2903
2904    #[test]
2905    fn test_comparison_both_blob_no_coercion() {
2906        assert_eq!(
2907            TypeAffinity::comparison_affinity(TypeAffinity::Blob, TypeAffinity::Blob),
2908            None
2909        );
2910    }
2911
2912    #[test]
2913    fn test_affinity_applied_to_needing_operand_only() {
2914        let left = SqliteValue::Integer(42);
2915        let right = SqliteValue::Text(SmallText::new("123"));
2916        let affinity = TypeAffinity::comparison_affinity(left.affinity(), right.affinity())
2917            .expect("numeric-vs-text comparison must request numeric coercion");
2918
2919        // Numeric side should remain unchanged.
2920        let left_after = left.clone();
2921        // Text side is the side that needs conversion for numeric comparison.
2922        let right_after = right.apply_affinity(affinity);
2923
2924        assert_eq!(left_after, left);
2925        assert_eq!(right_after, SqliteValue::Integer(123));
2926    }
2927
2928    #[test]
2929    fn test_comparison_numeric_subtypes() {
2930        // INTEGER vs REAL: both numeric, different variants but no coercion needed
2931        // per SQLite rules (they share the numeric class).
2932        assert_eq!(
2933            TypeAffinity::comparison_affinity(TypeAffinity::Integer, TypeAffinity::Real),
2934            None
2935        );
2936        assert_eq!(
2937            TypeAffinity::comparison_affinity(TypeAffinity::Integer, TypeAffinity::Numeric),
2938            None
2939        );
2940        assert_eq!(
2941            TypeAffinity::comparison_affinity(TypeAffinity::Real, TypeAffinity::Numeric),
2942            None
2943        );
2944    }
2945
2946    // ── 5A.1: BTreePageHeader::write_empty_leaf_table tests (bd-2yy6) ──
2947
2948    #[test]
2949    fn test_write_empty_leaf_table_basic() {
2950        let ps = PageSize::DEFAULT;
2951        let mut buf = vec![0u8; ps.as_usize()];
2952        BTreePageHeader::write_empty_leaf_table(&mut buf, 0, ps.get());
2953
2954        assert_eq!(buf[0], 0x0D, "page type LeafTable");
2955        assert_eq!(buf[1], 0, "first_freeblock hi");
2956        assert_eq!(buf[2], 0, "first_freeblock lo");
2957        assert_eq!(buf[3], 0, "cell_count hi");
2958        assert_eq!(buf[4], 0, "cell_count lo");
2959        // 4096 = 0x1000
2960        assert_eq!(buf[5], 0x10, "content_offset hi");
2961        assert_eq!(buf[6], 0x00, "content_offset lo");
2962        assert_eq!(buf[7], 0, "fragmented_free_bytes");
2963    }
2964
2965    #[test]
2966    fn test_write_empty_leaf_table_page1_offset() {
2967        let ps = PageSize::DEFAULT;
2968        let mut buf = vec![0u8; ps.as_usize()];
2969        BTreePageHeader::write_empty_leaf_table(&mut buf, DATABASE_HEADER_SIZE, ps.get());
2970
2971        assert_eq!(buf[DATABASE_HEADER_SIZE], 0x0D, "page type at offset 100");
2972        // Bytes before offset 100 should be untouched.
2973        assert!(buf[..DATABASE_HEADER_SIZE].iter().all(|&b| b == 0));
2974    }
2975
2976    #[test]
2977    fn test_write_empty_leaf_table_65536_encoding() {
2978        let ps = PageSize::new(65536).unwrap();
2979        let mut buf = vec![0u8; ps.as_usize()];
2980        BTreePageHeader::write_empty_leaf_table(&mut buf, 0, ps.get());
2981
2982        // 65536 is encoded as 0 in the B-tree header.
2983        assert_eq!(buf[5], 0x00, "65536 encoded as 0 hi");
2984        assert_eq!(buf[6], 0x00, "65536 encoded as 0 lo");
2985    }
2986
2987    #[test]
2988    fn test_write_empty_leaf_table_512_page_size() {
2989        let ps = PageSize::new(512).unwrap();
2990        let mut buf = vec![0u8; ps.as_usize()];
2991        BTreePageHeader::write_empty_leaf_table(&mut buf, 0, ps.get());
2992
2993        // 512 = 0x0200
2994        assert_eq!(buf[5], 0x02, "512 hi byte");
2995        assert_eq!(buf[6], 0x00, "512 lo byte");
2996    }
2997}