tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

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

996 lignes · 34048 octetsBrut · Historique
1//! The runtime's pure kernels and constants, shared by the native runtime
2//! (`louise_rt`), the reference interpreter (`louise_interp`) and the compiler.
3//!
4//! The interpreter is the native backend's test oracle, so it implements
5//! the runtime's semantics a second time on purpose. For leaf functions
6//! over numbers, strings and bytes, a second copy adds nothing to the
7//! oracle and drifts (the interpreter's `random.int` was biased while the
8//! runtime's was not), so both call the one here. Converting values to and
9//! from each back end's representation stays in each.
10//!
11//! `ring` is the one optional dependency, for the cryptographic hashes
12//! (crypto): already linked for TLS, and out of programs that never hash
13//! (`--gc-sections`). It is optional (the `crypto` feature, on by
14//! default): its build script needs a C cross-compiler the no-qemu
15//! aarch64 check does not have (scripts/ci.sh, ADR 0038). `num-bigint`
16//! (dec.rs) is already linked into every native program for `Int`.
17
18/// Cryptographic hashes (SHA-256, HMAC, PBKDF2) over `ring`.
19#[cfg(feature = "crypto")]
20pub mod crypto;
21
22/// The distribution wire format's kernel (ADR 0072, `docs/wire-format.md`):
23/// type descriptors, the definitions table, the structural type hash and
24/// the value encoding's primitives, shared by the compiler and the
25/// runtime's codec.
26pub mod wire;
27
28/// `Dec`'s kernels (`std/dec`, ADR 0070): fixed-point decimal arithmetic,
29/// parsing, showing, rounding and hashing, shared by both backends.
30pub mod dec;
31
32/// The blocking pools' sizes (ADR 0005, Revision 2): at most this many
33/// calls of each pool run at once.
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct BlockingSizes {
36 pub cpu: usize,
37 pub io: usize,
38}
39
40/// The blocking pools' sizes from the environment `var` reads, on a
41/// machine of `cores` cores, or the message refusing an invalid value:
42///
43/// - the CPU pool: `LOUISE_BLOCKING_CPU_THREADS`, else its shorthand
44/// `LOUISE_BLOCKING_THREADS` (plain `blocking` is `cpu`), else half the
45/// cores, between 1 and 4 (4 was the single pool's size): the scheduler
46/// keeps most of the machine;
47/// - the I/O pool: `LOUISE_BLOCKING_IO_THREADS`, else 16: waiting threads
48/// cost no CPU.
49pub fn blocking_sizes(
50 var: impl Fn(&str) -> Option<String>,
51 cores: usize,
52) -> Result<BlockingSizes, String> {
53 let read = |name: &str| -> Result<Option<usize>, String> {
54 match var(name) {
55 None => Ok(None),
56 Some(v) => match v.trim().parse::<usize>() {
57 Ok(n) if n > 0 => Ok(Some(n)),
58 _ => Err(format!(
59 "louise: {name} must be a positive integer (a number of threads), got \"{v}\""
60 )),
61 },
62 }
63 };
64 let general = read("LOUISE_BLOCKING_THREADS")?;
65 let cpu = read("LOUISE_BLOCKING_CPU_THREADS")?;
66 let io = read("LOUISE_BLOCKING_IO_THREADS")?;
67 Ok(BlockingSizes {
68 cpu: cpu.or(general).unwrap_or((cores / 2).clamp(1, 4)),
69 io: io.unwrap_or(16),
70 })
71}
72
73/// The `Int`s held unboxed: 63-bit two's complement, `-2^62 .. 2^62`
74/// (`TL_INT_MIN ..= TL_INT_MAX` in `louise_rt.h`). Others are big integers
75/// (ADR 0014).
76pub const SMALL_INT: std::ops::Range<i64> = -(1 << 62)..(1 << 62);
77
78/// The operations of `std/process.proc`, in declaration order: the root
79/// capability the runtime gives every actor holds one clause per
80/// operation, in this order (`louise_rt/src/process.rs`). Codegen refuses a
81/// `std/process` whose operations differ.
82pub const PROC_OPS: [&str; 17] = [
83 "spawn",
84 "self",
85 "subject",
86 "send",
87 "receive",
88 "link",
89 "monitor",
90 "kill",
91 "trap_exits",
92 "exits",
93 "sleep",
94 "receive_any",
95 "spawn_link",
96 "spawn_monitor",
97 "stop",
98 "demonitor",
99 "unlink",
100];
101
102/// The operations of `std/time.clock` and `std/random.random`, in
103/// declaration order: like [`PROC_OPS`], for their root capabilities
104/// (`louise_rt/src/clock.rs`, ADR 0036).
105pub const CLOCK_OPS: [&str; 2] = ["now_unix_ns", "monotonic_ns"];
106pub const RANDOM_OPS: [&str; 1] = ["bytes"];
107/// The operations of `std/file.fs`, in declaration order (ADR 0084).
108pub const FS_OPS: [&str; 5] = ["read_bytes", "write_bytes", "exists", "size", "list_dir"];
109/// The deterministic fs refusal for a `@remote`-provenance actor. Such calls
110/// never touch the path, on either backend (ADR 0084).
111pub const FS_REMOTE_DENIED: &str = "fs: access denied to a remote actor";
112
113/// The kind of a root capability, as `tl_root_cap` takes it
114/// (`TL_ROOT_PROC`, `TL_ROOT_CLOCK`, `TL_ROOT_RANDOM` and `TL_ROOT_FS` in
115/// `louise_rt.h`).
116#[derive(Clone, Copy, Debug, PartialEq, Eq)]
117#[repr(u8)]
118pub enum RootCap {
119 Proc = 0,
120 Clock = 1,
121 Random = 2,
122 Fs = 3,
123}
124
125impl RootCap {
126 /// The kind numbered `n`, if any.
127 pub fn from_u8(n: u8) -> Option<RootCap> {
128 [RootCap::Proc, RootCap::Clock, RootCap::Random, RootCap::Fs]
129 .into_iter()
130 .find(|k| *k as u8 == n)
131 }
132
133 /// The operations of its effect, in declaration order.
134 pub fn ops(self) -> &'static [&'static str] {
135 match self {
136 RootCap::Proc => &PROC_OPS,
137 RootCap::Clock => &CLOCK_OPS,
138 RootCap::Random => &RANDOM_OPS,
139 RootCap::Fs => &FS_OPS,
140 }
141 }
142
143 /// Its name in `louise_rt.h`.
144 pub fn c_name(self) -> &'static str {
145 match self {
146 RootCap::Proc => "TL_ROOT_PROC",
147 RootCap::Clock => "TL_ROOT_CLOCK",
148 RootCap::Random => "TL_ROOT_RANDOM",
149 RootCap::Fs => "TL_ROOT_FS",
150 }
151 }
152}
153
154// ---- hashing -------------------------------------------------------------------
155
156const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
157const FNV_PRIME: u64 = 0x100_0000_01b3;
158
159/// A 64-bit mixer (splitmix64's finalizer), reduced to 62 bits so hashes
160/// are non-negative small `Int`s.
161pub fn mix(mut z: u64) -> i64 {
162 z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
163 z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
164 ((z ^ (z >> 31)) >> 2) as i64
165}
166
167/// The hash of a string or `Bytes`: FNV-1a, then mixed.
168pub fn hash_bytes(bytes: &[u8]) -> i64 {
169 let h = bytes.iter().fold(FNV_OFFSET, |h, b| {
170 (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME)
171 });
172 mix(h)
173}
174
175/// The hash of a big `Int`, before mixing: FNV-1a over its 64-bit limbs
176/// (least significant first), complemented when it is negative.
177pub fn hash_limbs(negative: bool, limbs: &[u64]) -> u64 {
178 let h = limbs
179 .iter()
180 .fold(FNV_OFFSET, |h, l| (h ^ l).wrapping_mul(FNV_PRIME));
181 if negative { !h } else { h }
182}
183
184/// `hash_combine(a, b)` of two hashes (as saturated `Int`s).
185pub fn hash_combine(a: i64, b: i64) -> i64 {
186 let (x, y) = (a as u64, b as u64);
187 mix(x.wrapping_mul(31).wrapping_add(y) ^ (x >> 7))
188}
189
190// ---- strings ---------------------------------------------------------------------
191
192/// The parts of `s` between occurrences of `sep`; all of `s` if `sep` is
193/// empty.
194pub fn split<'a>(s: &'a str, sep: &str) -> Vec<&'a str> {
195 if sep.is_empty() {
196 vec![s]
197 } else {
198 s.split(sep).collect()
199 }
200}
201
202/// The characters of `s` (Unicode scalar values) as single-character
203/// strings.
204pub fn chars(s: &str) -> Vec<&str> {
205 s.char_indices()
206 .map(|(i, c)| &s[i..i + c.len_utf8()])
207 .collect()
208}
209
210/// The characters of `s` from `start` up to `end` (excluded); both are
211/// clamped to `0..=s.chars().count()`, and the slice is empty when
212/// `end <= start`. One pass over the bytes, stopping at `end`.
213pub fn char_slice(s: &str, start: i64, end: i64) -> &str {
214 if end <= start {
215 return "";
216 }
217 let (start, end) = (start.max(0) as usize, end.max(0) as usize);
218 // `from` stays `usize::MAX` when `start` is past the last character.
219 let (mut from, mut to) = (usize::MAX, s.len());
220 for (i, (byte, _)) in s.char_indices().enumerate() {
221 if i == start {
222 from = byte;
223 }
224 if i == end {
225 to = byte;
226 break;
227 }
228 }
229 if from == usize::MAX || from >= to {
230 return "";
231 }
232 &s[from..to]
233}
234
235/// A float read from text (the platform's `f64` parser), or why not.
236pub fn parse_float(s: &str) -> Result<f64, String> {
237 s.parse::<f64>().map_err(|_| format!("not a float: {s:?}"))
238}
239
240// ---- substring search (string.find, string.contains) --------------------------
241
242mod find;
243
244pub use find::find;
245
246/// The HTML replacement of a metacharacter, if `b` is one (`& < > " '`).
247fn html_replacement(b: u8) -> Option<&'static [u8]> {
248 match b {
249 b'&' => Some(b"&amp;"),
250 b'<' => Some(b"&lt;"),
251 b'>' => Some(b"&gt;"),
252 b'"' => Some(b"&quot;"),
253 b'\'' => Some(b"&#39;"),
254 _ => None,
255 }
256}
257
258/// The pieces of `s`'s escaped form: its spans without metacharacters and
259/// the replacements of its metacharacters, in order. One pass, no
260/// allocation; the runtime writes them straight into a string block or a
261/// builder.
262pub fn html_escaped(s: &str) -> impl Iterator<Item = &[u8]> {
263 let bytes = s.as_bytes();
264 let mut at = 0; // the next byte not yet yielded
265 std::iter::from_fn(move || {
266 if at >= bytes.len() {
267 return None;
268 }
269 if let Some(rep) = html_replacement(bytes[at]) {
270 at += 1;
271 return Some(rep);
272 }
273 let start = at;
274 while at < bytes.len() && html_replacement(bytes[at]).is_none() {
275 at += 1;
276 }
277 Some(&bytes[start..at])
278 })
279}
280
281/// The length of `s`'s escaped form, or `None` when nothing needs
282/// escaping (the escaped form is `s` itself).
283pub fn html_escaped_len(s: &str) -> Option<usize> {
284 let mut extra = 0usize; // beyond `s.len()`
285 let mut dirty = false;
286 for &b in s.as_bytes() {
287 if let Some(rep) = html_replacement(b) {
288 dirty = true;
289 extra = extra
290 .checked_add(rep.len() - 1)
291 .expect("louise: string too large");
292 }
293 }
294 if !dirty {
295 return None;
296 }
297 Some(
298 s.len()
299 .checked_add(extra)
300 .expect("louise: string too large"),
301 )
302}
303
304/// `s` with `&`, `<`, `>`, `"` and `'` escaped for HTML text and
305/// attribute values.
306pub fn html_escape(s: &str) -> String {
307 match html_escaped_len(s) {
308 None => s.to_owned(),
309 Some(len) => {
310 let mut out = String::with_capacity(len);
311 for chunk in html_escaped(s) {
312 // A span of `s` cut at ASCII bytes, or an ASCII
313 // replacement: valid UTF-8.
314 out.push_str(std::str::from_utf8(chunk).expect("louise: html_escape chunk"));
315 }
316 out
317 }
318 }
319}
320
321// ---- base64 (RFC 4648) ------------------------------------------------------
322// PostgreSQL's SCRAM-SHA-256 exchange (RFC 7677) is base64'd.
323
324const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
325
326/// `data` in base64, with `=` padding.
327pub fn base64_encode(data: &[u8]) -> String {
328 let mut out = String::with_capacity(data.len() * 4 / 3 + 4);
329 for chunk in data.chunks(3) {
330 // The chunk, left-aligned in 24 bits.
331 let n = chunk.iter().fold(0u32, |n, &b| n << 8 | u32::from(b)) << (8 * (3 - chunk.len()));
332 let sextets = [
333 n >> 18,
334 n >> 12 & 63,
335 if chunk.len() > 1 { n >> 6 & 63 } else { 64 },
336 if chunk.len() > 2 { n & 63 } else { 64 },
337 ];
338 for s in sextets {
339 out.push(if s < 64 {
340 char::from(B64_ALPHABET[s as usize])
341 } else {
342 '='
343 });
344 }
345 }
346 out
347}
348
349/// The bytes of a base64 text: its length a multiple of 4, no whitespace,
350/// `=` padding only as the last one or two characters. (PostgreSQL sends
351/// canonical base64; the pad bits are not checked.)
352pub fn base64_decode(text: &str) -> Result<Vec<u8>, &'static str> {
353 let bytes = text.as_bytes();
354 if !bytes.len().is_multiple_of(4) {
355 return Err("base64: the length is not a multiple of 4");
356 }
357 let sextet = |i: usize, b: u8| -> Result<u32, &'static str> {
358 match b {
359 b'A'..=b'Z' => Ok(u32::from(b - b'A')),
360 b'a'..=b'z' => Ok(u32::from(b - b'a' + 26)),
361 b'0'..=b'9' => Ok(u32::from(b - b'0' + 52)),
362 b'+' => Ok(62),
363 b'/' => Ok(63),
364 b'=' if i >= bytes.len() - 2 => Ok(0), // padding, at the end only
365 _ => Err("base64: not a base64 character"),
366 }
367 };
368 let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
369 for (c, chunk) in bytes.chunks(4).enumerate() {
370 if chunk[2] == b'=' && chunk[3] != b'=' {
371 return Err("base64: `=` padding only ends the text");
372 }
373 let mut n = 0u32;
374 for (i, &b) in chunk.iter().enumerate() {
375 n = n << 6 | sextet(c * 4 + i, b)?;
376 }
377 out.push((n >> 16) as u8);
378 if chunk[2] != b'=' {
379 out.push((n >> 8) as u8);
380 }
381 if chunk[3] != b'=' {
382 out.push(n as u8);
383 }
384 }
385 Ok(out)
386}
387
388/// Whether `url_decode` changes `s`: it holds a `%` or a `+`.
389pub fn url_needs_decode(s: &str) -> bool {
390 s.bytes().any(|b| matches!(b, b'%' | b'+'))
391}
392
393/// Decode `%XX` and `+` (URL form encoding) into `out`, which has room
394/// for `s.len()` bytes (the decoded form is never longer); the decoded
395/// length is returned. Invalid escapes stay, and the result may not be
396/// valid UTF-8 (`url_decode` lossy-converts it).
397pub fn url_decode_into(s: &str, out: &mut [u8]) -> usize {
398 let bytes = s.as_bytes();
399 debug_assert!(out.len() >= bytes.len());
400 let mut n = 0;
401 let mut i = 0;
402 while i < bytes.len() {
403 match bytes[i] {
404 b'+' => out[n] = b' ',
405 b'%' if i + 2 < bytes.len() => {
406 let hex = |b: u8| (b as char).to_digit(16);
407 match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
408 (Some(h), Some(l)) => {
409 out[n] = (h * 16 + l) as u8;
410 i += 2;
411 }
412 _ => out[n] = b'%',
413 }
414 }
415 b => out[n] = b,
416 }
417 n += 1;
418 i += 1;
419 }
420 n
421}
422
423/// Decode `%XX` and `+` (URL form encoding); invalid escapes stay, and
424/// invalid UTF-8 becomes U+FFFD.
425pub fn url_decode(s: &str) -> String {
426 if !url_needs_decode(s) {
427 return s.to_owned();
428 }
429 let mut buf = vec![0; s.len()];
430 let n = url_decode_into(s, &mut buf);
431 buf.truncate(n);
432 String::from_utf8_lossy(&buf).into_owned()
433}
434
435/// Whether `b` is unreserved (RFC 3986): the one set of bytes
436/// `url_encode` leaves as they are.
437fn url_unreserved(b: u8) -> bool {
438 matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~')
439}
440
441/// Whether `url_encode` changes `s`: it holds a byte that is not
442/// unreserved.
443pub fn url_needs_encode(s: &str) -> bool {
444 s.bytes().any(|b| !url_unreserved(b))
445}
446
447/// Percent-encode `s` into `out`, which has room for `3 * s.len()` bytes
448/// (every byte may become `%XX`); the encoded length is returned.
449pub fn url_encode_into(s: &str, out: &mut [u8]) -> usize {
450 const HEX: &[u8; 16] = b"0123456789ABCDEF";
451 debug_assert!(out.len() >= 3 * s.len());
452 let mut n = 0;
453 for &b in s.as_bytes() {
454 if url_unreserved(b) {
455 out[n] = b;
456 n += 1;
457 } else {
458 out[n..n + 3].copy_from_slice(&[
459 b'%',
460 HEX[usize::from(b >> 4)],
461 HEX[usize::from(b & 15)],
462 ]);
463 n += 3;
464 }
465 }
466 n
467}
468
469/// Percent-encode `s` for a URL path or query (RFC 3986): every byte
470/// outside the unreserved set becomes `%XX` (uppercase hex); a space is
471/// `%20`, not `+` (`url_decode` maps both back to a space, and a `+`
472/// decodes as a space only in a query or form). `url_decode` inverts it:
473/// `url_decode(url_encode(s)) == s`.
474pub fn url_encode(s: &str) -> String {
475 if !url_needs_encode(s) {
476 return s.to_owned();
477 }
478 let mut buf = vec![0; 3 * s.len()];
479 let n = url_encode_into(s, &mut buf);
480 buf.truncate(n);
481 // Unreserved bytes and `%XX` triplets are all ASCII.
482 String::from_utf8(buf).expect("louise: percent-encoded bytes are ASCII")
483}
484
485/// The fields of an `application/x-www-form-urlencoded` body or query
486/// string (`std/http.form`): pairs split on `&`, each on its first `=`,
487/// both sides percent-decoded with `+` a space (as [`url_decode`], so a
488/// query and a form body decode the same way). Empty pairs are dropped;
489/// a bare `k` is `("k", "")`.
490///
491/// One pass, one reused decode buffer: a side without `%` or `+` is
492/// copied once, undecoded.
493pub fn query_params(s: &str) -> Vec<(String, String)> {
494 let mut out = Vec::new();
495 let mut scratch = Vec::new();
496 for pair in s.split('&') {
497 if pair.is_empty() {
498 continue;
499 }
500 // Only the first `=` separates the name from the value.
501 let (name, value) = match pair.find('=') {
502 Some(i) => (&pair[..i], &pair[i + 1..]),
503 None => (pair, ""),
504 };
505 out.push((
506 decode_side(name, &mut scratch),
507 decode_side(value, &mut scratch),
508 ));
509 }
510 out
511}
512
513/// One side of a pair, decoded as [`url_decode`] decodes, reusing
514/// `scratch`.
515fn decode_side(s: &str, scratch: &mut Vec<u8>) -> String {
516 if !s.bytes().any(|b| b == b'%' || b == b'+') {
517 // Nothing to decode: the slice is already valid UTF-8.
518 return s.to_string();
519 }
520 scratch.clear();
521 let bytes = s.as_bytes();
522 let mut i = 0;
523 while i < bytes.len() {
524 match bytes[i] {
525 b'+' => scratch.push(b' '),
526 b'%' if i + 2 < bytes.len() => {
527 let hex = |b: u8| (b as char).to_digit(16);
528 match (hex(bytes[i + 1]), hex(bytes[i + 2])) {
529 (Some(h), Some(l)) => {
530 scratch.push((h * 16 + l) as u8);
531 i += 2;
532 }
533 _ => scratch.push(b'%'),
534 }
535 }
536 b => scratch.push(b),
537 }
538 i += 1;
539 }
540 String::from_utf8_lossy(scratch).into_owned()
541}
542
543// ---- numbers (std/int, std/float, std/u64; ADR 0035) ----------------------------------
544
545/// `int.shift_left` refuses a shift of `2^32` bits or more of a non-zero
546/// number: the result could not be allocated, and both backends give this
547/// message instead of running out of memory.
548pub const MAX_SHIFT: u64 = 1 << 32;
549
550/// The panic of a shift by a negative amount `k` (`op` is `int.shift_left`,
551/// `u64.shift_right`, ...).
552pub fn negative_shift(op: &str, k: &str) -> String {
553 format!("{op}: negative shift amount {k}")
554}
555
556/// The panic of `int.shift_left` by `k ≥ MAX_SHIFT` bits.
557pub fn shift_too_large(k: &str) -> String {
558 format!("int.shift_left: shift amount {k} is too large")
559}
560
561pub const U64_DIVISION_BY_ZERO: &str = "u64.div: division by zero";
562pub const U64_REMAINDER_BY_ZERO: &str = "u64.rem: division by zero";
563
564/// `x` as an IEEE 754 single (round to nearest, ties to even), its bits.
565/// A NaN keeps its sign, its quiet bit and the top 22 bits of its payload,
566/// computed here rather than by the hardware so every backend agrees.
567pub fn f64_to_f32_bits(x: f64) -> u32 {
568 if x.is_nan() {
569 let b = x.to_bits();
570 let sign = ((b >> 63) as u32) << 31;
571 let payload = ((b >> 29) & 0x007F_FFFF) as u32;
572 // A payload that loses all its bits keeps one, so it stays a NaN.
573 let payload = if payload == 0 { 1 } else { payload };
574 return sign | 0x7F80_0000 | payload;
575 }
576 (x as f32).to_bits()
577}
578
579/// The single with bits `b`, widened (exactly) to a double. A NaN keeps
580/// its sign and payload, the reverse of `f64_to_f32_bits`.
581pub fn f32_bits_to_f64(b: u32) -> f64 {
582 let x = f32::from_bits(b);
583 if x.is_nan() {
584 let sign = u64::from(b >> 31) << 63;
585 let payload = u64::from(b & 0x007F_FFFF) << 29;
586 return f64::from_bits(sign | 0x7FF0_0000_0000_0000 | payload);
587 }
588 f64::from(x)
589}
590
591// ---- randomness (std/random) ---------------------------------------------------------
592
593/// `n` bytes from the operating system's random source: what the root
594/// handler of `std/random.random` answers `bytes(n)` with (ADR 0036).
595///
596/// # Panics
597/// If `/dev/urandom` cannot be read.
598pub fn random_bytes(n: usize) -> Vec<u8> {
599 use std::io::Read;
600 let mut buf = vec![0u8; n];
601 std::fs::File::open("/dev/urandom")
602 .and_then(|mut f| f.read_exact(&mut buf))
603 .expect("louise: cannot read /dev/urandom");
604 buf
605}
606
607#[cfg(test)]
608mod tests {
609 use super::{BlockingSizes, FS_OPS, RootCap, blocking_sizes};
610
611 fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
612 move |name| {
613 vars.iter()
614 .find(|(n, _)| *n == name)
615 .map(|(_, v)| (*v).to_owned())
616 }
617 }
618
619 #[test]
620 fn blocking_pools_default_to_a_small_cpu_pool() {
621 let sizes = |cpu, io| Ok(BlockingSizes { cpu, io });
622 assert_eq!(blocking_sizes(env(&[]), 22), sizes(4, 16));
623 assert_eq!(blocking_sizes(env(&[]), 4), sizes(2, 16));
624 assert_eq!(blocking_sizes(env(&[]), 1), sizes(1, 16));
625 }
626
627 #[test]
628 fn the_specific_pool_variable_wins_over_the_shorthand() {
629 let both = [
630 ("LOUISE_BLOCKING_THREADS", "16"),
631 ("LOUISE_BLOCKING_CPU_THREADS", "3"),
632 ];
633 assert_eq!(
634 blocking_sizes(env(&both), 8),
635 Ok(BlockingSizes { cpu: 3, io: 16 })
636 );
637 let general = [
638 ("LOUISE_BLOCKING_THREADS", "16"),
639 ("LOUISE_BLOCKING_IO_THREADS", "64"),
640 ];
641 assert_eq!(
642 blocking_sizes(env(&general), 8),
643 Ok(BlockingSizes { cpu: 16, io: 64 })
644 );
645 }
646
647 #[test]
648 fn zero_and_garbage_pool_sizes_are_refused() {
649 for bad in ["0", "-1", "four", ""] {
650 let err = blocking_sizes(env(&[("LOUISE_BLOCKING_IO_THREADS", bad)]), 8).unwrap_err();
651 assert_eq!(
652 err,
653 format!(
654 "louise: LOUISE_BLOCKING_IO_THREADS must be a positive integer (a number of threads), got \"{bad}\""
655 )
656 );
657 }
658 }
659
660 #[test]
661 fn floats_narrow_and_widen_keeping_nan_payloads() {
662 use super::{f32_bits_to_f64, f64_to_f32_bits};
663 assert_eq!(f64_to_f32_bits(1.0), 0x3F80_0000);
664 assert_eq!(f64_to_f32_bits(-0.0), 0x8000_0000);
665 assert_eq!(f64_to_f32_bits(0.1), 0x3DCC_CCCD); // rounded to nearest
666 assert_eq!(f64_to_f32_bits(f64::INFINITY), 0x7F80_0000);
667 assert_eq!(f64_to_f32_bits(1e300), 0x7F80_0000); // overflow: infinity
668 // A signalling NaN stays signalling, with its payload's top bits.
669 let snan = f64::from_bits(0x7FF4_0000_0000_0001 | (0x12345 << 29));
670 let narrowed = f64_to_f32_bits(snan);
671 assert_eq!(narrowed & 0x7FC0_0000, 0x7F80_0000, "still signalling");
672 assert_eq!(
673 f32_bits_to_f64(narrowed).to_bits() >> 29,
674 snan.to_bits() >> 29
675 );
676 // Every single round-trips through a double, NaNs included.
677 for b in [
678 0,
679 1,
680 0x0080_0000,
681 0x3F80_0000,
682 0x7F80_0000,
683 0x7FC0_0001,
684 0xFFBF_FFFF,
685 ] {
686 assert_eq!(f64_to_f32_bits(f32_bits_to_f64(b)), b, "{b:#x}");
687 }
688 }
689
690 use super::*;
691
692 #[test]
693 fn fs_root_is_appended_without_changing_existing_discriminants() {
694 assert_eq!(RootCap::from_u8(0), Some(RootCap::Proc));
695 assert_eq!(RootCap::from_u8(1), Some(RootCap::Clock));
696 assert_eq!(RootCap::from_u8(2), Some(RootCap::Random));
697 assert_eq!(RootCap::from_u8(3), Some(RootCap::Fs));
698 assert_eq!(RootCap::from_u8(4), None, "an old runtime's unknown kind");
699 assert_eq!(RootCap::Fs as u8, 3);
700 assert_eq!(RootCap::Fs.c_name(), "TL_ROOT_FS");
701 assert_eq!(RootCap::Fs.ops(), FS_OPS.as_slice());
702 }
703
704 #[test]
705 fn small_ints_are_63_bits() {
706 assert_eq!(SMALL_INT.start, -(1 << 62));
707 assert_eq!(SMALL_INT.end - 1, (1 << 62) - 1);
708 }
709
710 #[test]
711 fn url_decoding_keeps_invalid_escapes() {
712 assert_eq!(url_decode("a+b%20c"), "a b c");
713 assert_eq!(url_decode("%41%zz%4"), "A%zz%4");
714 assert_eq!(url_decode("%"), "%");
715 assert_eq!(url_decode("%ff"), "\u{fffd}");
716 // Clean inputs (no `%`, no `+`) come back unchanged.
717 assert!(!url_needs_decode("plain text"));
718 assert!(!url_needs_decode("é"));
719 assert!(url_needs_decode("a+b") && url_needs_decode("a%b"));
720 assert_eq!(url_decode(""), "");
721 assert_eq!(url_decode("plain text"), "plain text");
722 // `+` at the edges, and escapes at the edges.
723 assert_eq!(url_decode("+a+"), " a ");
724 assert_eq!(url_decode("%41"), "A");
725 assert_eq!(url_decode("%41%42%43"), "ABC");
726 // Invalid escapes stay, byte for byte.
727 assert_eq!(url_decode("%2"), "%2");
728 assert_eq!(url_decode("%2G"), "%2G");
729 assert_eq!(url_decode("%zz"), "%zz");
730 assert_eq!(url_decode("%%41"), "%A");
731 // Decoded bytes: NUL is valid UTF-8; multibyte sequences may span
732 // escapes; invalid bytes become U+FFFD each.
733 assert_eq!(url_decode("%00"), "\0");
734 assert_eq!(url_decode("%C3%A9"), "é");
735 assert_eq!(url_decode("%c3%a9"), "é");
736 assert_eq!(url_decode("%C3"), "\u{fffd}");
737 assert_eq!(url_decode("%A9%C3"), "\u{fffd}\u{fffd}");
738 assert_eq!(url_decode("é"), "é");
739 }
740
741 #[test]
742 fn url_encoding_escapes_everything_but_the_unreserved() {
743 // Clean inputs (only unreserved bytes) come back unchanged.
744 assert!(!url_needs_encode(""));
745 assert!(!url_needs_encode("plain-text_1.0~x"));
746 assert_eq!(url_encode(""), "");
747 assert_eq!(url_encode("abcXYZ019-_.~"), "abcXYZ019-_.~");
748 // Everything else becomes `%XX`, uppercase; a space is `%20`.
749 assert!(url_needs_encode("a b"));
750 assert_eq!(url_encode("a b"), "a%20b");
751 assert_eq!(url_encode("=&?/#%+"), "%3D%26%3F%2F%23%25%2B");
752 assert_eq!(url_encode("\0"), "%00");
753 // Unicode is UTF-8, each byte escaped.
754 assert_eq!(url_encode("é"), "%C3%A9");
755 assert_eq!(url_encode("☃"), "%E2%98%83");
756 // Encoding is not idempotent: `%` becomes `%25`.
757 assert_eq!(url_encode("%41"), "%2541");
758 assert_eq!(url_encode("100%"), "100%25");
759 // `url_decode` inverts it, arbitrary unicode included.
760 for s in [
761 "",
762 "a",
763 "A Z",
764 "a+b",
765 "100%",
766 "%41",
767 "=",
768 "&",
769 "x=y",
770 "é",
771 "☃",
772 "a/b?c",
773 " ",
774 "+",
775 "%",
776 "\t",
777 "ünïcodé",
778 ] {
779 assert_eq!(url_decode(&url_encode(s)), s, "round-trip {s:?}");
780 }
781 }
782
783 #[test]
784 fn char_slices_clamp_to_the_character_bounds() {
785 assert_eq!(char_slice("hello", 1, 4), "ell");
786 assert_eq!(char_slice("hello", 0, 5), "hello");
787 // Multibyte characters are indexed, not their bytes.
788 assert_eq!(char_slice("héllo", 1, 3), "él");
789 assert_eq!(char_slice("日本語", 1, 2), "本");
790 // Both bounds clamp to `0..=length`; `end <= start` is empty.
791 assert_eq!(char_slice("héllo", 0, i64::MAX), "héllo");
792 assert_eq!(char_slice("héllo", -3, 2), "hé");
793 assert_eq!(char_slice("héllo", 3, 100), "lo");
794 assert_eq!(char_slice("héllo", 5, 5), "");
795 assert_eq!(char_slice("héllo", 4, 2), "");
796 assert_eq!(char_slice("héllo", 7, 9), "");
797 assert_eq!(char_slice("héllo", -2, -1), "");
798 assert_eq!(char_slice("", 0, 1), "");
799 }
800
801 /// `query_params` against what `std/http.form` did before it: split
802 /// on `&`, drop empty pairs, split each on `=`, decode both sides
803 /// (the value re-joined on `=`).
804 #[test]
805 fn query_params_match_the_split_and_decode_recipe() {
806 fn reference(body: &str) -> Vec<(String, String)> {
807 split(body, "&")
808 .into_iter()
809 .filter(|p| !p.is_empty())
810 .map(|pair| match split(pair, "=").as_slice() {
811 [k] => (url_decode(k), String::new()),
812 [k, rest @ ..] => (url_decode(k), url_decode(&rest.join("="))),
813 [] => (String::new(), String::new()),
814 })
815 .collect()
816 }
817 for case in [
818 "",
819 "&",
820 "&&",
821 "a",
822 "a=",
823 "=b",
824 "=",
825 "==",
826 "a=b=c",
827 "a&&b",
828 "a=1&b=two+words&bare&c=x%3Dy",
829 "%",
830 "%4",
831 "%41",
832 "%zz",
833 "%4z",
834 "+",
835 "a+b",
836 "+a+",
837 "%ff",
838 "%c3%a9",
839 "é=x",
840 "%e2%82%ac",
841 "a=%ff%fe",
842 "&&&",
843 "=&=",
844 "k=+%20",
845 "%2f=%2F",
846 "a=b&",
847 "&a=b",
848 "%%41",
849 "%4%41",
850 "a%26b=c%3Dd",
851 ] {
852 assert_eq!(query_params(case), reference(case), "{case:?}");
853 }
854 }
855
856 /// Every byte percent-encoded comes back as itself, however tricky
857 /// the fragment.
858 #[test]
859 fn query_params_round_trip_encoded_pairs() {
860 let fragments = [
861 "",
862 "a",
863 "A Z",
864 "a+b",
865 "100%",
866 "%41",
867 "=",
868 "&",
869 "x=y",
870 "é",
871 "☃",
872 "a/b?c",
873 " ",
874 "+",
875 "%",
876 "\t",
877 "ünïcodé",
878 ];
879 let encode = |s: &str| s.bytes().map(|b| format!("%{b:02X}")).collect::<String>();
880 let expected: Vec<(String, String)> = fragments
881 .iter()
882 .flat_map(|n| {
883 fragments
884 .iter()
885 .map(move |v| (n.to_string(), v.to_string()))
886 })
887 .collect();
888 let encoded = expected
889 .iter()
890 .map(|(n, v)| format!("{}={}", encode(n), encode(v)))
891 .collect::<Vec<_>>()
892 .join("&");
893 assert_eq!(query_params(&encoded), expected);
894 }
895
896 #[test]
897 fn html_escaping() {
898 assert_eq!(
899 html_escape(r#"<a href="x">Tom & 'Jerry'</a>"#),
900 "&lt;a href=&quot;x&quot;&gt;Tom &amp; &#39;Jerry&#39;&lt;/a&gt;"
901 );
902 // The chunked form is the same escaping, and `html_escaped_len`
903 // agrees with both (None exactly when nothing changes).
904 for s in [
905 "",
906 "plain",
907 "&",
908 "<>&\"'",
909 "a & b <c>",
910 "&amp;",
911 "héllo 🦀",
912 "日本<語",
913 "é<é",
914 &"ab<&cd".repeat(100),
915 ] {
916 let escaped = html_escape(s);
917 assert_eq!(
918 html_escaped(s).collect::<Vec<_>>().concat(),
919 escaped.as_bytes(),
920 "{s:?}"
921 );
922 assert_eq!(
923 html_escaped_len(s),
924 (escaped != s).then_some(escaped.len()),
925 "{s:?}"
926 );
927 }
928 }
929
930 #[test]
931 fn splitting_on_an_empty_separator_keeps_the_string() {
932 assert_eq!(split("a,b,,c", ","), ["a", "b", "", "c"]);
933 assert_eq!(split("abc", ""), ["abc"]);
934 assert_eq!(split("", ","), [""]);
935 }
936
937 #[test]
938 fn chars_splits_on_scalar_values() {
939 assert_eq!(chars("héllo"), ["h", "é", "l", "l", "o"]);
940 assert_eq!(chars(""), Vec::<&str>::new());
941 assert_eq!(chars("a🦀b"), ["a", "🦀", "b"]);
942 }
943
944 #[test]
945 fn floats_from_text() {
946 assert_eq!(parse_float("1.5"), Ok(1.5));
947 assert_eq!(parse_float("-2e3"), Ok(-2000.0));
948 assert_eq!(parse_float("NaN").map(f64::is_nan), Ok(true));
949 assert!(parse_float("1.5x").is_err());
950 assert!(parse_float("").is_err());
951 }
952
953 #[test]
954 fn base64_rfc4648_vectors() {
955 let cases = [
956 ("", ""),
957 ("f", "Zg=="),
958 ("fo", "Zm8="),
959 ("foo", "Zm9v"),
960 ("foob", "Zm9vYg=="),
961 ("fooba", "Zm9vYmE="),
962 ("foobar", "Zm9vYmFy"),
963 ];
964 for (raw, encoded) in cases {
965 assert_eq!(base64_encode(raw.as_bytes()), encoded);
966 assert_eq!(base64_decode(encoded).unwrap(), raw.as_bytes());
967 }
968 assert!(base64_decode("Zg=").is_err());
969 assert!(base64_decode("Zg== ").is_err());
970 assert!(base64_decode("Z===").is_err());
971 assert!(base64_decode("Zm 9v").is_err());
972 assert!(base64_decode("Zm$v").is_err());
973 }
974
975 #[test]
976 fn hashes_are_non_negative_small_ints() {
977 for h in [
978 hash_bytes(b""),
979 hash_bytes(b"louise"),
980 mix(u64::MAX),
981 hash_combine(-1, i64::MAX),
982 ] {
983 assert!(SMALL_INT.contains(&h) && h >= 0, "{h}");
984 }
985 assert_eq!(hash_limbs(true, &[1, 2]), !hash_limbs(false, &[1, 2]));
986 }
987
988 /// Hashes are observable (`hash`, dictionary order), so these values
989 /// pin the formulas; `louise run` and native programs print the same.
990 #[test]
991 fn hashes_are_stable() {
992 assert_eq!(mix(0), 0);
993 assert_eq!(hash_bytes(b""), 4_416_489_145_408_256_550);
994 assert_eq!(hash_bytes(b"louise"), 1_206_155_588_114_856_828);
995 }
996}