#[cfg(not(feature = "std"))]
#[allow(unused_imports)]
use alloc::{
borrow::ToOwned,
format,
string::{String, ToString},
vec,
vec::Vec,
};
use core::cmp::{max, min};
use crate::cast::As;
use crate::types::{Color, EcLevel, Version};
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum Module {
Empty,
Masked(Color),
Unmasked(Color),
}
impl From<Module> for Color {
fn from(module: Module) -> Self {
match module {
Module::Empty => Color::Light,
Module::Masked(c) | Module::Unmasked(c) => c,
}
}
}
impl Module {
pub fn is_dark(self) -> bool {
Color::from(self) == Color::Dark
}
#[must_use]
pub fn mask(self, should_invert: bool) -> Self {
match (self, should_invert) {
(Module::Empty, true) => Module::Masked(Color::Dark),
(Module::Empty, false) => Module::Masked(Color::Light),
(Module::Unmasked(c), true) => Module::Masked(!c),
(Module::Unmasked(c), false) | (Module::Masked(c), _) => Module::Masked(c),
}
}
}
#[derive(Clone)]
pub struct Canvas {
width: i16,
version: Version,
ec_level: EcLevel,
modules: Vec<Module>,
}
impl Canvas {
pub fn new(version: Version, ec_level: EcLevel) -> Self {
let width = version.width();
Self { width, version, ec_level, modules: vec![Module::Empty; (width * width).as_usize()] }
}
#[cfg(test)]
fn to_debug_str(&self) -> String {
let width = self.width;
let mut res = String::with_capacity((width * (width + 1)).as_usize());
for y in 0..width {
res.push('\n');
for x in 0..width {
res.push(match self.get(x, y) {
Module::Empty => '?',
Module::Masked(Color::Light) => '.',
Module::Masked(Color::Dark) => '#',
Module::Unmasked(Color::Light) => '-',
Module::Unmasked(Color::Dark) => '*',
});
}
}
res
}
fn coords_to_index(&self, x: i16, y: i16) -> usize {
let x = if x < 0 { x + self.width } else { x }.as_usize();
let y = if y < 0 { y + self.width } else { y }.as_usize();
y * self.width.as_usize() + x
}
pub fn get(&self, x: i16, y: i16) -> Module {
self.modules[self.coords_to_index(x, y)]
}
pub fn get_mut(&mut self, x: i16, y: i16) -> &mut Module {
let index = self.coords_to_index(x, y);
&mut self.modules[index]
}
pub fn put(&mut self, x: i16, y: i16, color: Color) {
*self.get_mut(x, y) = Module::Masked(color);
}
}
#[cfg(test)]
mod basic_canvas_tests {
use crate::canvas::{Canvas, Module};
use crate::types::{Color, EcLevel, Version};
#[test]
fn test_index() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
assert_eq!(c.get(0, 4), Module::Empty);
assert_eq!(c.get(-1, -7), Module::Empty);
assert_eq!(c.get(21 - 1, 21 - 7), Module::Empty);
c.put(0, 0, Color::Dark);
c.put(-1, -7, Color::Light);
assert_eq!(c.get(0, 0), Module::Masked(Color::Dark));
assert_eq!(c.get(21 - 1, -7), Module::Masked(Color::Light));
assert_eq!(c.get(-1, 21 - 7), Module::Masked(Color::Light));
}
#[test]
fn test_debug_str() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
for i in 3_i16..20 {
for j in 3_i16..20 {
*c.get_mut(i, j) = match ((i * 3) ^ j) % 5 {
0 => Module::Empty,
1 => Module::Masked(Color::Light),
2 => Module::Masked(Color::Dark),
3 => Module::Unmasked(Color::Light),
4 => Module::Unmasked(Color::Dark),
_ => unreachable!(),
};
}
}
assert_eq!(
&*c.to_debug_str(),
"\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????####****....---?\n\
???--.##-..##?..#??.?\n\
???#*?-.*?#.-*#?-*.??\n\
?????*?*?****-*-*---?\n\
???*.-.-.-?-?#?#?#*#?\n\
???.*#.*.*#.*#*#.*#*?\n\
?????.#-#--??.?.#---?\n\
???-.?*.-#?-.?#*-#?.?\n\
???##*??*..##*--*..??\n\
?????-???--??---?---?\n\
???*.#.*.#**.#*#.#*#?\n\
???##.-##..##..?#..??\n\
???.-?*.-?#.-?#*-?#*?\n\
????-.#?-.**#?-.#?-.?\n\
???**?-**??--**?-**??\n\
???#?*?#?*#.*-.-*-.-?\n\
???..-...--??###?###?\n\
?????????????????????"
);
}
}
impl Canvas {
fn draw_finder_pattern_at(&mut self, x: i16, y: i16) {
let (dx_left, dx_right) = if x >= 0 { (-3, 4) } else { (-4, 3) };
let (dy_top, dy_bottom) = if y >= 0 { (-3, 4) } else { (-4, 3) };
for j in dy_top..=dy_bottom {
for i in dx_left..=dx_right {
self.put(
x + i,
y + j,
#[allow(clippy::match_same_arms)]
match (i, j) {
(4 | -4, _) | (_, 4 | -4) => Color::Light,
(3 | -3, _) | (_, 3 | -3) => Color::Dark,
(2 | -2, _) | (_, 2 | -2) => Color::Light,
_ => Color::Dark,
},
);
}
}
}
fn draw_finder_patterns(&mut self) {
self.draw_finder_pattern_at(3, 3);
match self.version {
Version::Micro(_) => {}
Version::Normal(_) => {
self.draw_finder_pattern_at(-4, 3);
self.draw_finder_pattern_at(3, -4);
}
}
}
}
#[cfg(test)]
mod finder_pattern_tests {
use crate::canvas::Canvas;
use crate::types::{EcLevel, Version};
#[test]
fn test_qr() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_finder_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.?????.#######\n\
#.....#.?????.#.....#\n\
#.###.#.?????.#.###.#\n\
#.###.#.?????.#.###.#\n\
#.###.#.?????.#.###.#\n\
#.....#.?????.#.....#\n\
#######.?????.#######\n\
........?????........\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
........?????????????\n\
#######.?????????????\n\
#.....#.?????????????\n\
#.###.#.?????????????\n\
#.###.#.?????????????\n\
#.###.#.?????????????\n\
#.....#.?????????????\n\
#######.?????????????"
);
}
#[test]
fn test_micro_qr() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_finder_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.???\n\
#.....#.???\n\
#.###.#.???\n\
#.###.#.???\n\
#.###.#.???\n\
#.....#.???\n\
#######.???\n\
........???\n\
???????????\n\
???????????\n\
???????????"
);
}
}
impl Canvas {
fn draw_alignment_pattern_at(&mut self, x: i16, y: i16) {
if self.get(x, y) != Module::Empty {
return;
}
for j in -2..=2 {
for i in -2..=2 {
self.put(
x + i,
y + j,
match (i, j) {
(2 | -2, _) | (_, 2 | -2) | (0, 0) => Color::Dark,
_ => Color::Light,
},
);
}
}
}
fn draw_alignment_patterns(&mut self) {
match self.version {
Version::Micro(_) | Version::Normal(1) => {}
Version::Normal(a @ 2..=40) => {
let positions = alignment_pattern_positions(a);
for x in positions {
for y in positions {
self.draw_alignment_pattern_at(*x, *y);
}
}
}
Version::Normal(_) => {}
}
}
}
#[cfg(test)]
mod alignment_pattern_tests {
use crate::canvas::{Canvas, alignment_pattern_positions};
use crate::types::{EcLevel, Version};
#[test]
fn test_draw_alignment_patterns_1() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_finder_patterns();
c.draw_alignment_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.?????.#######\n\
#.....#.?????.#.....#\n\
#.###.#.?????.#.###.#\n\
#.###.#.?????.#.###.#\n\
#.###.#.?????.#.###.#\n\
#.....#.?????.#.....#\n\
#######.?????.#######\n\
........?????........\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
........?????????????\n\
#######.?????????????\n\
#.....#.?????????????\n\
#.###.#.?????????????\n\
#.###.#.?????????????\n\
#.###.#.?????????????\n\
#.....#.?????????????\n\
#######.?????????????"
);
}
#[test]
fn test_draw_alignment_patterns_3() {
let mut c = Canvas::new(Version::Normal(3), EcLevel::L);
c.draw_finder_patterns();
c.draw_alignment_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.?????????????.#######\n\
#.....#.?????????????.#.....#\n\
#.###.#.?????????????.#.###.#\n\
#.###.#.?????????????.#.###.#\n\
#.###.#.?????????????.#.###.#\n\
#.....#.?????????????.#.....#\n\
#######.?????????????.#######\n\
........?????????????........\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
?????????????????????????????\n\
????????????????????#####????\n\
........????????????#...#????\n\
#######.????????????#.#.#????\n\
#.....#.????????????#...#????\n\
#.###.#.????????????#####????\n\
#.###.#.?????????????????????\n\
#.###.#.?????????????????????\n\
#.....#.?????????????????????\n\
#######.?????????????????????"
);
}
#[test]
fn test_draw_alignment_patterns_7() {
let mut c = Canvas::new(Version::Normal(7), EcLevel::L);
c.draw_finder_patterns();
c.draw_alignment_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.?????????????????????????????.#######\n\
#.....#.?????????????????????????????.#.....#\n\
#.###.#.?????????????????????????????.#.###.#\n\
#.###.#.?????????????????????????????.#.###.#\n\
#.###.#.????????????#####????????????.#.###.#\n\
#.....#.????????????#...#????????????.#.....#\n\
#######.????????????#.#.#????????????.#######\n\
........????????????#...#????????????........\n\
????????????????????#####????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
????#####???????????#####???????????#####????\n\
????#...#???????????#...#???????????#...#????\n\
????#.#.#???????????#.#.#???????????#.#.#????\n\
????#...#???????????#...#???????????#...#????\n\
????#####???????????#####???????????#####????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
????????????????????#####???????????#####????\n\
........????????????#...#???????????#...#????\n\
#######.????????????#.#.#???????????#.#.#????\n\
#.....#.????????????#...#???????????#...#????\n\
#.###.#.????????????#####???????????#####????\n\
#.###.#.?????????????????????????????????????\n\
#.###.#.?????????????????????????????????????\n\
#.....#.?????????????????????????????????????\n\
#######.?????????????????????????????????????"
);
}
#[test]
fn generated_alignment_pattern_positions_match_known_versions() {
assert_eq!(alignment_pattern_positions(1), &[]);
assert_eq!(alignment_pattern_positions(2), &[6, 18]);
assert_eq!(alignment_pattern_positions(7), &[6, 22, 38]);
assert_eq!(alignment_pattern_positions(14), &[6, 26, 46, 66]);
assert_eq!(alignment_pattern_positions(32), &[6, 34, 60, 86, 112, 138]);
assert_eq!(alignment_pattern_positions(40), &[6, 30, 58, 86, 114, 142, 170]);
}
}
static ALIGNMENT_PATTERN_POSITIONS: [AlignmentPatternPositions; 40] = generate_alignment_pattern_positions();
const MAX_ALIGNMENT_PATTERNS: usize = 7;
#[derive(Clone, Copy)]
struct AlignmentPatternPositions {
positions: [i16; MAX_ALIGNMENT_PATTERNS],
len: usize,
}
impl AlignmentPatternPositions {
fn as_slice(&self) -> &[i16] {
&self.positions[..self.len]
}
}
fn alignment_pattern_positions(version: i16) -> &'static [i16] {
match version {
1..=40 => ALIGNMENT_PATTERN_POSITIONS[(version - 1) as usize].as_slice(),
_ => &[],
}
}
const fn generate_alignment_pattern_positions() -> [AlignmentPatternPositions; 40] {
let mut table = [AlignmentPatternPositions { positions: [0; MAX_ALIGNMENT_PATTERNS], len: 0 }; 40];
let mut version = 1;
while version <= 40 {
table[(version - 1) as usize] = compute_alignment_pattern_positions(version);
version += 1;
}
table
}
const fn compute_alignment_pattern_positions(version: i16) -> AlignmentPatternPositions {
let count = if version == 1 { 0 } else { version / 7 + 2 };
let mut result = AlignmentPatternPositions { positions: [0; MAX_ALIGNMENT_PATTERNS], len: count as usize };
if count == 0 {
return result;
}
let width = version * 4 + 17;
let step = alignment_pattern_step(version, count);
let mut index = count - 1;
let mut position = width - 7;
while index > 0 {
result.positions[index as usize] = position;
position -= step;
index -= 1;
}
result.positions[0] = 6;
result
}
const fn alignment_pattern_step(version: i16, count: i16) -> i16 {
if version == 32 { 26 } else { ((version * 4 + count * 2 + 1) / (count * 2 - 2)) * 2 }
}
impl Canvas {
fn draw_line(&mut self, x1: i16, y1: i16, x2: i16, y2: i16, color_even: Color, color_odd: Color) {
debug_assert!(x1 == x2 || y1 == y2);
if y1 == y2 {
for x in x1..=x2 {
self.put(x, y1, if x % 2 == 0 { color_even } else { color_odd });
}
} else {
for y in y1..=y2 {
self.put(x1, y, if y % 2 == 0 { color_even } else { color_odd });
}
}
}
fn draw_timing_patterns(&mut self) {
let width = self.width;
let (y, x1, x2) = match self.version {
Version::Micro(_) => (0, 8, width - 1),
Version::Normal(_) => (6, 8, width - 9),
};
self.draw_line(x1, y, x2, y, Color::Dark, Color::Light);
self.draw_line(y, x1, y, x2, Color::Dark, Color::Light);
}
}
#[cfg(test)]
mod timing_pattern_tests {
use crate::canvas::Canvas;
use crate::types::{EcLevel, Version};
#[test]
fn test_draw_timing_patterns_qr() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_timing_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
????????#.#.#????????\n\
?????????????????????\n\
??????#??????????????\n\
??????.??????????????\n\
??????#??????????????\n\
??????.??????????????\n\
??????#??????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????"
);
}
#[test]
fn test_draw_timing_patterns_micro_qr() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_timing_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
????????#.#\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
#??????????\n\
.??????????\n\
#??????????"
);
}
}
impl Canvas {
fn draw_number(&mut self, number: u32, bits: u32, on_color: Color, off_color: Color, coords: &[(i16, i16)]) {
let mut mask = 1 << (bits - 1);
for &(x, y) in coords {
let color = if (mask & number) == 0 { off_color } else { on_color };
self.put(x, y, color);
mask >>= 1;
}
}
fn draw_format_info_patterns_with_number(&mut self, format_info: u16) {
let format_info = u32::from(format_info);
match self.version {
Version::Micro(_) => {
self.draw_number(format_info, 15, Color::Dark, Color::Light, &FORMAT_INFO_COORDS_MICRO_QR);
}
Version::Normal(_) => {
self.draw_number(format_info, 15, Color::Dark, Color::Light, &FORMAT_INFO_COORDS_QR_MAIN);
self.draw_number(format_info, 15, Color::Dark, Color::Light, &FORMAT_INFO_COORDS_QR_SIDE);
self.put(8, -8, Color::Dark); }
}
}
fn draw_reserved_format_info_patterns(&mut self) {
self.draw_format_info_patterns_with_number(0);
}
fn draw_version_info_patterns(&mut self) {
match self.version {
Version::Micro(_) | Version::Normal(1..=6) => {}
Version::Normal(a) => {
let version_info = VERSION_INFOS[(a - 7).as_usize()];
self.draw_number(version_info, 18, Color::Dark, Color::Light, &VERSION_INFO_COORDS_BL);
self.draw_number(version_info, 18, Color::Dark, Color::Light, &VERSION_INFO_COORDS_TR);
}
}
}
}
#[cfg(test)]
mod draw_version_info_tests {
use crate::canvas::Canvas;
use crate::types::{Color, EcLevel, Version};
#[test]
fn test_draw_number() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_number(0b1010_1101, 8, Color::Dark, Color::Light, &[(0, 0), (0, -1), (-2, -2), (-2, 0)]);
assert_eq!(
&*c.to_debug_str(),
"\n\
#????????.?\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
???????????\n\
?????????#?\n\
.??????????"
);
}
#[test]
fn test_draw_version_info_1() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_version_info_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????"
);
}
#[test]
fn test_draw_version_info_7() {
let mut c = Canvas::new(Version::Normal(7), EcLevel::L);
c.draw_version_info_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
??????????????????????????????????..#????????\n\
??????????????????????????????????.#.????????\n\
??????????????????????????????????.#.????????\n\
??????????????????????????????????.##????????\n\
??????????????????????????????????###????????\n\
??????????????????????????????????...????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
....#.???????????????????????????????????????\n\
.####.???????????????????????????????????????\n\
#..##.???????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????\n\
?????????????????????????????????????????????"
);
}
#[test]
fn test_draw_reserved_format_info_patterns_qr() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_reserved_format_info_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
?????????????????????\n\
????????.????????????\n\
......?..????........\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
????????#????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????\n\
????????.????????????"
);
}
#[test]
fn test_draw_reserved_format_info_patterns_micro_qr() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_reserved_format_info_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
???????????\n\
????????.??\n\
????????.??\n\
????????.??\n\
????????.??\n\
????????.??\n\
????????.??\n\
????????.??\n\
?........??\n\
???????????\n\
???????????"
);
}
}
static VERSION_INFO_COORDS_BL: [(i16, i16); 18] = [
(5, -9),
(5, -10),
(5, -11),
(4, -9),
(4, -10),
(4, -11),
(3, -9),
(3, -10),
(3, -11),
(2, -9),
(2, -10),
(2, -11),
(1, -9),
(1, -10),
(1, -11),
(0, -9),
(0, -10),
(0, -11),
];
static VERSION_INFO_COORDS_TR: [(i16, i16); 18] = [
(-9, 5),
(-10, 5),
(-11, 5),
(-9, 4),
(-10, 4),
(-11, 4),
(-9, 3),
(-10, 3),
(-11, 3),
(-9, 2),
(-10, 2),
(-11, 2),
(-9, 1),
(-10, 1),
(-11, 1),
(-9, 0),
(-10, 0),
(-11, 0),
];
static FORMAT_INFO_COORDS_QR_MAIN: [(i16, i16); 15] = [
(0, 8),
(1, 8),
(2, 8),
(3, 8),
(4, 8),
(5, 8),
(7, 8),
(8, 8),
(8, 7),
(8, 5),
(8, 4),
(8, 3),
(8, 2),
(8, 1),
(8, 0),
];
static FORMAT_INFO_COORDS_QR_SIDE: [(i16, i16); 15] = [
(8, -1),
(8, -2),
(8, -3),
(8, -4),
(8, -5),
(8, -6),
(8, -7),
(-8, 8),
(-7, 8),
(-6, 8),
(-5, 8),
(-4, 8),
(-3, 8),
(-2, 8),
(-1, 8),
];
static FORMAT_INFO_COORDS_MICRO_QR: [(i16, i16); 15] = [
(1, 8),
(2, 8),
(3, 8),
(4, 8),
(5, 8),
(6, 8),
(7, 8),
(8, 8),
(8, 7),
(8, 6),
(8, 5),
(8, 4),
(8, 3),
(8, 2),
(8, 1),
];
static VERSION_INFOS: [u32; 34] = [
0x07c94, 0x085bc, 0x09a99, 0x0a4d3, 0x0bbf6, 0x0c762, 0x0d847, 0x0e60d, 0x0f928, 0x10b78, 0x1145d, 0x12a17,
0x13532, 0x149a6, 0x15683, 0x168c9, 0x177ec, 0x18ec4, 0x191e1, 0x1afab, 0x1b08e, 0x1cc1a, 0x1d33f, 0x1ed75,
0x1f250, 0x209d5, 0x216f0, 0x228ba, 0x2379f, 0x24b0b, 0x2542e, 0x26a64, 0x27541, 0x28c69,
];
impl Canvas {
pub fn draw_all_functional_patterns(&mut self) {
self.draw_finder_patterns();
self.draw_alignment_patterns();
self.draw_reserved_format_info_patterns();
self.draw_timing_patterns();
self.draw_version_info_patterns();
}
}
pub fn is_functional(version: Version, width: i16, x: i16, y: i16) -> bool {
debug_assert!(width == version.width());
let x = if x < 0 { x + width } else { x };
let y = if y < 0 { y + width } else { y };
match version {
Version::Micro(_) => x == 0 || y == 0 || (x < 9 && y < 9),
Version::Normal(a) => {
let non_alignment_test = x == 6 || y == 6 || (x < 9 && y < 9) || (x < 9 && y >= width - 8) || (x >= width - 8 && y < 9); match a {
_ if non_alignment_test => true,
1 => false,
2..=40 => {
let positions = alignment_pattern_positions(a);
let last = positions.len() - 1;
for (i, align_x) in positions.iter().enumerate() {
for (j, align_y) in positions.iter().enumerate() {
if i == 0 && (j == 0 || j == last) || (i == last && j == 0) {
continue;
}
if (*align_x - x).abs() <= 2 && (*align_y - y).abs() <= 2 {
return true;
}
}
}
false
}
_ => false,
}
}
}
}
#[cfg(test)]
mod all_functional_patterns_tests {
use crate::canvas::{Canvas, is_functional};
use crate::types::{EcLevel, Version};
#[test]
fn test_all_functional_patterns_qr() {
let mut c = Canvas::new(Version::Normal(2), EcLevel::L);
c.draw_all_functional_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######..????????.#######\n\
#.....#..????????.#.....#\n\
#.###.#..????????.#.###.#\n\
#.###.#..????????.#.###.#\n\
#.###.#..????????.#.###.#\n\
#.....#..????????.#.....#\n\
#######.#.#.#.#.#.#######\n\
.........????????........\n\
......#..????????........\n\
??????.??????????????????\n\
??????#??????????????????\n\
??????.??????????????????\n\
??????#??????????????????\n\
??????.??????????????????\n\
??????#??????????????????\n\
??????.??????????????????\n\
??????#?????????#####????\n\
........#???????#...#????\n\
#######..???????#.#.#????\n\
#.....#..???????#...#????\n\
#.###.#..???????#####????\n\
#.###.#..????????????????\n\
#.###.#..????????????????\n\
#.....#..????????????????\n\
#######..????????????????"
);
}
#[test]
fn test_all_functional_patterns_micro_qr() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_all_functional_patterns();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.#.#\n\
#.....#..??\n\
#.###.#..??\n\
#.###.#..??\n\
#.###.#..??\n\
#.....#..??\n\
#######..??\n\
.........??\n\
#........??\n\
.??????????\n\
#??????????"
);
}
#[test]
fn test_is_functional_qr_1() {
let version = Version::Normal(1);
assert!(is_functional(version, version.width(), 0, 0));
assert!(is_functional(version, version.width(), 10, 6));
assert!(!is_functional(version, version.width(), 10, 5));
assert!(!is_functional(version, version.width(), 14, 14));
assert!(is_functional(version, version.width(), 6, 11));
assert!(!is_functional(version, version.width(), 4, 11));
assert!(is_functional(version, version.width(), 4, 13));
assert!(is_functional(version, version.width(), 17, 7));
assert!(!is_functional(version, version.width(), 17, 17));
}
#[test]
fn test_is_functional_qr_3() {
let version = Version::Normal(3);
assert!(is_functional(version, version.width(), 0, 0));
assert!(!is_functional(version, version.width(), 25, 24));
assert!(is_functional(version, version.width(), 24, 24));
assert!(!is_functional(version, version.width(), 9, 25));
assert!(!is_functional(version, version.width(), 20, 0));
assert!(is_functional(version, version.width(), 21, 0));
}
#[test]
fn test_is_functional_qr_7() {
let version = Version::Normal(7);
assert!(is_functional(version, version.width(), 21, 4));
assert!(is_functional(version, version.width(), 7, 21));
assert!(is_functional(version, version.width(), 22, 22));
assert!(is_functional(version, version.width(), 8, 8));
assert!(!is_functional(version, version.width(), 19, 5));
assert!(!is_functional(version, version.width(), 36, 3));
assert!(!is_functional(version, version.width(), 4, 36));
assert!(is_functional(version, version.width(), 38, 38));
}
#[test]
fn test_is_functional_micro() {
let version = Version::Micro(1);
assert!(is_functional(version, version.width(), 8, 0));
assert!(is_functional(version, version.width(), 10, 0));
assert!(!is_functional(version, version.width(), 10, 1));
assert!(is_functional(version, version.width(), 8, 8));
assert!(is_functional(version, version.width(), 0, 9));
assert!(!is_functional(version, version.width(), 1, 9));
}
}
struct DataModuleIter {
x: i16,
y: i16,
width: i16,
timing_pattern_column: i16,
}
impl DataModuleIter {
fn new(version: Version) -> Self {
let width = version.width();
Self {
x: width - 1,
y: width - 1,
width,
timing_pattern_column: match version {
Version::Micro(_) => 0,
Version::Normal(_) => 6,
},
}
}
}
impl Iterator for DataModuleIter {
type Item = (i16, i16);
fn next(&mut self) -> Option<(i16, i16)> {
let adjusted_ref_col = if self.x <= self.timing_pattern_column { self.x + 1 } else { self.x };
if adjusted_ref_col <= 0 {
return None;
}
let res = (self.x, self.y);
let column_type = (self.width - adjusted_ref_col) % 4;
match column_type {
2 if self.y > 0 => {
self.y -= 1;
self.x += 1;
}
0 if self.y < self.width - 1 => {
self.y += 1;
self.x += 1;
}
0 | 2 if self.x == self.timing_pattern_column + 1 => {
self.x -= 2;
}
_ => {
self.x -= 1;
}
}
Some(res)
}
}
#[cfg(test)]
#[rustfmt::skip] mod data_iter_tests {
use crate::canvas::DataModuleIter;
use crate::types::Version;
#[test]
fn test_qr() {
let res = DataModuleIter::new(Version::Normal(1)).collect::<Vec<(i16, i16)>>();
assert_eq!(res, vec![
(20, 20), (19, 20), (20, 19), (19, 19), (20, 18), (19, 18),
(20, 17), (19, 17), (20, 16), (19, 16), (20, 15), (19, 15),
(20, 14), (19, 14), (20, 13), (19, 13), (20, 12), (19, 12),
(20, 11), (19, 11), (20, 10), (19, 10), (20, 9), (19, 9),
(20, 8), (19, 8), (20, 7), (19, 7), (20, 6), (19, 6),
(20, 5), (19, 5), (20, 4), (19, 4), (20, 3), (19, 3),
(20, 2), (19, 2), (20, 1), (19, 1), (20, 0), (19, 0),
(18, 0), (17, 0), (18, 1), (17, 1), (18, 2), (17, 2),
(18, 3), (17, 3), (18, 4), (17, 4), (18, 5), (17, 5),
(18, 6), (17, 6), (18, 7), (17, 7), (18, 8), (17, 8),
(18, 9), (17, 9), (18, 10), (17, 10), (18, 11), (17, 11),
(18, 12), (17, 12), (18, 13), (17, 13), (18, 14), (17, 14),
(18, 15), (17, 15), (18, 16), (17, 16), (18, 17), (17, 17),
(18, 18), (17, 18), (18, 19), (17, 19), (18, 20), (17, 20),
(16, 20), (15, 20), (16, 19), (15, 19), (16, 18), (15, 18),
(16, 17), (15, 17), (16, 16), (15, 16), (16, 15), (15, 15),
(16, 14), (15, 14), (16, 13), (15, 13), (16, 12), (15, 12),
(16, 11), (15, 11), (16, 10), (15, 10), (16, 9), (15, 9),
(16, 8), (15, 8), (16, 7), (15, 7), (16, 6), (15, 6),
(16, 5), (15, 5), (16, 4), (15, 4), (16, 3), (15, 3),
(16, 2), (15, 2), (16, 1), (15, 1), (16, 0), (15, 0),
(14, 0), (13, 0), (14, 1), (13, 1), (14, 2), (13, 2),
(14, 3), (13, 3), (14, 4), (13, 4), (14, 5), (13, 5),
(14, 6), (13, 6), (14, 7), (13, 7), (14, 8), (13, 8),
(14, 9), (13, 9), (14, 10), (13, 10), (14, 11), (13, 11),
(14, 12), (13, 12), (14, 13), (13, 13), (14, 14), (13, 14),
(14, 15), (13, 15), (14, 16), (13, 16), (14, 17), (13, 17),
(14, 18), (13, 18), (14, 19), (13, 19), (14, 20), (13, 20),
(12, 20), (11, 20), (12, 19), (11, 19), (12, 18), (11, 18),
(12, 17), (11, 17), (12, 16), (11, 16), (12, 15), (11, 15),
(12, 14), (11, 14), (12, 13), (11, 13), (12, 12), (11, 12),
(12, 11), (11, 11), (12, 10), (11, 10), (12, 9), (11, 9),
(12, 8), (11, 8), (12, 7), (11, 7), (12, 6), (11, 6),
(12, 5), (11, 5), (12, 4), (11, 4), (12, 3), (11, 3),
(12, 2), (11, 2), (12, 1), (11, 1), (12, 0), (11, 0),
(10, 0), (9, 0), (10, 1), (9, 1), (10, 2), (9, 2),
(10, 3), (9, 3), (10, 4), (9, 4), (10, 5), (9, 5),
(10, 6), (9, 6), (10, 7), (9, 7), (10, 8), (9, 8),
(10, 9), (9, 9), (10, 10), (9, 10), (10, 11), (9, 11),
(10, 12), (9, 12), (10, 13), (9, 13), (10, 14), (9, 14),
(10, 15), (9, 15), (10, 16), (9, 16), (10, 17), (9, 17),
(10, 18), (9, 18), (10, 19), (9, 19), (10, 20), (9, 20),
(8, 20), (7, 20), (8, 19), (7, 19), (8, 18), (7, 18),
(8, 17), (7, 17), (8, 16), (7, 16), (8, 15), (7, 15),
(8, 14), (7, 14), (8, 13), (7, 13), (8, 12), (7, 12),
(8, 11), (7, 11), (8, 10), (7, 10), (8, 9), (7, 9),
(8, 8), (7, 8), (8, 7), (7, 7), (8, 6), (7, 6),
(8, 5), (7, 5), (8, 4), (7, 4), (8, 3), (7, 3),
(8, 2), (7, 2), (8, 1), (7, 1), (8, 0), (7, 0),
(5, 0), (4, 0), (5, 1), (4, 1), (5, 2), (4, 2),
(5, 3), (4, 3), (5, 4), (4, 4), (5, 5), (4, 5),
(5, 6), (4, 6), (5, 7), (4, 7), (5, 8), (4, 8),
(5, 9), (4, 9), (5, 10), (4, 10), (5, 11), (4, 11),
(5, 12), (4, 12), (5, 13), (4, 13), (5, 14), (4, 14),
(5, 15), (4, 15), (5, 16), (4, 16), (5, 17), (4, 17),
(5, 18), (4, 18), (5, 19), (4, 19), (5, 20), (4, 20),
(3, 20), (2, 20), (3, 19), (2, 19), (3, 18), (2, 18),
(3, 17), (2, 17), (3, 16), (2, 16), (3, 15), (2, 15),
(3, 14), (2, 14), (3, 13), (2, 13), (3, 12), (2, 12),
(3, 11), (2, 11), (3, 10), (2, 10), (3, 9), (2, 9),
(3, 8), (2, 8), (3, 7), (2, 7), (3, 6), (2, 6),
(3, 5), (2, 5), (3, 4), (2, 4), (3, 3), (2, 3),
(3, 2), (2, 2), (3, 1), (2, 1), (3, 0), (2, 0),
(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2),
(1, 3), (0, 3), (1, 4), (0, 4), (1, 5), (0, 5),
(1, 6), (0, 6), (1, 7), (0, 7), (1, 8), (0, 8),
(1, 9), (0, 9), (1, 10), (0, 10), (1, 11), (0, 11),
(1, 12), (0, 12), (1, 13), (0, 13), (1, 14), (0, 14),
(1, 15), (0, 15), (1, 16), (0, 16), (1, 17), (0, 17),
(1, 18), (0, 18), (1, 19), (0, 19), (1, 20), (0, 20),
]);
}
#[test]
fn test_micro_qr() {
let res = DataModuleIter::new(Version::Micro(1)).collect::<Vec<(i16, i16)>>();
assert_eq!(res, vec![
(10, 10), (9, 10), (10, 9), (9, 9), (10, 8), (9, 8),
(10, 7), (9, 7), (10, 6), (9, 6), (10, 5), (9, 5),
(10, 4), (9, 4), (10, 3), (9, 3), (10, 2), (9, 2),
(10, 1), (9, 1), (10, 0), (9, 0),
(8, 0), (7, 0), (8, 1), (7, 1), (8, 2), (7, 2),
(8, 3), (7, 3), (8, 4), (7, 4), (8, 5), (7, 5),
(8, 6), (7, 6), (8, 7), (7, 7), (8, 8), (7, 8),
(8, 9), (7, 9), (8, 10), (7, 10),
(6, 10), (5, 10), (6, 9), (5, 9), (6, 8), (5, 8),
(6, 7), (5, 7), (6, 6), (5, 6), (6, 5), (5, 5),
(6, 4), (5, 4), (6, 3), (5, 3), (6, 2), (5, 2),
(6, 1), (5, 1), (6, 0), (5, 0),
(4, 0), (3, 0), (4, 1), (3, 1), (4, 2), (3, 2),
(4, 3), (3, 3), (4, 4), (3, 4), (4, 5), (3, 5),
(4, 6), (3, 6), (4, 7), (3, 7), (4, 8), (3, 8),
(4, 9), (3, 9), (4, 10), (3, 10),
(2, 10), (1, 10), (2, 9), (1, 9), (2, 8), (1, 8),
(2, 7), (1, 7), (2, 6), (1, 6), (2, 5), (1, 5),
(2, 4), (1, 4), (2, 3), (1, 3), (2, 2), (1, 2),
(2, 1), (1, 1), (2, 0), (1, 0),
]);
}
#[test]
fn test_micro_qr_2() {
let res = DataModuleIter::new(Version::Micro(2)).collect::<Vec<(i16, i16)>>();
assert_eq!(res, vec![
(12, 12), (11, 12), (12, 11), (11, 11), (12, 10), (11, 10),
(12, 9), (11, 9), (12, 8), (11, 8), (12, 7), (11, 7),
(12, 6), (11, 6), (12, 5), (11, 5), (12, 4), (11, 4),
(12, 3), (11, 3), (12, 2), (11, 2), (12, 1), (11, 1),
(12, 0), (11, 0),
(10, 0), (9, 0), (10, 1), (9, 1), (10, 2), (9, 2),
(10, 3), (9, 3), (10, 4), (9, 4), (10, 5), (9, 5),
(10, 6), (9, 6), (10, 7), (9, 7), (10, 8), (9, 8),
(10, 9), (9, 9), (10, 10), (9, 10), (10, 11), (9, 11),
(10, 12), (9, 12),
(8, 12), (7, 12), (8, 11), (7, 11), (8, 10), (7, 10),
(8, 9), (7, 9), (8, 8), (7, 8), (8, 7), (7, 7),
(8, 6), (7, 6), (8, 5), (7, 5), (8, 4), (7, 4),
(8, 3), (7, 3), (8, 2), (7, 2), (8, 1), (7, 1),
(8, 0), (7, 0),
(6, 0), (5, 0), (6, 1), (5, 1), (6, 2), (5, 2),
(6, 3), (5, 3), (6, 4), (5, 4), (6, 5), (5, 5),
(6, 6), (5, 6), (6, 7), (5, 7), (6, 8), (5, 8),
(6, 9), (5, 9), (6, 10), (5, 10), (6, 11), (5, 11),
(6, 12), (5, 12),
(4, 12), (3, 12), (4, 11), (3, 11), (4, 10), (3, 10),
(4, 9), (3, 9), (4, 8), (3, 8), (4, 7), (3, 7),
(4, 6), (3, 6), (4, 5), (3, 5), (4, 4), (3, 4),
(4, 3), (3, 3), (4, 2), (3, 2), (4, 1), (3, 1),
(4, 0), (3, 0),
(2, 0), (1, 0), (2, 1), (1, 1), (2, 2), (1, 2),
(2, 3), (1, 3), (2, 4), (1, 4), (2, 5), (1, 5),
(2, 6), (1, 6), (2, 7), (1, 7), (2, 8), (1, 8),
(2, 9), (1, 9), (2, 10), (1, 10), (2, 11), (1, 11),
(2, 12), (1, 12),
]);
}
}
impl Canvas {
fn draw_codewords<I>(&mut self, codewords: &[u8], is_half_codeword_at_end: bool, coords: &mut I)
where
I: Iterator<Item = (i16, i16)>,
{
let length = codewords.len();
let last_word = if is_half_codeword_at_end { length - 1 } else { length };
for (i, b) in codewords.iter().enumerate() {
let bits_end = if i == last_word { 4 } else { 0 };
'outside: for j in (bits_end..=7).rev() {
let color = if (*b & (1 << j)) == 0 { Color::Light } else { Color::Dark };
for (x, y) in coords.by_ref() {
let r = self.get_mut(x, y);
if *r == Module::Empty {
*r = Module::Unmasked(color);
continue 'outside;
}
}
return;
}
}
}
pub fn draw_data(&mut self, data: &[u8], ec: &[u8]) {
let is_half_codeword_at_end = matches!(
(self.version, self.ec_level),
(Version::Micro(1 | 3), EcLevel::L) | (Version::Micro(3), EcLevel::M)
);
let mut coords = DataModuleIter::new(self.version);
self.draw_codewords(data, is_half_codeword_at_end, &mut coords);
self.draw_codewords(ec, false, &mut coords);
}
}
#[cfg(test)]
mod draw_codewords_test {
use crate::canvas::Canvas;
use crate::types::{EcLevel, Version};
#[test]
fn test_micro_qr_1() {
let mut c = Canvas::new(Version::Micro(1), EcLevel::L);
c.draw_all_functional_patterns();
c.draw_data(b"\x6e\x5d\xe2", b"\x2b\x63");
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.#.#\n\
#.....#..-*\n\
#.###.#..**\n\
#.###.#..*-\n\
#.###.#..**\n\
#.....#..*-\n\
#######..*-\n\
.........-*\n\
#........**\n\
.***-**---*\n\
#---*-*-**-"
);
}
#[test]
fn test_qr_2() {
let mut c = Canvas::new(Version::Normal(2), EcLevel::L);
c.draw_all_functional_patterns();
c.draw_data(
b"\x92I$\x92I$\x92I$\x92I$\x92I$\x92I$\x92I$\x92I$\
\x92I$\x92I$\x92I$\x92I$\x92I$\x92I$\x92I$",
b"",
);
assert_eq!(
&*c.to_debug_str(),
"\n\
#######..--*---*-.#######\n\
#.....#..-*-*-*-*.#.....#\n\
#.###.#..*---*---.#.###.#\n\
#.###.#..--*---*-.#.###.#\n\
#.###.#..-*-*-*-*.#.###.#\n\
#.....#..*---*---.#.....#\n\
#######.#.#.#.#.#.#######\n\
.........--*---*-........\n\
......#..-*-*-*-*........\n\
--*-*-.-**---*---*--**--*\n\
-*-*--#----*---*---------\n\
*----*.*--*-*-*-*-**--**-\n\
--*-*-#-**---*---*--**--*\n\
-*-*--.----*---*---------\n\
*----*#*--*-*-*-*-**--**-\n\
--*-*-.-**---*---*--**--*\n\
-*-*--#----*---*#####----\n\
........#-*-*-*-#...#-**-\n\
#######..*---*--#.#.#*--*\n\
#.....#..--*---*#...#----\n\
#.###.#..-*-*-*-#####-**-\n\
#.###.#..*---*--*----*--*\n\
#.###.#..--*------**-----\n\
#.....#..-*-*-**-*--*-**-\n\
#######..*---*--*----*--*"
);
}
}
#[derive(Debug, Copy, Clone)]
pub enum MaskPattern {
Checkerboard = 0b000,
HorizontalLines = 0b001,
VerticalLines = 0b010,
DiagonalLines = 0b011,
LargeCheckerboard = 0b100,
Fields = 0b101,
Diamonds = 0b110,
Meadow = 0b111,
}
mod mask_functions {
pub fn checkerboard(x: i16, y: i16) -> bool {
(x + y) % 2 == 0
}
pub fn horizontal_lines(_: i16, y: i16) -> bool {
y % 2 == 0
}
pub fn vertical_lines(x: i16, _: i16) -> bool {
x % 3 == 0
}
pub fn diagonal_lines(x: i16, y: i16) -> bool {
(x + y) % 3 == 0
}
pub fn large_checkerboard(x: i16, y: i16) -> bool {
((y / 2) + (x / 3)) % 2 == 0
}
pub fn fields(x: i16, y: i16) -> bool {
(x * y) % 2 + (x * y) % 3 == 0
}
pub fn diamonds(x: i16, y: i16) -> bool {
((x * y) % 2 + (x * y) % 3) % 2 == 0
}
pub fn meadow(x: i16, y: i16) -> bool {
((x + y) % 2 + (x * y) % 3) % 2 == 0
}
}
fn get_mask_function(pattern: MaskPattern) -> fn(i16, i16) -> bool {
match pattern {
MaskPattern::Checkerboard => mask_functions::checkerboard,
MaskPattern::HorizontalLines => mask_functions::horizontal_lines,
MaskPattern::VerticalLines => mask_functions::vertical_lines,
MaskPattern::DiagonalLines => mask_functions::diagonal_lines,
MaskPattern::LargeCheckerboard => mask_functions::large_checkerboard,
MaskPattern::Fields => mask_functions::fields,
MaskPattern::Diamonds => mask_functions::diamonds,
MaskPattern::Meadow => mask_functions::meadow,
}
}
impl Canvas {
pub fn apply_mask(&mut self, pattern: MaskPattern) {
let mask_fn = get_mask_function(pattern);
for x in 0..self.width {
for y in 0..self.width {
let module = self.get_mut(x, y);
*module = module.mask(mask_fn(x, y));
}
}
self.draw_format_info_patterns(pattern);
}
fn draw_format_info_patterns(&mut self, pattern: MaskPattern) {
let format_number = match self.version {
Version::Normal(_) => {
let simple_format_number = ((self.ec_level as usize) ^ 1) << 3 | (pattern as usize);
FORMAT_INFOS_QR[simple_format_number]
}
Version::Micro(a) => {
let micro_pattern_number = match pattern {
MaskPattern::HorizontalLines => 0b00,
MaskPattern::LargeCheckerboard => 0b01,
MaskPattern::Diamonds => 0b10,
MaskPattern::Meadow => 0b11,
_ => panic!("Unsupported mask pattern in Micro QR code"),
};
let symbol_number = match (a, self.ec_level) {
(1, EcLevel::L) => 0b000,
(2, EcLevel::L) => 0b001,
(2, EcLevel::M) => 0b010,
(3, EcLevel::L) => 0b011,
(3, EcLevel::M) => 0b100,
(4, EcLevel::L) => 0b101,
(4, EcLevel::M) => 0b110,
(4, EcLevel::Q) => 0b111,
_ => panic!("Unsupported version/ec_level combination in Micro QR code"),
};
let simple_format_number = symbol_number << 2 | micro_pattern_number;
FORMAT_INFOS_MICRO_QR[simple_format_number]
}
};
self.draw_format_info_patterns_with_number(format_number);
}
}
#[cfg(test)]
mod mask_tests {
use crate::canvas::{Canvas, FORMAT_INFOS_MICRO_QR, FORMAT_INFOS_QR, MaskPattern};
use crate::types::{EcLevel, Version};
#[test]
fn test_apply_mask_qr() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_all_functional_patterns();
c.apply_mask(MaskPattern::Checkerboard);
assert_eq!(
&*c.to_debug_str(),
"\n\
#######...#.#.#######\n\
#.....#..#.#..#.....#\n\
#.###.#.#.#.#.#.###.#\n\
#.###.#..#.#..#.###.#\n\
#.###.#...#.#.#.###.#\n\
#.....#..#.#..#.....#\n\
#######.#.#.#.#######\n\
........##.#.........\n\
###.#####.#.###...#..\n\
.#.#.#.#.#.#.#.#.#.#.\n\
#.#.#.#.#.#.#.#.#.#.#\n\
.#.#.#.#.#.#.#.#.#.#.\n\
#.#.#.#.#.#.#.#.#.#.#\n\
........##.#.#.#.#.#.\n\
#######.#.#.#.#.#.#.#\n\
#.....#.##.#.#.#.#.#.\n\
#.###.#.#.#.#.#.#.#.#\n\
#.###.#..#.#.#.#.#.#.\n\
#.###.#.#.#.#.#.#.#.#\n\
#.....#.##.#.#.#.#.#.\n\
#######.#.#.#.#.#.#.#"
);
}
#[test]
fn test_draw_format_info_patterns_qr() {
let mut c = Canvas::new(Version::Normal(1), EcLevel::L);
c.draw_format_info_patterns(MaskPattern::LargeCheckerboard);
assert_eq!(
&*c.to_debug_str(),
"\n\
????????#????????????\n\
????????#????????????\n\
????????#????????????\n\
????????#????????????\n\
????????.????????????\n\
????????#????????????\n\
?????????????????????\n\
????????.????????????\n\
##..##?..????..#.####\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
?????????????????????\n\
????????#????????????\n\
????????.????????????\n\
????????#????????????\n\
????????#????????????\n\
????????.????????????\n\
????????.????????????\n\
????????#????????????\n\
????????#????????????"
);
}
#[test]
fn test_draw_format_info_patterns_micro_qr() {
let mut c = Canvas::new(Version::Micro(2), EcLevel::L);
c.draw_format_info_patterns(MaskPattern::LargeCheckerboard);
assert_eq!(
&*c.to_debug_str(),
"\n\
?????????????\n\
????????#????\n\
????????.????\n\
????????.????\n\
????????#????\n\
????????#????\n\
????????.????\n\
????????.????\n\
?#.#....#????\n\
?????????????\n\
?????????????\n\
?????????????\n\
?????????????"
);
}
#[test]
fn generated_format_info_tables_match_known_values() {
assert_eq!(FORMAT_INFOS_QR[0], 0x5412);
assert_eq!(FORMAT_INFOS_QR[31], 0x2bed);
assert_eq!(FORMAT_INFOS_MICRO_QR[0], 0x4445);
assert_eq!(FORMAT_INFOS_MICRO_QR[31], 0x3bba);
}
}
const FORMAT_INFOS_QR: [u16; 32] = generate_format_infos(0x5412);
const FORMAT_INFOS_MICRO_QR: [u16; 32] = generate_format_infos(0x4445);
const FORMAT_INFO_GENERATOR: u16 = 0x537;
const fn generate_format_infos(mask: u16) -> [u16; 32] {
let mut table = [0; 32];
let mut data = 0;
while data < table.len() {
table[data] = format_info(data as u16, mask);
data += 1;
}
table
}
const fn format_info(data: u16, mask: u16) -> u16 {
let mut remainder = data << 10;
let mut bit = 14;
while bit >= 10 {
if remainder & (1 << bit) != 0 {
remainder ^= FORMAT_INFO_GENERATOR << (bit - 10);
}
if bit == 10 {
break;
}
bit -= 1;
}
((data << 10) | remainder) ^ mask
}
impl Canvas {
#[cfg(test)]
fn compute_adjacent_penalty_score(&self, is_horizontal: bool) -> u16 {
compute_adjacent_penalty_score(self.width.as_usize(), &module_bytes(&self.modules), is_horizontal)
}
#[cfg(test)]
fn compute_block_penalty_score(&self) -> u16 {
compute_block_penalty_score(self.width.as_usize(), &module_bytes(&self.modules))
}
#[cfg(test)]
fn compute_finder_penalty_score(&self, is_horizontal: bool) -> u16 {
compute_finder_penalty_score(self.width.as_usize(), &module_bytes(&self.modules), is_horizontal)
}
#[cfg(test)]
fn compute_balance_penalty_score(&self) -> u16 {
compute_balance_penalty_score(&module_bytes(&self.modules))
}
#[cfg(test)]
fn compute_light_side_penalty_score(&self) -> u16 {
compute_light_side_penalty_score(self.width.as_usize(), &module_bytes(&self.modules))
}
#[cfg(test)]
fn compute_total_penalty_scores(&self) -> u16 {
compute_total_penalty_score_scalar(self.version, self.width, &self.modules)
}
fn compute_total_penalty_scores_with_scratch(&self, scratch: &mut Vec<u8>) -> u16 {
debug_assert_eq!((self.width * self.width).as_usize(), self.modules.len());
write_module_bytes(&self.modules, scratch);
compute_total_penalty_score_from_bytes(self.version, self.width.as_usize(), scratch)
}
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
pub fn score_mask_for_bench(&self, scratch: &mut Vec<u8>) -> u16 {
self.compute_total_penalty_scores_with_scratch(scratch)
}
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
pub fn score_mask_scalar_for_bench(&self, scratch: &mut Vec<u8>) -> u16 {
debug_assert_eq!((self.width * self.width).as_usize(), self.modules.len());
write_module_bytes(&self.modules, scratch);
compute_total_penalty_score_from_bytes_scalar(self.version, self.width.as_usize(), scratch)
}
}
#[cfg(test)]
fn module_bytes(modules: &[Module]) -> Vec<u8> {
modules.iter().map(|module| u8::from(module.is_dark())).collect()
}
fn write_module_bytes(modules: &[Module], output: &mut Vec<u8>) {
output.clear();
output.extend(modules.iter().map(|module| u8::from(module.is_dark())));
}
fn count_dark_modules(modules: &[u8]) -> usize {
#[cfg(target_arch = "aarch64")]
{
unsafe { count_dark_modules_neon(modules) }
}
#[cfg(target_arch = "x86_64")]
{
if avx2_available() {
return unsafe { count_dark_modules_avx2(modules) };
}
if sse2_available() {
return unsafe { count_dark_modules_sse2(modules) };
}
count_dark_modules_scalar(modules)
}
#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
{
count_dark_modules_scalar(modules)
}
}
fn count_dark_modules_scalar(modules: &[u8]) -> usize {
modules.iter().filter(|&&module| module != 0).count()
}
fn compute_balance_penalty_score(modules: &[u8]) -> u16 {
let dark_modules = count_dark_modules(modules);
let total_modules = modules.len();
let ratio = dark_modules * 200 / total_modules;
ratio.abs_diff(100).as_u16()
}
#[cfg(any(test, feature = "bench-internals"))]
fn compute_balance_penalty_score_scalar(modules: &[u8]) -> u16 {
let dark_modules = count_dark_modules_scalar(modules);
let total_modules = modules.len();
let ratio = dark_modules * 200 / total_modules;
ratio.abs_diff(100).as_u16()
}
fn compute_light_side_penalty_score(width: usize, modules: &[u8]) -> u16 {
let bottom_row = &modules[(width - 1) * width..][..width];
let h = (1..width).filter(|&x| bottom_row[x] == 0).count();
let v = (1..width).filter(|&y| modules[y * width + width - 1] == 0).count();
(h + v + 15 * max(h, v)).as_u16()
}
fn compute_adjacent_penalty_score(width: usize, modules: &[u8], is_horizontal: bool) -> u16 {
if is_horizontal {
compute_horizontal_adjacent_penalty_score(width, modules)
} else {
compute_vertical_adjacent_penalty_score(width, modules)
}
}
fn compute_horizontal_adjacent_penalty_score(width: usize, modules: &[u8]) -> u16 {
modules.chunks_exact(width).map(compute_line_adjacent_penalty_score).sum()
}
fn compute_vertical_adjacent_penalty_score(width: usize, modules: &[u8]) -> u16 {
let mut total_score = 0;
for x in 0..width {
let mut last_color = 2;
let mut consecutive_len = 1_u16;
for y in 0..width {
let color = modules[y * width + x];
if color == last_color {
consecutive_len += 1;
} else {
last_color = color;
if consecutive_len >= 5 {
total_score += consecutive_len - 2;
}
consecutive_len = 1;
}
}
total_score += adjacent_run_score(consecutive_len);
}
total_score
}
fn compute_line_adjacent_penalty_score(line: &[u8]) -> u16 {
let mut total_score = 0;
let mut last_color = 2;
let mut consecutive_len = 1_u16;
for &color in line {
if color == last_color {
consecutive_len += 1;
} else {
last_color = color;
if consecutive_len >= 5 {
total_score += consecutive_len - 2;
}
consecutive_len = 1;
}
}
total_score + adjacent_run_score(consecutive_len)
}
fn adjacent_run_score(consecutive_len: u16) -> u16 {
if consecutive_len >= 5 { consecutive_len - 2 } else { 0 }
}
const FINDER_LIKE_PATTERN_BITS: u8 = 0b1011101;
const FINDER_LIKE_PATTERN_WIDTH: usize = 7;
const FINDER_LIKE_PATTERN_MASK: u8 = (1 << FINDER_LIKE_PATTERN_WIDTH) - 1;
fn compute_finder_penalty_score(width: usize, modules: &[u8], is_horizontal: bool) -> u16 {
let total_score = if is_horizontal {
compute_horizontal_finder_penalty_score(width, modules)
} else {
compute_vertical_finder_penalty_score(width, modules)
};
total_score - 360
}
fn compute_horizontal_finder_penalty_score(width: usize, modules: &[u8]) -> u16 {
modules.chunks_exact(width).map(compute_line_finder_penalty_score).sum()
}
fn compute_vertical_finder_penalty_score(width: usize, modules: &[u8]) -> u16 {
let mut total_score = 0;
for x in 0..width {
let mut window = initial_vertical_finder_window(width, modules, x);
for y in 0..width.saturating_sub(FINDER_LIKE_PATTERN_WIDTH - 1) {
if y > 0 {
window = roll_finder_window(window, modules[(y + FINDER_LIKE_PATTERN_WIDTH - 1) * width + x]);
}
if window != FINDER_LIKE_PATTERN_BITS {
continue;
}
if !vertical_range_has_dark(width, modules, x, y.saturating_sub(4), y)
|| !vertical_range_has_dark(
width,
modules,
x,
y + FINDER_LIKE_PATTERN_WIDTH,
min(y + FINDER_LIKE_PATTERN_WIDTH + 4, width),
)
{
total_score += 40;
}
}
}
total_score
}
fn compute_line_finder_penalty_score(line: &[u8]) -> u16 {
let mut total_score = 0;
let mut window = initial_finder_window(line);
for offset in 0..line.len().saturating_sub(FINDER_LIKE_PATTERN_WIDTH - 1) {
if offset > 0 {
window = roll_finder_window(window, line[offset + FINDER_LIKE_PATTERN_WIDTH - 1]);
}
if window != FINDER_LIKE_PATTERN_BITS {
continue;
}
if !line_range_has_dark(line, offset.saturating_sub(4), offset)
|| !line_range_has_dark(
line,
offset + FINDER_LIKE_PATTERN_WIDTH,
min(offset + FINDER_LIKE_PATTERN_WIDTH + 4, line.len()),
)
{
total_score += 40;
}
}
total_score
}
fn initial_finder_window(line: &[u8]) -> u8 {
line.iter().take(FINDER_LIKE_PATTERN_WIDTH).fold(0, |window, &module| roll_finder_window(window, module))
}
fn initial_vertical_finder_window(width: usize, modules: &[u8], x: usize) -> u8 {
(0..min(FINDER_LIKE_PATTERN_WIDTH, width)).fold(0, |window, y| roll_finder_window(window, modules[y * width + x]))
}
fn roll_finder_window(window: u8, module: u8) -> u8 {
((window << 1) | (module & 1)) & FINDER_LIKE_PATTERN_MASK
}
fn vertical_range_has_dark(width: usize, modules: &[u8], x: usize, start: usize, end: usize) -> bool {
(start..end).any(|y| modules[y * width + x] != 0)
}
fn line_range_has_dark(line: &[u8], start: usize, end: usize) -> bool {
line[start..end].iter().any(|&module| module != 0)
}
fn compute_block_penalty_score(width: usize, modules: &[u8]) -> u16 {
#[cfg(target_arch = "aarch64")]
{
unsafe { compute_block_penalty_score_neon(width, modules) }
}
#[cfg(target_arch = "x86_64")]
{
if avx2_available() {
return unsafe { compute_block_penalty_score_avx2(width, modules) };
}
if sse2_available() {
return unsafe { compute_block_penalty_score_sse2(width, modules) };
}
compute_block_penalty_score_scalar(width, modules)
}
#[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]
{
compute_block_penalty_score_scalar(width, modules)
}
}
#[cfg(any(
test,
feature = "bench-internals",
target_arch = "x86_64",
not(any(target_arch = "aarch64", target_arch = "x86_64"))
))]
fn compute_block_penalty_score_scalar(width: usize, modules: &[u8]) -> u16 {
let mut total_score = 0;
for y in 0..width.saturating_sub(1) {
let row = &modules[y * width..][..width];
let next_row = &modules[(y + 1) * width..][..width];
for x in 0..width.saturating_sub(1) {
let this = row[x];
if this == row[x + 1] && this == next_row[x] && this == next_row[x + 1] {
total_score += 3;
}
}
}
total_score
}
#[cfg(all(target_arch = "x86_64", feature = "std"))]
fn sse2_available() -> bool {
std::is_x86_feature_detected!("sse2")
}
#[cfg(all(target_arch = "x86_64", not(feature = "std")))]
fn sse2_available() -> bool {
true
}
#[cfg(all(target_arch = "x86_64", feature = "std"))]
fn avx2_available() -> bool {
std::is_x86_feature_detected!("avx2")
}
#[cfg(all(target_arch = "x86_64", not(feature = "std")))]
fn avx2_available() -> bool {
false
}
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn count_dark_modules_neon(modules: &[u8]) -> usize {
use core::arch::aarch64::{vaddvq_u8, vceqq_u8, vcntq_u8, vdupq_n_u8, vld1q_u8, vmvnq_u8};
let mut count = 0;
let mut offset = 0;
let zero = vdupq_n_u8(0);
while offset + 16 <= modules.len() {
let chunk = unsafe { vld1q_u8(modules.as_ptr().wrapping_add(offset)) };
let nonzero_lanes = vmvnq_u8(vceqq_u8(chunk, zero));
count += (vaddvq_u8(vcntq_u8(nonzero_lanes)) / 8) as usize;
offset += 16;
}
count + count_dark_modules_scalar(&modules[offset..])
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn count_dark_modules_avx2(modules: &[u8]) -> usize {
use core::arch::x86_64::{
__m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8, _mm256_setzero_si256,
};
let mut count = 0;
let mut offset = 0;
let zero = _mm256_setzero_si256();
while offset + 32 <= modules.len() {
let ptr = modules.as_ptr().wrapping_add(offset).cast::<__m256i>();
let chunk = unsafe { _mm256_loadu_si256(ptr) };
let zero_lanes = _mm256_movemask_epi8(_mm256_cmpeq_epi8(chunk, zero)) as u32;
count += 32 - zero_lanes.count_ones() as usize;
offset += 32;
}
count + count_dark_modules_sse2_remainder(&modules[offset..])
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
unsafe fn count_dark_modules_sse2(modules: &[u8]) -> usize {
count_dark_modules_sse2_remainder(modules)
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
fn count_dark_modules_sse2_remainder(modules: &[u8]) -> usize {
use core::arch::x86_64::{__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8, _mm_setzero_si128};
let mut count = 0;
let mut offset = 0;
let zero = _mm_setzero_si128();
while offset + 16 <= modules.len() {
let ptr = modules.as_ptr().wrapping_add(offset).cast::<__m128i>();
let chunk = unsafe { _mm_loadu_si128(ptr) };
let zero_lanes = _mm_movemask_epi8(_mm_cmpeq_epi8(chunk, zero)) as u32;
count += 16 - zero_lanes.count_ones() as usize;
offset += 16;
}
count + count_dark_modules_scalar(&modules[offset..])
}
#[cfg(target_arch = "aarch64")]
#[target_feature(enable = "neon")]
unsafe fn compute_block_penalty_score_neon(width: usize, modules: &[u8]) -> u16 {
use core::arch::aarch64::{vaddvq_u8, vandq_u8, vceqq_u8, vcntq_u8, vld1q_u8};
let mut total_score = 0;
for y in 0..width.saturating_sub(1) {
let row = &modules[y * width..][..width];
let next_row = &modules[(y + 1) * width..][..width];
let mut x = 0;
while x + 16 < width {
let row_chunk = unsafe { vld1q_u8(row.as_ptr().wrapping_add(x)) };
let row_right_chunk = unsafe { vld1q_u8(row.as_ptr().wrapping_add(x + 1)) };
let next_chunk = unsafe { vld1q_u8(next_row.as_ptr().wrapping_add(x)) };
let next_right_chunk = unsafe { vld1q_u8(next_row.as_ptr().wrapping_add(x + 1)) };
let horizontal = vceqq_u8(row_chunk, row_right_chunk);
let vertical = vceqq_u8(row_chunk, next_chunk);
let diagonal = vceqq_u8(row_chunk, next_right_chunk);
let blocks = vandq_u8(vandq_u8(horizontal, vertical), diagonal);
total_score += (vaddvq_u8(vcntq_u8(blocks)) / 8) as u16 * 3;
x += 16;
}
total_score += compute_block_penalty_score_scalar_tail(row, next_row, x);
}
total_score
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn compute_block_penalty_score_avx2(width: usize, modules: &[u8]) -> u16 {
use core::arch::x86_64::{__m256i, _mm256_and_si256, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8};
let mut total_score = 0;
for y in 0..width.saturating_sub(1) {
let row = &modules[y * width..][..width];
let next_row = &modules[(y + 1) * width..][..width];
let mut x = 0;
while x + 32 < width {
let row_ptr = row.as_ptr().wrapping_add(x).cast::<__m256i>();
let row_right_ptr = row.as_ptr().wrapping_add(x + 1).cast::<__m256i>();
let next_ptr = next_row.as_ptr().wrapping_add(x).cast::<__m256i>();
let next_right_ptr = next_row.as_ptr().wrapping_add(x + 1).cast::<__m256i>();
let row_chunk = unsafe { _mm256_loadu_si256(row_ptr) };
let row_right_chunk = unsafe { _mm256_loadu_si256(row_right_ptr) };
let next_chunk = unsafe { _mm256_loadu_si256(next_ptr) };
let next_right_chunk = unsafe { _mm256_loadu_si256(next_right_ptr) };
let horizontal = _mm256_cmpeq_epi8(row_chunk, row_right_chunk);
let vertical = _mm256_cmpeq_epi8(row_chunk, next_chunk);
let diagonal = _mm256_cmpeq_epi8(row_chunk, next_right_chunk);
let blocks = _mm256_and_si256(_mm256_and_si256(horizontal, vertical), diagonal);
total_score += (_mm256_movemask_epi8(blocks) as u32).count_ones() as u16 * 3;
x += 32;
}
total_score += compute_block_penalty_score_scalar_tail(row, next_row, x);
}
total_score
}
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "sse2")]
unsafe fn compute_block_penalty_score_sse2(width: usize, modules: &[u8]) -> u16 {
use core::arch::x86_64::{__m128i, _mm_and_si128, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8};
let mut total_score = 0;
for y in 0..width.saturating_sub(1) {
let row = &modules[y * width..][..width];
let next_row = &modules[(y + 1) * width..][..width];
let mut x = 0;
while x + 16 < width {
let row_ptr = row.as_ptr().wrapping_add(x).cast::<__m128i>();
let row_right_ptr = row.as_ptr().wrapping_add(x + 1).cast::<__m128i>();
let next_ptr = next_row.as_ptr().wrapping_add(x).cast::<__m128i>();
let next_right_ptr = next_row.as_ptr().wrapping_add(x + 1).cast::<__m128i>();
let row_chunk = unsafe { _mm_loadu_si128(row_ptr) };
let row_right_chunk = unsafe { _mm_loadu_si128(row_right_ptr) };
let next_chunk = unsafe { _mm_loadu_si128(next_ptr) };
let next_right_chunk = unsafe { _mm_loadu_si128(next_right_ptr) };
let horizontal = _mm_cmpeq_epi8(row_chunk, row_right_chunk);
let vertical = _mm_cmpeq_epi8(row_chunk, next_chunk);
let diagonal = _mm_cmpeq_epi8(row_chunk, next_right_chunk);
let blocks = _mm_and_si128(_mm_and_si128(horizontal, vertical), diagonal);
total_score += (_mm_movemask_epi8(blocks) as u32).count_ones() as u16 * 3;
x += 16;
}
total_score += compute_block_penalty_score_scalar_tail(row, next_row, x);
}
total_score
}
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
fn compute_block_penalty_score_scalar_tail(row: &[u8], next_row: &[u8], start: usize) -> u16 {
let mut total_score = 0;
let mut x = start;
while x + 1 < row.len() {
let this = row[x];
if this == row[x + 1] && this == next_row[x] && this == next_row[x + 1] {
total_score += 3;
}
x += 1;
}
total_score
}
fn compute_total_penalty_score_from_bytes(version: Version, width: usize, modules: &[u8]) -> u16 {
match version {
Version::Normal(_) => {
let s1_a = compute_adjacent_penalty_score(width, modules, true);
let s1_b = compute_adjacent_penalty_score(width, modules, false);
let s2 = compute_block_penalty_score(width, modules);
let s3_a = compute_finder_penalty_score(width, modules, true);
let s3_b = compute_finder_penalty_score(width, modules, false);
let s4 = compute_balance_penalty_score(modules);
s1_a + s1_b + s2 + s3_a + s3_b + s4
}
Version::Micro(_) => compute_light_side_penalty_score(width, modules),
}
}
#[cfg(any(test, feature = "bench-internals"))]
fn compute_total_penalty_score_from_bytes_scalar(version: Version, width: usize, modules: &[u8]) -> u16 {
match version {
Version::Normal(_) => {
let s1_a = compute_adjacent_penalty_score(width, modules, true);
let s1_b = compute_adjacent_penalty_score(width, modules, false);
let s2 = compute_block_penalty_score_scalar(width, modules);
let s3_a = compute_finder_penalty_score(width, modules, true);
let s3_b = compute_finder_penalty_score(width, modules, false);
let s4 = compute_balance_penalty_score_scalar(modules);
s1_a + s1_b + s2 + s3_a + s3_b + s4
}
Version::Micro(_) => compute_light_side_penalty_score(width, modules),
}
}
#[cfg(test)]
fn compute_total_penalty_score_scalar(version: Version, width: i16, modules: &[Module]) -> u16 {
debug_assert_eq!((width * width).as_usize(), modules.len());
let modules = modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
compute_total_penalty_score_from_bytes_scalar(version, width.as_usize(), &modules)
}
#[cfg(test)]
mod penalty_tests {
use crate::canvas::{
Canvas, MaskPattern, compute_adjacent_penalty_score, compute_balance_penalty_score,
compute_block_penalty_score, compute_block_penalty_score_scalar, compute_finder_penalty_score,
compute_light_side_penalty_score, compute_total_penalty_score_from_bytes,
compute_total_penalty_score_from_bytes_scalar, compute_total_penalty_score_scalar, count_dark_modules,
count_dark_modules_scalar,
};
use crate::cast::As;
use crate::types::{Color, EcLevel, Version};
fn create_test_canvas() -> Canvas {
let mut c = Canvas::new(Version::Normal(1), EcLevel::Q);
c.draw_all_functional_patterns();
c.draw_data(
b"\x20\x5b\x0b\x78\xd1\x72\xdc\x4d\x43\x40\xec\x11\x00",
b"\xa8\x48\x16\x52\xd9\x36\x9c\x00\x2e\x0f\xb4\x7a\x10",
);
c.apply_mask(MaskPattern::Checkerboard);
c
}
#[test]
fn check_penalty_canvas() {
let c = create_test_canvas();
assert_eq!(
&*c.to_debug_str(),
"\n\
#######.##....#######\n\
#.....#.#..#..#.....#\n\
#.###.#.#..##.#.###.#\n\
#.###.#.#.....#.###.#\n\
#.###.#.#.#...#.###.#\n\
#.....#...#...#.....#\n\
#######.#.#.#.#######\n\
........#............\n\
.##.#.##....#.#.#####\n\
.#......####....#...#\n\
..##.###.##...#.##...\n\
.##.##.#..##.#.#.###.\n\
#...#.#.#.###.###.#.#\n\
........##.#..#...#.#\n\
#######.#.#....#.##..\n\
#.....#..#.##.##.#...\n\
#.###.#.#.#...#######\n\
#.###.#..#.#.#.#...#.\n\
#.###.#.#...####.#..#\n\
#.....#.#.##.#...#.##\n\
#######.....####....#"
);
}
#[test]
fn test_penalty_score_adjacent() {
let c = create_test_canvas();
assert_eq!(c.compute_adjacent_penalty_score(true), 88);
assert_eq!(c.compute_adjacent_penalty_score(false), 92);
}
#[test]
fn adjacent_penalty_score_matches_canvas_wrapper() {
let c = create_test_canvas();
let modules = c.modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
assert_eq!(
compute_adjacent_penalty_score(c.width.as_usize(), &modules, true),
c.compute_adjacent_penalty_score(true)
);
assert_eq!(
compute_adjacent_penalty_score(c.width.as_usize(), &modules, false),
c.compute_adjacent_penalty_score(false)
);
}
#[test]
fn test_penalty_score_block() {
let c = create_test_canvas();
assert_eq!(c.compute_block_penalty_score(), 90);
}
#[test]
fn block_penalty_score_matches_scalar_for_varied_widths() {
for width in [1_usize, 2, 7, 21, 45] {
let modules = (0..width * width).map(|i| u8::from((i + i / width) % 5 < 2)).collect::<Vec<_>>();
assert_eq!(
compute_block_penalty_score(width, &modules),
compute_block_penalty_score_scalar(width, &modules)
);
}
}
#[test]
fn test_penalty_score_finder() {
let c = create_test_canvas();
assert_eq!(c.compute_finder_penalty_score(true), 0);
assert_eq!(c.compute_finder_penalty_score(false), 40);
}
#[test]
fn finder_penalty_score_matches_canvas_wrapper() {
let c = create_test_canvas();
let modules = c.modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
assert_eq!(
compute_finder_penalty_score(c.width.as_usize(), &modules, true),
c.compute_finder_penalty_score(true)
);
assert_eq!(
compute_finder_penalty_score(c.width.as_usize(), &modules, false),
c.compute_finder_penalty_score(false)
);
}
#[test]
fn test_penalty_score_balance() {
let c = create_test_canvas();
assert_eq!(c.compute_balance_penalty_score(), 2);
}
#[test]
fn balance_penalty_score_matches_canvas_wrapper() {
let c = create_test_canvas();
let modules = c.modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
assert_eq!(compute_balance_penalty_score(&modules), c.compute_balance_penalty_score());
}
#[test]
fn dark_module_count_matches_scalar_for_varied_lengths() {
for len in 0..65 {
let modules = (0..len).map(|i| u8::from(i % 3 == 0 || i % 7 == 0)).collect::<Vec<_>>();
assert_eq!(count_dark_modules(&modules), count_dark_modules_scalar(&modules));
}
}
#[test]
fn scalar_penalty_score_matches_canvas_wrapper() {
let c = create_test_canvas();
assert_eq!(
compute_total_penalty_score_scalar(c.version, c.width, &c.modules),
c.compute_total_penalty_scores()
);
}
#[test]
fn accelerated_penalty_score_matches_scalar_byte_grid() {
let c = create_test_canvas();
let modules = c.modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
assert_eq!(
compute_total_penalty_score_from_bytes(c.version, c.width.as_usize(), &modules),
compute_total_penalty_score_from_bytes_scalar(c.version, c.width.as_usize(), &modules)
);
}
#[test]
fn scratch_penalty_score_matches_canvas_wrapper() {
let c = create_test_canvas();
let mut scratch = Vec::new();
assert_eq!(c.compute_total_penalty_scores_with_scratch(&mut scratch), c.compute_total_penalty_scores());
assert_eq!(scratch.len(), c.modules.len());
}
#[test]
fn test_penalty_score_light_sides() {
static HORIZONTAL_SIDE: [Color; 17] = [
Color::Dark,
Color::Light,
Color::Light,
Color::Dark,
Color::Dark,
Color::Dark,
Color::Light,
Color::Light,
Color::Dark,
Color::Light,
Color::Dark,
Color::Light,
Color::Light,
Color::Dark,
Color::Light,
Color::Light,
Color::Light,
];
static VERTICAL_SIDE: [Color; 17] = [
Color::Dark,
Color::Dark,
Color::Dark,
Color::Light,
Color::Light,
Color::Dark,
Color::Dark,
Color::Light,
Color::Dark,
Color::Light,
Color::Dark,
Color::Light,
Color::Dark,
Color::Light,
Color::Light,
Color::Dark,
Color::Light,
];
let mut c = Canvas::new(Version::Micro(4), EcLevel::Q);
for i in 0_i16..17 {
c.put(i, -1, HORIZONTAL_SIDE[i.as_usize()]);
c.put(-1, i, VERTICAL_SIDE[i.as_usize()]);
}
assert_eq!(c.compute_light_side_penalty_score(), 168);
}
#[test]
fn light_side_penalty_score_matches_canvas_wrapper() {
let mut c = Canvas::new(Version::Micro(4), EcLevel::Q);
c.draw_all_functional_patterns();
let modules = c.modules.iter().map(|module| u8::from(module.is_dark())).collect::<Vec<_>>();
assert_eq!(
compute_light_side_penalty_score(c.width.as_usize(), &modules),
c.compute_light_side_penalty_score()
);
}
}
static ALL_PATTERNS_QR: [MaskPattern; 8] = [
MaskPattern::Checkerboard,
MaskPattern::HorizontalLines,
MaskPattern::VerticalLines,
MaskPattern::DiagonalLines,
MaskPattern::LargeCheckerboard,
MaskPattern::Fields,
MaskPattern::Diamonds,
MaskPattern::Meadow,
];
static ALL_PATTERNS_MICRO_QR: [MaskPattern; 4] =
[MaskPattern::HorizontalLines, MaskPattern::LargeCheckerboard, MaskPattern::Diamonds, MaskPattern::Meadow];
impl Canvas {
#[must_use]
pub fn apply_best_mask(&self) -> Self {
let patterns: &[MaskPattern] = match self.version {
Version::Normal(_) => &ALL_PATTERNS_QR,
Version::Micro(_) => &ALL_PATTERNS_MICRO_QR,
};
let mut scratch = Vec::with_capacity(self.modules.len());
let mut best_canvas = None;
let mut best_score = u16::MAX;
for &pattern in patterns {
let mut c = self.clone();
c.apply_mask(pattern);
let score = c.compute_total_penalty_scores_with_scratch(&mut scratch);
if score < best_score {
best_score = score;
best_canvas = Some(c);
}
}
best_canvas.expect("at least one pattern")
}
pub fn into_colors(self) -> Vec<Color> {
self.modules.into_iter().map(Color::from).collect()
}
}