write_barcodes.rs

Le fichier Rust de l’exemple « Tous les codes-barres linéaires sur une page ». Neuf codes-barres de l’atelier, de l’entrepôt, de la caisse, de la banque du sang et de la librairie, chacun au-dessus du texte que le scanner en restitue.

Rust 740 lignes

À quoi sert cet exemple

Un atelier, un entrepôt et une caisse ne lisent pas les mêmes barres. L’étiquette d’un emplacement de stockage est en Code 39, le carton de groupage livré à un magasin en ITF-14, une poche de sang en Codabar, et un magazine affiche son numéro de parution dans un petit bloc à côté de son code principal. Si l’étiquette est imprimée dans la mauvaise famille, le scanner au bout de la chaîne ne la lit pas du tout, et quelqu’un doit taper le numéro à la main.

Ce que montre cet exemple

  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
730
731
732
733
734
735
736
737
738
739
740
//! Draws every linear barcode a request can ask for by name, each one beside
//! what a scanner reads back from it.
//!
//! A linear code is a run of bars and spaces built out of one width — a module
//! — and a reader needs a clear margin each side. Each box on this page is
//! filled the way a request fills it: a margin of `QUIET_ZONE` modules each
//! side, and the bars taking the rest of the width at the box's full height.
//!
//! What the page says about the codes is held in `Words`, once per language,
//! and `HQF_PDF_LANG` picks which set the sheet is written in. What the codes
//! carry stands apart from them: a scanner reads it, and it is the same in
//! every language.
//!
//! Usage: `cargo run --example write_barcodes -- tmp/barcodes.pdf [font.ttf]`
//!        `HQF_PDF_LANG=fr cargo run --example write_barcodes -- tmp/barcodes_fr.pdf`

use std::env;
use std::fs;
use std::path::{Path, PathBuf};

use hqf_pdf::barcode::QUIET_ZONE;
use hqf_pdf::content::Content;
use hqf_pdf::layout::Align;
use hqf_pdf::{
    AddOn2, AddOn5, Codabar, Code39, Code93, DataBar, Document, Ean13, Error, Font, FontHandle,
    Itf14, Page, TextFlow, UpcE,
};

#[path = "shared/out.rs"]
mod out;

#[path = "shared/licence.rs"]
mod licence;

#[path = "shared/language.rs"]
mod language;

#[path = "shared/failure.rs"]
mod failure;

use language::Language;

/// The font the example draws with when none is given on the command line.
fn default_font() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests")
        .join("fonts")
        .join("DejaVuSans.ttf")
}

/// The words the sheet is written in, one set per language.
#[derive(Debug)]
struct Words {
    /// What the file says it is, in what it says of itself.
    title: &'static str,
    /// The heading at the top of the sheet.
    heading: &'static str,
    /// What the sheet says under its heading, a line each.
    lines: [&'static str; 2],
    /// What stands under each code, in the order the page draws them: the
    /// symbology, where it is met, and what a scanner reads back from it.
    captions: [&'static str; 9],
}

impl Words {
    /// The words the sheet is written in, in `language`.
    fn of(language: Language) -> &'static Self {
        language::pick(&WORDS, language)
    }
}

/// The sheet in English.
const ENGLISH: Words = Words {
    title: "The linear barcodes a request can ask for by name",
    heading: "The barcodes a workshop, a warehouse and a till read",
    lines: [
        "Each box below is one module to the point, so every bar edge lands on a whole",
        "pixel of a printer. Under each code is what a scanner reads back from it.",
    ],
    captions: [
        "Code 39, the workshop label: BAY 12-A",
        "Code 39 carrying its modulo 43 check character: 159F",
        "Code 93, the same text in half the room: BAY 12-A",
        "ITF-14, the outer case a shop takes delivery of: 00012345678905",
        "Codabar, the blood bag and the borrower's card: A31600$D",
        "UPC-E, the small North American package: 01234565",
        "A magazine, its issue number in a two-digit add-on: 9780201379624 53",
        "A book, the price its publisher suggests in a five-digit add-on: 9781234567897 51999",
        "GS1 DataBar, the loose cut of meat and the small pack: 00012345678905",
    ],
};

/// The sheet in French.
const FRENCH: Words = Words {
    title: "Les codes-barres linéaires qu’une requête peut demander par leur nom",
    heading: "Codes-barres d’atelier, d’entrepôt et de caisse",
    lines: [
        "Ci-dessous, un module mesure un point : chaque bord de barre tombe ainsi sur un",
        "pixel entier de l’imprimante. Sous chaque code, ce qu’un lecteur y lit.",
    ],
    captions: [
        "Code 39, l’étiquette d’atelier : BAY 12-A",
        "Code 39 avec son caractère de contrôle modulo 43 : 159F",
        "Code 93, le même texte dans deux fois moins de place : BAY 12-A",
        "ITF-14, le carton livré au magasin : 00012345678905",
        "Codabar, la poche de sang et la carte de bibliothèque : A31600$D",
        "UPC-E, le petit emballage nord-américain : 01234565",
        "Un magazine et son numéro, en extension à deux chiffres : 9780201379624 53",
        "Un livre et son prix conseillé, en extension à cinq chiffres : 9781234567897 51999",
        "GS1 DataBar, la viande à la coupe et le petit conditionnement : 00012345678905",
    ],
};

/// The sheet in German.
const GERMAN: Words = Words {
    title: "Die linearen Strichcodes, die eine Anfrage namentlich verlangen kann",
    heading: "Strichcodes für Werkstatt, Lager und Kasse",
    lines: [
        "Ein Modul misst hier einen Punkt, sodass jede Balkenkante auf ein ganzes",
        "Druckerpixel fällt. Unter jedem Code steht, was ein Scanner daraus liest.",
    ],
    captions: [
        "Code 39, das Werkstattetikett: BAY 12-A",
        "Code 39 mit Prüfzeichen nach Modulo 43: 159F",
        "Code 93, derselbe Text auf halber Breite: BAY 12-A",
        "ITF-14, der Umkarton, den ein Laden geliefert bekommt: 00012345678905",
        "Codabar, der Blutbeutel und der Bibliotheksausweis: A31600$D",
        "UPC-E, die kleine nordamerikanische Packung: 01234565",
        "Eine Zeitschrift mit der Heftnummer im zweistelligen Zusatzcode: 9780201379624 53",
        "Ein Buch mit Preisempfehlung im fünfstelligen Zusatzcode: 9781234567897 51999",
        "GS1 DataBar, das Fleisch von der Theke und die kleine Packung: 00012345678905",
    ],
};

/// The sheet in Spanish.
const SPANISH: Words = Words {
    title: "Los códigos de barras lineales que una solicitud puede pedir por su nombre",
    heading: "Códigos de barras de taller, almacén y caja",
    lines: [
        "Abajo, un módulo mide un punto: así cada borde de barra cae en un píxel entero",
        "de la impresora. Bajo cada código figura lo que lee un escáner.",
    ],
    captions: [
        "Code 39, la etiqueta del taller: BAY 12-A",
        "Code 39 con su carácter de control módulo 43: 159F",
        "Code 93, el mismo texto en la mitad de espacio: BAY 12-A",
        "ITF-14, la caja de envío que recibe una tienda: 00012345678905",
        "Codabar, la bolsa de sangre y el carné de biblioteca: A31600$D",
        "UPC-E, el envase pequeño norteamericano: 01234565",
        "Una revista y su número, en un suplemento de dos cifras: 9780201379624 53",
        "Un libro y su precio recomendado, en un suplemento de cinco cifras: 9781234567897 51999",
        "GS1 DataBar, la carne al corte y el envase pequeño: 00012345678905",
    ],
};

/// The sheet in Italian.
const ITALIAN: Words = Words {
    title: "I codici a barre lineari che una richiesta può chiedere per nome",
    heading: "Codici a barre per officina, magazzino e cassa",
    lines: [
        "Qui sotto un modulo misura un punto: ogni bordo di barra cade così su un pixel",
        "intero della stampante. Sotto ogni codice, ciò che un lettore vi legge.",
    ],
    captions: [
        "Code 39, l’etichetta d’officina: BAY 12-A",
        "Code 39 con il suo carattere di controllo modulo 43: 159F",
        "Code 93, lo stesso testo in metà dello spazio: BAY 12-A",
        "ITF-14, il cartone che un negozio riceve in consegna: 00012345678905",
        "Codabar, la sacca di sangue e la tessera della biblioteca: A31600$D",
        "UPC-E, la piccola confezione nordamericana: 01234565",
        "Una rivista e il suo numero, in un codice aggiuntivo a due cifre: 9780201379624 53",
        "Un libro e il prezzo consigliato, in un codice aggiuntivo a cinque cifre: \
9781234567897 51999",
        "GS1 DataBar, la carne al taglio e la piccola confezione: 00012345678905",
    ],
};

/// The sheet in Portuguese.
const PORTUGUESE: Words = Words {
    title: "Os códigos de barras lineares que um pedido pode designar pelo nome",
    heading: "Códigos de barras de oficina, armazém e loja",
    lines: [
        "Abaixo, cada módulo mede um ponto: assim, cada bordo de barra cai num píxel",
        "inteiro da impressora. Sob cada código está o que um leitor ótico lê nele.",
    ],
    captions: [
        "Code 39, a etiqueta da oficina: BAY 12-A",
        "Code 39 com o seu carácter de controlo módulo 43: 159F",
        "Code 93, o mesmo texto em metade do espaço: BAY 12-A",
        "ITF-14, a caixa de transporte que uma loja recebe: 00012345678905",
        "Codabar, a bolsa de sangue e o cartão de leitor: A31600$D",
        "UPC-E, a pequena embalagem norte-americana: 01234565",
        "Uma revista e o número da edição, num código suplementar de dois dígitos: \
9780201379624 53",
        "Um livro e o seu preço, num código suplementar de cinco dígitos: 9781234567897 51999",
        "GS1 DataBar, a carne ao corte e a embalagem pequena: 00012345678905",
    ],
};

/// The sheet in Dutch.
const DUTCH: Words = Words {
    title: "De lineaire streepjescodes die een verzoek bij naam kan opvragen",
    heading: "Streepjescodes voor werkplaats, magazijn en kassa",
    lines: [
        "Hieronder meet één module één punt, zodat elke streeprand op een hele pixel",
        "van de printer valt. Onder elke code staat wat een scanner eruit leest.",
    ],
    captions: [
        "Code 39, het werkplaatsetiket: BAY 12-A",
        "Code 39 met modulo-43-controleteken: 159F",
        "Code 93, dezelfde tekst in half zoveel ruimte: BAY 12-A",
        "ITF-14, de omdoos die een winkel binnenkrijgt: 00012345678905",
        "Codabar, de bloedzak en de bibliotheekpas: A31600$D",
        "UPC-E, de kleine Noord-Amerikaanse verpakking: 01234565",
        "Een tijdschrift, met het nummer in een aanvullende code van twee cijfers: \
9780201379624 53",
        "Een boek, met de adviesprijs in een aanvullende code van vijf cijfers: \
9781234567897 51999",
        "GS1 DataBar, los verkocht vlees en de kleine verpakking: 00012345678905",
    ],
};

/// Every language the example is written in. A language is added by writing its
/// own set of words and naming it here.
static WORDS: [(Language, &Words); 7] = [
    (Language::English, &ENGLISH),
    (Language::French, &FRENCH),
    (Language::German, &GERMAN),
    (Language::Spanish, &SPANISH),
    (Language::Italian, &ITALIAN),
    (Language::Portuguese, &PORTUGUESE),
    (Language::Dutch, &DUTCH),
];

/// The box a block of words goes in, and how it is set.
struct Block {
    size: f64,
    left: f64,
    top: f64,
    width: f64,
    set: Option<(f64, Align)>,
}

/// The box a code goes in: its lower-left corner and how far it runs.
struct Box2 {
    left: f64,
    low: f64,
    width: f64,
    height: f64,
}

fn main() -> std::process::ExitCode {
    failure::reported(run())
}

/// Writes the file, and says where it went.
fn run() -> Result<(), Box<dyn std::error::Error>> {
    let language = Language::from_environment()?;
    let words = Words::of(language);

    let mut args = env::args().skip(1);
    // A named file is written as named; the default one carries the language,
    // so the languages do not overwrite each other in `tmp/`.
    let path = args
        .next()
        .unwrap_or_else(|| language.file_name(&out::default_path("barcodes")));
    let font_path = args.next().map_or_else(default_font, PathBuf::from);

    let mut doc = Document::new();
    doc.set_license(licence::licensed());
    doc.set_info(hqf_pdf::cos::Name::new("Title"), words.title);

    let font = doc.add_font(Font::parse(fs::read(&font_path)?)?);
    doc.add_page(sheet(&font, words)?)?;

    let bytes = doc.to_bytes()?;
    if let Some(parent) = Path::new(&path).parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, &bytes)?;
    println!("wrote {path}: {} bytes", bytes.len());
    Ok(())
}

/// The one page: every code, each under the words that name it.
fn sheet(font: &FontHandle, words: &Words) -> Result<Page, Error> {
    let mut c = Content::new();

    run_1(&mut c, font, words)?;
    run_2(&mut c, font, words)?;
    run_3(&mut c, font, words)?;
    run_4(&mut c, font, words)?;
    run_5(&mut c, font, words)?;

    let mut page = Page::a4();
    page.content = c.into_bytes();
    Ok(page)
}

/// The 1ᵗʰ run of what the page draws, in order.
fn run_1(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    block(
        c,
        font,
        &Block {
            size: 16.0,
            left: 72.000,
            top: 813.200,
            width: 451.276,
            set: None,
        },
        words.heading,
    )?;
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 72.000,
            top: 782.600,
            width: 451.276,
            set: None,
        },
        words.lines[0],
    )?;
    block(
        c,
        font,
        &Block {
            size: 10.5,
            left: 72.000,
            top: 767.600,
            width: 451.276,
            set: None,
        },
        words.lines[1],
    )?;
    bars(
        c,
        &Code39::new("BAY 12-A")?,
        Content::draw_code39,
        &Box2 {
            left: 72.000,
            low: 690.000,
            width: 179.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 684.000,
            width: 451.276,
            set: None,
        },
        words.captions[0],
    )?;
    Ok(())
}

/// The 2ᵗʰ run of what the page draws, in order.
fn run_2(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    bars(
        c,
        &Code39::with_check_digit("159")?,
        Content::draw_code39,
        &Box2 {
            left: 72.000,
            low: 618.000,
            width: 115.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 612.000,
            width: 451.276,
            set: None,
        },
        words.captions[1],
    )?;
    bars(
        c,
        &Code93::new("BAY 12-A")?,
        Content::draw_code93,
        &Box2 {
            left: 72.000,
            low: 546.000,
            width: 129.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 540.000,
            width: 451.276,
            set: None,
        },
        words.captions[2],
    )?;
    bars(
        c,
        &Itf14::new("00012345678905")?,
        Content::draw_itf14,
        &Box2 {
            left: 72.000,
            low: 474.000,
            width: 155.000,
            height: 40.000,
        },
    )?;
    Ok(())
}

/// The 3ᵗʰ run of what the page draws, in order.
fn run_3(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 468.000,
            width: 451.276,
            set: None,
        },
        words.captions[3],
    )?;
    bars(
        c,
        &Codabar::new("A31600$D")?,
        Content::draw_codabar,
        &Box2 {
            left: 72.000,
            low: 402.000,
            width: 119.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 396.000,
            width: 451.276,
            set: None,
        },
        words.captions[4],
    )?;
    bars(
        c,
        &UpcE::new("01234565")?,
        Content::draw_upc_e,
        &Box2 {
            left: 72.000,
            low: 330.000,
            width: 71.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 324.000,
            width: 451.276,
            set: None,
        },
        words.captions[5],
    )?;
    Ok(())
}

/// The 4ᵗʰ run of what the page draws, in order.
fn run_4(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    bars(
        c,
        &Ean13::new("9780201379624")?,
        Content::draw_ean13,
        &Box2 {
            left: 72.000,
            low: 258.000,
            width: 115.000,
            height: 40.000,
        },
    )?;
    bars(
        c,
        &AddOn2::new("53")?,
        Content::draw_add_on2,
        &Box2 {
            left: 176.000,
            low: 258.000,
            width: 40.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 252.000,
            width: 451.276,
            set: None,
        },
        words.captions[6],
    )?;
    bars(
        c,
        &Ean13::new("9781234567897")?,
        Content::draw_ean13,
        &Box2 {
            left: 72.000,
            low: 186.000,
            width: 115.000,
            height: 40.000,
        },
    )?;
    bars(
        c,
        &AddOn5::new("51999")?,
        Content::draw_add_on5,
        &Box2 {
            left: 176.000,
            low: 186.000,
            width: 67.000,
            height: 40.000,
        },
    )?;
    Ok(())
}

/// The 5ᵗʰ run of what the page draws, in order.
fn run_5(c: &mut Content, font: &FontHandle, words: &Words) -> Result<(), Error> {
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 180.000,
            width: 451.276,
            set: None,
        },
        words.captions[7],
    )?;
    bars(
        c,
        &DataBar::new("00012345678905")?,
        Content::draw_data_bar,
        &Box2 {
            left: 72.000,
            low: 114.000,
            width: 116.000,
            height: 40.000,
        },
    )?;
    block(
        c,
        font,
        &Block {
            size: 9.0,
            left: 72.000,
            top: 108.000,
            width: 451.276,
            set: None,
        },
        words.captions[8],
    )?;
    Ok(())
}

/// Draws one block of words in the box it is given.
fn block(c: &mut Content, font: &FontHandle, at: &Block, text: &str) -> Result<(), Error> {
    let mut flow = TextFlow::new(font, at.size);
    if let Some((leading, align)) = at.set {
        flow = flow.leading(leading).align(align);
    }
    let lines = flow.break_lines(text, at.width);
    c.begin_text();
    flow.draw(c, &lines, at.left, at.top, at.width)?;
    c.end_text();
    Ok(())
}

/// What one symbology's drawing method looks like: the content it draws into,
/// the code, where it goes and how big.
type Drawn<T> =
    for<'a> fn(&'a mut Content, &T, f64, f64, f64, f64) -> Result<&'a mut Content, Error>;

/// Draws one code in the box it is given, with a margin of `QUIET_ZONE` modules
/// each side and the bars taking the rest of the width.
fn bars<T>(c: &mut Content, code: &T, drawn: Drawn<T>, at: &Box2) -> Result<(), Error>
where
    T: Modules,
{
    let modules = f64::from(u32::try_from(code.count()).unwrap_or(u32::MAX));
    let quiet = f64::from(u32::try_from(QUIET_ZONE).unwrap_or(u32::MAX));
    let unit = at.width / modules.mul_add(1.0, 2.0 * quiet);
    c.save_state();
    c.set_fill_rgb(0.0, 0.0, 0.0)?;
    drawn(
        c,
        code,
        quiet.mul_add(unit, at.left),
        at.low,
        modules * unit,
        at.height,
    )?;
    let _ = c;
    c.restore_state();
    Ok(())
}

/// How many modules a code is made of, whatever its symbology.
trait Modules {
    fn count(&self) -> usize;
}

impl Modules for AddOn2 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for AddOn5 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for Codabar {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for Code39 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for Code93 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for DataBar {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for Ean13 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for Itf14 {
    fn count(&self) -> usize {
        self.module_count()
    }
}

impl Modules for UpcE {
    fn count(&self) -> usize {
        self.module_count()
    }
}

#[cfg(test)]
mod tests {
    use hqf_pdf::{Document, Font, TextFlow};

    use super::{WORDS, default_font, language};

    /// The width every block of words on the sheet is set in.
    const WIDTH: f64 = 451.276;

    /// The lines two languages are allowed to write the same way. What the
    /// codes carry is read by a scanner and stands apart from `Words`, and no
    /// two languages say the rest alike.
    const SPARED: [&str; 0] = [];

    #[test]
    fn every_language_writes_the_sheet_in_its_own_words() {
        let untranslated = language::untranslated_lines(&WORDS, &SPARED);

        assert!(
            untranslated.is_empty(),
            "the sheet says these in more than one language: {untranslated:?}"
        );
    }

    /// Each block is set on one line, a code standing a fixed step under it. A
    /// block broken onto a second line is drawn over the code below it.
    #[test]
    fn every_block_of_every_language_stays_on_one_line() {
        let mut doc = Document::new();
        let font = doc.add_font(
            Font::parse(std::fs::read(default_font()).expect("the committed font is there"))
                .expect("the committed font parses"),
        );

        for (named, words) in WORDS {
            let blocks = std::iter::once((16.0, words.heading))
                .chain(words.lines.map(|line| (10.5, line)))
                .chain(words.captions.map(|caption| (9.0, caption)));
            for (size, text) in blocks {
                let lines = TextFlow::new(&font, size).break_lines(text, WIDTH).len();
                assert_eq!(
                    lines,
                    1,
                    "the {} sheet breaks {text:?} onto {lines} lines",
                    named.code()
                );
            }
        }
    }
}