qrcode-generator 6.0.0

Generates ISO/IEC 18004 QR Code and Micro QR Code symbols and ISO/IEC 23941 rMQR symbols in pure Rust, then renders them as grayscale, PNG and SVG 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
use alloc::{vec, vec::Vec};

#[cfg(feature = "kanji")]
use super::kanji_encoding;
use super::{
    MicroErrorCorrection, MicroMask, MicroVersion, Mode, Segment, Symbol, SymbolVersion,
    alphanumeric_value, bch_remainder, bits::BitBuffer, mode_rank, reed_solomon,
};
use crate::EncodeError;

pub(crate) fn optimize(data: &[u8], version: MicroVersion) -> Result<Vec<Segment>, EncodeError> {
    #[derive(Clone, Copy)]
    struct Step {
        bits:     usize,
        segments: usize,
        previous: usize,
        mode:     Mode,
    }

    // Each offset stores the shortest segmentation using only modes available to this Micro version.
    let mut best = vec![None; data.len() + 1];

    best[0] = Some(Step {
        bits: 0, segments: 0, previous: 0, mode: Mode::Numeric
    });

    for start in 0..data.len() {
        let Some(prefix) = best[start] else {
            continue;
        };

        for &mode in available_modes(version) {
            let Some((indicator_bits, cci_bits)) = mode_parameters(version, mode) else {
                continue;
            };

            let maximum = ((1usize << cci_bits) - 1).min(data.len() - start);

            for count in 1..=maximum {
                let slice = &data[start..start + count];
                let payload_bits = match mode {
                    Mode::Numeric if slice.iter().all(u8::is_ascii_digit) => {
                        count / 3 * 10 + [0, 4, 7][count % 3]
                    },
                    Mode::Alphanumeric
                        if slice.iter().all(|byte| alphanumeric_value(*byte).is_some()) =>
                    {
                        count / 2 * 11 + count % 2 * 6
                    },
                    Mode::Byte => count * 8,
                    _ => break,
                };

                let candidate = Step {
                    bits: prefix.bits + indicator_bits as usize + cci_bits as usize + payload_bits,
                    segments: prefix.segments + 1,
                    previous: start,
                    mode,
                };

                let slot = &mut best[start + count];

                if slot.is_none_or(|current| {
                    (
                        candidate.bits,
                        candidate.segments,
                        mode_rank(candidate.mode),
                        candidate.previous,
                    ) < (current.bits, current.segments, mode_rank(current.mode), current.previous)
                }) {
                    *slot = Some(candidate);
                }
            }
        }
    }

    if let Some(position) = best.iter().position(Option::is_none) {
        return Err(EncodeError::TextNotRepresentable {
            byte_offset: position - 1,
            family:      "Micro QR Code",
        });
    }

    let mut position = data.len();
    let mut ranges = Vec::new();

    while position != 0 {
        let step = best[position].expect("every byte position stays reachable");
        ranges.push((step.previous, position, step.mode));
        position = step.previous;
    }

    ranges.reverse();

    ranges
        .into_iter()
        .map(|(start, end, mode)| match mode {
            Mode::Numeric => Segment::numeric(
                core::str::from_utf8(&data[start..end]).expect("numeric data is UTF-8"),
            ),
            Mode::Alphanumeric => Segment::alphanumeric(
                core::str::from_utf8(&data[start..end]).expect("alphanumeric data is UTF-8"),
            ),
            Mode::Byte => Ok(Segment::bytes(&data[start..end])),
            Mode::Kanji | Mode::Eci => unreachable!(),
        })
        .collect()
}

pub(crate) fn optimize_text(
    text: &str,
    version: MicroVersion,
) -> Result<Vec<Segment>, EncodeError> {
    #[derive(Clone, Copy)]
    struct Step {
        bits:     usize,
        segments: usize,
        previous: usize,
        mode:     Mode,
    }

    let mut offsets: Vec<_> = text.char_indices().map(|(offset, _)| offset).collect();

    offsets.push(text.len());

    let length = offsets.len() - 1;

    #[cfg(feature = "kanji")]
    let kanji: Vec<bool> =
        text.chars().map(|character| kanji_encoding(character).is_some()).collect();

    // Scalar boundaries keep multibyte UTF-8 characters intact while evaluating Kanji mode.
    let mut best = vec![None; length + 1];

    best[0] = Some(Step {
        bits: 0, segments: 0, previous: 0, mode: Mode::Numeric
    });

    for start in 0..length {
        let Some(prefix) = best[start] else {
            continue;
        };

        for mode in [Mode::Numeric, Mode::Alphanumeric, Mode::Byte, Mode::Kanji] {
            let Some((indicator, cci)) = mode_parameters(version, mode) else {
                continue;
            };

            let maximum = (1usize << cci) - 1;

            for end in start + 1..=length.min(start + maximum) {
                let slice = &text[offsets[start]..offsets[end]];

                let payload = match mode {
                    Mode::Numeric if slice.bytes().all(|byte| byte.is_ascii_digit()) => {
                        let count = end - start;
                        count / 3 * 10 + [0, 4, 7][count % 3]
                    },
                    Mode::Alphanumeric
                        if slice.is_ascii()
                            && slice.bytes().all(|byte| alphanumeric_value(byte).is_some()) =>
                    {
                        let count = end - start;
                        count / 2 * 11 + count % 2 * 6
                    },
                    Mode::Byte if slice.chars().all(|character| u32::from(character) <= 0xFF) => {
                        (end - start) * 8
                    },
                    #[cfg(feature = "kanji")]
                    Mode::Kanji if kanji[end - 1] => (end - start) * 13,
                    _ => break,
                };

                let candidate = Step {
                    bits: prefix.bits + indicator as usize + cci as usize + payload,
                    segments: prefix.segments + 1,
                    previous: start,
                    mode,
                };

                let slot = &mut best[end];

                if slot.is_none_or(|current| {
                    (
                        candidate.bits,
                        candidate.segments,
                        mode_rank(candidate.mode),
                        candidate.previous,
                    ) < (current.bits, current.segments, mode_rank(current.mode), current.previous)
                }) {
                    *slot = Some(candidate);
                }
            }
        }
    }

    if let Some(position) = best.iter().position(Option::is_none) {
        return Err(EncodeError::TextNotRepresentable {
            byte_offset: offsets[position - 1],
            family:      "Micro QR Code",
        });
    }

    let mut position = length;
    let mut ranges = Vec::new();

    while position != 0 {
        let step = best[position].expect("every text position is reachable");
        ranges.push((step.previous, position, step.mode));
        position = step.previous;
    }

    ranges.reverse();

    ranges
        .into_iter()
        .map(|(start, end, mode)| {
            let slice = &text[offsets[start]..offsets[end]];
            match mode {
                Mode::Numeric => Segment::numeric(slice),
                Mode::Alphanumeric => Segment::alphanumeric(slice),
                Mode::Byte => Ok(Segment::bytes(
                    slice.chars().map(|character| character as u8).collect::<Vec<_>>(),
                )),
                #[cfg(feature = "kanji")]
                Mode::Kanji => Segment::kanji(slice),
                #[cfg(not(feature = "kanji"))]
                Mode::Kanji => unreachable!(),
                Mode::Eci => unreachable!(),
            }
        })
        .collect()
}

pub(crate) fn encode(
    segments: &[Segment],
    version: MicroVersion,
    mut error_correction: MicroErrorCorrection,
    requested_mask: Option<MicroMask>,
    boost_error_correction: bool,
) -> Result<Symbol, EncodeError> {
    // DetectionOnly is intentionally M1-only, so other versions reject it here instead of upgrading it to Low.
    let mut capacity_info =
        capacity(version, error_correction).ok_or(EncodeError::UnsupportedErrorCorrection {
            version:          SymbolVersion::Micro(version),
            error_correction: error_correction.into(),
        })?;
    let used_bits = total_bits(segments, version)?;

    if used_bits > capacity_info.data_bits {
        return Err(EncodeError::DataTooLong {
            required_bits: Some(used_bits),
            capacity_bits: capacity_info.data_bits,
        });
    }

    if boost_error_correction {
        for candidate in [MicroErrorCorrection::Medium, MicroErrorCorrection::Quartile] {
            if candidate > error_correction
                && let Some(candidate_capacity) = capacity(version, candidate)
                && used_bits <= candidate_capacity.data_bits
            {
                error_correction = candidate;
                capacity_info = candidate_capacity;
            }
        }
    }

    let mut data_bits = BitBuffer::with_capacity(capacity_info.data_bits);

    for segment in segments {
        let (indicator_bits, cci_bits) =
            mode_parameters(version, segment.mode).ok_or(EncodeError::UnsupportedMode {
                mode:   mode_name(segment.mode),
                family: "the selected Micro QR version",
            })?;

        if indicator_bits != 0 {
            data_bits.append(mode_indicator(version, segment.mode), indicator_bits);
        }

        data_bits.append(segment.character_count as u32, cci_bits);
        data_bits.extend(&segment.bits);
    }

    let terminator = match version {
        MicroVersion::M1 => 3,
        MicroVersion::M2 => 5,
        MicroVersion::M3 => 7,
        MicroVersion::M4 => 9,
    };

    data_bits.append(0, (capacity_info.data_bits - data_bits.len()).min(terminator) as u8);

    while data_bits.len() < capacity_info.data_bits && data_bits.len() & 7 != 0 {
        data_bits.push(false);
    }

    let mut pad = true;

    while data_bits.len() + 8 <= capacity_info.data_bits {
        data_bits.append(if pad { 0xEC } else { 0x11 }, 8);
        pad = !pad;
    }

    while data_bits.len() < capacity_info.data_bits {
        data_bits.push(false);
    }

    // M1 and M3 pad the final four data bits only while calculating the Reed-Solomon remainder.
    let data_bytes = data_bits.clone().into_padded_bytes();
    let ecc =
        reed_solomon::remainder(&data_bytes, &reed_solomon::divisor(capacity_info.ecc_codewords));
    let mut final_bits = data_bits;

    for byte in ecc {
        final_bits.append(u32::from(byte), 8);
    }

    debug_assert_eq!(
        final_bits.len(),
        version.size() * version.size() - function_module_count(version) - 15
    );

    let mut matrix = Matrix::new(version, error_correction);

    matrix.draw_data(&final_bits);

    let mask = if let Some(mask) = requested_mask {
        mask.value()
    } else {
        // Micro QR selects the candidate with the highest dark-edge score.
        let mut best_mask = 0;
        let mut best_score = -1;

        for candidate in 0..4 {
            matrix.apply_mask(candidate);

            // The score only reads the right column and bottom row, which never hold format modules.
            let score = matrix.score();

            if score > best_score {
                best_mask = candidate;
                best_score = score;
            }

            matrix.apply_mask(candidate);
        }

        best_mask
    };

    matrix.apply_mask(mask);
    matrix.draw_format(mask);

    Ok(Symbol {
        version: SymbolVersion::Micro(version),
        error_correction: error_correction.into(),
        mask,
        modules: matrix.modules,
        #[cfg(feature = "qr")]
        structured_append: None,
    })
}

fn total_bits(segments: &[Segment], version: MicroVersion) -> Result<usize, EncodeError> {
    let mut result = 0usize;

    for segment in segments {
        let (indicator, cci) =
            mode_parameters(version, segment.mode).ok_or(EncodeError::UnsupportedMode {
                mode:   mode_name(segment.mode),
                family: "the selected Micro QR version",
            })?;

        if segment.character_count >= 1usize << cci {
            return Err(EncodeError::DataTooLong {
                required_bits: None, capacity_bits: 0
            });
        }

        result = result.checked_add(indicator as usize + cci as usize + segment.bits.len()).ok_or(
            EncodeError::DataTooLong {
                required_bits: None, capacity_bits: 0
            },
        )?;
    }
    Ok(result)
}

#[inline]
const fn available_modes(version: MicroVersion) -> &'static [Mode] {
    match version {
        MicroVersion::M1 => &[Mode::Numeric],
        MicroVersion::M2 => &[Mode::Numeric, Mode::Alphanumeric],
        MicroVersion::M3 | MicroVersion::M4 => &[Mode::Numeric, Mode::Alphanumeric, Mode::Byte],
    }
}

#[inline]
const fn mode_parameters(version: MicroVersion, mode: Mode) -> Option<(u8, u8)> {
    let indicator = match version {
        MicroVersion::M1 => 0,
        MicroVersion::M2 => 1,
        MicroVersion::M3 => 2,
        MicroVersion::M4 => 3,
    };

    let cci = match (version, mode) {
        (MicroVersion::M1, Mode::Numeric) => 3,
        (MicroVersion::M2, Mode::Numeric) => 4,
        (MicroVersion::M2, Mode::Alphanumeric) => 3,
        (MicroVersion::M3, Mode::Numeric) => 5,
        (MicroVersion::M3, Mode::Alphanumeric | Mode::Byte) => 4,
        (MicroVersion::M3, Mode::Kanji) => 3,
        (MicroVersion::M4, Mode::Numeric) => 6,
        (MicroVersion::M4, Mode::Alphanumeric | Mode::Byte) => 5,
        (MicroVersion::M4, Mode::Kanji) => 4,
        _ => return None,
    };
    Some((indicator, cci))
}

#[inline]
const fn mode_indicator(version: MicroVersion, mode: Mode) -> u32 {
    match (version, mode) {
        (MicroVersion::M1, Mode::Numeric)
        | (MicroVersion::M2, Mode::Numeric)
        | (MicroVersion::M3, Mode::Numeric)
        | (MicroVersion::M4, Mode::Numeric) => 0,
        (MicroVersion::M2, Mode::Alphanumeric)
        | (MicroVersion::M3, Mode::Alphanumeric)
        | (MicroVersion::M4, Mode::Alphanumeric) => 1,
        (MicroVersion::M3, Mode::Byte) | (MicroVersion::M4, Mode::Byte) => 2,
        (MicroVersion::M3, Mode::Kanji) | (MicroVersion::M4, Mode::Kanji) => 3,
        _ => unreachable!(),
    }
}

#[inline]
const fn mode_name(mode: Mode) -> &'static str {
    match mode {
        Mode::Numeric => "numeric",
        Mode::Alphanumeric => "alphanumeric",
        Mode::Byte => "byte",
        Mode::Kanji => "Kanji",
        Mode::Eci => "ECI",
    }
}

#[derive(Clone, Copy)]
struct Capacity {
    data_bits:     usize,
    ecc_codewords: usize,
}

#[inline]
const fn capacity(
    version: MicroVersion,
    error_correction: MicroErrorCorrection,
) -> Option<Capacity> {
    let values = match (version, error_correction) {
        (MicroVersion::M1, MicroErrorCorrection::DetectionOnly) => (20, 2),
        (MicroVersion::M2, MicroErrorCorrection::Low) => (40, 5),
        (MicroVersion::M2, MicroErrorCorrection::Medium) => (32, 6),
        (MicroVersion::M3, MicroErrorCorrection::Low) => (84, 6),
        (MicroVersion::M3, MicroErrorCorrection::Medium) => (68, 8),
        (MicroVersion::M4, MicroErrorCorrection::Low) => (128, 8),
        (MicroVersion::M4, MicroErrorCorrection::Medium) => (112, 10),
        (MicroVersion::M4, MicroErrorCorrection::Quartile) => (80, 14),
        _ => return None,
    };

    Some(Capacity {
        data_bits: values.0, ecc_codewords: values.1
    })
}

#[inline]
pub(crate) const fn input_capacity_upper_bound(
    version: MicroVersion,
    error_correction: MicroErrorCorrection,
) -> Option<(usize, usize)> {
    let Some(capacity) = capacity(version, error_correction) else {
        return None;
    };
    let Some((indicator_bits, cci_bits)) = mode_parameters(version, Mode::Numeric) else {
        return None;
    };
    let overhead_bits = indicator_bits as usize + cci_bits as usize;

    Some((super::numeric_character_capacity(capacity.data_bits, overhead_bits), capacity.data_bits))
}

#[inline]
const fn function_module_count(version: MicroVersion) -> usize {
    match version {
        MicroVersion::M1 => 70,
        MicroVersion::M2 => 74,
        MicroVersion::M3 => 78,
        MicroVersion::M4 => 82,
    }
}

struct Matrix {
    version:          MicroVersion,
    error_correction: MicroErrorCorrection,
    size:             usize,
    modules:          Vec<bool>,
    function:         Vec<bool>,
}

impl Matrix {
    fn new(version: MicroVersion, error_correction: MicroErrorCorrection) -> Self {
        let size = version.size();
        let mut result = Self {
            version,
            error_correction,
            size,
            modules: vec![false; size * size],
            function: vec![false; size * size],
        };

        for y in 0..7 {
            for x in 0..7 {
                let distance = (x as isize - 3).abs().max((y as isize - 3).abs());

                result.set_function(x, y, distance == 3 || distance <= 1);
            }
        }

        for coordinate in 0..=7 {
            result.set_function(coordinate, 7, false);
            result.set_function(7, coordinate, false);
        }

        for coordinate in 8..size {
            result.set_function(coordinate, 0, (coordinate - 8) % 2 == 0);
            result.set_function(0, coordinate, (coordinate - 8) % 2 == 0);
        }

        for offset in 0..8 {
            result.set_function(8, 1 + offset, false);
        }

        for offset in 0..7 {
            result.set_function(7 - offset, 8, false);
        }

        result
    }

    fn draw_data(&mut self, bits: &BitBuffer) {
        // Micro QR uses alternating two-column stripes without the Model 2 timing-column skip.
        let mut index = 0;
        let mut right = self.size - 1;
        let mut upward = true;

        while right >= 1 {
            for vertical in 0..self.size {
                let y = if upward { self.size - 1 - vertical } else { vertical };

                for offset in 0..2 {
                    let x = right - offset;
                    let module = y * self.size + x;
                    if !self.function[module] && index < bits.len() {
                        self.modules[module] = bits.bit(index);
                        index += 1;
                    }
                }
            }

            if right < 2 {
                break;
            }

            right -= 2;
            upward = !upward;
        }

        debug_assert_eq!(index, bits.len());
    }

    fn apply_mask(&mut self, mask: u8) {
        for y in 0..self.size {
            for x in 0..self.size {
                let invert = match mask {
                    0 => y % 2 == 0,
                    1 => (y / 2 + x / 3) % 2 == 0,
                    2 => (y * x % 2 + y * x % 3) % 2 == 0,
                    3 => ((y + x) % 2 + y * x % 3) % 2 == 0,
                    _ => unreachable!(),
                };

                let index = y * self.size + x;

                if invert && !self.function[index] {
                    self.modules[index] = !self.modules[index];
                }
            }
        }
    }

    fn draw_format(&mut self, mask: u8) {
        let data = u32::from(symbol_number(self.version, self.error_correction) << 2 | mask);
        let bits = (data << 10 | bch_remainder(data, 0x537, 10)) ^ 0x4445;

        for offset in 0..8 {
            self.set_function(8, 1 + offset, bits >> offset & 1 != 0);
        }

        for offset in 0..7 {
            self.set_function(7 - offset, 8, bits >> (8 + offset) & 1 != 0);
        }
    }

    fn score(&self) -> i32 {
        // The smaller edge count is the high-order part so balanced dark edges score better.
        let right =
            (1..self.size).filter(|&y| self.modules[y * self.size + self.size - 1]).count() as i32;

        let bottom = (1..self.size)
            .filter(|&x| self.modules[(self.size - 1) * self.size + x])
            .count() as i32;

        16 * right.min(bottom) + right.max(bottom)
    }

    #[inline]
    fn set_function(&mut self, x: usize, y: usize, value: bool) {
        let index = y * self.size + x;

        self.modules[index] = value;
        self.function[index] = true;
    }
}

#[inline]
const fn symbol_number(version: MicroVersion, error_correction: MicroErrorCorrection) -> u8 {
    match (version, error_correction) {
        (MicroVersion::M1, MicroErrorCorrection::DetectionOnly) => 0,
        (MicroVersion::M2, MicroErrorCorrection::Low) => 1,
        (MicroVersion::M2, MicroErrorCorrection::Medium) => 2,
        (MicroVersion::M3, MicroErrorCorrection::Low) => 3,
        (MicroVersion::M3, MicroErrorCorrection::Medium) => 4,
        (MicroVersion::M4, MicroErrorCorrection::Low) => 5,
        (MicroVersion::M4, MicroErrorCorrection::Medium) => 6,
        (MicroVersion::M4, MicroErrorCorrection::Quartile) => 7,
        _ => unreachable!(),
    }
}