//! The runtime's pure kernels and constants, shared by the native runtime //! (`louise_rt`), the reference interpreter (`louise_interp`) and the compiler. //! //! The interpreter is the native backend's test oracle, so it implements //! the runtime's semantics a second time on purpose. For leaf functions //! over numbers, strings and bytes, a second copy adds nothing to the //! oracle and drifts (the interpreter's `random.int` was biased while the //! runtime's was not), so both call the one here. Converting values to and //! from each back end's representation stays in each. //! //! `ring` is the one optional dependency, for the cryptographic hashes //! (crypto): already linked for TLS, and out of programs that never hash //! (`--gc-sections`). It is optional (the `crypto` feature, on by //! default): its build script needs a C cross-compiler the no-qemu //! aarch64 check does not have (scripts/ci.sh, ADR 0038). `num-bigint` //! (dec.rs) is already linked into every native program for `Int`. /// Cryptographic hashes (SHA-256, HMAC, PBKDF2) over `ring`. #[cfg(feature = "crypto")] pub mod crypto; /// The distribution wire format's kernel (ADR 0072, `docs/wire-format.md`): /// type descriptors, the definitions table, the structural type hash and /// the value encoding's primitives, shared by the compiler and the /// runtime's codec. pub mod wire; /// Running a program (`std/command`, ADR 0085): spawning, the pipes, the /// deadlines and reaping, driven by both back ends. #[cfg(feature = "command")] pub mod command; /// Standard input as lines and bytes (`std/io`, ADR 0086): the read-ahead /// buffer both back ends take lines and chunks from. pub mod stdin; /// Open files (`std/file/stream`, ADR 0087): reads and writes in chunks, /// shared by both backends. pub mod file; /// `Dec`'s kernels (`std/dec`, ADR 0070): fixed-point decimal arithmetic, /// parsing, showing, rounding and hashing, shared by both backends. pub mod dec; /// The blocking pools' sizes (ADR 0005, Revision 2): at most this many /// calls of each pool run at once. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct BlockingSizes { pub cpu: usize, pub io: usize, } /// The blocking pools' sizes from the environment `var` reads, on a /// machine of `cores` cores, or the message refusing an invalid value: /// /// - the CPU pool: `LOUISE_BLOCKING_CPU_THREADS`, else its shorthand /// `LOUISE_BLOCKING_THREADS` (plain `blocking` is `cpu`), else half the /// cores, between 1 and 4 (4 was the single pool's size): the scheduler /// keeps most of the machine; /// - the I/O pool: `LOUISE_BLOCKING_IO_THREADS`, else 16: waiting threads /// cost no CPU. pub fn blocking_sizes( var: impl Fn(&str) -> Option, cores: usize, ) -> Result { let read = |name: &str| -> Result, String> { match var(name) { None => Ok(None), Some(v) => match v.trim().parse::() { Ok(n) if n > 0 => Ok(Some(n)), _ => Err(format!( "louise: {name} must be a positive integer (a number of threads), got \"{v}\"" )), }, } }; let general = read("LOUISE_BLOCKING_THREADS")?; let cpu = read("LOUISE_BLOCKING_CPU_THREADS")?; let io = read("LOUISE_BLOCKING_IO_THREADS")?; Ok(BlockingSizes { cpu: cpu.or(general).unwrap_or((cores / 2).clamp(1, 4)), io: io.unwrap_or(16), }) } /// The `Int`s held unboxed: 63-bit two's complement, `-2^62 .. 2^62` /// (`TL_INT_MIN ..= TL_INT_MAX` in `louise_rt.h`). Others are big integers /// (ADR 0014). pub const SMALL_INT: std::ops::Range = -(1 << 62)..(1 << 62); /// The operations of `std/process.proc`, in declaration order: the root /// capability the runtime gives every actor holds one clause per /// operation, in this order (`louise_rt/src/process.rs`). Codegen refuses a /// `std/process` whose operations differ. pub const PROC_OPS: [&str; 17] = [ "spawn", "self", "subject", "send", "receive", "link", "monitor", "kill", "trap_exits", "exits", "sleep", "receive_any", "spawn_link", "spawn_monitor", "stop", "demonitor", "unlink", ]; /// The operations of `std/time.clock` and `std/random.random`, in /// declaration order: like [`PROC_OPS`], for their root capabilities /// (`louise_rt/src/clock.rs`, ADR 0036). pub const CLOCK_OPS: [&str; 2] = ["now_unix_ns", "monotonic_ns"]; pub const RANDOM_OPS: [&str; 1] = ["bytes"]; /// The kind of a root capability, as `tl_root_cap` takes it /// (`TL_ROOT_PROC`, `TL_ROOT_CLOCK` and `TL_ROOT_RANDOM` in `louise_rt.h`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum RootCap { Proc = 0, Clock = 1, Random = 2, } impl RootCap { /// The kind numbered `n`, if any. pub fn from_u8(n: u8) -> Option { [RootCap::Proc, RootCap::Clock, RootCap::Random] .into_iter() .find(|k| *k as u8 == n) } /// The operations of its effect, in declaration order. pub fn ops(self) -> &'static [&'static str] { match self { RootCap::Proc => &PROC_OPS, RootCap::Clock => &CLOCK_OPS, RootCap::Random => &RANDOM_OPS, } } /// Its name in `louise_rt.h`. pub fn c_name(self) -> &'static str { match self { RootCap::Proc => "TL_ROOT_PROC", RootCap::Clock => "TL_ROOT_CLOCK", RootCap::Random => "TL_ROOT_RANDOM", } } } // ---- hashing ------------------------------------------------------------------- const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x100_0000_01b3; /// A 64-bit mixer (splitmix64's finalizer), reduced to 62 bits so hashes /// are non-negative small `Int`s. pub fn mix(mut z: u64) -> i64 { z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); ((z ^ (z >> 31)) >> 2) as i64 } /// The hash of a string or `Bytes`: FNV-1a, then mixed. pub fn hash_bytes(bytes: &[u8]) -> i64 { let h = bytes.iter().fold(FNV_OFFSET, |h, b| { (h ^ u64::from(*b)).wrapping_mul(FNV_PRIME) }); mix(h) } /// The hash of a big `Int`, before mixing: FNV-1a over its 64-bit limbs /// (least significant first), complemented when it is negative. pub fn hash_limbs(negative: bool, limbs: &[u64]) -> u64 { let h = limbs .iter() .fold(FNV_OFFSET, |h, l| (h ^ l).wrapping_mul(FNV_PRIME)); if negative { !h } else { h } } /// `hash_combine(a, b)` of two hashes (as saturated `Int`s). pub fn hash_combine(a: i64, b: i64) -> i64 { let (x, y) = (a as u64, b as u64); mix(x.wrapping_mul(31).wrapping_add(y) ^ (x >> 7)) } // ---- strings --------------------------------------------------------------------- /// The parts of `s` between occurrences of `sep`; all of `s` if `sep` is /// empty. pub fn split<'a>(s: &'a str, sep: &str) -> Vec<&'a str> { if sep.is_empty() { vec![s] } else { s.split(sep).collect() } } /// The characters of `s` (Unicode scalar values) as single-character /// strings. pub fn chars(s: &str) -> Vec<&str> { s.char_indices() .map(|(i, c)| &s[i..i + c.len_utf8()]) .collect() } /// The characters of `s` from `start` up to `end` (excluded); both are /// clamped to `0..=s.chars().count()`, and the slice is empty when /// `end <= start`. One pass over the bytes, stopping at `end`. pub fn char_slice(s: &str, start: i64, end: i64) -> &str { if end <= start { return ""; } let (start, end) = (start.max(0) as usize, end.max(0) as usize); // `from` stays `usize::MAX` when `start` is past the last character. let (mut from, mut to) = (usize::MAX, s.len()); for (i, (byte, _)) in s.char_indices().enumerate() { if i == start { from = byte; } if i == end { to = byte; break; } } if from == usize::MAX || from >= to { return ""; } &s[from..to] } /// A float read from text (the platform's `f64` parser), or why not. pub fn parse_float(s: &str) -> Result { s.parse::().map_err(|_| format!("not a float: {s:?}")) } // ---- substring search (string.find, string.contains) -------------------------- mod find; pub use find::find; /// The HTML replacement of a metacharacter, if `b` is one (`& < > " '`). fn html_replacement(b: u8) -> Option<&'static [u8]> { match b { b'&' => Some(b"&"), b'<' => Some(b"<"), b'>' => Some(b">"), b'"' => Some(b"""), b'\'' => Some(b"'"), _ => None, } } /// The pieces of `s`'s escaped form: its spans without metacharacters and /// the replacements of its metacharacters, in order. One pass, no /// allocation; the runtime writes them straight into a string block or a /// builder. pub fn html_escaped(s: &str) -> impl Iterator { let bytes = s.as_bytes(); let mut at = 0; // the next byte not yet yielded std::iter::from_fn(move || { if at >= bytes.len() { return None; } if let Some(rep) = html_replacement(bytes[at]) { at += 1; return Some(rep); } let start = at; while at < bytes.len() && html_replacement(bytes[at]).is_none() { at += 1; } Some(&bytes[start..at]) }) } /// The length of `s`'s escaped form, or `None` when nothing needs /// escaping (the escaped form is `s` itself). pub fn html_escaped_len(s: &str) -> Option { let mut extra = 0usize; // beyond `s.len()` let mut dirty = false; for &b in s.as_bytes() { if let Some(rep) = html_replacement(b) { dirty = true; extra = extra .checked_add(rep.len() - 1) .expect("louise: string too large"); } } if !dirty { return None; } Some( s.len() .checked_add(extra) .expect("louise: string too large"), ) } /// `s` with `&`, `<`, `>`, `"` and `'` escaped for HTML text and /// attribute values. pub fn html_escape(s: &str) -> String { match html_escaped_len(s) { None => s.to_owned(), Some(len) => { let mut out = String::with_capacity(len); for chunk in html_escaped(s) { // A span of `s` cut at ASCII bytes, or an ASCII // replacement: valid UTF-8. out.push_str(std::str::from_utf8(chunk).expect("louise: html_escape chunk")); } out } } } // ---- base64 (RFC 4648) ------------------------------------------------------ // PostgreSQL's SCRAM-SHA-256 exchange (RFC 7677) is base64'd. const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// `data` in base64, with `=` padding. pub fn base64_encode(data: &[u8]) -> String { let mut out = String::with_capacity(data.len() * 4 / 3 + 4); for chunk in data.chunks(3) { // The chunk, left-aligned in 24 bits. let n = chunk.iter().fold(0u32, |n, &b| n << 8 | u32::from(b)) << (8 * (3 - chunk.len())); let sextets = [ n >> 18, n >> 12 & 63, if chunk.len() > 1 { n >> 6 & 63 } else { 64 }, if chunk.len() > 2 { n & 63 } else { 64 }, ]; for s in sextets { out.push(if s < 64 { char::from(B64_ALPHABET[s as usize]) } else { '=' }); } } out } /// The bytes of a base64 text: its length a multiple of 4, no whitespace, /// `=` padding only as the last one or two characters. (PostgreSQL sends /// canonical base64; the pad bits are not checked.) pub fn base64_decode(text: &str) -> Result, &'static str> { let bytes = text.as_bytes(); if !bytes.len().is_multiple_of(4) { return Err("base64: the length is not a multiple of 4"); } let sextet = |i: usize, b: u8| -> Result { match b { b'A'..=b'Z' => Ok(u32::from(b - b'A')), b'a'..=b'z' => Ok(u32::from(b - b'a' + 26)), b'0'..=b'9' => Ok(u32::from(b - b'0' + 52)), b'+' => Ok(62), b'/' => Ok(63), b'=' if i >= bytes.len() - 2 => Ok(0), // padding, at the end only _ => Err("base64: not a base64 character"), } }; let mut out = Vec::with_capacity(bytes.len() / 4 * 3); for (c, chunk) in bytes.chunks(4).enumerate() { if chunk[2] == b'=' && chunk[3] != b'=' { return Err("base64: `=` padding only ends the text"); } let mut n = 0u32; for (i, &b) in chunk.iter().enumerate() { n = n << 6 | sextet(c * 4 + i, b)?; } out.push((n >> 16) as u8); if chunk[2] != b'=' { out.push((n >> 8) as u8); } if chunk[3] != b'=' { out.push(n as u8); } } Ok(out) } /// Whether `url_decode` changes `s`: it holds a `%` or a `+`. pub fn url_needs_decode(s: &str) -> bool { s.bytes().any(|b| matches!(b, b'%' | b'+')) } /// Decode `%XX` and `+` (URL form encoding) into `out`, which has room /// for `s.len()` bytes (the decoded form is never longer); the decoded /// length is returned. Invalid escapes stay, and the result may not be /// valid UTF-8 (`url_decode` lossy-converts it). pub fn url_decode_into(s: &str, out: &mut [u8]) -> usize { let bytes = s.as_bytes(); debug_assert!(out.len() >= bytes.len()); let mut n = 0; let mut i = 0; while i < bytes.len() { match bytes[i] { b'+' => out[n] = b' ', b'%' if i + 2 < bytes.len() => { let hex = |b: u8| (b as char).to_digit(16); match (hex(bytes[i + 1]), hex(bytes[i + 2])) { (Some(h), Some(l)) => { out[n] = (h * 16 + l) as u8; i += 2; } _ => out[n] = b'%', } } b => out[n] = b, } n += 1; i += 1; } n } /// Decode `%XX` and `+` (URL form encoding); invalid escapes stay, and /// invalid UTF-8 becomes U+FFFD. pub fn url_decode(s: &str) -> String { if !url_needs_decode(s) { return s.to_owned(); } let mut buf = vec![0; s.len()]; let n = url_decode_into(s, &mut buf); buf.truncate(n); String::from_utf8_lossy(&buf).into_owned() } /// Whether `b` is unreserved (RFC 3986): the one set of bytes /// `url_encode` leaves as they are. fn url_unreserved(b: u8) -> bool { matches!(b, b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~') } /// Whether `url_encode` changes `s`: it holds a byte that is not /// unreserved. pub fn url_needs_encode(s: &str) -> bool { s.bytes().any(|b| !url_unreserved(b)) } /// Percent-encode `s` into `out`, which has room for `3 * s.len()` bytes /// (every byte may become `%XX`); the encoded length is returned. pub fn url_encode_into(s: &str, out: &mut [u8]) -> usize { const HEX: &[u8; 16] = b"0123456789ABCDEF"; debug_assert!(out.len() >= 3 * s.len()); let mut n = 0; for &b in s.as_bytes() { if url_unreserved(b) { out[n] = b; n += 1; } else { out[n..n + 3].copy_from_slice(&[ b'%', HEX[usize::from(b >> 4)], HEX[usize::from(b & 15)], ]); n += 3; } } n } /// Percent-encode `s` for a URL path or query (RFC 3986): every byte /// outside the unreserved set becomes `%XX` (uppercase hex); a space is /// `%20`, not `+` (`url_decode` maps both back to a space, and a `+` /// decodes as a space only in a query or form). `url_decode` inverts it: /// `url_decode(url_encode(s)) == s`. pub fn url_encode(s: &str) -> String { if !url_needs_encode(s) { return s.to_owned(); } let mut buf = vec![0; 3 * s.len()]; let n = url_encode_into(s, &mut buf); buf.truncate(n); // Unreserved bytes and `%XX` triplets are all ASCII. String::from_utf8(buf).expect("louise: percent-encoded bytes are ASCII") } /// The fields of an `application/x-www-form-urlencoded` body or query /// string (`std/http.form`): pairs split on `&`, each on its first `=`, /// both sides percent-decoded with `+` a space (as [`url_decode`], so a /// query and a form body decode the same way). Empty pairs are dropped; /// a bare `k` is `("k", "")`. /// /// One pass, one reused decode buffer: a side without `%` or `+` is /// copied once, undecoded. pub fn query_params(s: &str) -> Vec<(String, String)> { let mut out = Vec::new(); let mut scratch = Vec::new(); for pair in s.split('&') { if pair.is_empty() { continue; } // Only the first `=` separates the name from the value. let (name, value) = match pair.find('=') { Some(i) => (&pair[..i], &pair[i + 1..]), None => (pair, ""), }; out.push(( decode_side(name, &mut scratch), decode_side(value, &mut scratch), )); } out } /// One side of a pair, decoded as [`url_decode`] decodes, reusing /// `scratch`. fn decode_side(s: &str, scratch: &mut Vec) -> String { if !s.bytes().any(|b| b == b'%' || b == b'+') { // Nothing to decode: the slice is already valid UTF-8. return s.to_string(); } scratch.clear(); let bytes = s.as_bytes(); let mut i = 0; while i < bytes.len() { match bytes[i] { b'+' => scratch.push(b' '), b'%' if i + 2 < bytes.len() => { let hex = |b: u8| (b as char).to_digit(16); match (hex(bytes[i + 1]), hex(bytes[i + 2])) { (Some(h), Some(l)) => { scratch.push((h * 16 + l) as u8); i += 2; } _ => scratch.push(b'%'), } } b => scratch.push(b), } i += 1; } String::from_utf8_lossy(scratch).into_owned() } // ---- numbers (std/int, std/float, std/u64; ADR 0035) ---------------------------------- /// `int.shift_left` refuses a shift of `2^32` bits or more of a non-zero /// number: the result could not be allocated, and both backends give this /// message instead of running out of memory. pub const MAX_SHIFT: u64 = 1 << 32; /// The panic of a shift by a negative amount `k` (`op` is `int.shift_left`, /// `u64.shift_right`, ...). pub fn negative_shift(op: &str, k: &str) -> String { format!("{op}: negative shift amount {k}") } /// The panic of `int.shift_left` by `k ≥ MAX_SHIFT` bits. pub fn shift_too_large(k: &str) -> String { format!("int.shift_left: shift amount {k} is too large") } pub const U64_DIVISION_BY_ZERO: &str = "u64.div: division by zero"; pub const U64_REMAINDER_BY_ZERO: &str = "u64.rem: division by zero"; /// `x` as an IEEE 754 single (round to nearest, ties to even), its bits. /// A NaN keeps its sign, its quiet bit and the top 22 bits of its payload, /// computed here rather than by the hardware so every backend agrees. pub fn f64_to_f32_bits(x: f64) -> u32 { if x.is_nan() { let b = x.to_bits(); let sign = ((b >> 63) as u32) << 31; let payload = ((b >> 29) & 0x007F_FFFF) as u32; // A payload that loses all its bits keeps one, so it stays a NaN. let payload = if payload == 0 { 1 } else { payload }; return sign | 0x7F80_0000 | payload; } (x as f32).to_bits() } /// The single with bits `b`, widened (exactly) to a double. A NaN keeps /// its sign and payload, the reverse of `f64_to_f32_bits`. pub fn f32_bits_to_f64(b: u32) -> f64 { let x = f32::from_bits(b); if x.is_nan() { let sign = u64::from(b >> 31) << 63; let payload = u64::from(b & 0x007F_FFFF) << 29; return f64::from_bits(sign | 0x7FF0_0000_0000_0000 | payload); } f64::from(x) } // ---- randomness (std/random) --------------------------------------------------------- /// `n` bytes from the operating system's random source: what the root /// handler of `std/random.random` answers `bytes(n)` with (ADR 0036). /// /// # Panics /// If `/dev/urandom` cannot be read. pub fn random_bytes(n: usize) -> Vec { use std::io::Read; let mut buf = vec![0u8; n]; std::fs::File::open("/dev/urandom") .and_then(|mut f| f.read_exact(&mut buf)) .expect("louise: cannot read /dev/urandom"); buf } #[cfg(test)] mod tests { use super::{BlockingSizes, blocking_sizes}; fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { move |name| { vars.iter() .find(|(n, _)| *n == name) .map(|(_, v)| (*v).to_owned()) } } #[test] fn blocking_pools_default_to_a_small_cpu_pool() { let sizes = |cpu, io| Ok(BlockingSizes { cpu, io }); assert_eq!(blocking_sizes(env(&[]), 22), sizes(4, 16)); assert_eq!(blocking_sizes(env(&[]), 4), sizes(2, 16)); assert_eq!(blocking_sizes(env(&[]), 1), sizes(1, 16)); } #[test] fn the_specific_pool_variable_wins_over_the_shorthand() { let both = [ ("LOUISE_BLOCKING_THREADS", "16"), ("LOUISE_BLOCKING_CPU_THREADS", "3"), ]; assert_eq!( blocking_sizes(env(&both), 8), Ok(BlockingSizes { cpu: 3, io: 16 }) ); let general = [ ("LOUISE_BLOCKING_THREADS", "16"), ("LOUISE_BLOCKING_IO_THREADS", "64"), ]; assert_eq!( blocking_sizes(env(&general), 8), Ok(BlockingSizes { cpu: 16, io: 64 }) ); } #[test] fn zero_and_garbage_pool_sizes_are_refused() { for bad in ["0", "-1", "four", ""] { let err = blocking_sizes(env(&[("LOUISE_BLOCKING_IO_THREADS", bad)]), 8).unwrap_err(); assert_eq!( err, format!( "louise: LOUISE_BLOCKING_IO_THREADS must be a positive integer (a number of threads), got \"{bad}\"" ) ); } } #[test] fn floats_narrow_and_widen_keeping_nan_payloads() { use super::{f32_bits_to_f64, f64_to_f32_bits}; assert_eq!(f64_to_f32_bits(1.0), 0x3F80_0000); assert_eq!(f64_to_f32_bits(-0.0), 0x8000_0000); assert_eq!(f64_to_f32_bits(0.1), 0x3DCC_CCCD); // rounded to nearest assert_eq!(f64_to_f32_bits(f64::INFINITY), 0x7F80_0000); assert_eq!(f64_to_f32_bits(1e300), 0x7F80_0000); // overflow: infinity // A signalling NaN stays signalling, with its payload's top bits. let snan = f64::from_bits(0x7FF4_0000_0000_0001 | (0x12345 << 29)); let narrowed = f64_to_f32_bits(snan); assert_eq!(narrowed & 0x7FC0_0000, 0x7F80_0000, "still signalling"); assert_eq!( f32_bits_to_f64(narrowed).to_bits() >> 29, snan.to_bits() >> 29 ); // Every single round-trips through a double, NaNs included. for b in [ 0, 1, 0x0080_0000, 0x3F80_0000, 0x7F80_0000, 0x7FC0_0001, 0xFFBF_FFFF, ] { assert_eq!(f64_to_f32_bits(f32_bits_to_f64(b)), b, "{b:#x}"); } } use super::*; #[test] fn small_ints_are_63_bits() { assert_eq!(SMALL_INT.start, -(1 << 62)); assert_eq!(SMALL_INT.end - 1, (1 << 62) - 1); } #[test] fn url_decoding_keeps_invalid_escapes() { assert_eq!(url_decode("a+b%20c"), "a b c"); assert_eq!(url_decode("%41%zz%4"), "A%zz%4"); assert_eq!(url_decode("%"), "%"); assert_eq!(url_decode("%ff"), "\u{fffd}"); // Clean inputs (no `%`, no `+`) come back unchanged. assert!(!url_needs_decode("plain text")); assert!(!url_needs_decode("é")); assert!(url_needs_decode("a+b") && url_needs_decode("a%b")); assert_eq!(url_decode(""), ""); assert_eq!(url_decode("plain text"), "plain text"); // `+` at the edges, and escapes at the edges. assert_eq!(url_decode("+a+"), " a "); assert_eq!(url_decode("%41"), "A"); assert_eq!(url_decode("%41%42%43"), "ABC"); // Invalid escapes stay, byte for byte. assert_eq!(url_decode("%2"), "%2"); assert_eq!(url_decode("%2G"), "%2G"); assert_eq!(url_decode("%zz"), "%zz"); assert_eq!(url_decode("%%41"), "%A"); // Decoded bytes: NUL is valid UTF-8; multibyte sequences may span // escapes; invalid bytes become U+FFFD each. assert_eq!(url_decode("%00"), "\0"); assert_eq!(url_decode("%C3%A9"), "é"); assert_eq!(url_decode("%c3%a9"), "é"); assert_eq!(url_decode("%C3"), "\u{fffd}"); assert_eq!(url_decode("%A9%C3"), "\u{fffd}\u{fffd}"); assert_eq!(url_decode("é"), "é"); } #[test] fn url_encoding_escapes_everything_but_the_unreserved() { // Clean inputs (only unreserved bytes) come back unchanged. assert!(!url_needs_encode("")); assert!(!url_needs_encode("plain-text_1.0~x")); assert_eq!(url_encode(""), ""); assert_eq!(url_encode("abcXYZ019-_.~"), "abcXYZ019-_.~"); // Everything else becomes `%XX`, uppercase; a space is `%20`. assert!(url_needs_encode("a b")); assert_eq!(url_encode("a b"), "a%20b"); assert_eq!(url_encode("=&?/#%+"), "%3D%26%3F%2F%23%25%2B"); assert_eq!(url_encode("\0"), "%00"); // Unicode is UTF-8, each byte escaped. assert_eq!(url_encode("é"), "%C3%A9"); assert_eq!(url_encode("☃"), "%E2%98%83"); // Encoding is not idempotent: `%` becomes `%25`. assert_eq!(url_encode("%41"), "%2541"); assert_eq!(url_encode("100%"), "100%25"); // `url_decode` inverts it, arbitrary unicode included. for s in [ "", "a", "A Z", "a+b", "100%", "%41", "=", "&", "x=y", "é", "☃", "a/b?c", " ", "+", "%", "\t", "ünïcodé", ] { assert_eq!(url_decode(&url_encode(s)), s, "round-trip {s:?}"); } } #[test] fn char_slices_clamp_to_the_character_bounds() { assert_eq!(char_slice("hello", 1, 4), "ell"); assert_eq!(char_slice("hello", 0, 5), "hello"); // Multibyte characters are indexed, not their bytes. assert_eq!(char_slice("héllo", 1, 3), "él"); assert_eq!(char_slice("日本語", 1, 2), "本"); // Both bounds clamp to `0..=length`; `end <= start` is empty. assert_eq!(char_slice("héllo", 0, i64::MAX), "héllo"); assert_eq!(char_slice("héllo", -3, 2), "hé"); assert_eq!(char_slice("héllo", 3, 100), "lo"); assert_eq!(char_slice("héllo", 5, 5), ""); assert_eq!(char_slice("héllo", 4, 2), ""); assert_eq!(char_slice("héllo", 7, 9), ""); assert_eq!(char_slice("héllo", -2, -1), ""); assert_eq!(char_slice("", 0, 1), ""); } /// `query_params` against what `std/http.form` did before it: split /// on `&`, drop empty pairs, split each on `=`, decode both sides /// (the value re-joined on `=`). #[test] fn query_params_match_the_split_and_decode_recipe() { fn reference(body: &str) -> Vec<(String, String)> { split(body, "&") .into_iter() .filter(|p| !p.is_empty()) .map(|pair| match split(pair, "=").as_slice() { [k] => (url_decode(k), String::new()), [k, rest @ ..] => (url_decode(k), url_decode(&rest.join("="))), [] => (String::new(), String::new()), }) .collect() } for case in [ "", "&", "&&", "a", "a=", "=b", "=", "==", "a=b=c", "a&&b", "a=1&b=two+words&bare&c=x%3Dy", "%", "%4", "%41", "%zz", "%4z", "+", "a+b", "+a+", "%ff", "%c3%a9", "é=x", "%e2%82%ac", "a=%ff%fe", "&&&", "=&=", "k=+%20", "%2f=%2F", "a=b&", "&a=b", "%%41", "%4%41", "a%26b=c%3Dd", ] { assert_eq!(query_params(case), reference(case), "{case:?}"); } } /// Every byte percent-encoded comes back as itself, however tricky /// the fragment. #[test] fn query_params_round_trip_encoded_pairs() { let fragments = [ "", "a", "A Z", "a+b", "100%", "%41", "=", "&", "x=y", "é", "☃", "a/b?c", " ", "+", "%", "\t", "ünïcodé", ]; let encode = |s: &str| s.bytes().map(|b| format!("%{b:02X}")).collect::(); let expected: Vec<(String, String)> = fragments .iter() .flat_map(|n| { fragments .iter() .map(move |v| (n.to_string(), v.to_string())) }) .collect(); let encoded = expected .iter() .map(|(n, v)| format!("{}={}", encode(n), encode(v))) .collect::>() .join("&"); assert_eq!(query_params(&encoded), expected); } #[test] fn html_escaping() { assert_eq!( html_escape(r#"Tom & 'Jerry'"#), "<a href="x">Tom & 'Jerry'</a>" ); // The chunked form is the same escaping, and `html_escaped_len` // agrees with both (None exactly when nothing changes). for s in [ "", "plain", "&", "<>&\"'", "a & b ", "&", "héllo 🦀", "日本<語", "é<é", &"ab<&cd".repeat(100), ] { let escaped = html_escape(s); assert_eq!( html_escaped(s).collect::>().concat(), escaped.as_bytes(), "{s:?}" ); assert_eq!( html_escaped_len(s), (escaped != s).then_some(escaped.len()), "{s:?}" ); } } #[test] fn splitting_on_an_empty_separator_keeps_the_string() { assert_eq!(split("a,b,,c", ","), ["a", "b", "", "c"]); assert_eq!(split("abc", ""), ["abc"]); assert_eq!(split("", ","), [""]); } #[test] fn chars_splits_on_scalar_values() { assert_eq!(chars("héllo"), ["h", "é", "l", "l", "o"]); assert_eq!(chars(""), Vec::<&str>::new()); assert_eq!(chars("a🦀b"), ["a", "🦀", "b"]); } #[test] fn floats_from_text() { assert_eq!(parse_float("1.5"), Ok(1.5)); assert_eq!(parse_float("-2e3"), Ok(-2000.0)); assert_eq!(parse_float("NaN").map(f64::is_nan), Ok(true)); assert!(parse_float("1.5x").is_err()); assert!(parse_float("").is_err()); } #[test] fn base64_rfc4648_vectors() { let cases = [ ("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE="), ("foobar", "Zm9vYmFy"), ]; for (raw, encoded) in cases { assert_eq!(base64_encode(raw.as_bytes()), encoded); assert_eq!(base64_decode(encoded).unwrap(), raw.as_bytes()); } assert!(base64_decode("Zg=").is_err()); assert!(base64_decode("Zg== ").is_err()); assert!(base64_decode("Z===").is_err()); assert!(base64_decode("Zm 9v").is_err()); assert!(base64_decode("Zm$v").is_err()); } #[test] fn hashes_are_non_negative_small_ints() { for h in [ hash_bytes(b""), hash_bytes(b"louise"), mix(u64::MAX), hash_combine(-1, i64::MAX), ] { assert!(SMALL_INT.contains(&h) && h >= 0, "{h}"); } assert_eq!(hash_limbs(true, &[1, 2]), !hash_limbs(false, &[1, 2])); } /// Hashes are observable (`hash`, dictionary order), so these values /// pin the formulas; `louise run` and native programs print the same. #[test] fn hashes_are_stable() { assert_eq!(mix(0), 0); assert_eq!(hash_bytes(b""), 4_416_489_145_408_256_550); assert_eq!(hash_bytes(b"louise"), 1_206_155_588_114_856_828); } }