iso-7064 0.2.2

A Rust implementation of ISO/IEC 7064:2003 Check character systems
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
//! The [`System`] structure providing a check character system interface.
//!
//! ```rust
//! use iso_7064::{accumulator, charset, system::System};
//!
//! // Build a custom MOD 11,10 with case-insensitive alphabetic character set.
//! let my_mod11_10 =
//!     System::<1, accumulator::Mod11_10, _, _>::with_charset(charset::Alphabetic, |c: char| {
//!         c.to_digit(36)?.checked_sub(10)
//!     });
//!
//! assert_eq!(my_mod11_10.compute("AhJe")?, ['F']);
//! assert!(my_mod11_10.verify("aHjEf")?);
//! assert!(my_mod11_10.verify("AhJe5").is_err());
//! # Ok::<_, Box<dyn core::error::Error>>(())
//! ```

use core::{error, fmt, marker};

#[cfg(feature = "alloc")]
extern crate alloc;

use crate::accumulator::{self, AccumulateResult, Accumulator};
use crate::charset::{self, Decoder, Encoder};

/// A generic facade structure combining [`Accumulator`] and character set into a check character
/// system interface.
///
/// This type provides computation and verification methods for four types of input as follows. Each
/// method has its `_lax` variant that ignores any invalid characters in the input, rather than
/// reporting an error.
///
/// | Input           | Computation method                                   | Verification method                                |
/// | --------------- | ---------------------------------------------------- | -------------------------------------------------- |
/// | `&mut String`   | [`protect`](System::protect)                         | N/A                                                |
/// | `&str`          | [`compute`](System::compute)                         | [`verify`](System::verify)                         |
/// | `char` iterator | [`compute_from_chars`](System::compute_from_chars)   | [`verify_from_chars`](System::verify_from_chars)   |
/// | `u32` iterator  | [`compute_from_values`](System::compute_from_values) | [`verify_from_values`](System::verify_from_values) |
#[derive(Debug, Default)]
pub struct System<const N_CC: usize, Acc, Enc, Dec> {
    _acc: marker::PhantomData<Acc>,
    encoder: Enc,
    decoder: Dec,
}

impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
where
    Acc: Accumulator<Computed = [u32; N_CC]> + Default,
    Enc: Encoder,
    Dec: Decoder,
{
    /// Computes the check characters for the string `s` and appends them.
    ///
    /// # Errors
    ///
    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
    /// set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD11_2;
    ///
    /// let mut buf = String::from("327");
    /// MOD11_2.protect(&mut buf)?;
    /// assert_eq!(buf, "327X");
    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[cfg(feature = "alloc")]
    #[track_caller]
    pub fn protect(&self, s: &mut alloc::string::String) -> Result<(), ComputeError<char>> {
        self.compute(s).map(|cc| s.extend(cc))
    }

    /// Computes the check characters for the string `s` and appends them, ignoring any invalid
    /// characters.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD11_2;
    ///
    /// let mut buf = String::from("3.2.7.");
    /// MOD11_2.protect_lax(&mut buf);
    /// assert_eq!(buf, "3.2.7.X");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[cfg(feature = "alloc")]
    #[track_caller]
    pub fn protect_lax(&self, s: &mut alloc::string::String) {
        s.extend(self.compute_lax(s));
    }

    /// Computes the check characters for the string `s`.
    ///
    /// # Errors
    ///
    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
    /// set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD37_2;
    ///
    /// assert_eq!(MOD37_2.compute("5S7U")?, ['G']);
    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[track_caller]
    pub fn compute(&self, s: &str) -> Result<[char; N_CC], ComputeError<char>> {
        self.compute_from_chars(s.chars())
    }

    /// Computes the check characters for the string `s`, ignoring any invalid characters.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD37_2;
    ///
    /// assert_eq!(MOD37_2.compute_lax("5S=7U"), ['G']);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[track_caller]
    pub fn compute_lax(&self, s: &str) -> [char; N_CC] {
        self.compute_from_chars_lax(s.chars())
    }

    /// Computes the check characters from an iterator of characters.
    ///
    /// # Errors
    ///
    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
    /// set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD11_10;
    ///
    /// let iter = ['2', '0', '6', '5', '1'];
    /// assert_eq!(MOD11_10.compute_from_chars(iter)?, ['8']);
    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[track_caller]
    pub fn compute_from_chars(
        &self,
        chars: impl IntoIterator<Item = char>,
    ) -> Result<[char; N_CC], ComputeError<char>> {
        let vs = self.compute_from_iter(chars)?;
        Ok(self.encode_computed(vs))
    }

    /// Computes the check characters from an iterator of characters, ignoring any invalid
    /// characters.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD11_10;
    ///
    /// let iter = ['2', '0', '-', '6', '5', '-', '1', '.'];
    /// assert_eq!(MOD11_10.compute_from_chars_lax(iter), ['8']);
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
    /// pair such that the encoder cannot encode check character values produced by the accumulator.
    #[track_caller]
    pub fn compute_from_chars_lax(&self, chars: impl IntoIterator<Item = char>) -> [char; N_CC] {
        let vs = self.lax_from_iter(chars).compute();
        self.encode_computed(vs)
    }

    #[track_caller]
    fn encode_computed(&self, values: [u32; N_CC]) -> [char; N_CC] {
        const ERR: &str = "invalid charset implementation";
        let mut chars = [char::default(); N_CC];
        for (p, v) in chars.iter_mut().zip(values) {
            *p = self.encoder.encode(v).expect(ERR);
        }
        chars
    }
}

impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
where
    Acc: Accumulator + Default,
    Dec: Decoder,
{
    /// Verifies whether the check characters in the string `s` are valid.
    ///
    /// # Errors
    ///
    /// Returns a [`VerifyError`] if the input contains any character that is not in the character
    /// set, or if a supplementary check character (e.g., `X` or `*`) is found before the end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD661_26;
    ///
    /// assert!(MOD661_26.verify("MVEISJV")?);
    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
    /// ```
    pub fn verify(&self, s: &str) -> Result<bool, VerifyError<char>> {
        self.verify_from_chars(s.chars())
    }

    /// Verifies whether the check characters in the string `s` are valid, ignoring any invalid
    /// characters.
    ///
    /// For this purpose, supplementary check characters (e.g., `X` or `*`) found before the end are
    /// regarded as invalid and ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD661_26;
    ///
    /// assert!(MOD661_26.verify_lax("MV-EIS:JV"));
    /// ```
    pub fn verify_lax(&self, s: &str) -> bool {
        self.verify_from_chars_lax(s.chars())
    }

    /// Verifies whether the check characters in the iterator of characters are valid.
    ///
    /// # Errors
    ///
    /// Returns a [`VerifyError`] if the input contains any character that is not in the character
    /// set, or if a supplementary check character (e.g., `X` or `*`) is found before the end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD97_10;
    ///
    /// let iter = "3793".chars().chain(['6', '8']);
    /// assert!(MOD97_10.verify_from_chars(iter)?);
    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
    /// ```
    pub fn verify_from_chars(
        &self,
        chars: impl IntoIterator<Item = char>,
    ) -> Result<bool, VerifyError<char>> {
        self.verify_from_iter(chars)
    }

    /// Verifies whether the check characters in the iterator of characters are valid, ignoring any
    /// invalid characters.
    ///
    /// For this purpose, supplementary check characters (e.g., `X` or `*`) found before the end are
    /// regarded as invalid and ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD97_10;
    ///
    /// let iter = "[3793]".chars().chain(['(', '6', '8', ')']);
    /// assert!(MOD97_10.verify_from_chars_lax(iter));
    /// ```
    pub fn verify_from_chars_lax(&self, chars: impl IntoIterator<Item = char>) -> bool {
        self.lax_from_iter(chars).verify()
    }
}

impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
where
    Acc: Accumulator + Default,
{
    /// Computes the check character values from an iterator of numerical values.
    ///
    /// # Errors
    ///
    /// Returns a [`ComputeError`] if the input contains any value that is not in the character set.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD37_36;
    ///
    /// let iter = [21, 14, 5, 34];
    /// assert_eq!(MOD37_36.compute_from_values(iter)?, [17]);
    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
    /// ```
    pub fn compute_from_values(
        &self,
        values: impl IntoIterator<Item = u32>,
    ) -> Result<Acc::Computed, ComputeError<u32>> {
        self.compute_from_iter(values)
    }

    /// Computes the check character values from an iterator of numerical values, ignoring any
    /// invalid values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD37_36;
    ///
    /// let iter = [21, 99, 14, 999, 5, 9999, 34];
    /// assert_eq!(MOD37_36.compute_from_values_lax(iter), [17]);
    /// ```
    pub fn compute_from_values_lax(&self, values: impl IntoIterator<Item = u32>) -> Acc::Computed {
        self.lax_from_iter(values).compute()
    }

    /// Verifies whether the check character values in the iterator of numerical values are valid.
    ///
    /// # Errors
    ///
    /// Returns a [`VerifyError`] if the input contains any value that is not in the character set,
    /// or if a supplementary check character value is found before the end.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD27_26;
    ///
    /// let iter = [2, 13, 17, 11].into_iter().chain([15]);
    /// assert!(MOD27_26.verify_from_values(iter)?);
    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
    /// ```
    pub fn verify_from_values(
        &self,
        values: impl IntoIterator<Item = u32>,
    ) -> Result<bool, VerifyError<u32>> {
        self.verify_from_iter(values)
    }

    /// Verifies whether the check character values in the iterator of numerical values are valid,
    /// ignoring any invalid values.
    ///
    /// For this purpose, supplementary check character values found before the end are regarded as
    /// invalid and ignored.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use iso_7064::MOD27_26;
    ///
    /// let iter = [2, 13, 28, 17, 11].into_iter().chain([29, 15, 30, 31]);
    /// assert!(MOD27_26.verify_from_values_lax(iter));
    /// ```
    pub fn verify_from_values_lax(&self, values: impl IntoIterator<Item = u32>) -> bool {
        self.lax_from_iter(values).verify()
    }

    fn compute_from_iter<T: Accumulatable<Dec> + Copy>(
        &self,
        iter: impl IntoIterator<Item = T>,
    ) -> Result<Acc::Computed, ComputeError<T>> {
        let mut acc = Acc::default();
        for (pos, val) in iter.into_iter().enumerate() {
            let AccumulateResult::Processed = val.accumulate_to(&mut acc, &self.decoder) else {
                return Err(ComputeError { val, pos });
            };
        }
        Ok(acc.compute())
    }

    fn verify_from_iter<T: Accumulatable<Dec> + Copy>(
        &self,
        iter: impl IntoIterator<Item = T>,
    ) -> Result<bool, VerifyError<T>> {
        let mut acc = Acc::default();
        let mut it = iter.into_iter().enumerate();
        while let Some((pos, val)) = it.next() {
            match val.accumulate_to(&mut acc, &self.decoder) {
                AccumulateResult::Processed => (),
                AccumulateResult::SupplFound => match it.next() {
                    None => break,
                    Some(_) => {
                        let kind = VerifyErrorKind::UnexpectedSuppl;
                        return Err(VerifyError { val, pos, kind });
                    }
                },
                AccumulateResult::NotInCharset => {
                    let kind = VerifyErrorKind::NotInCharset;
                    return Err(VerifyError { val, pos, kind });
                }
            }
        }
        Ok(acc.verify())
    }

    fn lax_from_iter<T: Accumulatable<Dec>>(&self, iter: impl IntoIterator<Item = T>) -> Acc {
        let mut acc = Acc::default();
        for val in iter {
            let _ = val.accumulate_to(&mut acc, &self.decoder);
        }
        acc
    }

    /// Creates an instance with [`Encoder`] and [`Decoder`].
    pub const fn with_charset(encoder: Enc, decoder: Dec) -> Self {
        Self {
            _acc: marker::PhantomData,
            encoder,
            decoder,
        }
    }
}

trait Accumulatable<Dec> {
    fn accumulate_to(self, acc: &mut impl Accumulator, decoder: &Dec) -> AccumulateResult;
}

impl<Dec> Accumulatable<Dec> for u32 {
    #[inline]
    fn accumulate_to(self, acc: &mut impl Accumulator, _decoder: &Dec) -> AccumulateResult {
        acc.accumulate(self)
    }
}

impl<Dec: Decoder> Accumulatable<Dec> for char {
    #[inline]
    fn accumulate_to(self, acc: &mut impl Accumulator, decoder: &Dec) -> AccumulateResult {
        match decoder.decode(self) {
            Some(value) => acc.accumulate(value),
            None => AccumulateResult::NotInCharset,
        }
    }
}

/// The ISO/IEC 7064, MOD 11-2 pure system with a single check character.
pub type Mod11_2 = System<1, accumulator::Mod11_2, charset::NumericX, charset::NumericX>;

/// The ISO/IEC 7064, MOD 37-2 pure system with a single check character.
pub type Mod37_2 =
    System<1, accumulator::Mod37_2, charset::AlphanumericAst, charset::AlphanumericAst>;

/// The ISO/IEC 7064, MOD 97-10 pure system with two check characters.
pub type Mod97_10 = System<2, accumulator::Mod97_10, charset::Numeric, charset::Numeric>;

/// The ISO/IEC 7064, MOD 661-26 pure system with two check characters.
pub type Mod661_26 = System<2, accumulator::Mod661_26, charset::Alphabetic, charset::Alphabetic>;

/// The ISO/IEC 7064, MOD 1271-36 pure system with two check characters.
pub type Mod1271_36 =
    System<2, accumulator::Mod1271_36, charset::Alphanumeric, charset::Alphanumeric>;

/// The ISO/IEC 7064, MOD 11,10 hybrid system.
pub type Mod11_10 = System<1, accumulator::Mod11_10, charset::Numeric, charset::Numeric>;

/// The ISO/IEC 7064, MOD 27,26 hybrid system.
pub type Mod27_26 = System<1, accumulator::Mod27_26, charset::Alphabetic, charset::Alphabetic>;

/// The ISO/IEC 7064, MOD 37,36 hybrid system.
pub type Mod37_36 = System<1, accumulator::Mod37_36, charset::Alphanumeric, charset::Alphanumeric>;

/// An error returned when check character computation fails.
#[derive(Debug)]
pub struct ComputeError<T> {
    val: T,
    pos: usize,
}

impl<T: fmt::Debug> fmt::Display for ComputeError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let kind = VerifyErrorKind::NotInCharset;
        write!(f, "{}: {:?} at {}", kind, self.val, self.pos)
    }
}

impl<T: fmt::Debug> error::Error for ComputeError<T> {}

/// An error returned when check character verification fails.
#[derive(Debug)]
pub struct VerifyError<T> {
    val: T,
    pos: usize,
    kind: VerifyErrorKind,
}

impl<T: fmt::Debug> fmt::Display for VerifyError<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {:?} at {}", self.kind, self.val, self.pos)
    }
}

impl<T: fmt::Debug> error::Error for VerifyError<T> {}

/// The specific kind of a verification error.
#[derive(Debug)]
enum VerifyErrorKind {
    /// A character in the input was not found in the character set.
    NotInCharset,

    /// A supplementary check character was found before the end of the input.
    UnexpectedSuppl,
}

impl fmt::Display for VerifyErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotInCharset => f.write_str("char not in charset"),
            Self::UnexpectedSuppl => f.write_str("suppl check char not at end"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "alloc")]
    #[test]
    fn do_not_mutate_on_error() {
        let mod1271_36 = Mod1271_36::default();
        let mut buf = alloc::string::String::from("0 1 2 3");
        assert!(mod1271_36.protect(&mut buf).is_err());
        assert_eq!(buf, "0 1 2 3");
    }

    #[test]
    fn reject_unexpected_suppl() {
        let mod11_2 = Mod11_2::default();
        assert!(mod11_2.compute("012X34").is_err());
        assert!(mod11_2.compute("01234X").is_err());
        assert!(mod11_2.verify("012X34").is_err());
        assert!(mod11_2.verify("01234X").is_ok());
    }

    #[test]
    fn ignore_unexpected_suppl() {
        let mod11_2 = Mod11_2::default();
        assert_eq!(mod11_2.compute_lax("32X37"), ['X']);
        assert_eq!(mod11_2.compute_lax("3237X"), ['X']);
        assert!(mod11_2.verify_lax("32X37X"));
        assert!(mod11_2.verify_lax("3237XX"));
        assert!(mod11_2.verify_lax("3237X"));
    }
}