
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 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 | |
| 10 | use louise_rt_prims::hash_bytes; |
| 11 | |
| 12 | use crate::abi::{Ctx, Value, int}; |
| 13 | use crate::int::saturating; |
| 14 | use crate::prims::{boolean, order, panic_with}; |
| 15 | use 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)] |
| 20 | pub 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)] |
| 30 | pub 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. |
| 38 | fn 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)] |
| 49 | pub 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)] |
| 61 | pub 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)] |
| 73 | pub 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)] |
| 88 | pub 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)] |
| 105 | pub 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)] |
| 120 | pub 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)] |
| 133 | pub 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)] |
| 143 | pub 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)] |
| 151 | pub 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)] |
| 162 | pub 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)] |
| 174 | pub 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)] |
| 185 | pub 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). |
| 197 | pub 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)] |
| 206 | pub 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)] |
| 220 | pub 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)] |
| 246 | pub 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)] |
| 270 | pub 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 | #[cfg(test)] |
| 277 | mod tests { |
| 278 | use super::*; |
| 279 | use crate::abi::{Block, UNIT, int, int_get}; |
| 280 | use crate::heap::drop_value; |
| 281 | use crate::values::bytes_from; |
| 282 | |
| 283 | fn error_of(bytes: &[u8]) -> String { |
| 284 | super::utf8_error(&std::str::from_utf8(bytes).unwrap_err()) |
| 285 | } |
| 286 | |
| 287 | #[test] |
| 288 | fn utf8_errors_name_the_first_invalid_byte() { |
| 289 | assert_eq!(error_of(b"ab\xffc"), "invalid UTF-8 at byte 2"); |
| 290 | // A sequence cut short is invalid where it starts. |
| 291 | assert_eq!(error_of(b"caf\xc3"), "invalid UTF-8 at byte 3"); |
| 292 | } |
| 293 | |
| 294 | /// A `Result`'s constructor tag (0 `Ok`, 1 `Error`) and its payload |
| 295 | /// as text. |
| 296 | /// |
| 297 | /// # Safety |
| 298 | /// `r` must be a live `Result` of a string and a string. |
| 299 | unsafe fn result_text(r: Value) -> (u16, String) { |
| 300 | // SAFETY: forwarded caller guarantee. |
| 301 | unsafe { |
| 302 | let b = r as *mut Block; |
| 303 | let tag = (*b).header.tag; |
| 304 | let field = Block::fields_ptr(b).read(); |
| 305 | (tag, String::from_utf8_lossy(bytes_of(field)).into_owned()) |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// The scenarios run as one root actor, so drops have a context. |
| 310 | unsafe extern "C" fn scenarios(ctx: *mut Ctx) -> Value { |
| 311 | // SAFETY: every value is owned by this test. |
| 312 | unsafe { |
| 313 | let b = bytes_from(ctx, &[0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0xff]); |
| 314 | // In-range big-endian reads; out of range (also negative, or |
| 315 | // reaching past the end) is -1. |
| 316 | assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(0))), 0x1234); |
| 317 | assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(7))), 0xf0ff); |
| 318 | assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(8))), -1); |
| 319 | assert_eq!(int_get(tl_bytes_read_u16be(ctx, b, int(-1))), -1); |
| 320 | assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(1))), 0x3456789a); |
| 321 | assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(4))), 0x9abcdef0); |
| 322 | assert_eq!( |
| 323 | int_get(tl_bytes_read_u32be(ctx, b, int(5))), |
| 324 | 0xbcdef0ffu32 as i64 |
| 325 | ); |
| 326 | assert_eq!(int_get(tl_bytes_read_u32be(ctx, b, int(6))), -1); |
| 327 | let small = tl_bytes_read_u64be(ctx, b, int(0)); |
| 328 | assert_eq!( |
| 329 | crate::int::to_big(small), |
| 330 | num_bigint::BigInt::from(0x123456789abcdef0_u64) |
| 331 | ); |
| 332 | assert_eq!(int_get(tl_bytes_read_u64be(ctx, b, int(2))), -1); |
| 333 | drop_value(ctx, b); |
| 334 | // Above 2^62 the read is a big integer. |
| 335 | let max = bytes_from(ctx, &[0xff; 8]); |
| 336 | let big = tl_bytes_read_u64be(ctx, max, int(0)); |
| 337 | assert_eq!(crate::int::to_big(big), num_bigint::BigInt::from(u64::MAX)); |
| 338 | drop_value(ctx, max); |
| 339 | drop_value(ctx, big); |
| 340 | |
| 341 | let s = bytes_from(ctx, "héllo".as_bytes()); |
| 342 | // The whole range, a subrange, and clamped bounds. |
| 343 | let whole = tl_bytes_to_string_range(ctx, s, int(0), int(6)); |
| 344 | assert_eq!(result_text(whole), (0, "héllo".to_owned())); |
| 345 | let sub = tl_bytes_to_string_range(ctx, s, int(3), int(2)); |
| 346 | assert_eq!(result_text(sub), (0, "ll".to_owned())); |
| 347 | let clamped = tl_bytes_to_string_range(ctx, s, int(3), int(100)); |
| 348 | assert_eq!(result_text(clamped), (0, "llo".to_owned())); |
| 349 | let negative = tl_bytes_to_string_range(ctx, s, int(-2), int(3)); |
| 350 | assert_eq!(result_text(negative), (0, "h".to_owned())); |
| 351 | let empty = tl_bytes_to_string_range(ctx, s, int(4), int(-9)); |
| 352 | assert_eq!(result_text(empty), (0, String::new())); |
| 353 | // The error names the first invalid byte of the range. |
| 354 | let half = tl_bytes_to_string_range(ctx, s, int(1), int(1)); |
| 355 | assert_eq!(result_text(half), (1, "invalid UTF-8 at byte 0".to_owned())); |
| 356 | let cut = tl_bytes_to_string_range(ctx, s, int(0), int(2)); |
| 357 | assert_eq!(result_text(cut), (1, "invalid UTF-8 at byte 1".to_owned())); |
| 358 | for r in [whole, sub, clamped, negative, empty, half, cut] { |
| 359 | drop_value(ctx, r); |
| 360 | } |
| 361 | drop_value(ctx, s); |
| 362 | } |
| 363 | assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); |
| 364 | UNIT |
| 365 | } |
| 366 | |
| 367 | #[test] |
| 368 | fn cursor_reads_and_string_ranges() { |
| 369 | // SAFETY: `scenarios` follows the generated-code convention. |
| 370 | assert_eq!(unsafe { crate::sched::run_test_actor(scenarios) }, 0); |
| 371 | } |
| 372 | } |