migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
Documentation
//! Canonical `migratrom/ops/v1` byte encoding of an operation list.
//!
//! This is a normative, cross-language format (see `migratrom.swift/docs/CHECKSUM_FORMAT.md`):
//! length-prefixed, big-endian `u32` lengths, UTF-8 fields.
use crate::types::{Check, ExecuteStep, Operation};

const FORMAT_VERSION: &str = "migratrom/ops/v1";

/// Encode an operation list to its canonical bytes.
pub fn canonical_encode(operations: &[Operation]) -> Vec<u8> {
    let mut out = Vec::new();
    append_field(&mut out, FORMAT_VERSION);
    append_u32(&mut out, operations.len() as u32);
    for op in operations {
        append_field(&mut out, &op.id);
        append_field(&mut out, &op.label);
        out.push(if op.outside_transaction { 1 } else { 0 });
        encode_checks(&mut out, &op.precheck);
        encode_steps(&mut out, &op.execute);
        encode_checks(&mut out, &op.postcheck);
    }
    out
}

fn encode_checks(out: &mut Vec<u8>, checks: &[Check]) {
    append_u32(out, checks.len() as u32);
    for check in checks {
        append_field(out, &check.description);
        append_field(out, &check.sql);
    }
}

fn encode_steps(out: &mut Vec<u8>, steps: &[ExecuteStep]) {
    append_u32(out, steps.len() as u32);
    for step in steps {
        append_field(out, &step.description);
        append_field(out, &step.sql);
    }
}

/// Append a big-endian `u32`.
fn append_u32(out: &mut Vec<u8>, value: u32) {
    out.extend_from_slice(&value.to_be_bytes());
}

/// Append a length-prefixed UTF-8 field: `u32` byte length then the bytes.
fn append_field(out: &mut Vec<u8>, value: &str) {
    let bytes = value.as_bytes();
    append_u32(out, bytes.len() as u32);
    out.extend_from_slice(bytes);
}