sark-http 0.39.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
use std::{mem::MaybeUninit, num::NonZero, slice};

use super::Wire;

pub const PAIRS: [[u8; 2]; 100] = {
    let mut pairs = [[0; 2]; 100];
    let mut value = 0;
    while value < pairs.len() {
        pairs[value] = [b'0' + (value / 10) as u8, b'0' + (value % 10) as u8];
        value += 1;
    }
    pairs
};

impl Wire for usize {
    fn decimal_len(mut self) -> NonZero<usize> {
        let mut len = NonZero::<usize>::MIN;
        while self >= 10 {
            self /= 10;
            len = len.saturating_add(1);
        }
        len
    }

    fn decimal(self, buf: &mut [u8; 20]) -> &[u8] {
        decimal(self, buf)
    }

    fn decimal_uninit(self, buf: &mut [MaybeUninit<u8>; 20]) -> &[u8] {
        decimal_into::<20, { usize::BITS <= 32 }>(self as u64, buf)
    }
}

pub(crate) const fn decimal(value: usize, buf: &mut [u8; 20]) -> &[u8] {
    // SAFETY: both arrays have the same layout and every write is an initialized u8.
    decimal_into::<20, { usize::BITS <= 32 }>(value as u64, unsafe {
        &mut *(buf as *mut [u8; 20]).cast()
    })
}

pub const fn decimal_uninit(value: u64, buf: &mut [MaybeUninit<u8>; 20]) -> &[u8] {
    decimal_into::<20, false>(value, buf)
}

pub const fn decimal_u32(value: u32, buf: &mut [u8; 10]) -> &[u8] {
    // SAFETY: the arrays have identical layout and every stored byte is initialized.
    decimal_into::<10, true>(value as u64, unsafe { &mut *(buf as *mut [u8; 10]).cast() })
}

const fn decimal_into<const N: usize, const U32: bool>(
    mut value: u64,
    buf: &mut [MaybeUninit<u8>; N],
) -> &[u8] {
    let mut start = buf.len();
    let output = buf.as_mut_ptr().cast::<u8>();
    while value >= 100 {
        let (remainder, next) = if U32 {
            let value = value as u32;
            ((value % 100) as usize, (value / 100) as u64)
        } else {
            ((value % 100) as usize, value / 100)
        };
        start -= 2;
        // SAFETY: callers admit u32/10 bytes or u64/20 bytes; the remainder is below 100.
        unsafe {
            output.add(start).cast::<[u8; 2]>().write(*PAIRS.as_ptr().add(remainder));
        }
        value = next;
    }
    if value < 10 {
        start -= 1;
        // SAFETY: the last digit fits the remaining prefix without touching earlier bytes.
        unsafe { output.add(start).write(b'0' + value as u8) };
    } else {
        start -= 2;
        // SAFETY: the final value is below 100 and the two-byte suffix remains available.
        unsafe { output.add(start).cast::<[u8; 2]>().write(*PAIRS.as_ptr().add(value as usize)) };
    }
    // SAFETY: every byte of this suffix was initialized under the original exclusive loan.
    unsafe { slice::from_raw_parts(output.add(start), buf.len() - start) }
}