//! The encoder itself: bits, Reed–Solomon over GF(256), the matrix, the mask.//!//! Read top to bottom it is the order the standard builds a symbol in, which//! is the order `encode.ts` is written in, which is why this file reads as a//! transliteration rather than a rewrite: every function here answers to a//! function there by name, and a case in `encode_tests.rs` answers to a case in//! `packages/core/__tests__/qr/encode.test.ts`.use std::fmt;/// Why a payload could not be encoded.////// `Empty` and `TooLong` are the caller's to handle — one is a bug upstream,/// the other is a payload that has to be shortened before it can be a symbol./// `Internal` is the encoder saying something it believes impossible happened,/// and no caller can do anything with it but report it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pubenumQrErrorKind {Empty,TooLong,Internal,}/// The one error this encoder returns.////// The KIND is the contract and the message is for the log. Both callers show/// a person a sentence about a refusal — the consent page and the Mac's/// Sharing panel — and a sentence chosen by matching on message text is a/// sentence that changes when somebody rewords the throw.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]#[error("{message}")]pubstructQrError {pub kind: QrErrorKind,pub message: String,}implQrError {fn new(kind: QrErrorKind, message: implInto<String>) -> Self {Self { kind, message: message.into(), } }}impl fmt::DisplayforQrErrorKind {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(matchself {Self::Empty => "empty",Self::TooLong => "too_long",Self::Internal => "internal", }) }}/// A finished symbol: `size` modules on a side, dark where `modules` is true.#[derive(Debug, Clone, PartialEq, Eq)]pubstructQrMatrix {pub size: usize,pub modules: Vec<Vec<bool>>,}/// How a matrix is drawn.////// DIVERGENCE, recorded: `moduleSize` and `quietZone` are JavaScript numbers in/// the original and whole modules here. Every caller passes an integer, and the/// only thing a fraction would buy is a chance for Rust and JavaScript to/// format the same coordinate differently inside a `<path>` the consent-page/// suite compares character for character.#[derive(Debug, Clone, PartialEq, Eq)]pubstructQrSvgOptions {/// Side of one module in the SVG's user units.pub module_size: u32,/// Width of the blank border, in modules. The standard's is 4.pub quiet_zone: u32,/// Fill for the dark modules.pub dark: String,/// Fill behind the symbol; `"none"` paints nothing.pub light: String,}implDefaultforQrSvgOptions {fn default() -> Self {Self { module_size: 1, quiet_zone: 4, dark: "#000".to_string(), light: "none".to_string(), } }}structEcBlockSpec {/// Total codewords in the symbol (data + error correction). #[allow(dead_code)] total: usize, ec_per_block: usize,/// (block count, data codewords per block) for group 1. g1: (usize, usize),/// (block count, data codewords per block) for group 2; (0, 0) when absent. g2: (usize, usize),}/// Level M, versions 1–10, indexed by version - 1.////// One line per version, because that is how ISO/IEC 18004 Table 9 reads and/// how anybody checking a row against the standard will want to read it.#[rustfmt::skip]const EC_M: [EcBlockSpec; 10] = [EcBlockSpec { total: 26, ec_per_block: 10, g1: (1, 16), g2: (0, 0) },EcBlockSpec { total: 44, ec_per_block: 16, g1: (1, 28), g2: (0, 0) },EcBlockSpec { total: 70, ec_per_block: 26, g1: (1, 44), g2: (0, 0) },EcBlockSpec { total: 100, ec_per_block: 18, g1: (2, 32), g2: (0, 0) },EcBlockSpec { total: 134, ec_per_block: 24, g1: (2, 43), g2: (0, 0) },EcBlockSpec { total: 172, ec_per_block: 16, g1: (4, 27), g2: (0, 0) },EcBlockSpec { total: 196, ec_per_block: 18, g1: (4, 31), g2: (0, 0) },EcBlockSpec { total: 242, ec_per_block: 22, g1: (2, 38), g2: (2, 39) },EcBlockSpec { total: 292, ec_per_block: 22, g1: (3, 36), g2: (2, 37) },EcBlockSpec { total: 346, ec_per_block: 26, g1: (4, 43), g2: (1, 44) },];/// Alignment-pattern centre coordinates per version (empty for version 1).const ALIGNMENT: [&[usize]; 10] = [ &[], &[6, 18], &[6, 22], &[6, 26], &[6, 30], &[6, 34], &[6, 22, 38], &[6, 24, 42], &[6, 26, 46], &[6, 28, 50],];/// Bits left over after the codewords, per version.const REMAINDER_BITS: [usize; 10] = [0, 7, 7, 7, 7, 7, 0, 0, 0, 0];pubconst MIN_VERSION: usize = 1;pubconst MAX_VERSION: usize = 10;const MODE_BYTE: u32 = 0b0100;const PAD_CODEWORDS: [u8; 2] = [0xec, 0x11];// ── GF(256), the QR field: x^8 + x^4 + x^3 + x^2 + 1 (0x11d) ─────────────────/// The field's exponent and log tables, built once.////// A `OnceLock` rather than the TypeScript's module-level block because the/// tables are 768 bytes of derived data and a `const fn` that filled them would/// have to be a second, differently-written copy of the same loop.structGaloisField { exp: [u8; 512], log: [u8; 256],}fn field() -> &'staticGaloisField {static FIELD: std::sync::OnceLock<GaloisField> = std::sync::OnceLock::new(); FIELD.get_or_init(|| {letmut exp = [0u8; 512];letmut log = [0u8; 256];letmut x: u16 = 1;for (i, slot) in exp.iter_mut().enumerate().take(255) { *slot = x as u8; log[x as usize] = i as u8; x <<= 1;if x & 0x100 != 0 { x ^= 0x11d; } }// Doubling the exponent table lets a product skip the modulo on the logs.for i in255..512usize { exp[i] = exp[i - 255]; }GaloisField { exp, log } })}fn gf_mul(a: u8, b: u8) -> u8 {if a == 0 || b == 0 {return0; }let f = field(); f.exp[f.log[a as usize] as usize + f.log[b as usize] as usize]}/// The generator polynomial for `degree` error-correction codewords: ∏ (x - α^i).fn generator_poly(degree: usize) -> Vec<u8> {letmut poly = vec![1u8];for i in0..degree {letmut next = vec![0u8; poly.len() + 1];for j in0..poly.len() { next[j] ^= poly[j]; next[j + 1] ^= gf_mul(poly[j], field().exp[i]); } poly = next; } poly}/// The `ec_count` error-correction codewords for one block: the remainder of/// the data polynomial divided by the generator polynomial over GF(256).////// Public for the ISO/IEC 18004 Annex I vector test — the encoder's own callers/// only ever reach it through [`encode_qr`].pubfn rs_encode(data: &[u8], ec_count: usize) -> Vec<u8> {let gen = generator_poly(ec_count);letmut remainder = vec![0u8; ec_count];for &byte in data {let factor = byte ^ remainder[0]; remainder.remove(0); remainder.push(0);if factor != 0 {for i in0..ec_count { remainder[i] ^= gf_mul(gen[i + 1], factor); } } } remainder}// ── The bit stream ───────────────────────────────────────────────────────────#[derive(Default)]structBitBuffer { bits: Vec<bool>,}implBitBuffer {fn len(&self) -> usize {self.bits.len() }fn put(&mutself, value: u32, width: usize) {for i in (0..width).rev() {self.bits.push((value >> i) & 1 == 1); } }fn pad_to_byte(&mutself) {while !self.bits.len().is_multiple_of(8) {self.bits.push(false); } }fn to_bytes(&self) -> Vec<u8> {self.bits .chunks(8) .map(|chunk| {letmut byte = 0u8;for j in0..8 { byte = (byte << 1) | u8::from(chunk.get(j).copied().unwrap_or(false)); } byte }) .collect() }}/// Width of the character count field in byte mode: 8 bits to version 9, 16 from 10.fn count_bits(version: usize) -> usize {if version <= 9 {8 } else {16 }}fn data_codeword_count(spec: &EcBlockSpec) -> usize { spec.g1.0 * spec.g1.1 + spec.g2.0 * spec.g2.1}/// The most bytes a byte-mode payload can occupy at this version, level M.fn byte_capacity(version: usize) -> usize {let spec = &EC_M[version - 1];let usable = data_codeword_count(spec) * 8 - 4 - count_bits(version); usable / 8}fn smallest_version(byte_length: usize) -> Result<usize, QrError> {for version in MIN_VERSION..=MAX_VERSION {if byte_length <= byte_capacity(version) {returnOk(version); } }Err(QrError::new(QrErrorKind::TooLong, format!("QR payload too long: {byte_length} bytes, and version {MAX_VERSION} at level M holds {}", byte_capacity(MAX_VERSION) ), ))}/// The data codewords: header, payload, terminator, padding to the version's capacity.fn data_codewords(bytes: &[u8], version: usize) -> Vec<u8> {let spec = &EC_M[version - 1];let capacity = data_codeword_count(spec);letmut buffer = BitBuffer::default(); buffer.put(MODE_BYTE, 4); buffer.put(bytes.len() as u32, count_bits(version));for &byte in bytes { buffer.put(u32::from(byte), 8); }// Terminator: up to four zero bits, fewer if the capacity is nearly full.let terminator = std::cmp::min(4, capacity * 8 - buffer.len()); buffer.put(0, terminator); buffer.pad_to_byte();letmut codewords = buffer.to_bytes();letmut i = 0;while codewords.len() < capacity { codewords.push(PAD_CODEWORDS[i % 2]); i += 1; } codewords}/// Interleave the data blocks, then the error-correction blocks, per §8.6.fn interleave(codewords: &[u8], version: usize) -> Vec<u8> {let spec = &EC_M[version - 1];letmut data_blocks: Vec<Vec<u8>> = Vec::new();letmut ec_blocks: Vec<Vec<u8>> = Vec::new();letmut offset = 0usize;for (block_count, per_block) in [spec.g1, spec.g2] {for _ in0..block_count {let block = codewords[offset..offset + per_block].to_vec(); offset += per_block; ec_blocks.push(rs_encode(&block, spec.ec_per_block)); data_blocks.push(block); } }letmut out: Vec<u8> = Vec::new();let longest = data_blocks.iter().map(Vec::len).max().unwrap_or(0);for i in0..longest {for block in &data_blocks {ifletSome(&byte) = block.get(i) { out.push(byte); } } }for i in0..spec.ec_per_block {for block in &ec_blocks { out.push(block[i]); } } out}// ── The matrix ───────────────────────────────────────────────────────────────structCanvas { size: usize, modules: Vec<Vec<bool>>,/// True where a function pattern lives: never masked, never written by data. reserved: Vec<Vec<bool>>,}fn blank_canvas(size: usize) -> Canvas {Canvas { size, modules: vec![vec![false; size]; size], reserved: vec![vec![false; size]; size], }}fn set_function(canvas: &mutCanvas, row: usize, col: usize, dark: bool) { canvas.modules[row][col] = dark; canvas.reserved[row][col] = true;}fn draw_finder(canvas: &mutCanvas, row: usize, col: usize) {// The 7×7 pattern plus its separator: every module of the 9×9 around it// that falls inside the symbol is a function module, dark only inside the// rings.let size = canvas.size as isize;for r in -1isize..=7 {for c in -1isize..=7 {let rr = row as isize + r;let cc = col as isize + c;if rr < 0 || rr >= size || cc < 0 || cc >= size {continue; }let in_ring = (r == 0 || r == 6) && (0..=6).contains(&c);let in_column = (c == 0 || c == 6) && (0..=6).contains(&r);let in_core = (2..=4).contains(&r) && (2..=4).contains(&c); set_function( canvas, rr as usize, cc as usize, in_ring || in_column || in_core, ); } }}fn draw_alignment(canvas: &mutCanvas, row: usize, col: usize) {for r in -2isize..=2 {for c in -2isize..=2 {let outer = std::cmp::max(r.abs(), c.abs());let rr = (row as isize + r) as usize;let cc = (col as isize + c) as usize; set_function(canvas, rr, cc, outer != 1); } }}fn draw_function_patterns(canvas: &mutCanvas, version: usize) {let size = canvas.size; draw_finder(canvas, 0, 0); draw_finder(canvas, 0, size - 7); draw_finder(canvas, size - 7, 0);// Timing patterns, alternating from the first module outside the separators.for i in8..size - 8 {let dark = i.is_multiple_of(2); set_function(canvas, 6, i, dark); set_function(canvas, i, 6, dark); }// Alignment patterns at every pair of centres, minus the three that would// sit on a finder.let centres = ALIGNMENT[version - 1];for &row in centres {for &col in centres {let on_finder = (row == 6 && col == 6) || (row == 6 && col == size - 7) || (row == size - 7 && col == 6);if !on_finder { draw_alignment(canvas, row, col); } } }// Format-information area: reserved now, written once the mask is chosen.for i in0..=8usize {if i != 6 { set_function(canvas, 8, i, false); set_function(canvas, i, 8, false); } }for i in0..8usize { set_function(canvas, 8, size - 1 - i, false); set_function(canvas, size - 1 - i, 8, false); }// The dark module, always set, just above the bottom-left format strip. set_function(canvas, size - 8, 8, true);if version >= 7 { draw_version_info(canvas, version); }}/// The 18-bit version information — BCH(18,6) under 0x1f25 — in both corners.fn draw_version_info(canvas: &mutCanvas, version: usize) {letmut remainder = version as u32;for _ in0..12 { remainder = (remainder << 1) ^ if remainder >> 11 != 0 { 0x1f25 } else { 0 }; }let bits = ((version as u32) << 12) | (remainder & 0xfff);for i in0..18usize {let dark = (bits >> i) & 1 == 1;let a = canvas.size - 11 + (i % 3);let b = i / 3; set_function(canvas, b, a, dark); set_function(canvas, a, b, dark); }}/// The 15-bit format information — BCH(15,5) under 0x537, masked with 0x5412.fn draw_format_info(canvas: &mutCanvas, mask: usize) {let size = canvas.size;const EC_LEVEL_M: u32 = 0b00;let data = (EC_LEVEL_M << 3) | mask as u32;letmut remainder = data;for _ in0..10 { remainder = (remainder << 1) ^ if remainder >> 9 != 0 { 0x537 } else { 0 }; }let bits = (((data << 10) | (remainder & 0x3ff)) ^ 0x5412) & 0x7fff;let bit = |i: usize| (bits >> i) & 1 == 1;// First copy, around the top-left finder.for i in0..=5usize { set_function(canvas, i, 8, bit(i)); } set_function(canvas, 7, 8, bit(6)); set_function(canvas, 8, 8, bit(7)); set_function(canvas, 8, 7, bit(8));for i in9..15usize { set_function(canvas, 8, 14 - i, bit(i)); }// Second copy, split between the other two finders.for i in0..8usize { set_function(canvas, 8, size - 1 - i, bit(i)); }for i in8..15usize { set_function(canvas, size - 15 + i, 8, bit(i)); } set_function(canvas, size - 8, 8, true);}/// Lay the codeword bits into the free modules, two columns at a time, zigzag.fn place_codewords(canvas: &mutCanvas, codewords: &[u8], version: usize) {let size = canvas.size;let total_bits = codewords.len() * 8 + REMAINDER_BITS[version - 1];letmut index = 0usize;letmut right = size as isize - 1;while right >= 1 {// Column 6 is the vertical timing pattern; the pairs step around it.if right == 6 { right = 5; }for vertical in0..size {for j in0..2isize {let col = (right - j) as usize;let upward = ((right + 1) & 2) == 0;let row = if upward { size - 1 - vertical } else { vertical };if canvas.reserved[row][col] {continue; }if index < total_bits {// Remainder bits are zero, and there is no codeword for them.let byte = codewords.get(index >> 3).copied().unwrap_or(0); canvas.modules[row][col] = (byte >> (7 - (index & 7))) & 1 == 1; } index += 1; } } right -= 2; }}const MASK_COUNT: usize = 8;fn mask_at(mask: usize, r: usize, c: usize) -> bool {match mask {0 => (r + c).is_multiple_of(2),1 => r.is_multiple_of(2),2 => c.is_multiple_of(3),3 => (r + c).is_multiple_of(3),4 => (r / 2 + c / 3).is_multiple_of(2),5 => (r * c) % 2 + (r * c) % 3 == 0,6 => ((r * c) % 2 + (r * c) % 3).is_multiple_of(2), _ => ((r + c) % 2 + (r * c) % 3).is_multiple_of(2), }}const PENALTY_N1: u32 = 3;const PENALTY_N2: u32 = 3;const PENALTY_N3: u32 = 40;const PENALTY_N4: u32 = 10;/// The finder-lookalike the third penalty rule hunts for, and its mirror.const FINDER_LIKE: [bool; 7] = [true, false, true, true, true, false, true];fn penalty(modules: &[Vec<bool>], size: usize) -> u32 {letmut score = 0u32;// Rule 1 — runs of five or more of one colour, in every row and column.let run_score = |at: &dynFn(usize) -> bool| -> u32 {letmut total = 0u32;letmut run = 1u32;for i in1..size {if at(i) == at(i - 1) { run += 1;if run == 5 { total += PENALTY_N1; } elseif run > 5 { total += 1; } } else { run = 1; } } total };for (i, row) in modules.iter().enumerate().take(size) { score += run_score(&|j| row[j]); score += run_score(&|j| modules[j][i]); }// Rule 2 — every 2×2 block of one colour.for r in0..size.saturating_sub(1) {for c in0..size.saturating_sub(1) {let first = modules[r][c];if modules[r][c + 1] == first && modules[r + 1][c] == first && modules[r + 1][c + 1] == first { score += PENALTY_N2; } } }// Rule 3 — 1011101 with four light modules on either side.let matches = |at: &dynFn(usize) -> bool, start: usize| -> bool { (0..7).all(|k| at(start + k) == FINDER_LIKE[k]) };// The four light modules must be inside the symbol: the standard leaves it// open whether the quiet zone counts, and ZXing — the decoder family this// has to please — requires them in-symbol, so that is the reading taken// here.let clear = |at: &dynFn(usize) -> bool, start: isize| -> bool {if start < 0 || start as usize + 4 > size {returnfalse; } (0..4).all(|k| !at(start as usize + k)) };let pattern_score = |at: &dynFn(usize) -> bool| -> u32 {letmut total = 0u32;for i in0..=size.saturating_sub(7) {if i + 7 > size || !matches(at, i) {continue; }if clear(at, i as isize - 4) || clear(at, i as isize + 7) { total += PENALTY_N3; } } total };for (i, row) in modules.iter().enumerate().take(size) { score += pattern_score(&|j| row[j]); score += pattern_score(&|j| modules[j][i]); }// Rule 4 — how far the proportion of dark modules strays from half.letmut dark = 0usize;for row in modules.iter().take(size) {for &module in row.iter().take(size) {if module { dark += 1; } } }let percent = (dark as f64 * 100.0) / (size * size) as f64; score += ((percent - 50.0).abs() / 5.0).floor() as u32 * PENALTY_N4; score}fn apply_mask(canvas: &Canvas, mask: usize) -> Canvas {letmut masked = Canvas { size: canvas.size, modules: canvas.modules.clone(), reserved: canvas.reserved.clone(), };for r in0..canvas.size {for c in0..canvas.size {if !canvas.reserved[r][c] && mask_at(mask, r, c) { masked.modules[r][c] = !masked.modules[r][c]; } } } draw_format_info(&mut masked, mask); masked}/// Encode `text` as a QR symbol: byte mode, error-correction level M, the/// smallest version from 1 to 10 that holds it, and the mask the standard's/// four penalty rules like best.////// Refuses an empty payload (`Empty`) and one longer than version 10 at level M/// holds — 213 bytes (`TooLong`).////// The payload's LENGTH is its UTF-8 byte length, which a Rust `&str` already/// is: `encode.ts` hand-rolls that conversion only because it cannot count on a/// `TextEncoder` in all three of its runtimes.pubfn encode_qr(text: &str) -> Result<QrMatrix, QrError> {let bytes = text.as_bytes();// An empty payload is refused rather than encoded: the standard admits a// symbol whose only content is the terminator, but readers disagree about// it (ZXing finds nothing in one), and no caller here has anything to say// with an empty string.if bytes.is_empty() {returnErr(QrError::new(QrErrorKind::Empty,"QR payload is empty: there is nothing to encode", )); }let version = smallest_version(bytes.len())?;let codewords = interleave(&data_codewords(bytes, version), version);letmut canvas = blank_canvas(17 + 4 * version); draw_function_patterns(&mut canvas, version); place_codewords(&mut canvas, &codewords, version);letmut best: Option<Canvas> = None;letmut best_score = u32::MAX;for mask in0..MASK_COUNT {let candidate = apply_mask(&canvas, mask);let score = penalty(&candidate.modules, candidate.size);if score < best_score { best_score = score; best = Some(candidate); } }// Eight masks are always evaluated and the first scores below `u32::MAX`,// so this arm is for the type rather than for a case that can happen.let best = best .ok_or_else(|| QrError::new(QrErrorKind::Internal, "QR encoder: no mask was evaluated"))?;Ok(QrMatrix { size: best.size, modules: best.modules, })}// ── SVG ──────────────────────────────────────────────────────────────────────/// Escape a caller-supplied colour so it cannot break out of its attribute.fn escape_attribute(value: &str) -> String {letmut out = String::with_capacity(value.len());for ch in value.chars() {match ch { '&' => out.push_str("&"), '"' => out.push_str("""), '<' => out.push_str("<"), '>' => out.push_str(">"), _ => out.push(ch), } } out}/// Render a matrix as a standalone `<svg>` string: one `<path>` holding every/// dark module as a run of horizontal rectangles, a quiet zone around it, and/// no script of any kind — the consent page inlines this under a strict CSP.pubfn qr_svg(matrix: &QrMatrix, options: &QrSvgOptions) -> String {letQrSvgOptions { module_size, quiet_zone, dark, light, } = options;let size = matrix.size;let side = (size as u32 + quiet_zone * 2) * module_size;letmut parts = String::new();for r in0..size {letmut c = 0usize;while c < size {if !matrix.modules[r][c] { c += 1;continue; }letmut run = 1usize;while c + run < size && matrix.modules[r][c + run] { run += 1; }let x = (c as u32 + quiet_zone) * module_size;let y = (r as u32 + quiet_zone) * module_size;let width = run as u32 * module_size; parts.push_str(&format!("M{x} {y}h{width}v{module_size}h-{width}z")); c += run; } }let background = if light == "none" {String::new() } else { format!(r#"<rect width="{side}" height="{side}" fill="{}"/>"#, escape_attribute(light) ) }; format!(r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {side} {side}" shape-rendering="crispEdges">{background}<path fill="{}" d="{parts}"/></svg>"#, escape_attribute(dark) )}#[cfg(test)]#[path = "encode_tests.rs"]mod encode_tests;