//! `std/bytes`: immutable binary data (ADR 0012). //! //! A `Bytes` block is a `TAG_BYTES` block whose raw area holds an i64 //! length and the bytes. Every operation copies into a fresh block: there //! are no views into another block, so a small slice never keeps a large //! buffer alive. Like every `@extern` function these borrow their //! arguments, and they must behave exactly like the interpreter's //! (`louise_interp`). use louise_rt_prims::hash_bytes; use crate::abi::{Ctx, Value, int}; use crate::int::saturating; use crate::prims::{boolean, order, panic_with}; use crate::values::{bytes_from, bytes_of, error, list, list_items, ok, tl_string_from}; /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_length(_ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. int(unsafe { bytes_of(b) }.len() as i64) } /// The byte at index `i`, or -1 when `i` is out of range. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_at(_ctx: *mut Ctx, b: Value, i: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let (bytes, i) = unsafe { (bytes_of(b), saturating(i)) }; let byte = usize::try_from(i).ok().and_then(|i| bytes.get(i)); int(byte.map_or(-1, |&b| i64::from(b))) } /// The `N` bytes at `off`, if they are all there. fn read_be(bytes: &[u8], off: i64) -> Option<[u8; N]> { let off = usize::try_from(off).ok()?; bytes.get(off..off.checked_add(N)?)?.try_into().ok() } /// The unsigned big-endian 16-bit integer at `off`, or -1 when /// `off..off + 2` is out of range. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_read_u16be(_ctx: *mut Ctx, b: Value, off: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let n = unsafe { read_be::<2>(bytes_of(b), saturating(off)) }; int(n.map_or(-1, |c| i64::from(u16::from_be_bytes(c)))) } /// The unsigned big-endian 32-bit integer at `off`, or -1 when /// `off..off + 4` is out of range. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_read_u32be(_ctx: *mut Ctx, b: Value, off: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let n = unsafe { read_be::<4>(bytes_of(b), saturating(off)) }; int(n.map_or(-1, |c| i64::from(u32::from_be_bytes(c)))) } /// The unsigned big-endian 64-bit integer at `off` (a big integer above /// 2^62), or -1 when `off..off + 8` is out of range. /// /// # Safety /// `b` must be live `Bytes`; `ctx` the running actor's context. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_read_u64be(ctx: *mut Ctx, b: Value, off: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let n = unsafe { read_be::<8>(bytes_of(b), saturating(off)) }; match n { None => int(-1), Some(c) => crate::int::from_big(ctx, &num_bigint::BigInt::from(u64::from_be_bytes(c))), } } /// The bytes from `start` up to `end` (excluded), both clamped to the /// bounds; empty when `end <= start`. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_slice( ctx: *mut Ctx, b: Value, start: Value, end: Value, ) -> Value { // SAFETY: caller guarantees live `Bytes`. let bytes = unsafe { bytes_of(b) }; // SAFETY: caller guarantees live Ints. let clamp = |v: Value| unsafe { saturating(v) }.clamp(0, bytes.len() as i64) as usize; let (start, end) = (clamp(start), clamp(end)); bytes_from(ctx, &bytes[start..end.max(start)]) } /// # Safety /// Both arguments must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_concat(ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. let (a, b) = unsafe { (bytes_of(a), bytes_of(b)) }; let parts = || [a, b].into_iter(); let (out, at) = crate::values::bytes_uninit(ctx, crate::values::joined_len(parts(), 0)); // SAFETY: `at` has room for both. unsafe { crate::values::write_joined(at, parts(), &[]) }; out } /// The concatenation of a `List`, in one allocation. /// /// # Safety /// `parts` must be a live list of `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_concat_all(ctx: *mut Ctx, parts: Value) -> Value { // Two passes over the list, straight into the result (issue #129). // SAFETY: caller guarantees a list of `Bytes`, live meanwhile. let items = || unsafe { list_items(parts).map(|p| bytes_of(p)) }; let (out, at) = crate::values::bytes_uninit(ctx, crate::values::joined_len(items(), 0)); // SAFETY: `at` has room for the joined length of the same parts. unsafe { crate::values::write_joined(at, items(), &[]) }; out } /// # Safety /// Both arguments must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_eq(_ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. boolean(unsafe { bytes_of(a) == bytes_of(b) }) } /// Lexicographic, byte by byte (a prefix is smaller). /// /// # Safety /// Both arguments must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_compare(_ctx: *mut Ctx, a: Value, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. order(unsafe { bytes_of(a).cmp(bytes_of(b)) }) } /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_hash_bytes(_ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. int(hash_bytes(unsafe { bytes_of(b) })) } /// `b"..."`, printable ASCII as is and other bytes escaped (Rust's /// `escape_ascii`). /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_debug(ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. let text = format!("b\"{}\"", unsafe { bytes_of(b) }.escape_ascii()); // SAFETY: `text` is valid for its length. unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) } } /// The UTF-8 encoding of a string. /// /// # Safety /// `s` must be a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_from_string(ctx: *mut Ctx, s: Value) -> Value { // SAFETY: caller guarantees a live string. bytes_from(ctx, unsafe { bytes_of(s) }) } /// `Ok(text)` if `b` is valid UTF-8, else `Error` naming the first /// invalid byte. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_to_string(ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. match std::str::from_utf8(unsafe { bytes_of(b) }) { // SAFETY: `text` is valid for its length. Ok(text) => ok(ctx, unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) }), Err(e) => error(ctx, &utf8_error(&e)), } } /// The message of a failed UTF-8 conversion (also the interpreter's). pub fn utf8_error(e: &std::str::Utf8Error) -> String { format!("invalid UTF-8 at byte {}", e.valid_up_to()) } /// `b` as text, with each invalid sequence replaced by U+FFFD. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_to_string_lossy(ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. let text = String::from_utf8_lossy(unsafe { bytes_of(b) }); // SAFETY: `text` is valid for its length. unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) } } /// `to_string` of `slice(b, off, off + len)` without the intermediate /// `Bytes`: the bounds are clamped the same way, and the error names the /// first invalid byte of the range. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_to_string_range( ctx: *mut Ctx, b: Value, off: Value, len: Value, ) -> Value { // SAFETY: caller guarantees live `Bytes`. let bytes = unsafe { bytes_of(b) }; // SAFETY: caller guarantees live Ints. let (off, len) = unsafe { (saturating(off), saturating(len)) }; let clamp = |v: i64| v.clamp(0, bytes.len() as i64) as usize; let (start, end) = (clamp(off), clamp(off.saturating_add(len))); match std::str::from_utf8(&bytes[start..end.max(start)]) { // SAFETY: `text` is valid for its length. Ok(text) => ok(ctx, unsafe { tl_string_from(ctx, text.as_ptr().cast(), text.len()) }), Err(e) => error(ctx, &utf8_error(&e)), } } /// `Bytes` from a `List`; panics on an Int that is not a byte. /// /// # Safety /// `ctx` must be the running actor's context; `items` a live list of Ints. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_from_list(ctx: *mut Ctx, items: Value) -> Value { let mut bytes = Vec::new(); // SAFETY: caller guarantees a list of Ints. for v in unsafe { list_items(items) } { // SAFETY: the list holds live Ints. match u8::try_from(unsafe { saturating(v) }) { Ok(b) => bytes.push(b), Err(_) => { // SAFETY: as above. let shown = unsafe { crate::int::to_big(v) }; let message = format!("bytes.from_list: {shown} is not a byte"); // SAFETY: caller guarantees the running actor's context. return unsafe { panic_with(ctx, &message) }; } } } bytes_from(ctx, &bytes) } /// The bytes of `b` as a `List`. /// /// # Safety /// `b` must be live `Bytes`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_to_list(ctx: *mut Ctx, b: Value) -> Value { // SAFETY: caller guarantees live `Bytes`. let bytes = unsafe { bytes_of(b) }; list(ctx, bytes.iter().map(|&b| int(i64::from(b)))) } /// The length of `b`, for C bindings (`tl_bytes_ptr` gives its bytes). /// /// # Safety /// `b` must be live `Bytes` (borrowed). #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_len(b: Value) -> usize { // SAFETY: caller guarantees live `Bytes`. unsafe { bytes_of(b) }.len() } /// The first byte of `b`, for C bindings: `tl_bytes_len(b)` bytes, valid /// while `b` lives, not NUL-terminated (`Bytes` may hold zeros). /// /// # Safety /// `b` must be live `Bytes` (borrowed). #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_ptr(b: Value) -> *const u8 { // SAFETY: caller guarantees live `Bytes`. unsafe { bytes_of(b) }.as_ptr() } /// New `Bytes` (owned) holding a copy of the `len` bytes at `bytes`, for C /// bindings. `bytes` may be null when `len` is 0. /// /// # Safety /// `ctx` must be the running actor's context; `bytes` valid for reads of /// `len` bytes. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_bytes_from(ctx: *mut Ctx, bytes: *const u8, len: usize) -> Value { if len == 0 { return bytes_from(ctx, &[]); } // SAFETY: caller guarantees `len` readable bytes (non-null when len > 0). bytes_from(ctx, unsafe { std::slice::from_raw_parts(bytes, len) }) } #[cfg(test)] mod tests { use super::*; use crate::abi::{Block, UNIT, int, int_get}; use crate::heap::drop_value; use crate::values::bytes_from; fn error_of(bytes: &[u8]) -> String { super::utf8_error(&std::str::from_utf8(bytes).unwrap_err()) } #[test] fn utf8_errors_name_the_first_invalid_byte() { assert_eq!(error_of(b"ab\xffc"), "invalid UTF-8 at byte 2"); // A sequence cut short is invalid where it starts. assert_eq!(error_of(b"caf\xc3"), "invalid UTF-8 at byte 3"); } /// A `Result`'s constructor tag (0 `Ok`, 1 `Error`) and its payload /// as text. /// /// # Safety /// `r` must be a live `Result` of a string and a string. unsafe fn result_text(r: Value) -> (u16, String) { // SAFETY: forwarded caller guarantee. unsafe { let b = r as *mut Block; let tag = (*b).header.tag; let field = Block::fields_ptr(b).read(); (tag, String::from_utf8_lossy(bytes_of(field)).into_owned()) } } /// The scenarios run as one root actor, so drops have a context. unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { // SAFETY: every value is owned by this test. unsafe { let b = bytes_from(ctx, &[0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0xff]); // In-range big-endian reads; out of range (also negative, or // reaching past the end) is -1. assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(0))), 0x1234); assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(7))), 0xf0ff); assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(8))), -1); assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(-1))), -1); assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(1))), 0x3456789a); assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(4))), 0x9abcdef0); assert_eq!( int_get(tl_bytes_read_u32be(ctx, b, int(5))), 0xbcdef0ffu32 as i64 ); assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(6))), -1); let small = tl_bytes_read_u64be(ctx, b, int(0)); assert_eq!( crate::int::to_big(small), num_bigint::BigInt::from(0x123456789abcdef0_u64) ); assert_eq!(int_get(tl_bytes_read_u64be(ctx, b, int(2))), -1); drop_value(ctx, b); // Above 2^62 the read is a big integer. let max = bytes_from(ctx, &[0xff; 8]); let big = tl_bytes_read_u64be(ctx, max, int(0)); assert_eq!(crate::int::to_big(big), num_bigint::BigInt::from(u64::MAX)); drop_value(ctx, max); drop_value(ctx, big); let s = bytes_from(ctx, "héllo".as_bytes()); // The whole range, a subrange, and clamped bounds. let whole = tl_bytes_to_string_range(ctx, s, int(0), int(6)); assert_eq!(result_text(whole), (0, "héllo".to_owned())); let sub = tl_bytes_to_string_range(ctx, s, int(3), int(2)); assert_eq!(result_text(sub), (0, "ll".to_owned())); let clamped = tl_bytes_to_string_range(ctx, s, int(3), int(100)); assert_eq!(result_text(clamped), (0, "llo".to_owned())); let negative = tl_bytes_to_string_range(ctx, s, int(-2), int(3)); assert_eq!(result_text(negative), (0, "h".to_owned())); let empty = tl_bytes_to_string_range(ctx, s, int(4), int(-9)); assert_eq!(result_text(empty), (0, String::new())); // The error names the first invalid byte of the range. let half = tl_bytes_to_string_range(ctx, s, int(1), int(1)); assert_eq!(result_text(half), (1, "invalid UTF-8 at byte 0".to_owned())); let cut = tl_bytes_to_string_range(ctx, s, int(0), int(2)); assert_eq!(result_text(cut), (1, "invalid UTF-8 at byte 1".to_owned())); for r in [whole, sub, clamped, negative, empty, half, cut] { drop_value(ctx, r); } drop_value(ctx, s); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } /// The C bindings' accessors: a copy in, the same bytes out, zeros /// included; an empty copy from a null pointer. unsafe extern "C" fn binding_accessors(ctx: *mut Ctx) -> Value { // SAFETY: every value is owned by this test. unsafe { let data = [0u8, 1, 0, 255, 7]; let b = tl_bytes_from(ctx, data.as_ptr(), data.len()); assert_eq!(tl_bytes_len(b), 5); assert_eq!(std::slice::from_raw_parts(tl_bytes_ptr(b), 5), data); assert_eq!(int_get(tl_bytes_length(ctx, b)), 5); let empty = tl_bytes_from(ctx, std::ptr::null(), 0); assert_eq!(tl_bytes_len(empty), 0); drop_value(ctx, b); drop_value(ctx, empty); } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn binding_accessors_round_trip() { // SAFETY: `binding_accessors` follows the generated-code convention. let code = unsafe { crate::sched::run_test_actor(binding_accessors) }; assert_eq!(code, 0); } #[test] fn cursor_reads_and_string_ranges() { // SAFETY: `scenarios` follows the generated-code convention. assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); } }