tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

434 lignes · 16689 octetsBrut · Historique
1//! `std/bytes`: immutable binary data (ADR 0012).
2//!
3//! A `Bytes` block is a `TAG_BYTES` block whose raw area holds an i64
4//! length and the bytes. Every operation copies into a fresh block: there
5//! are no views into another block, so a small slice never keeps a large
6//! buffer alive. Like every `@extern` function these borrow their
7//! arguments, and they must behave exactly like the interpreter's
8//! (`louise_interp`).
9
10use louise_rt_prims::hash_bytes;
11
12use crate::abi::{Ctx, Value, int};
13use crate::int::saturating;
14use crate::prims::{boolean, order, panic_with};
15use crate::values::{bytes_from, bytes_of, error, list, list_items, ok, tl_string_from};
16
17/// # Safety
18/// `b` must be live `Bytes`.
19#[unsafe(no_mangle)]
20pub unsafe extern "C" fn tl_bytes_length(_ctx: *mut Ctx, b: Value) -> Value {
21 // SAFETY: caller guarantees live `Bytes`.
22 int(unsafe { bytes_of(b) }.len() as i64)
23}
24
25/// The byte at index `i`, or -1 when `i` is out of range.
26///
27/// # Safety
28/// `b` must be live `Bytes`.
29#[unsafe(no_mangle)]
30pub unsafe extern "C" fn tl_bytes_at(_ctx: *mut Ctx, b: Value, i: Value) -> Value {
31 // SAFETY: caller guarantees live `Bytes` and a live Int.
32 let (bytes, i) = unsafe { (bytes_of(b), saturating(i)) };
33 let byte = usize::try_from(i).ok().and_then(|i| bytes.get(i));
34 int(byte.map_or(-1, |&b| i64::from(b)))
35}
36
37/// The `N` bytes at `off`, if they are all there.
38fn read_be<const N: usize>(bytes: &[u8], off: i64) -> Option<[u8; N]> {
39 let off = usize::try_from(off).ok()?;
40 bytes.get(off..off.checked_add(N)?)?.try_into().ok()
41}
42
43/// The unsigned big-endian 16-bit integer at `off`, or -1 when
44/// `off..off + 2` is out of range.
45///
46/// # Safety
47/// `b` must be live `Bytes`.
48#[unsafe(no_mangle)]
49pub unsafe extern "C" fn tl_bytes_read_u16be(_ctx: *mut Ctx, b: Value, off: Value) -> Value {
50 // SAFETY: caller guarantees live `Bytes` and a live Int.
51 let n = unsafe { read_be::<2>(bytes_of(b), saturating(off)) };
52 int(n.map_or(-1, |c| i64::from(u16::from_be_bytes(c))))
53}
54
55/// The unsigned big-endian 32-bit integer at `off`, or -1 when
56/// `off..off + 4` is out of range.
57///
58/// # Safety
59/// `b` must be live `Bytes`.
60#[unsafe(no_mangle)]
61pub unsafe extern "C" fn tl_bytes_read_u32be(_ctx: *mut Ctx, b: Value, off: Value) -> Value {
62 // SAFETY: caller guarantees live `Bytes` and a live Int.
63 let n = unsafe { read_be::<4>(bytes_of(b), saturating(off)) };
64 int(n.map_or(-1, |c| i64::from(u32::from_be_bytes(c))))
65}
66
67/// The unsigned big-endian 64-bit integer at `off` (a big integer above
68/// 2^62), or -1 when `off..off + 8` is out of range.
69///
70/// # Safety
71/// `b` must be live `Bytes`; `ctx` the running actor's context.
72#[unsafe(no_mangle)]
73pub unsafe extern "C" fn tl_bytes_read_u64be(ctx: *mut Ctx, b: Value, off: Value) -> Value {
74 // SAFETY: caller guarantees live `Bytes` and a live Int.
75 let n = unsafe { read_be::<8>(bytes_of(b), saturating(off)) };
76 match n {
77 None => int(-1),
78 Some(c) => crate::int::from_big(ctx, &num_bigint::BigInt::from(u64::from_be_bytes(c))),
79 }
80}
81
82/// The bytes from `start` up to `end` (excluded), both clamped to the
83/// bounds; empty when `end <= start`.
84///
85/// # Safety
86/// `b` must be live `Bytes`.
87#[unsafe(no_mangle)]
88pub unsafe extern "C" fn tl_bytes_slice(
89 ctx: *mut Ctx,
90 b: Value,
91 start: Value,
92 end: Value,
93) -> Value {
94 // SAFETY: caller guarantees live `Bytes`.
95 let bytes = unsafe { bytes_of(b) };
96 // SAFETY: caller guarantees live Ints.
97 let clamp = |v: Value| unsafe { saturating(v) }.clamp(0, bytes.len() as i64) as usize;
98 let (start, end) = (clamp(start), clamp(end));
99 bytes_from(ctx, &bytes[start..end.max(start)])
100}
101
102/// # Safety
103/// Both arguments must be live `Bytes`.
104#[unsafe(no_mangle)]
105pub unsafe extern "C" fn tl_bytes_concat(ctx: *mut Ctx, a: Value, b: Value) -> Value {
106 // SAFETY: caller guarantees live `Bytes`.
107 let (a, b) = unsafe { (bytes_of(a), bytes_of(b)) };
108 let parts = || [a, b].into_iter();
109 let (out, at) = crate::values::bytes_uninit(ctx, crate::values::joined_len(parts(), 0));
110 // SAFETY: `at` has room for both.
111 unsafe { crate::values::write_joined(at, parts(), &[]) };
112 out
113}
114
115/// The concatenation of a `List<Bytes>`, in one allocation.
116///
117/// # Safety
118/// `parts` must be a live list of `Bytes`.
119#[unsafe(no_mangle)]
120pub unsafe extern "C" fn tl_bytes_concat_all(ctx: *mut Ctx, parts: Value) -> Value {
121 // Two passes over the list, straight into the result (issue #129).
122 // SAFETY: caller guarantees a list of `Bytes`, live meanwhile.
123 let items = || unsafe { list_items(parts).map(|p| bytes_of(p)) };
124 let (out, at) = crate::values::bytes_uninit(ctx, crate::values::joined_len(items(), 0));
125 // SAFETY: `at` has room for the joined length of the same parts.
126 unsafe { crate::values::write_joined(at, items(), &[]) };
127 out
128}
129
130/// # Safety
131/// Both arguments must be live `Bytes`.
132#[unsafe(no_mangle)]
133pub unsafe extern "C" fn tl_bytes_eq(_ctx: *mut Ctx, a: Value, b: Value) -> Value {
134 // SAFETY: caller guarantees live `Bytes`.
135 boolean(unsafe { bytes_of(a) == bytes_of(b) })
136}
137
138/// Lexicographic, byte by byte (a prefix is smaller).
139///
140/// # Safety
141/// Both arguments must be live `Bytes`.
142#[unsafe(no_mangle)]
143pub unsafe extern "C" fn tl_bytes_compare(_ctx: *mut Ctx, a: Value, b: Value) -> Value {
144 // SAFETY: caller guarantees live `Bytes`.
145 order(unsafe { bytes_of(a).cmp(bytes_of(b)) })
146}
147
148/// # Safety
149/// `b` must be live `Bytes`.
150#[unsafe(no_mangle)]
151pub unsafe extern "C" fn tl_hash_bytes(_ctx: *mut Ctx, b: Value) -> Value {
152 // SAFETY: caller guarantees live `Bytes`.
153 int(hash_bytes(unsafe { bytes_of(b) }))
154}
155
156/// `b"..."`, printable ASCII as is and other bytes escaped (Rust's
157/// `escape_ascii`).
158///
159/// # Safety
160/// `b` must be live `Bytes`.
161#[unsafe(no_mangle)]
162pub unsafe extern "C" fn tl_bytes_debug(ctx: *mut Ctx, b: Value) -> Value {
163 // SAFETY: caller guarantees live `Bytes`.
164 let text = format!("b\"{}\"", unsafe { bytes_of(b) }.escape_ascii());
165 // SAFETY: `text` is valid for its length.
166 unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) }
167}
168
169/// The UTF-8 encoding of a string.
170///
171/// # Safety
172/// `s` must be a live string.
173#[unsafe(no_mangle)]
174pub unsafe extern "C" fn tl_bytes_from_string(ctx: *mut Ctx, s: Value) -> Value {
175 // SAFETY: caller guarantees a live string.
176 bytes_from(ctx, unsafe { bytes_of(s) })
177}
178
179/// `Ok(text)` if `b` is valid UTF-8, else `Error` naming the first
180/// invalid byte.
181///
182/// # Safety
183/// `b` must be live `Bytes`.
184#[unsafe(no_mangle)]
185pub unsafe extern "C" fn tl_bytes_to_string(ctx: *mut Ctx, b: Value) -> Value {
186 // SAFETY: caller guarantees live `Bytes`.
187 match std::str::from_utf8(unsafe { bytes_of(b) }) {
188 // SAFETY: `text` is valid for its length.
189 Ok(text) => ok(ctx, unsafe {
190 tl_string_from(ctx, text.as_ptr().cast(), text.len())
191 }),
192 Err(e) => error(ctx, &utf8_error(&e)),
193 }
194}
195
196/// The message of a failed UTF-8 conversion (also the interpreter's).
197pub fn utf8_error(e: &std::str::Utf8Error) -> String {
198 format!("invalid UTF-8 at byte {}", e.valid_up_to())
199}
200
201/// `b` as text, with each invalid sequence replaced by U+FFFD.
202///
203/// # Safety
204/// `b` must be live `Bytes`.
205#[unsafe(no_mangle)]
206pub unsafe extern "C" fn tl_bytes_to_string_lossy(ctx: *mut Ctx, b: Value) -> Value {
207 // SAFETY: caller guarantees live `Bytes`.
208 let text = String::from_utf8_lossy(unsafe { bytes_of(b) });
209 // SAFETY: `text` is valid for its length.
210 unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) }
211}
212
213/// `to_string` of `slice(b, off, off + len)` without the intermediate
214/// `Bytes`: the bounds are clamped the same way, and the error names the
215/// first invalid byte of the range.
216///
217/// # Safety
218/// `b` must be live `Bytes`.
219#[unsafe(no_mangle)]
220pub unsafe extern "C" fn tl_bytes_to_string_range(
221 ctx: *mut Ctx,
222 b: Value,
223 off: Value,
224 len: Value,
225) -> Value {
226 // SAFETY: caller guarantees live `Bytes`.
227 let bytes = unsafe { bytes_of(b) };
228 // SAFETY: caller guarantees live Ints.
229 let (off, len) = unsafe { (saturating(off), saturating(len)) };
230 let clamp = |v: i64| v.clamp(0, bytes.len() as i64) as usize;
231 let (start, end) = (clamp(off), clamp(off.saturating_add(len)));
232 match std::str::from_utf8(&bytes[start..end.max(start)]) {
233 // SAFETY: `text` is valid for its length.
234 Ok(text) => ok(ctx, unsafe {
235 tl_string_from(ctx, text.as_ptr().cast(), text.len())
236 }),
237 Err(e) => error(ctx, &utf8_error(&e)),
238 }
239}
240
241/// `Bytes` from a `List<Int>`; panics on an Int that is not a byte.
242///
243/// # Safety
244/// `ctx` must be the running actor's context; `items` a live list of Ints.
245#[unsafe(no_mangle)]
246pub unsafe extern "C" fn tl_bytes_from_list(ctx: *mut Ctx, items: Value) -> Value {
247 let mut bytes = Vec::new();
248 // SAFETY: caller guarantees a list of Ints.
249 for v in unsafe { list_items(items) } {
250 // SAFETY: the list holds live Ints.
251 match u8::try_from(unsafe { saturating(v) }) {
252 Ok(b) => bytes.push(b),
253 Err(_) => {
254 // SAFETY: as above.
255 let shown = unsafe { crate::int::to_big(v) };
256 let message = format!("bytes.from_list: {shown} is not a byte");
257 // SAFETY: caller guarantees the running actor's context.
258 return unsafe { panic_with(ctx, &message) };
259 }
260 }
261 }
262 bytes_from(ctx, &bytes)
263}
264
265/// The bytes of `b` as a `List<Int>`.
266///
267/// # Safety
268/// `b` must be live `Bytes`.
269#[unsafe(no_mangle)]
270pub unsafe extern "C" fn tl_bytes_to_list(ctx: *mut Ctx, b: Value) -> Value {
271 // SAFETY: caller guarantees live `Bytes`.
272 let bytes = unsafe { bytes_of(b) };
273 list(ctx, bytes.iter().map(|&b| int(i64::from(b))))
274}
275
276/// The length of `b`, for C bindings (`tl_bytes_ptr` gives its bytes).
277///
278/// # Safety
279/// `b` must be live `Bytes` (borrowed).
280#[unsafe(no_mangle)]
281pub unsafe extern "C" fn tl_bytes_len(b: Value) -> usize {
282 // SAFETY: caller guarantees live `Bytes`.
283 unsafe { bytes_of(b) }.len()
284}
285
286/// The first byte of `b`, for C bindings: `tl_bytes_len(b)` bytes, valid
287/// while `b` lives, not NUL-terminated (`Bytes` may hold zeros).
288///
289/// # Safety
290/// `b` must be live `Bytes` (borrowed).
291#[unsafe(no_mangle)]
292pub unsafe extern "C" fn tl_bytes_ptr(b: Value) -> *const u8 {
293 // SAFETY: caller guarantees live `Bytes`.
294 unsafe { bytes_of(b) }.as_ptr()
295}
296
297/// New `Bytes` (owned) holding a copy of the `len` bytes at `bytes`, for C
298/// bindings. `bytes` may be null when `len` is 0.
299///
300/// # Safety
301/// `ctx` must be the running actor's context; `bytes` valid for reads of
302/// `len` bytes.
303#[unsafe(no_mangle)]
304pub unsafe extern "C" fn tl_bytes_from(ctx: *mut Ctx, bytes: *const u8, len: usize) -> Value {
305 if len == 0 {
306 return bytes_from(ctx, &[]);
307 }
308 // SAFETY: caller guarantees `len` readable bytes (non-null when len > 0).
309 bytes_from(ctx, unsafe { std::slice::from_raw_parts(bytes, len) })
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315 use crate::abi::{Block, UNIT, int, int_get};
316 use crate::heap::drop_value;
317 use crate::values::bytes_from;
318
319 fn error_of(bytes: &[u8]) -> String {
320 super::utf8_error(&std::str::from_utf8(bytes).unwrap_err())
321 }
322
323 #[test]
324 fn utf8_errors_name_the_first_invalid_byte() {
325 assert_eq!(error_of(b"ab\xffc"), "invalid UTF-8 at byte 2");
326 // A sequence cut short is invalid where it starts.
327 assert_eq!(error_of(b"caf\xc3"), "invalid UTF-8 at byte 3");
328 }
329
330 /// A `Result`'s constructor tag (0 `Ok`, 1 `Error`) and its payload
331 /// as text.
332 ///
333 /// # Safety
334 /// `r` must be a live `Result` of a string and a string.
335 unsafe fn result_text(r: Value) -> (u16, String) {
336 // SAFETY: forwarded caller guarantee.
337 unsafe {
338 let b = r as *mut Block;
339 let tag = (*b).header.tag;
340 let field = Block::fields_ptr(b).read();
341 (tag, String::from_utf8_lossy(bytes_of(field)).into_owned())
342 }
343 }
344
345 /// The scenarios run as one root actor, so drops have a context.
346 unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value {
347 // SAFETY: every value is owned by this test.
348 unsafe {
349 let b = bytes_from(ctx, &[0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0xff]);
350 // In-range big-endian reads; out of range (also negative, or
351 // reaching past the end) is -1.
352 assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(0))), 0x1234);
353 assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(7))), 0xf0ff);
354 assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(8))), -1);
355 assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(-1))), -1);
356 assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(1))), 0x3456789a);
357 assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(4))), 0x9abcdef0);
358 assert_eq!(
359 int_get(tl_bytes_read_u32be(ctx, b, int(5))),
360 0xbcdef0ffu32 as i64
361 );
362 assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(6))), -1);
363 let small = tl_bytes_read_u64be(ctx, b, int(0));
364 assert_eq!(
365 crate::int::to_big(small),
366 num_bigint::BigInt::from(0x123456789abcdef0_u64)
367 );
368 assert_eq!(int_get(tl_bytes_read_u64be(ctx, b, int(2))), -1);
369 drop_value(ctx, b);
370 // Above 2^62 the read is a big integer.
371 let max = bytes_from(ctx, &[0xff; 8]);
372 let big = tl_bytes_read_u64be(ctx, max, int(0));
373 assert_eq!(crate::int::to_big(big), num_bigint::BigInt::from(u64::MAX));
374 drop_value(ctx, max);
375 drop_value(ctx, big);
376
377 let s = bytes_from(ctx, "héllo".as_bytes());
378 // The whole range, a subrange, and clamped bounds.
379 let whole = tl_bytes_to_string_range(ctx, s, int(0), int(6));
380 assert_eq!(result_text(whole), (0, "héllo".to_owned()));
381 let sub = tl_bytes_to_string_range(ctx, s, int(3), int(2));
382 assert_eq!(result_text(sub), (0, "ll".to_owned()));
383 let clamped = tl_bytes_to_string_range(ctx, s, int(3), int(100));
384 assert_eq!(result_text(clamped), (0, "llo".to_owned()));
385 let negative = tl_bytes_to_string_range(ctx, s, int(-2), int(3));
386 assert_eq!(result_text(negative), (0, "h".to_owned()));
387 let empty = tl_bytes_to_string_range(ctx, s, int(4), int(-9));
388 assert_eq!(result_text(empty), (0, String::new()));
389 // The error names the first invalid byte of the range.
390 let half = tl_bytes_to_string_range(ctx, s, int(1), int(1));
391 assert_eq!(result_text(half), (1, "invalid UTF-8 at byte 0".to_owned()));
392 let cut = tl_bytes_to_string_range(ctx, s, int(0), int(2));
393 assert_eq!(result_text(cut), (1, "invalid UTF-8 at byte 1".to_owned()));
394 for r in [whole, sub, clamped, negative, empty, half, cut] {
395 drop_value(ctx, r);
396 }
397 drop_value(ctx, s);
398 }
399 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
400 UNIT
401 }
402
403 /// The C bindings' accessors: a copy in, the same bytes out, zeros
404 /// included; an empty copy from a null pointer.
405 unsafe extern "C" fn binding_accessors(ctx: *mut Ctx) -> Value {
406 // SAFETY: every value is owned by this test.
407 unsafe {
408 let data = [0u8, 1, 0, 255, 7];
409 let b = tl_bytes_from(ctx, data.as_ptr(), data.len());
410 assert_eq!(tl_bytes_len(b), 5);
411 assert_eq!(std::slice::from_raw_parts(tl_bytes_ptr(b), 5), data);
412 assert_eq!(int_get(tl_bytes_length(ctx, b)), 5);
413 let empty = tl_bytes_from(ctx, std::ptr::null(), 0);
414 assert_eq!(tl_bytes_len(empty), 0);
415 drop_value(ctx, b);
416 drop_value(ctx, empty);
417 }
418 assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0);
419 UNIT
420 }
421
422 #[test]
423 fn binding_accessors_round_trip() {
424 // SAFETY: `binding_accessors` follows the generated-code convention.
425 let code = unsafe { crate::sched::run_test_actor(binding_accessors) };
426 assert_eq!(code, 0);
427 }
428
429 #[test]
430 fn cursor_reads_and_string_ranges() {
431 // SAFETY: `scenarios` follows the generated-code convention.
432 assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0);
433 }
434}