tobogganSe connecter

louise

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

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