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