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