tobogganSe connecter

louise

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

984 lignes · 33258 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/// Running a program (`std/command`, ADR 0085): spawning, the pipes, the
29/// deadlines and reaping, driven by both back ends.
30#[cfg(feature = "command")]
31pub mod command;
32
33/// Open files (`std/file/stream`, ADR 0087): reads and writes in chunks,
34/// shared by both backends.
35pub mod file;
36
37/// `Dec`'s kernels (`std/dec`, ADR 0070): fixed-point decimal arithmetic,
38/// parsing, showing, rounding and hashing, shared by both backends.
39pub mod dec;
40
41/// The blocking pools' sizes (ADR 0005, Revision 2): at most this many
42/// calls of each pool run at once.
43#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct BlockingSizes {
45 pub cpu: usize,
46 pub io: usize,
47}
48
49/// The blocking pools' sizes from the environment `var` reads, on a
50/// machine of `cores` cores, or the message refusing an invalid value:
51///
52/// - the CPU pool: `LOUISE_BLOCKING_CPU_THREADS`, else its shorthand
53/// `LOUISE_BLOCKING_THREADS` (plain `blocking` is `cpu`), else half the
54/// cores, between 1 and 4 (4 was the single pool's size): the scheduler
55/// keeps most of the machine;
56/// - the I/O pool: `LOUISE_BLOCKING_IO_THREADS`, else 16: waiting threads
57/// cost no CPU.
58pub fn blocking_sizes(
59 var: impl Fn(&str) -> Option<String>,
60 cores: usize,
61) -> Result<BlockingSizes, String> {
62 let read = |name: &str| -> Result<Option<usize>, String> {
63 match var(name) {
64 None => Ok(None),
65 Some(v) => match v.trim().parse::<usize>() {
66 Ok(n) if n > 0 => Ok(Some(n)),
67 _ => Err(format!(
68 "louise: {name} must be a positive integer (a number of threads), got \"{v}\""
69 )),
70 },
71 }
72 };
73 let general = read("LOUISE_BLOCKING_THREADS")?;
74 let cpu = read("LOUISE_BLOCKING_CPU_THREADS")?;
75 let io = read("LOUISE_BLOCKING_IO_THREADS")?;
76 Ok(BlockingSizes {
77 cpu: cpu.or(general).unwrap_or((cores / 2).clamp(1, 4)),
78 io: io.unwrap_or(16),
79 })
80}
81
82/// The `Int`s held unboxed: 63-bit two's complement, `-2^62 .. 2^62`
83/// (`TL_INT_MIN ..= TL_INT_MAX` in `louise_rt.h`). Others are big integers
84/// (ADR 0014).
85pub const SMALL_INT: std::ops::Range<i64> = -(1 << 62)..(1 << 62);
86
87/// The operations of `std/process.proc`, in declaration order: the root
88/// capability the runtime gives every actor holds one clause per
89/// operation, in this order (`louise_rt/src/process.rs`). Codegen refuses a
90/// `std/process` whose operations differ.
91pub const PROC_OPS: [&str; 17] = [
92 "spawn",
93 "self",
94 "subject",
95 "send",
96 "receive",
97 "link",
98 "monitor",
99 "kill",
100 "trap_exits",
101 "exits",
102 "sleep",
103 "receive_any",
104 "spawn_link",
105 "spawn_monitor",
106 "stop",
107 "demonitor",
108 "unlink",
109];
110
111/// The operations of `std/time.clock` and `std/random.random`, in
112/// declaration order: like [`PROC_OPS`], for their root capabilities
113/// (`louise_rt/src/clock.rs`, ADR 0036).
114pub const CLOCK_OPS: [&str; 2] = ["now_unix_ns", "monotonic_ns"];
115pub const RANDOM_OPS: [&str; 1] = ["bytes"];
116
117/// The kind of a root capability, as `tl_root_cap` takes it
118/// (`TL_ROOT_PROC`, `TL_ROOT_CLOCK` and `TL_ROOT_RANDOM` in `louise_rt.h`).
119#[derive(Clone, Copy, Debug, PartialEq, Eq)]
120#[repr(u8)]
121pub enum RootCap {
122 Proc = 0,
123 Clock = 1,
124 Random = 2,
125}
126
127impl RootCap {
128 /// The kind numbered `n`, if any.
129 pub fn from_u8(n: u8) -> Option<RootCap> {
130 [RootCap::Proc, RootCap::Clock, RootCap::Random]
131 .into_iter()
132 .find(|k| *k as u8 == n)
133 }
134
135 /// The operations of its effect, in declaration order.
136 pub fn ops(self) -> &'static [&'static str] {
137 match self {
138 RootCap::Proc => &PROC_OPS,
139 RootCap::Clock => &CLOCK_OPS,
140 RootCap::Random => &RANDOM_OPS,
141 }
142 }
143
144 /// Its name in `louise_rt.h`.
145 pub fn c_name(self) -> &'static str {
146 match self {
147 RootCap::Proc => "TL_ROOT_PROC",
148 RootCap::Clock => "TL_ROOT_CLOCK",
149 RootCap::Random => "TL_ROOT_RANDOM",
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, 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 small_ints_are_63_bits() {
694 assert_eq!(SMALL_INT.start, -(1 << 62));
695 assert_eq!(SMALL_INT.end - 1, (1 << 62) - 1);
696 }
697
698 #[test]
699 fn url_decoding_keeps_invalid_escapes() {
700 assert_eq!(url_decode("a+b%20c"), "a b c");
701 assert_eq!(url_decode("%41%zz%4"), "A%zz%4");
702 assert_eq!(url_decode("%"), "%");
703 assert_eq!(url_decode("%ff"), "\u{fffd}");
704 // Clean inputs (no `%`, no `+`) come back unchanged.
705 assert!(!url_needs_decode("plain text"));
706 assert!(!url_needs_decode("é"));
707 assert!(url_needs_decode("a+b") && url_needs_decode("a%b"));
708 assert_eq!(url_decode(""), "");
709 assert_eq!(url_decode("plain text"), "plain text");
710 // `+` at the edges, and escapes at the edges.
711 assert_eq!(url_decode("+a+"), " a ");
712 assert_eq!(url_decode("%41"), "A");
713 assert_eq!(url_decode("%41%42%43"), "ABC");
714 // Invalid escapes stay, byte for byte.
715 assert_eq!(url_decode("%2"), "%2");
716 assert_eq!(url_decode("%2G"), "%2G");
717 assert_eq!(url_decode("%zz"), "%zz");
718 assert_eq!(url_decode("%%41"), "%A");
719 // Decoded bytes: NUL is valid UTF-8; multibyte sequences may span
720 // escapes; invalid bytes become U+FFFD each.
721 assert_eq!(url_decode("%00"), "\0");
722 assert_eq!(url_decode("%C3%A9"), "é");
723 assert_eq!(url_decode("%c3%a9"), "é");
724 assert_eq!(url_decode("%C3"), "\u{fffd}");
725 assert_eq!(url_decode("%A9%C3"), "\u{fffd}\u{fffd}");
726 assert_eq!(url_decode("é"), "é");
727 }
728
729 #[test]
730 fn url_encoding_escapes_everything_but_the_unreserved() {
731 // Clean inputs (only unreserved bytes) come back unchanged.
732 assert!(!url_needs_encode(""));
733 assert!(!url_needs_encode("plain-text_1.0~x"));
734 assert_eq!(url_encode(""), "");
735 assert_eq!(url_encode("abcXYZ019-_.~"), "abcXYZ019-_.~");
736 // Everything else becomes `%XX`, uppercase; a space is `%20`.
737 assert!(url_needs_encode("a b"));
738 assert_eq!(url_encode("a b"), "a%20b");
739 assert_eq!(url_encode("=&?/#%+"), "%3D%26%3F%2F%23%25%2B");
740 assert_eq!(url_encode("\0"), "%00");
741 // Unicode is UTF-8, each byte escaped.
742 assert_eq!(url_encode("é"), "%C3%A9");
743 assert_eq!(url_encode("☃"), "%E2%98%83");
744 // Encoding is not idempotent: `%` becomes `%25`.
745 assert_eq!(url_encode("%41"), "%2541");
746 assert_eq!(url_encode("100%"), "100%25");
747 // `url_decode` inverts it, arbitrary unicode included.
748 for s in [
749 "",
750 "a",
751 "A Z",
752 "a+b",
753 "100%",
754 "%41",
755 "=",
756 "&",
757 "x=y",
758 "é",
759 "☃",
760 "a/b?c",
761 " ",
762 "+",
763 "%",
764 "\t",
765 "ünïcodé",
766 ] {
767 assert_eq!(url_decode(&url_encode(s)), s, "round-trip {s:?}");
768 }
769 }
770
771 #[test]
772 fn char_slices_clamp_to_the_character_bounds() {
773 assert_eq!(char_slice("hello", 1, 4), "ell");
774 assert_eq!(char_slice("hello", 0, 5), "hello");
775 // Multibyte characters are indexed, not their bytes.
776 assert_eq!(char_slice("héllo", 1, 3), "él");
777 assert_eq!(char_slice("日本語", 1, 2), "本");
778 // Both bounds clamp to `0..=length`; `end <= start` is empty.
779 assert_eq!(char_slice("héllo", 0, i64::MAX), "héllo");
780 assert_eq!(char_slice("héllo", -3, 2), "hé");
781 assert_eq!(char_slice("héllo", 3, 100), "lo");
782 assert_eq!(char_slice("héllo", 5, 5), "");
783 assert_eq!(char_slice("héllo", 4, 2), "");
784 assert_eq!(char_slice("héllo", 7, 9), "");
785 assert_eq!(char_slice("héllo", -2, -1), "");
786 assert_eq!(char_slice("", 0, 1), "");
787 }
788
789 /// `query_params` against what `std/http.form` did before it: split
790 /// on `&`, drop empty pairs, split each on `=`, decode both sides
791 /// (the value re-joined on `=`).
792 #[test]
793 fn query_params_match_the_split_and_decode_recipe() {
794 fn reference(body: &str) -> Vec<(String, String)> {
795 split(body, "&")
796 .into_iter()
797 .filter(|p| !p.is_empty())
798 .map(|pair| match split(pair, "=").as_slice() {
799 [k] => (url_decode(k), String::new()),
800 [k, rest @ ..] => (url_decode(k), url_decode(&rest.join("="))),
801 [] => (String::new(), String::new()),
802 })
803 .collect()
804 }
805 for case in [
806 "",
807 "&",
808 "&&",
809 "a",
810 "a=",
811 "=b",
812 "=",
813 "==",
814 "a=b=c",
815 "a&&b",
816 "a=1&b=two+words&bare&c=x%3Dy",
817 "%",
818 "%4",
819 "%41",
820 "%zz",
821 "%4z",
822 "+",
823 "a+b",
824 "+a+",
825 "%ff",
826 "%c3%a9",
827 "é=x",
828 "%e2%82%ac",
829 "a=%ff%fe",
830 "&&&",
831 "=&=",
832 "k=+%20",
833 "%2f=%2F",
834 "a=b&",
835 "&a=b",
836 "%%41",
837 "%4%41",
838 "a%26b=c%3Dd",
839 ] {
840 assert_eq!(query_params(case), reference(case), "{case:?}");
841 }
842 }
843
844 /// Every byte percent-encoded comes back as itself, however tricky
845 /// the fragment.
846 #[test]
847 fn query_params_round_trip_encoded_pairs() {
848 let fragments = [
849 "",
850 "a",
851 "A Z",
852 "a+b",
853 "100%",
854 "%41",
855 "=",
856 "&",
857 "x=y",
858 "é",
859 "☃",
860 "a/b?c",
861 " ",
862 "+",
863 "%",
864 "\t",
865 "ünïcodé",
866 ];
867 let encode = |s: &str| s.bytes().map(|b| format!("%{b:02X}")).collect::<String>();
868 let expected: Vec<(String, String)> = fragments
869 .iter()
870 .flat_map(|n| {
871 fragments
872 .iter()
873 .map(move |v| (n.to_string(), v.to_string()))
874 })
875 .collect();
876 let encoded = expected
877 .iter()
878 .map(|(n, v)| format!("{}={}", encode(n), encode(v)))
879 .collect::<Vec<_>>()
880 .join("&");
881 assert_eq!(query_params(&encoded), expected);
882 }
883
884 #[test]
885 fn html_escaping() {
886 assert_eq!(
887 html_escape(r#"<a href="x">Tom & 'Jerry'</a>"#),
888 "&lt;a href=&quot;x&quot;&gt;Tom &amp; &#39;Jerry&#39;&lt;/a&gt;"
889 );
890 // The chunked form is the same escaping, and `html_escaped_len`
891 // agrees with both (None exactly when nothing changes).
892 for s in [
893 "",
894 "plain",
895 "&",
896 "<>&\"'",
897 "a & b <c>",
898 "&amp;",
899 "héllo 🦀",
900 "日本<語",
901 "é<é",
902 &"ab<&cd".repeat(100),
903 ] {
904 let escaped = html_escape(s);
905 assert_eq!(
906 html_escaped(s).collect::<Vec<_>>().concat(),
907 escaped.as_bytes(),
908 "{s:?}"
909 );
910 assert_eq!(
911 html_escaped_len(s),
912 (escaped != s).then_some(escaped.len()),
913 "{s:?}"
914 );
915 }
916 }
917
918 #[test]
919 fn splitting_on_an_empty_separator_keeps_the_string() {
920 assert_eq!(split("a,b,,c", ","), ["a", "b", "", "c"]);
921 assert_eq!(split("abc", ""), ["abc"]);
922 assert_eq!(split("", ","), [""]);
923 }
924
925 #[test]
926 fn chars_splits_on_scalar_values() {
927 assert_eq!(chars("héllo"), ["h", "é", "l", "l", "o"]);
928 assert_eq!(chars(""), Vec::<&str>::new());
929 assert_eq!(chars("a🦀b"), ["a", "🦀", "b"]);
930 }
931
932 #[test]
933 fn floats_from_text() {
934 assert_eq!(parse_float("1.5"), Ok(1.5));
935 assert_eq!(parse_float("-2e3"), Ok(-2000.0));
936 assert_eq!(parse_float("NaN").map(f64::is_nan), Ok(true));
937 assert!(parse_float("1.5x").is_err());
938 assert!(parse_float("").is_err());
939 }
940
941 #[test]
942 fn base64_rfc4648_vectors() {
943 let cases = [
944 ("", ""),
945 ("f", "Zg=="),
946 ("fo", "Zm8="),
947 ("foo", "Zm9v"),
948 ("foob", "Zm9vYg=="),
949 ("fooba", "Zm9vYmE="),
950 ("foobar", "Zm9vYmFy"),
951 ];
952 for (raw, encoded) in cases {
953 assert_eq!(base64_encode(raw.as_bytes()), encoded);
954 assert_eq!(base64_decode(encoded).unwrap(), raw.as_bytes());
955 }
956 assert!(base64_decode("Zg=").is_err());
957 assert!(base64_decode("Zg== ").is_err());
958 assert!(base64_decode("Z===").is_err());
959 assert!(base64_decode("Zm 9v").is_err());
960 assert!(base64_decode("Zm$v").is_err());
961 }
962
963 #[test]
964 fn hashes_are_non_negative_small_ints() {
965 for h in [
966 hash_bytes(b""),
967 hash_bytes(b"louise"),
968 mix(u64::MAX),
969 hash_combine(-1, i64::MAX),
970 ] {
971 assert!(SMALL_INT.contains(&h) && h >= 0, "{h}");
972 }
973 assert_eq!(hash_limbs(true, &[1, 2]), !hash_limbs(false, &[1, 2]));
974 }
975
976 /// Hashes are observable (`hash`, dictionary order), so these values
977 /// pin the formulas; `louise run` and native programs print the same.
978 #[test]
979 fn hashes_are_stable() {
980 assert_eq!(mix(0), 0);
981 assert_eq!(hash_bytes(b""), 4_416_489_145_408_256_550);
982 assert_eq!(hash_bytes(b"louise"), 1_206_155_588_114_856_828);
983 }
984}