smart-package-tracker 0.4.0

Generate package tracking IDs, render them as Code 128 barcodes (PNG and SVG), and read them back out of images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Turning [`Symbol`]s into images.
//!
//! Renderers share a single [`Layout`] computation, so PNG and SVG output are
//! geometrically identical for the same [`RenderOptions`] — an SVG preview
//! matches what the PNG will print.

mod hri;

#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "svg")]
pub mod svg;

#[cfg(feature = "png")]
pub use png::Png;
#[cfg(feature = "svg")]
pub use svg::Svg;

use alloc::string::String;

use crate::error::{Error, Result};
use crate::symbology::Symbol;

/// Refuse to allocate images larger than this on either axis.
///
/// A barcode that needs more than 20,000 pixels a side is a configuration
/// mistake, and failing loudly beats attempting a multi-gigabyte allocation.
const MAX_DIMENSION_PX: u32 = 20_000;

/// Refuse to allocate images with more pixels than this in total.
///
/// The per-axis limit alone does not bound memory: two dimensions each within
/// it multiply out to 400 megapixels, which the PNG renderer would rasterise
/// into a 1.6 GiB RGBA buffer in a single allocation. 64 megapixels is
/// 256 MiB — still far beyond any real label, which at 600 dpi on a 4x6 inch
/// stock is under 9 megapixels.
pub(crate) const MAX_PIXELS: u64 = 64_000_000;

/// A physical or device length.
///
/// Barcode geometry is specified in physical units — the X-dimension of a
/// shipping label is 13 mil, not "3 pixels" — so lengths carry their unit and
/// are converted against the output DPI.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Length {
    /// Device pixels, used as-is regardless of DPI.
    Px(f64),
    /// Millimetres.
    Mm(f64),
    /// Thousandths of an inch. The conventional unit for barcode
    /// X-dimensions; 13 mil is the common shipping-label default.
    Mils(f64),
    /// Inches.
    Inch(f64),
}

impl Length {
    /// Convert to device pixels at `dpi`.
    pub fn to_px(self, dpi: u32) -> f64 {
        let dpi = f64::from(dpi);
        match self {
            Self::Px(v) => v,
            Self::Mm(v) => v / 25.4 * dpi,
            Self::Mils(v) => v / 1000.0 * dpi,
            Self::Inch(v) => v * dpi,
        }
    }

    /// Convert to millimetres at `dpi` (needed for SVG physical dimensions).
    pub fn to_mm(self, dpi: u32) -> f64 {
        self.to_px(dpi) / f64::from(dpi) * 25.4
    }

    fn is_positive(self) -> bool {
        let v = match self {
            Self::Px(v) | Self::Mm(v) | Self::Mils(v) | Self::Inch(v) => v,
        };
        v.is_finite() && v > 0.0
    }
}

/// An 8-bit RGBA colour.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Color {
    /// Red channel.
    pub r: u8,
    /// Green channel.
    pub g: u8,
    /// Blue channel.
    pub b: u8,
    /// Alpha channel; 255 is opaque.
    pub a: u8,
}

impl Color {
    /// Opaque black.
    pub const BLACK: Self = Self::rgb(0, 0, 0);
    /// Opaque white.
    pub const WHITE: Self = Self::rgb(255, 255, 255);
    /// Fully transparent.
    pub const TRANSPARENT: Self = Self::rgba(0, 0, 0, 0);

    /// An opaque colour.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    /// A colour with an explicit alpha channel.
    pub const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }

    /// Whether the colour is fully opaque.
    pub const fn is_opaque(self) -> bool {
        self.a == 255
    }

    /// CSS hex notation: `#rrggbb`, or `#rrggbbaa` when not opaque.
    pub fn to_hex(self) -> String {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut s = String::with_capacity(9);
        s.push('#');
        let mut push = |v: u8| {
            s.push(HEX[(v >> 4) as usize] as char);
            s.push(HEX[(v & 0x0f) as usize] as char);
        };
        push(self.r);
        push(self.g);
        push(self.b);
        if !self.is_opaque() {
            push(self.a);
        }
        s
    }
}

/// How much blank space to leave around the symbol.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum QuietZone {
    /// Whatever the symbology's specification requires — 10 modules for
    /// Code 128. This is the default and the only setting that guarantees
    /// reliable scanning.
    #[default]
    Standard,
    /// An explicit number of modules per side.
    Modules(u32),
    /// No quiet zone.
    ///
    /// Only appropriate when the surrounding layout already guarantees blank
    /// space. A barcode printed flush against other content will frequently
    /// fail to scan.
    None,
}

/// How a symbol should be drawn.
///
/// Defaults target a 300 DPI thermal shipping-label printer: a 13 mil
/// X-dimension, 25 mm bar height, standard quiet zones, and human-readable
/// text.
///
/// # Examples
///
/// ```
/// use smart_package_tracker::{Color, Length, QuietZone, RenderOptions};
///
/// let options = RenderOptions::builder()
///     .module_width(Length::Mils(13.0))
///     .height(Length::Mm(25.0))
///     .quiet_zone(QuietZone::Standard)
///     .dpi(300)
///     .colors(Color::BLACK, Color::WHITE)
///     .human_readable(true)
///     .build()?;
///
/// assert_eq!(options.dpi(), 300);
/// # Ok::<(), smart_package_tracker::Error>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct RenderOptions {
    module_width: Length,
    height: Length,
    quiet_zone: QuietZone,
    dpi: u32,
    foreground: Color,
    background: Color,
    human_readable: bool,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            module_width: Length::Mils(13.0),
            height: Length::Mm(25.0),
            quiet_zone: QuietZone::Standard,
            dpi: 300,
            foreground: Color::BLACK,
            background: Color::WHITE,
            human_readable: true,
        }
    }
}

impl RenderOptions {
    /// Start from the defaults and override what you need.
    pub fn builder() -> RenderOptionsBuilder {
        RenderOptionsBuilder::default()
    }

    /// The X-dimension: width of one module.
    pub fn module_width(&self) -> Length {
        self.module_width
    }

    /// Bar height, for linear symbologies.
    pub fn height(&self) -> Length {
        self.height
    }

    /// Quiet zone setting.
    pub fn quiet_zone(&self) -> QuietZone {
        self.quiet_zone
    }

    /// Output resolution, used to convert physical lengths to pixels.
    pub fn dpi(&self) -> u32 {
        self.dpi
    }

    /// Colour of dark modules.
    pub fn foreground(&self) -> Color {
        self.foreground
    }

    /// Colour of light modules and margins.
    pub fn background(&self) -> Color {
        self.background
    }

    /// Whether to print the payload beneath the symbol.
    pub fn human_readable(&self) -> bool {
        self.human_readable
    }

    /// Compute the pixel geometry for `symbol` under these options.
    ///
    /// Exposed because label layout often needs the final size before
    /// rendering.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidRenderOptions`] if the result would exceed
    /// 20,000 pixels on either axis, or 64 megapixels in total.
    pub fn layout(&self, symbol: &Symbol) -> Result<Layout> {
        Layout::compute(symbol, self)
    }
}

/// Builder for [`RenderOptions`].
#[derive(Debug, Clone, Default)]
pub struct RenderOptionsBuilder {
    options: RenderOptions,
}

impl RenderOptionsBuilder {
    /// Set the X-dimension (width of one module).
    pub fn module_width(mut self, width: Length) -> Self {
        self.options.module_width = width;
        self
    }

    /// Set the bar height. Ignored by matrix symbologies, which derive height
    /// from their module grid.
    pub fn height(mut self, height: Length) -> Self {
        self.options.height = height;
        self
    }

    /// Set the quiet zone.
    pub fn quiet_zone(mut self, quiet_zone: QuietZone) -> Self {
        self.options.quiet_zone = quiet_zone;
        self
    }

    /// Set the output resolution.
    pub fn dpi(mut self, dpi: u32) -> Self {
        self.options.dpi = dpi;
        self
    }

    /// Set foreground and background colours.
    pub fn colors(mut self, foreground: Color, background: Color) -> Self {
        self.options.foreground = foreground;
        self.options.background = background;
        self
    }

    /// Enable or disable the human-readable text line.
    pub fn human_readable(mut self, enabled: bool) -> Self {
        self.options.human_readable = enabled;
        self
    }

    /// Validate and build.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidRenderOptions`] for a non-positive DPI, module
    /// width, or height.
    pub fn build(self) -> Result<RenderOptions> {
        let o = &self.options;
        if o.dpi == 0 {
            return Err(Error::InvalidRenderOptions("dpi must be positive".into()));
        }
        if !o.module_width.is_positive() {
            return Err(Error::InvalidRenderOptions(
                "module_width must be a positive, finite length".into(),
            ));
        }
        if !o.height.is_positive() {
            return Err(Error::InvalidRenderOptions(
                "height must be a positive, finite length".into(),
            ));
        }
        Ok(self.options)
    }
}

/// Pixel geometry of a rendered symbol.
///
/// Every measurement is a whole number of pixels, and the symbol width is an
/// exact multiple of the module width. Snapping to integers matters: a module
/// that straddles a pixel boundary is rendered as a grey edge, which degrades
/// the contrast a scanner relies on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Layout {
    /// Width of one module, in pixels. Always at least 1.
    pub module_px: u32,
    /// Horizontal quiet zone per side, in pixels.
    pub quiet_x_px: u32,
    /// Vertical quiet zone per side, in pixels. Zero for linear symbologies,
    /// which need no vertical quiet zone.
    pub quiet_y_px: u32,
    /// Symbol width, in pixels.
    pub symbol_w_px: u32,
    /// Symbol height, in pixels. For linear symbologies this is the bar
    /// height; for matrix symbologies it follows the module grid.
    pub symbol_h_px: u32,
    /// Left edge of the symbol.
    pub symbol_x_px: u32,
    /// Top edge of the symbol.
    pub symbol_y_px: u32,
    /// Integer scale factor applied to the 5x7 HRI font. Zero when no HRI is
    /// drawn.
    pub hri_scale: u32,
    /// Total vertical space taken by the HRI line, including the gap above it.
    /// Zero when no HRI is drawn.
    pub hri_block_h_px: u32,
    /// Left edge of the HRI text.
    pub hri_x_px: u32,
    /// Top edge of the HRI text.
    pub hri_y_px: u32,
    /// Total image width.
    pub width_px: u32,
    /// Total image height.
    pub height_px: u32,
}

impl Layout {
    fn compute(symbol: &Symbol, options: &RenderOptions) -> Result<Self> {
        let modules = symbol.modules();

        let module_px = round_to_u32(options.module_width.to_px(options.dpi)).max(1);

        let quiet_modules = match options.quiet_zone {
            QuietZone::Standard => symbol.kind().required_quiet_zone(),
            QuietZone::Modules(n) => n,
            QuietZone::None => 0,
        };
        let quiet_x_px = quiet_modules.saturating_mul(module_px);
        let quiet_y_px = if symbol.is_linear() { 0 } else { quiet_x_px };

        let symbol_w_px = modules.width().saturating_mul(module_px);
        let symbol_h_px = if symbol.is_linear() {
            round_to_u32(options.height.to_px(options.dpi)).max(1)
        } else {
            modules.height().saturating_mul(module_px)
        };

        // HRI: scale the bitmap font up until the text fills the symbol width,
        // without letting it grow taller than the symbol itself.
        let char_count = symbol.payload().chars().count() as u32;
        let draw_hri = options.human_readable && char_count > 0;

        let (hri_scale, hri_block_h_px, text_w_px) = if draw_hri {
            let natural_w = hri::text_width(char_count);
            let width_limited = symbol_w_px.checked_div(natural_w).unwrap_or(1);
            let height_limited = symbol_h_px / hri::GLYPH_H;
            let scale = width_limited.min(height_limited).max(1);

            let gap = module_px;
            // Pad below the text as well as above it: glyphs flush against the
            // image edge are the first thing a thermal printer clips.
            (scale, gap + hri::GLYPH_H * scale + gap, natural_w * scale)
        } else {
            (0, 0, 0)
        };

        // At scale 1 the text can still be wider than the symbol, which is
        // reachable for a compact QR code with a long payload. Widen the image
        // to fit rather than letting glyphs run past its edge and be clipped.
        let content_w_px = symbol_w_px.max(text_w_px);

        let width_px = content_w_px.saturating_add(quiet_x_px.saturating_mul(2));
        let height_px = symbol_h_px
            .saturating_add(quiet_y_px.saturating_mul(2))
            .saturating_add(hri_block_h_px);

        // Centre the symbol and the text independently within the content box.
        let symbol_x_px = quiet_x_px + (content_w_px - symbol_w_px) / 2;
        let (hri_x_px, hri_y_px) = if draw_hri {
            // The text goes *below* the symbol's quiet zone, never inside it.
            // A linear symbology has no vertical quiet zone, so this is the
            // familiar one-module gap; a matrix symbology such as QR requires
            // four clear modules underneath, and text drawn into them costs
            // exactly the margin a scanner uses to find the symbol.
            (
                quiet_x_px + (content_w_px - text_w_px) / 2,
                quiet_y_px
                    .saturating_mul(2)
                    .saturating_add(symbol_h_px)
                    .saturating_add(module_px),
            )
        } else {
            (0, 0)
        };

        if width_px == 0 || height_px == 0 {
            return Err(Error::InvalidRenderOptions(
                "computed image has zero area".into(),
            ));
        }
        if width_px > MAX_DIMENSION_PX || height_px > MAX_DIMENSION_PX {
            return Err(Error::InvalidRenderOptions(alloc::format!(
                "computed image is {width_px}x{height_px} px, exceeding the {MAX_DIMENSION_PX} px limit; \
                 reduce module_width, height, or dpi"
            )));
        }
        if u64::from(width_px) * u64::from(height_px) > MAX_PIXELS {
            return Err(Error::InvalidRenderOptions(alloc::format!(
                "computed image is {width_px}x{height_px} px, over the {} megapixel limit; \
                 reduce module_width, height, or dpi",
                MAX_PIXELS / 1_000_000
            )));
        }

        Ok(Self {
            module_px,
            quiet_x_px,
            quiet_y_px,
            symbol_w_px,
            symbol_h_px,
            symbol_x_px,
            symbol_y_px: quiet_y_px,
            hri_scale,
            hri_block_h_px,
            hri_x_px,
            hri_y_px,
            width_px,
            height_px,
        })
    }
}

/// Round a positive `f64` to `u32`, saturating rather than wrapping.
fn round_to_u32(v: f64) -> u32 {
    if !v.is_finite() || v <= 0.0 {
        return 0;
    }
    let rounded = round_half_up(v);
    if rounded >= f64::from(u32::MAX) {
        u32::MAX
    } else {
        rounded as u32
    }
}

/// `f64::round` is not available in `core`, so round half away from zero by
/// hand. Inputs here are always non-negative.
fn round_half_up(v: f64) -> f64 {
    let truncated = v as i64 as f64;
    if v - truncated >= 0.5 {
        truncated + 1.0
    } else {
        truncated
    }
}

/// Whether every character in `text` has a real glyph in the embedded HRI font.
///
/// Human-readable text is drawn with a built-in 5x7 bitmap font covering
/// `0-9`, `A-Z`, space, and `- . / * + $ % :`. Anything else renders as a
/// hollow box. Call this to detect that before it reaches a label.
///
/// # Examples
///
/// ```
/// use smart_package_tracker::render::hri_supports;
///
/// assert!(hri_supports("PKG-9ED9285C"));
/// assert!(!hri_supports("pkg-lowercase"));
/// ```
pub fn hri_supports(text: &str) -> bool {
    text.chars().all(hri::is_supported)
}

/// Draws a [`Symbol`] into some output representation.
///
/// Implementations must honour the shared [`Layout`] so that all output
/// formats stay geometrically identical.
pub trait Renderer {
    /// What this renderer produces — `Vec<u8>` for PNG, `String` for SVG.
    type Output;

    /// Render `symbol`.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidRenderOptions`] if the geometry is unusable, or
    /// [`Error::Render`] if the underlying encoder fails.
    fn render(&self, symbol: &Symbol, options: &RenderOptions) -> Result<Self::Output>;
}

#[cfg(all(test, feature = "code128"))]
mod tests {
    use super::*;
    use crate::symbology::{Code128, Symbology};

    fn symbol() -> Symbol {
        Code128.encode("PKG-9ED9285C").unwrap()
    }

    #[test]
    fn lengths_convert_consistently() {
        assert_eq!(Length::Inch(1.0).to_px(300), 300.0);
        assert_eq!(Length::Mils(1000.0).to_px(300), 300.0);
        assert_eq!(Length::Px(42.0).to_px(300), 42.0);
        assert!((Length::Mm(25.4).to_px(300) - 300.0).abs() < 1e-9);
        assert!((Length::Inch(1.0).to_mm(300) - 25.4).abs() < 1e-9);
    }

    #[test]
    fn module_width_snaps_to_whole_pixels() {
        let s = symbol();
        // 13 mil at 300 dpi is 3.9 px, which must round to 4.
        let layout = RenderOptions::default().layout(&s).unwrap();
        assert_eq!(layout.module_px, 4);
        assert_eq!(layout.symbol_w_px % layout.module_px, 0);
    }

    #[test]
    fn module_width_never_collapses_to_zero() {
        let opts = RenderOptions::builder()
            .module_width(Length::Mils(1.0))
            .dpi(72)
            .build()
            .unwrap();
        assert_eq!(opts.layout(&symbol()).unwrap().module_px, 1);
    }

    #[test]
    fn standard_quiet_zone_is_ten_modules_per_side() {
        let s = symbol();
        let layout = RenderOptions::default().layout(&s).unwrap();
        assert_eq!(layout.quiet_x_px, 10 * layout.module_px);
        assert_eq!(layout.width_px, layout.symbol_w_px + 2 * layout.quiet_x_px);
    }

    #[test]
    fn linear_symbols_get_no_vertical_quiet_zone() {
        let layout = RenderOptions::default().layout(&symbol()).unwrap();
        assert_eq!(layout.quiet_y_px, 0);
        assert_eq!(layout.symbol_y_px, 0);
    }

    #[test]
    fn quiet_zone_can_be_overridden() {
        let s = symbol();
        let none = RenderOptions::builder()
            .quiet_zone(QuietZone::None)
            .build()
            .unwrap()
            .layout(&s)
            .unwrap();
        assert_eq!(none.quiet_x_px, 0);
        assert_eq!(none.width_px, none.symbol_w_px);

        let explicit = RenderOptions::builder()
            .quiet_zone(QuietZone::Modules(2))
            .build()
            .unwrap()
            .layout(&s)
            .unwrap();
        assert_eq!(explicit.quiet_x_px, 2 * explicit.module_px);
    }

    #[test]
    fn hri_is_centred_and_fits_within_the_symbol() {
        let s = symbol();
        let layout = RenderOptions::default().layout(&s).unwrap();
        assert!(layout.hri_scale >= 1);
        let text_w = hri::text_width(s.payload().chars().count() as u32) * layout.hri_scale;
        assert!(text_w <= layout.symbol_w_px, "HRI wider than the symbol");
        assert!(layout.hri_x_px >= layout.quiet_x_px);
        assert!(layout.hri_x_px + text_w <= layout.width_px);
        assert!(layout.hri_y_px + hri::GLYPH_H * layout.hri_scale <= layout.height_px);
    }

    #[test]
    fn hri_is_padded_away_from_both_edges() {
        let layout = RenderOptions::default().layout(&symbol()).unwrap();
        // Gap above the text, between it and the bars.
        assert!(layout.hri_y_px > layout.symbol_y_px + layout.symbol_h_px);
        // Gap below the text, before the image edge.
        let text_bottom = layout.hri_y_px + hri::GLYPH_H * layout.hri_scale;
        assert!(
            text_bottom < layout.height_px,
            "HRI is flush against the bottom edge and may be clipped"
        );
    }

    #[test]
    fn disabling_hri_removes_the_text_block() {
        let layout = RenderOptions::builder()
            .human_readable(false)
            .build()
            .unwrap()
            .layout(&symbol())
            .unwrap();
        assert_eq!(layout.hri_scale, 0);
        assert_eq!(layout.hri_block_h_px, 0);
        assert_eq!(layout.height_px, layout.symbol_h_px);
    }

    #[test]
    fn builder_rejects_degenerate_options() {
        assert!(RenderOptions::builder().dpi(0).build().is_err());
        assert!(RenderOptions::builder()
            .module_width(Length::Mm(0.0))
            .build()
            .is_err());
        assert!(RenderOptions::builder()
            .height(Length::Mm(-1.0))
            .build()
            .is_err());
        assert!(RenderOptions::builder()
            .module_width(Length::Mm(f64::NAN))
            .build()
            .is_err());
    }

    #[test]
    fn absurd_geometry_is_rejected_rather_than_allocated() {
        let opts = RenderOptions::builder()
            .module_width(Length::Inch(10.0))
            .dpi(1200)
            .build()
            .unwrap();
        assert!(matches!(
            opts.layout(&symbol()),
            Err(Error::InvalidRenderOptions(_))
        ));
    }

    #[test]
    #[cfg(feature = "qr")]
    fn a_huge_but_within_axis_limits_image_is_still_rejected() {
        // Both axes under MAX_DIMENSION_PX multiply out to an allocation the
        // per-axis check never sees: this geometry used to be accepted and
        // then rasterised into a 1.27 GiB buffer.
        use crate::symbology::{Qr, QrVersion};

        let big = Qr::new()
            .version(QrVersion::Fixed(40))
            .encode("PKG-9ED9285C")
            .unwrap();
        let opts = RenderOptions::builder()
            .module_width(Length::Px(100.0))
            .human_readable(false)
            .build()
            .unwrap();

        let err = opts.layout(&big).unwrap_err();
        assert!(matches!(err, Error::InvalidRenderOptions(_)), "got {err:?}");
        assert!(
            alloc::format!("{err}").contains("megapixel"),
            "the message should name the limit that was hit: {err}"
        );

        // A label-sized geometry is still comfortably allowed.
        let sane = RenderOptions::builder()
            .module_width(Length::Px(8.0))
            .build()
            .unwrap();
        assert!(sane.layout(&big).is_ok());
    }

    #[test]
    fn colors_format_as_css_hex() {
        assert_eq!(Color::BLACK.to_hex(), "#000000");
        assert_eq!(Color::WHITE.to_hex(), "#ffffff");
        assert_eq!(Color::rgba(1, 2, 3, 4).to_hex(), "#01020304");
        assert!(Color::BLACK.is_opaque());
        assert!(!Color::TRANSPARENT.is_opaque());
    }

    #[test]
    fn rounding_is_half_up_and_saturating() {
        assert_eq!(round_to_u32(3.4), 3);
        assert_eq!(round_to_u32(3.5), 4);
        assert_eq!(round_to_u32(-1.0), 0);
        assert_eq!(round_to_u32(f64::NAN), 0);
        assert_eq!(round_to_u32(f64::INFINITY), 0);
        assert_eq!(round_to_u32(1e30), u32::MAX);
    }
}