weavatrix-refactor-plan 0.1.1

Evidence metadata, validation profiles, and canonical fingerprints for Weavatrix refactor plans
Documentation
//! JSON string escaping and integer-to-decimal formatting shared by the
//! canonical serializer and its key sink.

use std::io;

/// Escapes one JSON string, quotes included, into `out`.
pub(super) fn write_escaped<W: io::Write>(out: &mut W, value: &str) -> io::Result<()> {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    out.write_all(b"\"")?;
    let bytes = value.as_bytes();
    let mut start = 0;
    for (index, &byte) in bytes.iter().enumerate() {
        if byte >= 0x20 && byte != b'"' && byte != b'\\' {
            continue;
        }
        if start < index {
            out.write_all(&bytes[start..index])?;
        }
        match byte {
            b'"' => out.write_all(b"\\\"")?,
            b'\\' => out.write_all(b"\\\\")?,
            0x08 => out.write_all(b"\\b")?,
            0x09 => out.write_all(b"\\t")?,
            0x0a => out.write_all(b"\\n")?,
            0x0c => out.write_all(b"\\f")?,
            0x0d => out.write_all(b"\\r")?,
            control => out.write_all(&[
                b'\\',
                b'u',
                b'0',
                b'0',
                HEX[usize::from(control >> 4)],
                HEX[usize::from(control & 0x0f)],
            ])?,
        }
        start = index + 1;
    }
    if start < bytes.len() {
        out.write_all(&bytes[start..])?;
    }
    out.write_all(b"\"")
}

pub(super) const U64_TEXT_CAPACITY: usize = 20;

/// Formats an unsigned integer into the tail of `buffer`.
pub(super) fn format_u64(value: u64, buffer: &mut [u8; U64_TEXT_CAPACITY]) -> &[u8] {
    let mut index = buffer.len();
    let mut rest = value;
    loop {
        index -= 1;
        buffer[index] = b'0' + u8::try_from(rest % 10).expect("decimal digit fits u8");
        rest /= 10;
        if rest == 0 {
            break;
        }
    }
    &buffer[index..]
}