← core

core/raw.kur

//! Raw reads over flat buffers.
// core::raw -- bounds-checked indexing over a flat buffer given as a plain
// `*T` plus a length (`raw_get`, `raw_byte_at`). Those are not
// capability-gated accessors like `Slice::get_ref`: a caller that has flattened a structure to `*T` + `len`
// can peek into it without threading a live `Exclusive!` through every
// read. The caller still vouches (hence `unsafe fn`) that `len` really
// bounds the buffer.
//
// `T: Copy` is required: reading a value out of raw memory by index, with
// no tracking of whether that slot's value has already been read, is only
// sound for values that can be freely duplicated. A linear `T` read this
// way could be duplicated through two reads with nothing to catch it.

use package as core;

use core::option::Option;
use core::ptr::offset;

/// Element `i` of the `len` values at `base`, bounds-checked: `None` past
/// `len`, `Some.(value)` otherwise. Caller: `base` addresses `len`
/// initialized `T`s, readable for the call.
forall T where Copy[T], Sized[T].
unsafe fn raw_get(base: *T, len: usize, i: usize) -> Option[T] {
    if i < len {
        Option::Some.(unsafe *(unsafe offset(base, i)))
    } else {
        Option::None
    }
}

/// Byte `i` of the `len` bytes at `base`, bounds-checked: out of range
/// reads come back as `0u8` (NUL)
/// rather than an `Option[u8]`, for scanners whose character-class tests
/// already treat `0u8` as matching nothing. Caller: `base[0..len)` is
/// initialized and readable for the call.
unsafe fn raw_byte_at(base: *u8, len: usize, i: usize) -> u8 {
    if i < len {
        unsafe *(unsafe offset(base, i))
    } else {
        0u8
    }
}