wal-backup 0.8.11

Embedded SQLite WAL replication to S3-compatible object storage. Not a sidecar — a library. Like Litestream, but embedded.
Documentation
//! SQLite WAL checksum algorithm.
//!
//! Implements the checksum algorithm from SQLite's `walChecksumBytes()` in `wal.c`:
//!
//! ```text
//! for i from 0 to n-1 step 2:
//!     s0 += x[i] + s1;
//!     s1 += x[i+1] + s0;
//! ```
//!
//! Key details:
//! - **Byte order**: Determined by the WAL magic number. `0x377f0682` = little-endian
//!   (native on x86), `0x377f0683` = big-endian. Controlled by the `big_endian` parameter.
//! - **Initial values**: Header checksum starts at `(0, 0)`. Frame checksums are cumulative,
//!   using the previous frame's (or header's) checksum as the initial values.
//! - **No final XOR**: Unlike some checksum schemes, there are no chunk constants or
//!   final XOR steps. The raw `s0` and `s1` values are the checksum.
//! - **Input**: The header checksum covers bytes 0..24 of the WAL header. Frame checksums
//!   cover the first 8 bytes of the frame header (page_number + db_size_after) plus the
//!   page data.
//!
//! Note: use `wal_checksum_pair` for correct WAL frame construction and validation.

/// Compute both halves of the SQLite WAL checksum.
///
/// `big_endian` should be `true` when WAL magic is `0x377f0683`, `false` for `0x377f0682`.
pub fn wal_checksum_pair(mut s0: u32, mut s1: u32, data: &[u8], big_endian: bool) -> (u32, u32) {
    let read_u32 = if big_endian {
        |x: &[u8], off: usize| u32::from_be_bytes([x[off], x[off + 1], x[off + 2], x[off + 3]])
    } else {
        |x: &[u8], off: usize| u32::from_le_bytes([x[off], x[off + 1], x[off + 2], x[off + 3]])
    };

    let mut i = 0;
    while i + 8 <= data.len() {
        let d0 = read_u32(data, i);
        let d1 = read_u32(data, i + 4);
        s0 = s0.wrapping_add(d0).wrapping_add(s1);
        s1 = s1.wrapping_add(d1).wrapping_add(s0);
        i += 8;
    }

    (s0, s1)
}