Skip to main content

inlean_runtime/
sarray.rs

1//! Lean's unboxed arrays: `ByteArray` and `FloatArray`.
2//!
3//! Each is a `Vec` of the element type inside a Lean object, so a `Vec<u8>` or `Vec<f64>`
4//! moves in and out without conversion. As in `lean.h`: an array a function changes is
5//! consumed, arrays and indexes that are only read are borrowed, results are owned.
6
7use crate::object::{box_, count_object, dec, dec_ref, is_exclusive, is_scalar, new_header, unbox, Header, Obj, TAG_SARRAY};
8
9#[repr(C)]
10struct Scalars<T> {
11    header: Header,
12    items: Vec<T>,
13}
14
15/// The size in bytes of the elements of a scalar array, kept in its header so that the
16/// object can be freed without knowing its type.
17unsafe fn element_size(o: Obj) -> u8 {
18    (*o.header()).other()
19}
20
21pub(crate) unsafe fn free(o: Obj) {
22    count_object(-1);
23    match element_size(o) {
24        1 => drop(Box::from_raw(o.header().cast::<Scalars<u8>>())),
25        _ => drop(Box::from_raw(o.header().cast::<Scalars<f64>>())),
26    }
27}
28
29fn from_vec<T>(items: Vec<T>) -> Obj {
30    count_object(1);
31    let array = Box::new(Scalars { header: new_header(TAG_SARRAY, size_of::<T>() as u8, 0), items });
32    Obj::from_header(Box::into_raw(array).cast())
33}
34
35unsafe fn items<'a, T>(a: Obj) -> &'a Vec<T> {
36    &(*a.header().cast::<Scalars<T>>()).items
37}
38
39/// The elements of an array the caller owns, for changing in place: `a` itself if nothing
40/// else refers to it, and otherwise a copy, with the reference to `a` given up.
41unsafe fn exclusive<'a, T: Clone>(a: Obj) -> (Obj, &'a mut Vec<T>) {
42    let a = if is_exclusive(a) {
43        a
44    } else {
45        let copy = from_vec(items::<T>(a).clone());
46        dec_ref(a);
47        copy
48    };
49    (a, &mut (*a.header().cast::<Scalars<T>>()).items)
50}
51
52/// The elements, giving up one reference. Takes the buffer without copying when nothing
53/// else refers to the array.
54unsafe fn into_vec<T: Clone>(a: Obj) -> Vec<T> {
55    if is_exclusive(a) {
56        count_object(-1);
57        return Box::from_raw(a.header().cast::<Scalars<T>>()).items;
58    }
59    let copy = items::<T>(a).clone();
60    dec_ref(a);
61    copy
62}
63
64/// An index given as a `Nat`, if it is inside an array of `len` elements.
65unsafe fn index(i: Obj, len: usize) -> Option<usize> {
66    (is_scalar(i) && unbox(i) < len).then(|| unbox(i))
67}
68
69#[cold]
70fn out_of_bounds() -> ! {
71    panic!("inlean: index out of bounds")
72}
73
74fn capacity(n: Obj) -> usize {
75    if is_scalar(n) {
76        unbox(n).min(1 << 20)
77    } else {
78        0
79    }
80}
81
82/// A `ByteArray` that takes over the buffer of `bytes`.
83pub fn byte_array_from_vec(bytes: Vec<u8>) -> Obj {
84    from_vec(bytes)
85}
86
87/// The bytes of a `ByteArray`, giving up one reference to it.
88pub unsafe fn byte_array_into_vec(a: Obj) -> Vec<u8> {
89    into_vec(a)
90}
91
92/// The bytes of a `ByteArray`.
93pub unsafe fn bytes<'a>(a: Obj) -> &'a [u8] {
94    items::<u8>(a)
95}
96
97/// A `FloatArray` that takes over the buffer of `values`.
98pub fn float_array_from_vec(values: Vec<f64>) -> Obj {
99    from_vec(values)
100}
101
102/// The values of a `FloatArray`, giving up one reference to it.
103pub unsafe fn float_array_into_vec(a: Obj) -> Vec<f64> {
104    into_vec(a)
105}
106
107pub unsafe fn mk_empty_byte_array(n: Obj) -> Obj {
108    from_vec(Vec::<u8>::with_capacity(capacity(n)))
109}
110
111/// A `ByteArray` from an `Array UInt8`, which it consumes.
112pub unsafe fn byte_array_mk(a: Obj) -> Obj {
113    let bytes = crate::array::elements(a).iter().map(|&item| unbox(item) as u8).collect();
114    dec(a);
115    from_vec::<u8>(bytes)
116}
117
118/// The bytes as an `Array UInt8`. Consumes `a`.
119pub unsafe fn byte_array_data(a: Obj) -> Obj {
120    let boxed = bytes(a).iter().map(|&b| box_(b as usize)).collect();
121    dec(a);
122    crate::array::from_vec(boxed)
123}
124
125pub unsafe fn byte_array_size(a: Obj) -> Obj {
126    box_(bytes(a).len())
127}
128
129pub unsafe fn sarray_size(a: Obj) -> usize {
130    match element_size(a) {
131        1 => items::<u8>(a).len(),
132        _ => items::<f64>(a).len(),
133    }
134}
135
136pub unsafe fn byte_array_uget(a: Obj, i: usize) -> u8 {
137    bytes(a)[i]
138}
139
140pub unsafe fn byte_array_fget(a: Obj, i: Obj) -> u8 {
141    bytes(a)[unbox(i)]
142}
143
144/// Lean's `bytes[i]!`: an index outside the array is a panic.
145pub unsafe fn byte_array_get(a: Obj, i: Obj) -> u8 {
146    match index(i, bytes(a).len()) {
147        Some(i) => bytes(a)[i],
148        None => out_of_bounds(),
149    }
150}
151
152pub unsafe fn byte_array_push(a: Obj, byte: u8) -> Obj {
153    let (a, items) = exclusive::<u8>(a);
154    items.push(byte);
155    a
156}
157
158pub unsafe fn byte_array_uset(a: Obj, i: usize, byte: u8) -> Obj {
159    let (a, items) = exclusive::<u8>(a);
160    items[i] = byte;
161    a
162}
163
164pub unsafe fn byte_array_fset(a: Obj, i: Obj, byte: u8) -> Obj {
165    byte_array_uset(a, unbox(i), byte)
166}
167
168/// Lean's `bytes.set! i b`: an index outside the array is a panic.
169pub unsafe fn byte_array_set(a: Obj, i: Obj, byte: u8) -> Obj {
170    match index(i, bytes(a).len()) {
171        Some(i) => byte_array_uset(a, i, byte),
172        None => out_of_bounds(),
173    }
174}
175
176/// `target` with `len` bytes of `source` from `source_offset` written over it at
177/// `target_offset`. The result ends where the copied bytes end if they reach past the end
178/// of `target`. Consumes `target`.
179pub unsafe fn byte_array_copy_slice(
180    source: Obj,
181    source_offset: Obj,
182    target: Obj,
183    target_offset: Obj,
184    len: Obj,
185    _exact: u8,
186) -> Obj {
187    let small = |n: Obj| if is_scalar(n) { unbox(n) } else { usize::MAX };
188    let source = bytes(source);
189    let from = small(source_offset).min(source.len());
190    let slice = source[from..from.saturating_add(small(len)).min(source.len())].to_vec();
191    let (target, items) = exclusive::<u8>(target);
192    let at = small(target_offset).min(items.len());
193    let tail = items.split_off((at + slice.len()).min(items.len()));
194    items.truncate(at);
195    items.extend_from_slice(&slice);
196    items.extend_from_slice(&tail);
197    target
198}
199
200/// Whether two arrays of the same kind hold the same bits.
201pub unsafe fn sarray_dec_eq(a: Obj, b: Obj) -> u8 {
202    let equal = match element_size(a) {
203        1 => items::<u8>(a) == items::<u8>(b),
204        _ => {
205            let (a, b) = (items::<f64>(a), items::<f64>(b));
206            a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
207        }
208    };
209    equal as u8
210}
211
212pub unsafe fn byte_array_dec_lt(a: Obj, b: Obj) -> u8 {
213    (bytes(a) < bytes(b)) as u8
214}
215
216/// An `Ordering`: 0 for less, 1 for equal, 2 for greater.
217pub unsafe fn byte_array_compare(a: Obj, b: Obj) -> u8 {
218    (bytes(a).cmp(bytes(b)) as i8 + 1) as u8
219}
220
221pub unsafe fn byte_array_hash(a: Obj) -> u64 {
222    crate::string::hash_bytes(bytes(a))
223}
224
225/// See `array::array_mark_linear`: the mark has no effect on values.
226pub unsafe fn sarray_mark_linear(a: Obj) -> Obj {
227    a
228}
229
230pub unsafe fn sarray_propagate_mark(_source: Obj, target: Obj) -> Obj {
231    target
232}
233
234pub unsafe fn mk_empty_float_array(n: Obj) -> Obj {
235    from_vec(Vec::<f64>::with_capacity(capacity(n)))
236}
237
238/// A `FloatArray` from an `Array Float`, which it consumes.
239pub unsafe fn float_array_mk(a: Obj) -> Obj {
240    let values = crate::array::elements(a).iter().map(|&item| crate::object::unbox_float(item)).collect();
241    dec(a);
242    from_vec::<f64>(values)
243}
244
245/// The values as an `Array Float`. Consumes `a`.
246pub unsafe fn float_array_data(a: Obj) -> Obj {
247    let boxed = items::<f64>(a).iter().map(|&v| crate::object::box_float(v)).collect();
248    dec(a);
249    crate::array::from_vec(boxed)
250}
251
252pub unsafe fn float_array_size(a: Obj) -> Obj {
253    box_(items::<f64>(a).len())
254}
255
256pub unsafe fn float_array_uget(a: Obj, i: usize) -> f64 {
257    items::<f64>(a)[i]
258}
259
260pub unsafe fn float_array_fget(a: Obj, i: Obj) -> f64 {
261    items::<f64>(a)[unbox(i)]
262}
263
264/// Lean's `values[i]!`: an index outside the array is a panic.
265pub unsafe fn float_array_get(a: Obj, i: Obj) -> f64 {
266    match index(i, items::<f64>(a).len()) {
267        Some(i) => items::<f64>(a)[i],
268        None => out_of_bounds(),
269    }
270}
271
272pub unsafe fn float_array_push(a: Obj, value: f64) -> Obj {
273    let (a, items) = exclusive::<f64>(a);
274    items.push(value);
275    a
276}
277
278pub unsafe fn float_array_uset(a: Obj, i: usize, value: f64) -> Obj {
279    let (a, items) = exclusive::<f64>(a);
280    items[i] = value;
281    a
282}
283
284pub unsafe fn float_array_fset(a: Obj, i: Obj, value: f64) -> Obj {
285    float_array_uset(a, unbox(i), value)
286}
287
288pub unsafe fn float_array_set(a: Obj, i: Obj, value: f64) -> Obj {
289    match index(i, items::<f64>(a).len()) {
290        Some(i) => float_array_uset(a, i, value),
291        None => out_of_bounds(),
292    }
293}
294
295/// The functions of this module that generated code may call, named as in `lean.h` without
296/// the `lean_` prefix.
297pub(crate) const OPS: &[&str] = &[
298    "mk_empty_byte_array", "byte_array_mk", "byte_array_data", "byte_array_size", "sarray_size", "byte_array_uget",
299    "byte_array_fget", "byte_array_get", "byte_array_push", "byte_array_uset", "byte_array_fset", "byte_array_set",
300    "byte_array_copy_slice", "sarray_dec_eq", "byte_array_dec_lt", "byte_array_compare", "byte_array_hash",
301    "sarray_mark_linear", "sarray_propagate_mark", "mk_empty_float_array", "float_array_mk", "float_array_data",
302    "float_array_size", "float_array_uget", "float_array_fget", "float_array_get", "float_array_push",
303    "float_array_uset", "float_array_fset", "float_array_set",
304];