use crate::payload::Payload;
#[cfg(feature = "serde")]
mod raw_b64 {
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S: Serializer>(bytes: &[u8], ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_str(&STANDARD.encode(bytes))
}
pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Vec<u8>, D::Error> {
let s = String::deserialize(de)?;
STANDARD.decode(s).map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "serde")]
mod decimal {
use serde::Serializer;
use serde::ser::SerializeTuple as _;
pub(super) fn of(value: f32) -> f64 {
let shortest = value.to_string();
let digits: String = shortest.chars().filter(char::is_ascii_digit).collect();
let significant = digits.trim_start_matches('0').trim_end_matches('0').len();
if !value.is_finite() || significant == 0 {
return f64::from(value);
}
let precision = significant - 1;
let even = format!("{value:.precision$e}");
let reads_back = even
.parse::<f32>()
.is_ok_and(|parsed| parsed.to_bits() == value.to_bits());
let spelled = if reads_back { even } else { shortest };
spelled.parse().unwrap_or(f64::from(value))
}
#[allow(
clippy::trivially_copy_pass_by_ref,
reason = "serde's serialize_with passes the field by reference"
)]
pub(super) fn serialize<S: Serializer>(value: &f32, ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_f64(of(*value))
}
pub(super) fn serialize_array<S: Serializer, const N: usize>(
values: &[f32; N],
ser: S,
) -> Result<S::Ok, S::Error> {
let mut tuple = ser.serialize_tuple(N)?;
for value in values {
tuple.serialize_element(&of(*value))?;
}
tuple.end()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
pub x: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
pub y: f32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Symbology {
QrCode,
MicroQrCode,
RectangularMicroQrCode,
DataMatrix,
Aztec,
Pdf417,
MaxiCode,
Ean13,
Ean8,
UpcA,
UpcE,
Code128,
Code39,
Code93,
Codabar,
Itf,
DataBar,
DataBarExpanded,
Telepen,
}
impl Symbology {
pub const ALL: [Self; 19] = [
Self::QrCode,
Self::MicroQrCode,
Self::RectangularMicroQrCode,
Self::DataMatrix,
Self::Aztec,
Self::Pdf417,
Self::MaxiCode,
Self::Ean13,
Self::Ean8,
Self::UpcA,
Self::UpcE,
Self::Code128,
Self::Code39,
Self::Code93,
Self::Codabar,
Self::Itf,
Self::DataBar,
Self::DataBarExpanded,
Self::Telepen,
];
#[must_use]
pub fn name(self) -> &'static str {
match self {
Self::QrCode => "qr_code",
Self::MicroQrCode => "micro_qr_code",
Self::RectangularMicroQrCode => "rectangular_micro_qr_code",
Self::DataMatrix => "data_matrix",
Self::Aztec => "aztec",
Self::Pdf417 => "pdf417",
Self::MaxiCode => "maxi_code",
Self::Ean13 => "ean13",
Self::Ean8 => "ean8",
Self::UpcA => "upc_a",
Self::UpcE => "upc_e",
Self::Code128 => "code128",
Self::Code39 => "code39",
Self::Code93 => "code93",
Self::Codabar => "codabar",
Self::Itf => "itf",
Self::DataBar => "data_bar",
Self::DataBarExpanded => "data_bar_expanded",
Self::Telepen => "telepen",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|symbology| symbology.name() == name)
}
#[must_use]
pub fn is_qr_family(self) -> bool {
matches!(
self,
Self::QrCode | Self::MicroQrCode | Self::RectangularMicroQrCode
)
}
#[must_use]
pub fn is_retail_gtin(self) -> bool {
matches!(self, Self::Ean13 | Self::Ean8 | Self::UpcA | Self::UpcE)
}
pub(crate) fn is_linear(self) -> bool {
matches!(
self,
Self::Ean13
| Self::Ean8
| Self::UpcA
| Self::UpcE
| Self::Code128
| Self::Code39
| Self::Code93
| Self::Codabar
| Self::Itf
| Self::DataBar
| Self::DataBarExpanded
| Self::Telepen
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum EngineKind {
Rxing,
Rqrr,
Rescue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum EcLevel {
L,
M,
Q,
H,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Charset {
Utf8,
ShiftJis,
Latin1,
Gb18030,
Eci,
Unknown,
#[cfg_attr(feature = "serde", serde(other, skip_serializing))]
Unrecognized,
}
impl Charset {
#[must_use]
pub const fn is_lossy(self) -> bool {
matches!(self, Self::Unknown)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct EciSegment {
pub designator: u32,
pub start: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Fnc1Position {
First,
Second,
#[cfg_attr(feature = "serde", serde(other, skip_serializing))]
Unrecognized,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct DecodedContent {
pub text: String,
#[cfg_attr(feature = "serde", serde(with = "raw_b64"))]
pub raw: Vec<u8>,
pub charset: Charset,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub eci: Option<Vec<EciSegment>>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub fnc1: Option<Fnc1Position>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct QrMeta {
pub version: Option<u8>,
pub ec_level: Option<EcLevel>,
pub mask: Option<u8>,
pub modules: Option<u8>,
pub inverted: Option<bool>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Detection {
pub symbology: Symbology,
pub content: DecodedContent,
pub payload: Payload,
pub corners: Option<[Point; 4]>,
pub meta: QrMeta,
pub engines: Vec<EngineKind>,
#[cfg_attr(feature = "serde", serde(default))]
pub occurrences: Vec<Occurrence>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Occurrence {
pub geometry: OccurrenceGeometry,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct OccurrenceGeometry {
pub kind: GeometryKind,
pub points: Vec<Point>,
pub reader: Option<EngineKind>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum GeometryKind {
Quad,
Segment,
Partial,
Unavailable,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Saturation {
pub reads: bool,
pub detections: bool,
pub occurrences: bool,
}
impl Saturation {
#[must_use]
pub fn either(a: Self, b: Self) -> Self {
Self {
reads: a.reads || b.reads,
detections: a.detections || b.detections,
occurrences: a.occurrences || b.occurrences,
}
}
#[must_use]
pub fn any(self) -> bool {
self.reads || self.detections || self.occurrences
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Grade {
Excellent,
Good,
Acceptable,
Fair,
Poor,
}
impl Grade {
#[must_use]
pub fn from_value(value: u8) -> Self {
match value {
80.. => Self::Excellent,
70..=79 => Self::Good,
60..=69 => Self::Acceptable,
40..=59 => Self::Fair,
0..=39 => Self::Poor,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum StressAxis {
Resolution,
Blur,
Contrast,
Perspective,
Rotation,
Lighting,
}
impl StressAxis {
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
match name {
"resolution" => Some(Self::Resolution),
"blur" => Some(Self::Blur),
"contrast" => Some(Self::Contrast),
"perspective" => Some(Self::Perspective),
"rotation" => Some(Self::Rotation),
"lighting" => Some(Self::Lighting),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AxisScore {
pub axis: StressAxis,
pub passed: u8,
pub total: u8,
pub failed_at: Option<String>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub refined_failed_at: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum UecGrade {
A,
B,
C,
D,
F,
}
impl UecGrade {
#[must_use]
pub fn from_margin(margin: f32) -> Self {
if margin >= 0.62 {
Self::A
} else if margin >= 0.50 {
Self::B
} else if margin >= 0.37 {
Self::C
} else if margin >= 0.25 {
Self::D
} else {
Self::F
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct UecReport {
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
pub margin: f32,
pub grade: UecGrade,
pub worst_block_errors: u8,
pub worst_block_capacity: u8,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct StructuralReport {
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize_array"))]
pub finder_integrity: [f32; 3],
pub quiet_zone_ok: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum IsoGrade {
A,
B,
C,
D,
F,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct IsoParameter {
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
pub value: f32,
pub grade: IsoGrade,
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Iso15415Report {
pub symbol_contrast: IsoParameter,
pub modulation: IsoParameter,
pub axial_nonuniformity: IsoParameter,
pub fixed_pattern_damage: IsoParameter,
pub unused_error_correction: Option<IsoParameter>,
pub overall: IsoGrade,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Score {
pub value: u8,
#[cfg_attr(feature = "serde", serde(default))]
pub weights_run: u8,
pub grade: Grade,
pub axes: Vec<AxisScore>,
pub structural: Option<StructuralReport>,
pub uec: Option<UecReport>,
pub iso15415: Option<Iso15415Report>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum AlphaMode {
Auto,
White,
Black,
Custom,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum AlphaPlacement {
Any,
LightOnly,
DarkOnly,
Mixed,
None,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AlphaProbe {
pub background_luma: u8,
pub decoded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AlphaPaletteProbe {
pub background: String,
pub background_luma: u8,
pub decoded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AlphaEnvelope {
pub probes: Vec<AlphaProbe>,
pub safe_luma: Vec<[u8; 2]>,
pub placement: AlphaPlacement,
pub palette: Vec<AlphaPaletteProbe>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct AlphaReport {
#[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
pub coverage: f32,
pub content_luma: u8,
pub mode: AlphaMode,
pub background: String,
pub fallback_used: bool,
pub envelope: Option<AlphaEnvelope>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "hint", rename_all = "snake_case"))]
#[non_exhaustive]
pub enum Hint {
RaiseErrorCorrection {
current: EcLevel,
},
IncreaseContrast,
EnlargeModules,
FixFinderPattern {
corner: u8,
},
RestoreQuietZone,
ReduceArtTexture,
LowCorrectionMargin {
errors: u8,
capacity: u8,
},
AlphaBackgroundDependent {
placement: AlphaPlacement,
},
AddBackgroundPlate {
color: PlateColor,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[non_exhaustive]
pub enum PlateColor {
White,
Black,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct StageTrace {
pub stage: String,
pub transforms_tried: u32,
pub ms: f64,
pub detections_found: u32,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct PipelineTrace {
pub stages: Vec<StageTrace>,
pub engine_panics: u8,
pub total_ms: f64,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub budget_exhausted: Option<bool>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub saturation: Option<Saturation>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub formats: Option<Vec<Symbology>>,
}
impl Default for PipelineTrace {
fn default() -> Self {
Self {
stages: Vec::new(),
engine_panics: 0,
total_ms: 0.0,
budget_exhausted: Some(false),
saturation: Some(Saturation::default()),
formats: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Versions {
pub scanner: String,
pub pipeline: u8,
pub score_contract: u8,
}
impl QrMeta {
#[must_use]
pub fn modules_per_side(version: u8) -> Option<u8> {
(1..=40).contains(&version).then(|| version * 4 + 17)
}
}
impl Versions {
#[must_use]
pub fn current() -> Self {
Self {
scanner: env!("CARGO_PKG_VERSION").to_owned(),
pipeline: 5,
score_contract: 6,
}
}
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct ScanReport {
pub detections: Vec<Detection>,
pub score: Option<Score>,
pub hints: Vec<Hint>,
#[cfg_attr(
feature = "serde",
serde(default, skip_serializing_if = "Option::is_none")
)]
pub alpha: Option<AlphaReport>,
pub trace: PipelineTrace,
pub versions: Versions,
}
impl ScanReport {
#[must_use]
pub fn empty() -> Self {
Self {
detections: Vec::new(),
score: None,
hints: Vec::new(),
alpha: None,
trace: PipelineTrace::default(),
versions: Versions::current(),
}
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::payload::Payload;
fn full_alpha() -> AlphaReport {
AlphaReport {
coverage: 0.612,
content_luma: 34,
mode: AlphaMode::Auto,
background: "white".into(),
fallback_used: false,
envelope: Some(AlphaEnvelope {
probes: [
(0, false),
(64, false),
(96, false),
(128, true),
(192, true),
(255, true),
]
.into_iter()
.map(|(background_luma, decoded)| AlphaProbe {
background_luma,
decoded,
})
.collect(),
safe_luma: vec![[128, 255]],
placement: AlphaPlacement::LightOnly,
palette: vec![AlphaPaletteProbe {
background: "#1a1a2e".into(),
background_luma: 28,
decoded: false,
}],
}),
}
}
fn full_score() -> Score {
Score {
value: 87,
grade: Grade::Excellent,
weights_run: 42,
axes: vec![
AxisScore {
axis: StressAxis::Resolution,
passed: 4,
total: 5,
failed_at: None,
refined_failed_at: None,
},
AxisScore {
axis: StressAxis::Perspective,
passed: 3,
total: 5,
failed_at: Some("34\u{b0}".into()),
refined_failed_at: Some("30\u{b0}".into()),
},
],
structural: Some(StructuralReport {
finder_integrity: [1.0, 0.96, 0.88],
quiet_zone_ok: true,
}),
uec: Some(UecReport {
margin: 0.85,
grade: UecGrade::A,
worst_block_errors: 1,
worst_block_capacity: 18,
}),
iso15415: Some(Iso15415Report {
symbol_contrast: IsoParameter {
value: 0.82,
grade: IsoGrade::A,
},
modulation: IsoParameter {
value: 0.46,
grade: IsoGrade::B,
},
axial_nonuniformity: IsoParameter {
value: 0.03,
grade: IsoGrade::A,
},
fixed_pattern_damage: IsoParameter {
value: 0.88,
grade: IsoGrade::C,
},
unused_error_correction: Some(IsoParameter {
value: 0.85,
grade: IsoGrade::A,
}),
overall: IsoGrade::C,
}),
}
}
fn full_report() -> ScanReport {
ScanReport {
detections: vec![Detection {
symbology: Symbology::QrCode,
content: DecodedContent {
text: "https://qrcode-ai.com".into(),
raw: b"https://qrcode-ai.com".to_vec(),
charset: Charset::Utf8,
eci: None,
fnc1: None,
},
payload: Payload::Text,
corners: Some([
Point { x: 10.0, y: 10.0 },
Point { x: 90.0, y: 10.5 },
Point { x: 90.5, y: 90.0 },
Point { x: 10.0, y: 89.5 },
]),
meta: QrMeta {
version: Some(5),
ec_level: Some(EcLevel::Q),
mask: Some(3),
modules: Some(37),
inverted: Some(false),
},
engines: vec![EngineKind::Rxing, EngineKind::Rqrr],
occurrences: vec![Occurrence {
geometry: OccurrenceGeometry {
kind: GeometryKind::Quad,
points: vec![
Point { x: 10.0, y: 10.0 },
Point { x: 86.5, y: 10.4 },
Point { x: 86.9, y: 86.0 },
Point { x: 10.0, y: 85.6 },
],
reader: Some(EngineKind::Rqrr),
},
}],
}],
score: Some(full_score()),
hints: vec![
Hint::RaiseErrorCorrection {
current: EcLevel::Q,
},
Hint::IncreaseContrast,
Hint::LowCorrectionMargin {
errors: 12,
capacity: 24,
},
Hint::AlphaBackgroundDependent {
placement: AlphaPlacement::LightOnly,
},
Hint::AddBackgroundPlate {
color: PlateColor::White,
},
],
alpha: Some(full_alpha()),
trace: PipelineTrace {
stages: vec![StageTrace {
stage: "direct".into(),
transforms_tried: 1,
ms: 12.5,
detections_found: 1,
}],
engine_panics: 0,
total_ms: 12.5,
budget_exhausted: Some(false),
saturation: Some(Saturation {
reads: false,
detections: false,
occurrences: true,
}),
formats: None,
},
versions: Versions::current(),
}
}
#[test]
fn symbology_wire_names_pinned() {
for (sym, wire) in [
(Symbology::QrCode, "qr_code"),
(Symbology::MicroQrCode, "micro_qr_code"),
(
Symbology::RectangularMicroQrCode,
"rectangular_micro_qr_code",
),
(Symbology::DataMatrix, "data_matrix"),
(Symbology::Aztec, "aztec"),
(Symbology::Pdf417, "pdf417"),
(Symbology::MaxiCode, "maxi_code"),
(Symbology::Ean13, "ean13"),
(Symbology::Ean8, "ean8"),
(Symbology::UpcA, "upc_a"),
(Symbology::UpcE, "upc_e"),
(Symbology::Code128, "code128"),
(Symbology::Code39, "code39"),
(Symbology::Code93, "code93"),
(Symbology::Codabar, "codabar"),
(Symbology::Itf, "itf"),
(Symbology::DataBar, "data_bar"),
(Symbology::DataBarExpanded, "data_bar_expanded"),
(Symbology::Telepen, "telepen"),
] {
assert_eq!(
serde_json::to_value(sym).unwrap(),
serde_json::Value::String(wire.to_owned())
);
}
}
#[cfg(feature = "serde")]
#[test]
fn content_wire_names_pinned() {
for (charset, wire) in [
(Charset::Utf8, "utf8"),
(Charset::ShiftJis, "shift_jis"),
(Charset::Latin1, "latin1"),
(Charset::Gb18030, "gb18030"),
(Charset::Eci, "eci"),
(Charset::Unknown, "unknown"),
] {
assert_eq!(serde_json::to_value(charset).unwrap(), wire);
let back: Charset = serde_json::from_value(wire.into()).unwrap();
assert_eq!(back, charset);
assert_eq!(charset.is_lossy(), charset == Charset::Unknown, "{wire}");
}
let future: Charset = serde_json::from_str("\"future_x\"").unwrap();
assert_eq!(future, Charset::Unrecognized);
assert!(!future.is_lossy());
assert!(serde_json::to_string(&Charset::Unrecognized).is_err());
for (position, wire) in [
(Fnc1Position::First, "first"),
(Fnc1Position::Second, "second"),
] {
assert_eq!(serde_json::to_value(position).unwrap(), wire);
}
let fifth: Fnc1Position = serde_json::from_str("\"fifth\"").unwrap();
assert_eq!(fifth, Fnc1Position::Unrecognized);
assert!(serde_json::to_string(&Fnc1Position::Unrecognized).is_err());
assert_eq!(
serde_json::to_value(EciSegment {
designator: 4,
start: 0
})
.unwrap(),
serde_json::json!({"designator": 4, "start": 0})
);
}
#[cfg(feature = "serde")]
#[test]
fn content_optional_keys_are_absent_or_present() {
let content = |eci, fnc1| DecodedContent {
text: "hi".into(),
raw: b"hi".to_vec(),
charset: Charset::Utf8,
eci,
fnc1,
};
assert_eq!(
serde_json::to_value(content(None, None)).unwrap(),
serde_json::json!({"text": "hi", "raw": "aGk=", "charset": "utf8"})
);
assert_eq!(
serde_json::to_value(content(Some(Vec::new()), Some(Fnc1Position::First))).unwrap(),
serde_json::json!({
"text": "hi", "raw": "aGk=", "charset": "utf8", "eci": [], "fnc1": "first"
})
);
let old: DecodedContent =
serde_json::from_str(r#"{"text":"hi","raw":"aGk=","charset":"utf8"}"#).unwrap();
assert_eq!(old, content(None, None));
let unknown: DecodedContent =
serde_json::from_str(r#"{"text":"日本中文","raw":"k/qWe9bQzsQ=","charset":"unknown"}"#)
.unwrap();
assert_eq!((unknown.charset, unknown.eci), (Charset::Unknown, None));
assert_eq!(
unknown.raw,
[0x93, 0xFA, 0x96, 0x7B, 0xD6, 0xD0, 0xCE, 0xC4]
);
}
#[test]
fn versions_pin_the_contract() {
let v = Versions::current();
assert_eq!(v.scanner, env!("CARGO_PKG_VERSION"));
assert_eq!(
v.pipeline, 5,
"pipeline v5 = occurrences of every physical copy and the capacities \
reached; a bump must be deliberate"
);
assert_eq!(
v.score_contract, 6,
"score contract v6 = the correction margin measured in the image, \
whatever read the symbol; a bump must be deliberate"
);
}
#[test]
fn empty_report_has_no_detections_and_no_score() {
let report = ScanReport::empty();
assert_eq!(report.detections.len(), 0);
assert!(report.score.is_none());
assert_eq!(report.hints.len(), 0);
assert_eq!(report.versions, Versions::current());
}
#[cfg(feature = "serde")]
#[test]
fn the_budget_flag_is_written_always_and_read_absent_as_unknown() {
let old: PipelineTrace =
serde_json::from_str(r#"{"stages":[],"engine_panics":0,"total_ms":0.0}"#).unwrap();
assert_eq!(old.budget_exhausted, None, "absent reads as unknown");
assert_eq!(
serde_json::to_value(&old).unwrap(),
serde_json::json!({"stages": [], "engine_panics": 0, "total_ms": 0.0}),
"an unknown flag is re-written absent, never as false"
);
let cut: PipelineTrace = serde_json::from_str(
r#"{"stages":[],"engine_panics":0,"total_ms":0.0,"budget_exhausted":true}"#,
)
.unwrap();
assert_eq!(cut.budget_exhausted, Some(true));
assert_eq!(
serde_json::to_value(&cut).unwrap()["budget_exhausted"],
true
);
assert_eq!(PipelineTrace::default().budget_exhausted, Some(false));
let empty = serde_json::to_value(ScanReport::empty()).unwrap();
assert_eq!(empty["trace"]["budget_exhausted"], false, "{empty}");
}
#[test]
fn is_qr_family_pins_exactly_the_three_qr_symbologies() {
for sym in [
Symbology::QrCode,
Symbology::MicroQrCode,
Symbology::RectangularMicroQrCode,
] {
assert!(sym.is_qr_family(), "{sym:?} is QR-family"); }
for sym in [
Symbology::DataMatrix,
Symbology::Aztec,
Symbology::Pdf417,
Symbology::MaxiCode,
Symbology::Ean13,
Symbology::Ean8,
Symbology::UpcA,
Symbology::UpcE,
Symbology::Code128,
Symbology::Code39,
Symbology::DataBar,
Symbology::Telepen,
] {
assert!(!sym.is_qr_family(), "{sym:?} is NOT QR-family"); }
}
#[test]
fn is_retail_gtin_pins_exactly_the_four_retail_symbologies() {
for sym in [
Symbology::Ean13,
Symbology::Ean8,
Symbology::UpcA,
Symbology::UpcE,
] {
assert!(sym.is_retail_gtin(), "{sym:?} is a retail GTIN carrier"); }
for sym in [
Symbology::QrCode,
Symbology::DataMatrix,
Symbology::Aztec,
Symbology::Code128,
Symbology::Itf,
Symbology::DataBar,
] {
assert!(!sym.is_retail_gtin(), "{sym:?} is NOT a retail GTIN"); }
}
#[test]
fn grade_bands_are_pinned() {
let bands = [
(100, Grade::Excellent),
(80, Grade::Excellent),
(79, Grade::Good),
(70, Grade::Good),
(69, Grade::Acceptable),
(60, Grade::Acceptable),
(59, Grade::Fair),
(40, Grade::Fair),
(39, Grade::Poor),
(0, Grade::Poor),
];
for (value, expected) in bands {
assert_eq!(Grade::from_value(value), expected, "value {value}");
}
}
#[test]
fn stress_axes_parse_from_their_wire_names_only() {
for (name, axis) in [
("resolution", StressAxis::Resolution),
("blur", StressAxis::Blur),
("contrast", StressAxis::Contrast),
("perspective", StressAxis::Perspective),
("rotation", StressAxis::Rotation),
("lighting", StressAxis::Lighting),
] {
assert_eq!(StressAxis::from_name(name), Some(axis), "{name}");
#[cfg(feature = "serde")]
assert_eq!(serde_json::to_string(&axis).unwrap(), format!("\"{name}\""));
}
for name in ["", "Blur", "BLUR", "exposure", "tilt"] {
assert_eq!(StressAxis::from_name(name), None, "{name}");
}
}
#[cfg(feature = "serde")]
#[test]
fn schema_snapshot_full() {
insta::assert_json_snapshot!("scan_report_full", full_report(), {
".versions.scanner" => "[crate-version]"
});
}
#[cfg(feature = "serde")]
#[test]
fn schema_snapshot_empty() {
insta::assert_json_snapshot!("scan_report_empty", ScanReport::empty(), {
".versions.scanner" => "[crate-version]"
});
}
#[cfg(feature = "serde")]
#[test]
fn float_fields_reach_serde_as_the_decimals_the_json_shows() {
let sum = 0.1_f32 + 0.2_f32; let third = 1.0_f32 / 3.0; let point = Point { x: 0.612, y: third };
let value = serde_json::to_value(point).unwrap();
assert_eq!(
(value["x"].as_f64(), value["y"].as_f64()),
(Some(0.612), Some(0.333_333_34))
);
let uec = UecReport {
margin: sum,
grade: UecGrade::A,
worst_block_errors: 0,
worst_block_capacity: 26,
};
assert_eq!(
serde_json::to_value(uec).unwrap()["margin"].as_f64(),
Some(0.3)
);
let structural = StructuralReport {
finder_integrity: [0.612, third, sum],
quiet_zone_ok: true,
};
assert_eq!(
serde_json::to_value(structural).unwrap()["finder_integrity"],
serde_json::json!([0.612, 0.333_333_34, 0.3])
);
let parameter = IsoParameter {
value: 0.612,
grade: IsoGrade::A,
};
assert_eq!(
serde_json::to_value(parameter).unwrap()["value"].as_f64(),
Some(0.612)
);
assert_eq!(
serde_json::to_value(full_alpha()).unwrap()["coverage"].as_f64(),
Some(0.612)
);
assert_eq!(
serde_json::to_string(&point).unwrap(),
r#"{"x":0.612,"y":0.33333334}"#
);
}
#[cfg(feature = "serde")]
#[test]
fn the_decimal_spelling_keeps_the_json_text() {
let mut same_text = 0;
for bits in (0..=u32::MAX).step_by(65_521) {
let value = f32::from_bits(bits);
if !value.is_finite() {
continue;
}
let widened = serde_json::to_string(&value).unwrap();
let decimal = serde_json::to_string(&decimal::of(value)).unwrap();
assert_eq!(
widened.parse::<f64>().unwrap().to_bits(),
decimal.parse::<f64>().unwrap().to_bits(),
"{value:e}: {widened} vs {decimal}"
);
let zero = bits.trailing_zeros() >= 31;
if zero || (1e-5..1e13).contains(&value.abs()) {
assert_eq!(widened, decimal, "{value:e}");
same_text += 1;
}
}
assert!(same_text > 10_000, "{same_text}");
}
#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip_preserves_everything() {
let report = full_report();
let json = serde_json::to_string(&report).unwrap();
let back: ScanReport = serde_json::from_str(&json).unwrap();
assert_eq!(report, back);
}
#[test]
fn two_saturations_keep_every_capacity_either_reached() {
let none = Saturation::default();
let reads = Saturation {
reads: true,
..none
};
let detections = Saturation {
detections: true,
..none
};
let occurrences = Saturation {
occurrences: true,
..none
};
for one in [reads, detections, occurrences] {
assert_eq!(Saturation::either(one, none), one, "{one:?} first");
assert_eq!(Saturation::either(none, one), one, "{one:?} second");
assert_eq!(Saturation::either(one, one), one, "{one:?} both");
assert!(one.any(), "{one:?}");
}
assert_eq!(Saturation::either(none, none), none);
assert!(!none.any());
assert_eq!(
Saturation::either(reads, Saturation::either(detections, occurrences)),
Saturation {
reads: true,
detections: true,
occurrences: true,
}
);
}
}