tobogganSe connecter

louise

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

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