inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
Documentation
//! Lean's unboxed arrays: `ByteArray` and `FloatArray`.
//!
//! Each is a `Vec` of the element type inside a Lean object, so a `Vec<u8>` or `Vec<f64>`
//! moves in and out without conversion. As in `lean.h`: an array a function changes is
//! consumed, arrays and indexes that are only read are borrowed, results are owned.

use crate::object::{box_, dec, is_scalar, unbox, Obj, TAG_SARRAY};
use crate::object::{held, held_mut, hold, into_held, take_held, Hold};

/// A byte array object holds a `Vec<u8>`, and a float array object a `Vec<f64>`. The size of
/// an element is in the header, so that the object can be freed without knowing its type.
impl Hold for Vec<u8> {
    const TAG: u8 = TAG_SARRAY;
    const OTHER: u8 = 1;

    unsafe fn copy(&self) -> Vec<u8> {
        self.clone()
    }
}

impl Hold for Vec<f64> {
    const TAG: u8 = TAG_SARRAY;
    const OTHER: u8 = 8;

    unsafe fn copy(&self) -> Vec<f64> {
        self.clone()
    }
}

/// The size in bytes of the elements of a scalar array, kept in its header so that the
/// object can be freed without knowing its type.
unsafe fn element_size(o: Obj) -> u8 {
    (*o.header()).other()
}

pub(crate) unsafe fn free(o: Obj) {
    match element_size(o) {
        1 => drop(take_held::<Vec<u8>>(o)),
        _ => drop(take_held::<Vec<f64>>(o)),
    }
}

fn from_vec<T>(items: Vec<T>) -> Obj
where
    Vec<T>: Hold,
{
    hold(items)
}

unsafe fn items<'a, T: 'a>(a: Obj) -> &'a Vec<T>
where
    Vec<T>: Hold,
{
    held(a)
}

/// The elements of an array the caller owns, for changing in place: `a` itself if nothing
/// else refers to it, and otherwise a copy, with the reference to `a` given up.
unsafe fn exclusive<'a, T: 'a>(a: Obj) -> (Obj, &'a mut Vec<T>)
where
    Vec<T>: Hold,
{
    held_mut(a)
}

/// The elements, giving up one reference. Takes the buffer without copying when nothing
/// else refers to the array.
unsafe fn into_vec<T>(a: Obj) -> Vec<T>
where
    Vec<T>: Hold,
{
    into_held(a)
}

/// An index given as a `Nat`, if it is inside an array of `len` elements.
unsafe fn index(i: Obj, len: usize) -> Option<usize> {
    (is_scalar(i) && unbox(i) < len).then(|| unbox(i))
}

#[cold]
fn out_of_bounds() -> ! {
    panic!("inlean: index out of bounds")
}

fn capacity(n: Obj) -> usize {
    if is_scalar(n) {
        unbox(n).min(1 << 20)
    } else {
        0
    }
}

/// A `ByteArray` that takes over the buffer of `bytes`.
pub fn byte_array_from_vec(bytes: Vec<u8>) -> Obj {
    from_vec(bytes)
}

/// The bytes of a `ByteArray`, giving up one reference to it.
pub unsafe fn byte_array_into_vec(a: Obj) -> Vec<u8> {
    into_vec(a)
}

/// The bytes of a `ByteArray`.
pub unsafe fn bytes<'a>(a: Obj) -> &'a [u8] {
    items::<u8>(a)
}

/// The `Vec` a `ByteArray` holds, for lending it as it is.
pub unsafe fn held_bytes<'a>(a: Obj) -> &'a Vec<u8> {
    items(a)
}

/// The `Vec` a `FloatArray` holds, for lending it as it is.
pub unsafe fn held_floats<'a>(a: Obj) -> &'a Vec<f64> {
    items(a)
}

/// A `FloatArray` that takes over the buffer of `values`.
pub fn float_array_from_vec(values: Vec<f64>) -> Obj {
    from_vec(values)
}

/// The values of a `FloatArray`, giving up one reference to it.
pub unsafe fn float_array_into_vec(a: Obj) -> Vec<f64> {
    into_vec(a)
}

pub unsafe fn mk_empty_byte_array(n: Obj) -> Obj {
    from_vec(Vec::<u8>::with_capacity(capacity(n)))
}

/// A `ByteArray` from an `Array UInt8`, which it consumes.
pub unsafe fn byte_array_mk(a: Obj) -> Obj {
    let bytes = crate::array::elements(a).iter().map(|&item| unbox(item) as u8).collect();
    dec(a);
    from_vec::<u8>(bytes)
}

/// The bytes as an `Array UInt8`. Consumes `a`.
pub unsafe fn byte_array_data(a: Obj) -> Obj {
    let boxed = bytes(a).iter().map(|&b| box_(b as usize)).collect();
    dec(a);
    crate::array::from_vec(boxed)
}

pub unsafe fn byte_array_size(a: Obj) -> Obj {
    box_(bytes(a).len())
}

pub unsafe fn sarray_size(a: Obj) -> usize {
    match element_size(a) {
        1 => items::<u8>(a).len(),
        _ => items::<f64>(a).len(),
    }
}

pub unsafe fn byte_array_uget(a: Obj, i: usize) -> u8 {
    bytes(a)[i]
}

pub unsafe fn byte_array_fget(a: Obj, i: Obj) -> u8 {
    bytes(a)[unbox(i)]
}

/// Lean's `bytes[i]!`: an index outside the array is a panic.
pub unsafe fn byte_array_get(a: Obj, i: Obj) -> u8 {
    match index(i, bytes(a).len()) {
        Some(i) => bytes(a)[i],
        None => out_of_bounds(),
    }
}

pub unsafe fn byte_array_push(a: Obj, byte: u8) -> Obj {
    let (a, items) = exclusive::<u8>(a);
    items.push(byte);
    a
}

pub unsafe fn byte_array_uset(a: Obj, i: usize, byte: u8) -> Obj {
    let (a, items) = exclusive::<u8>(a);
    items[i] = byte;
    a
}

pub unsafe fn byte_array_fset(a: Obj, i: Obj, byte: u8) -> Obj {
    byte_array_uset(a, unbox(i), byte)
}

/// Lean's `bytes.set! i b`: an index outside the array is a panic.
pub unsafe fn byte_array_set(a: Obj, i: Obj, byte: u8) -> Obj {
    match index(i, bytes(a).len()) {
        Some(i) => byte_array_uset(a, i, byte),
        None => out_of_bounds(),
    }
}

/// `target` with `len` bytes of `source` from `source_offset` written over it at
/// `target_offset`. The result ends where the copied bytes end if they reach past the end
/// of `target`. Consumes `target`.
pub unsafe fn byte_array_copy_slice(
    source: Obj,
    source_offset: Obj,
    target: Obj,
    target_offset: Obj,
    len: Obj,
    _exact: u8,
) -> Obj {
    let small = |n: Obj| if is_scalar(n) { unbox(n) } else { usize::MAX };
    let source = bytes(source);
    let from = small(source_offset).min(source.len());
    let slice = source[from..from.saturating_add(small(len)).min(source.len())].to_vec();
    let (target, items) = exclusive::<u8>(target);
    let at = small(target_offset).min(items.len());
    let tail = items.split_off((at + slice.len()).min(items.len()));
    items.truncate(at);
    items.extend_from_slice(&slice);
    items.extend_from_slice(&tail);
    target
}

/// Whether two arrays of the same kind hold the same bits.
pub unsafe fn sarray_dec_eq(a: Obj, b: Obj) -> u8 {
    let equal = match element_size(a) {
        1 => items::<u8>(a) == items::<u8>(b),
        _ => {
            let (a, b) = (items::<f64>(a), items::<f64>(b));
            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
        }
    };
    equal as u8
}

pub unsafe fn byte_array_dec_lt(a: Obj, b: Obj) -> u8 {
    (bytes(a) < bytes(b)) as u8
}

/// An `Ordering`: 0 for less, 1 for equal, 2 for greater.
pub unsafe fn byte_array_compare(a: Obj, b: Obj) -> u8 {
    (bytes(a).cmp(bytes(b)) as i8 + 1) as u8
}

pub unsafe fn byte_array_hash(a: Obj) -> u64 {
    crate::string::hash_bytes(bytes(a))
}

/// See `array::array_mark_linear`: the mark has no effect on values.
pub unsafe fn sarray_mark_linear(a: Obj) -> Obj {
    a
}

pub unsafe fn sarray_propagate_mark(_source: Obj, target: Obj) -> Obj {
    target
}

pub unsafe fn mk_empty_float_array(n: Obj) -> Obj {
    from_vec(Vec::<f64>::with_capacity(capacity(n)))
}

/// A `FloatArray` from an `Array Float`, which it consumes.
pub unsafe fn float_array_mk(a: Obj) -> Obj {
    let values = crate::array::elements(a).iter().map(|&item| crate::object::unbox_float(item)).collect();
    dec(a);
    from_vec::<f64>(values)
}

/// The values as an `Array Float`. Consumes `a`.
pub unsafe fn float_array_data(a: Obj) -> Obj {
    let boxed = items::<f64>(a).iter().map(|&v| crate::object::box_float(v)).collect();
    dec(a);
    crate::array::from_vec(boxed)
}

pub unsafe fn float_array_size(a: Obj) -> Obj {
    box_(items::<f64>(a).len())
}

pub unsafe fn float_array_uget(a: Obj, i: usize) -> f64 {
    items::<f64>(a)[i]
}

pub unsafe fn float_array_fget(a: Obj, i: Obj) -> f64 {
    items::<f64>(a)[unbox(i)]
}

/// Lean's `values[i]!`: an index outside the array is a panic.
pub unsafe fn float_array_get(a: Obj, i: Obj) -> f64 {
    match index(i, items::<f64>(a).len()) {
        Some(i) => items::<f64>(a)[i],
        None => out_of_bounds(),
    }
}

pub unsafe fn float_array_push(a: Obj, value: f64) -> Obj {
    let (a, items) = exclusive::<f64>(a);
    items.push(value);
    a
}

pub unsafe fn float_array_uset(a: Obj, i: usize, value: f64) -> Obj {
    let (a, items) = exclusive::<f64>(a);
    items[i] = value;
    a
}

pub unsafe fn float_array_fset(a: Obj, i: Obj, value: f64) -> Obj {
    float_array_uset(a, unbox(i), value)
}

pub unsafe fn float_array_set(a: Obj, i: Obj, value: f64) -> Obj {
    match index(i, items::<f64>(a).len()) {
        Some(i) => float_array_uset(a, i, value),
        None => out_of_bounds(),
    }
}

/// The functions of this module that generated code may call, named as in `lean.h` without
/// the `lean_` prefix.
pub(crate) const OPS: &[&str] = &[
    "mk_empty_byte_array", "byte_array_mk", "byte_array_data", "byte_array_size", "sarray_size", "byte_array_uget",
    "byte_array_fget", "byte_array_get", "byte_array_push", "byte_array_uset", "byte_array_fset", "byte_array_set",
    "byte_array_copy_slice", "sarray_dec_eq", "byte_array_dec_lt", "byte_array_compare", "byte_array_hash",
    "sarray_mark_linear", "sarray_propagate_mark", "mk_empty_float_array", "float_array_mk", "float_array_data",
    "float_array_size", "float_array_uget", "float_array_fget", "float_array_get", "float_array_push",
    "float_array_uset", "float_array_fset", "float_array_set",
];