Skip to main content

iso_7064/
system.rs

1//! The [`System`] structure providing a check character system interface.
2//!
3//! ```rust
4//! use iso_7064::{accumulator, charset, system::System};
5//!
6//! // Build a custom MOD 11,10 that decodes a letter into two digits (e.g., 'A' -> [1, 0]).
7//! let my_mod11_10: System<1, accumulator::Mod11_10, _, _> =
8//!     System::with_charset(charset::Numeric, |c: char| {
9//!         c.to_digit(36).map(|v| match v {
10//!             ..=9 => [v, 0].into_iter().take(1),
11//!             10.. => [v / 10, v % 10].into_iter().take(2),
12//!         })
13//!     });
14//!
15//! assert_eq!(my_mod11_10.compute("FGR895")?, ['0']);
16//! assert!(my_mod11_10.verify("fgr8950")?);
17//! # Ok::<_, Box<dyn core::error::Error>>(())
18//! ```
19
20use core::{error, fmt, marker};
21
22#[cfg(feature = "alloc")]
23extern crate alloc;
24
25use crate::accumulator::{self, AccumulateResult, Accumulator};
26use crate::charset::{self, Decoder, Encoder};
27
28/// A generic facade structure combining [`Accumulator`] and character set into a check character
29/// system interface.
30///
31/// This type provides computation and verification methods for four types of input as follows. Each
32/// method has its `_lax` variant that ignores any invalid characters in the input, rather than
33/// reporting an error.
34///
35/// | Input           | Computation method                                   | Verification method                                |
36/// | --------------- | ---------------------------------------------------- | -------------------------------------------------- |
37/// | `&mut String`   | [`protect`](System::protect)                         | N/A                                                |
38/// | `&str`          | [`compute`](System::compute)                         | [`verify`](System::verify)                         |
39/// | `char` iterator | [`compute_from_chars`](System::compute_from_chars)   | [`verify_from_chars`](System::verify_from_chars)   |
40/// | `u32` iterator  | [`compute_from_values`](System::compute_from_values) | [`verify_from_values`](System::verify_from_values) |
41#[derive(Debug, Default)]
42pub struct System<const N_CC: usize, Acc, Enc, Dec> {
43    _acc: marker::PhantomData<Acc>,
44    encoder: Enc,
45    decoder: Dec,
46}
47
48impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
49where
50    Acc: Accumulator<Computed = [u32; N_CC]> + Default,
51    Enc: Encoder,
52    Dec: Decoder<Decoded: IntoIterator<Item = u32>>,
53{
54    /// Computes the check characters for the string `s` and appends them.
55    ///
56    /// # Errors
57    ///
58    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
59    /// set.
60    ///
61    /// # Examples
62    ///
63    /// ```rust
64    /// use iso_7064::MOD11_2;
65    ///
66    /// let mut buf = String::from("327");
67    /// MOD11_2.protect(&mut buf)?;
68    /// assert_eq!(buf, "327X");
69    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
70    /// ```
71    ///
72    /// # Panics
73    ///
74    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
75    /// pair such that the encoder cannot encode check character values produced by the accumulator.
76    #[cfg(feature = "alloc")]
77    #[track_caller]
78    pub fn protect(&self, s: &mut alloc::string::String) -> Result<(), ComputeError<char>> {
79        self.compute(s).map(|cc| s.extend(cc))
80    }
81
82    /// Computes the check characters for the string `s` and appends them, ignoring any invalid
83    /// characters.
84    ///
85    /// # Examples
86    ///
87    /// ```rust
88    /// use iso_7064::MOD11_2;
89    ///
90    /// let mut buf = String::from("3.2.7.");
91    /// MOD11_2.protect_lax(&mut buf);
92    /// assert_eq!(buf, "3.2.7.X");
93    /// ```
94    ///
95    /// # Panics
96    ///
97    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
98    /// pair such that the encoder cannot encode check character values produced by the accumulator.
99    #[cfg(feature = "alloc")]
100    #[track_caller]
101    pub fn protect_lax(&self, s: &mut alloc::string::String) {
102        s.extend(self.compute_lax(s));
103    }
104
105    /// Computes the check characters for the string `s`.
106    ///
107    /// # Errors
108    ///
109    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
110    /// set.
111    ///
112    /// # Examples
113    ///
114    /// ```rust
115    /// use iso_7064::MOD37_2;
116    ///
117    /// assert_eq!(MOD37_2.compute("5S7U")?, ['G']);
118    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
119    /// ```
120    ///
121    /// # Panics
122    ///
123    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
124    /// pair such that the encoder cannot encode check character values produced by the accumulator.
125    #[track_caller]
126    pub fn compute(&self, s: &str) -> Result<[char; N_CC], ComputeError<char>> {
127        self.compute_from_chars(s.chars())
128    }
129
130    /// Computes the check characters for the string `s`, ignoring any invalid characters.
131    ///
132    /// # Examples
133    ///
134    /// ```rust
135    /// use iso_7064::MOD37_2;
136    ///
137    /// assert_eq!(MOD37_2.compute_lax("5S=7U"), ['G']);
138    /// ```
139    ///
140    /// # Panics
141    ///
142    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
143    /// pair such that the encoder cannot encode check character values produced by the accumulator.
144    #[track_caller]
145    pub fn compute_lax(&self, s: &str) -> [char; N_CC] {
146        self.compute_from_chars_lax(s.chars())
147    }
148
149    /// Computes the check characters from an iterator of characters.
150    ///
151    /// # Errors
152    ///
153    /// Returns a [`ComputeError`] if the input contains any character that is not in the character
154    /// set.
155    ///
156    /// # Examples
157    ///
158    /// ```rust
159    /// use iso_7064::MOD11_10;
160    ///
161    /// let iter = ['2', '0', '6', '5', '1'];
162    /// assert_eq!(MOD11_10.compute_from_chars(iter)?, ['8']);
163    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
164    /// ```
165    ///
166    /// # Panics
167    ///
168    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
169    /// pair such that the encoder cannot encode check character values produced by the accumulator.
170    #[track_caller]
171    pub fn compute_from_chars(
172        &self,
173        chars: impl IntoIterator<Item = char>,
174    ) -> Result<[char; N_CC], ComputeError<char>> {
175        let vs = self.compute_from_iter(chars)?;
176        Ok(self.encode_computed(vs))
177    }
178
179    /// Computes the check characters from an iterator of characters, ignoring any invalid
180    /// characters.
181    ///
182    /// # Examples
183    ///
184    /// ```rust
185    /// use iso_7064::MOD11_10;
186    ///
187    /// let iter = ['2', '0', '-', '6', '5', '-', '1', '.'];
188    /// assert_eq!(MOD11_10.compute_from_chars_lax(iter), ['8']);
189    /// ```
190    ///
191    /// # Panics
192    ///
193    /// Panics if the [`System`] is configured with an incompatible [`Encoder`] and [`Accumulator`]
194    /// pair such that the encoder cannot encode check character values produced by the accumulator.
195    #[track_caller]
196    pub fn compute_from_chars_lax(&self, chars: impl IntoIterator<Item = char>) -> [char; N_CC] {
197        let vs = self.lax_from_iter(chars).compute();
198        self.encode_computed(vs)
199    }
200
201    #[track_caller]
202    fn encode_computed(&self, values: [u32; N_CC]) -> [char; N_CC] {
203        const ERR: &str = "invalid charset implementation";
204        let mut chars = [char::default(); N_CC];
205        for (p, v) in chars.iter_mut().zip(values) {
206            *p = self.encoder.encode(v).expect(ERR);
207        }
208        chars
209    }
210}
211
212impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
213where
214    Acc: Accumulator + Default,
215    Dec: Decoder<Decoded: IntoIterator<Item = u32>>,
216{
217    /// Verifies whether the check characters in the string `s` are valid.
218    ///
219    /// # Errors
220    ///
221    /// Returns a [`VerifyError`] if the input contains any character that is not in the character
222    /// set, or if a supplementary check character (e.g., `X` or `*`) is found before the end.
223    ///
224    /// # Examples
225    ///
226    /// ```rust
227    /// use iso_7064::MOD661_26;
228    ///
229    /// assert!(MOD661_26.verify("MVEISJV")?);
230    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
231    /// ```
232    pub fn verify(&self, s: &str) -> Result<bool, VerifyError<char>> {
233        self.verify_from_chars(s.chars())
234    }
235
236    /// Verifies whether the check characters in the string `s` are valid, ignoring any invalid
237    /// characters.
238    ///
239    /// For this purpose, supplementary check characters (e.g., `X` or `*`) found before the end are
240    /// regarded as invalid and ignored.
241    ///
242    /// # Examples
243    ///
244    /// ```rust
245    /// use iso_7064::MOD661_26;
246    ///
247    /// assert!(MOD661_26.verify_lax("MV-EIS:JV"));
248    /// ```
249    pub fn verify_lax(&self, s: &str) -> bool {
250        self.verify_from_chars_lax(s.chars())
251    }
252
253    /// Verifies whether the check characters in the iterator of characters are valid.
254    ///
255    /// # Errors
256    ///
257    /// Returns a [`VerifyError`] if the input contains any character that is not in the character
258    /// set, or if a supplementary check character (e.g., `X` or `*`) is found before the end.
259    ///
260    /// # Examples
261    ///
262    /// ```rust
263    /// use iso_7064::MOD97_10;
264    ///
265    /// let iter = "3793".chars().chain(['6', '8']);
266    /// assert!(MOD97_10.verify_from_chars(iter)?);
267    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
268    /// ```
269    pub fn verify_from_chars(
270        &self,
271        chars: impl IntoIterator<Item = char>,
272    ) -> Result<bool, VerifyError<char>> {
273        self.verify_from_iter(chars)
274    }
275
276    /// Verifies whether the check characters in the iterator of characters are valid, ignoring any
277    /// invalid characters.
278    ///
279    /// For this purpose, supplementary check characters (e.g., `X` or `*`) found before the end are
280    /// regarded as invalid and ignored.
281    ///
282    /// # Examples
283    ///
284    /// ```rust
285    /// use iso_7064::MOD97_10;
286    ///
287    /// let iter = "[3793]".chars().chain(['(', '6', '8', ')']);
288    /// assert!(MOD97_10.verify_from_chars_lax(iter));
289    /// ```
290    pub fn verify_from_chars_lax(&self, chars: impl IntoIterator<Item = char>) -> bool {
291        self.lax_from_iter(chars).verify()
292    }
293}
294
295impl<const N_CC: usize, Acc, Enc, Dec> System<N_CC, Acc, Enc, Dec>
296where
297    Acc: Accumulator + Default,
298{
299    /// Computes the check character values from an iterator of numerical values.
300    ///
301    /// # Errors
302    ///
303    /// Returns a [`ComputeError`] if the input contains any value that is not in the character set.
304    ///
305    /// # Examples
306    ///
307    /// ```rust
308    /// use iso_7064::MOD37_36;
309    ///
310    /// let iter = [21, 14, 5, 34];
311    /// assert_eq!(MOD37_36.compute_from_values(iter)?, [17]);
312    /// # Ok::<_, iso_7064::system::ComputeError<_>>(())
313    /// ```
314    pub fn compute_from_values(
315        &self,
316        values: impl IntoIterator<Item = u32>,
317    ) -> Result<Acc::Computed, ComputeError<u32>> {
318        self.compute_from_iter(values)
319    }
320
321    /// Computes the check character values from an iterator of numerical values, ignoring any
322    /// invalid values.
323    ///
324    /// # Examples
325    ///
326    /// ```rust
327    /// use iso_7064::MOD37_36;
328    ///
329    /// let iter = [21, 99, 14, 999, 5, 9999, 34];
330    /// assert_eq!(MOD37_36.compute_from_values_lax(iter), [17]);
331    /// ```
332    pub fn compute_from_values_lax(&self, values: impl IntoIterator<Item = u32>) -> Acc::Computed {
333        self.lax_from_iter(values).compute()
334    }
335
336    /// Verifies whether the check character values in the iterator of numerical values are valid.
337    ///
338    /// # Errors
339    ///
340    /// Returns a [`VerifyError`] if the input contains any value that is not in the character set,
341    /// or if a supplementary check character value is found before the end.
342    ///
343    /// # Examples
344    ///
345    /// ```rust
346    /// use iso_7064::MOD27_26;
347    ///
348    /// let iter = [2, 13, 17, 11].into_iter().chain([15]);
349    /// assert!(MOD27_26.verify_from_values(iter)?);
350    /// # Ok::<_, iso_7064::system::VerifyError<_>>(())
351    /// ```
352    pub fn verify_from_values(
353        &self,
354        values: impl IntoIterator<Item = u32>,
355    ) -> Result<bool, VerifyError<u32>> {
356        self.verify_from_iter(values)
357    }
358
359    /// Verifies whether the check character values in the iterator of numerical values are valid,
360    /// ignoring any invalid values.
361    ///
362    /// For this purpose, supplementary check character values found before the end are regarded as
363    /// invalid and ignored.
364    ///
365    /// # Examples
366    ///
367    /// ```rust
368    /// use iso_7064::MOD27_26;
369    ///
370    /// let iter = [2, 13, 28, 17, 11].into_iter().chain([29, 15, 30, 31]);
371    /// assert!(MOD27_26.verify_from_values_lax(iter));
372    /// ```
373    pub fn verify_from_values_lax(&self, values: impl IntoIterator<Item = u32>) -> bool {
374        self.lax_from_iter(values).verify()
375    }
376
377    fn compute_from_iter<T: IntoValues<Dec> + Copy>(
378        &self,
379        iter: impl IntoIterator<Item = T>,
380    ) -> Result<Acc::Computed, ComputeError<T>> {
381        let mut acc = Acc::default();
382        for (pos, e) in iter.into_iter().enumerate() {
383            let Some(values) = e.into_values(&self.decoder) else {
384                return Err(ComputeError { val: e, pos });
385            };
386
387            for value in values {
388                let AccumulateResult::Processed = acc.accumulate(value) else {
389                    return Err(ComputeError { val: e, pos });
390                };
391            }
392        }
393        Ok(acc.compute())
394    }
395
396    fn verify_from_iter<T: IntoValues<Dec> + Copy>(
397        &self,
398        iter: impl IntoIterator<Item = T>,
399    ) -> Result<bool, VerifyError<T>> {
400        let mut acc = Acc::default();
401        let mut iter_outer = iter.into_iter().enumerate();
402        'outer: while let Some((pos, e)) = iter_outer.next() {
403            let Some(values) = e.into_values(&self.decoder) else {
404                let kind = VerifyErrorKind::NotInCharset;
405                return Err(VerifyError { val: e, pos, kind });
406            };
407
408            let mut iter_inner = values.into_iter();
409            while let Some(value) = iter_inner.next() {
410                match acc.accumulate(value) {
411                    AccumulateResult::Processed => (),
412                    AccumulateResult::SupplFound => match (iter_inner.next(), iter_outer.next()) {
413                        (None, None) => break 'outer,
414                        _ => {
415                            let kind = VerifyErrorKind::UnexpectedSuppl;
416                            return Err(VerifyError { val: e, pos, kind });
417                        }
418                    },
419                    AccumulateResult::NotInCharset => {
420                        let kind = VerifyErrorKind::NotInCharset;
421                        return Err(VerifyError { val: e, pos, kind });
422                    }
423                }
424            }
425        }
426        Ok(acc.verify())
427    }
428
429    fn lax_from_iter<T: IntoValues<Dec>>(&self, iter: impl IntoIterator<Item = T>) -> Acc {
430        let mut acc = Acc::default();
431        for e in iter {
432            if let Some(values) = e.into_values(&self.decoder) {
433                for value in values {
434                    let _ = acc.accumulate(value);
435                }
436            }
437        }
438        acc
439    }
440
441    /// Creates an instance with [`Encoder`] and [`Decoder`].
442    pub const fn with_charset(encoder: Enc, decoder: Dec) -> Self {
443        Self {
444            _acc: marker::PhantomData,
445            encoder,
446            decoder,
447        }
448    }
449}
450
451trait IntoValues<Dec> {
452    fn into_values(self, decoder: &Dec) -> Option<impl IntoIterator<Item = u32>>;
453}
454
455impl<Dec> IntoValues<Dec> for u32 {
456    #[inline]
457    fn into_values(self, _decoder: &Dec) -> Option<impl IntoIterator<Item = u32>> {
458        Some([self])
459    }
460}
461
462impl<Dec> IntoValues<Dec> for char
463where
464    Dec: Decoder<Decoded: IntoIterator<Item = u32>>,
465{
466    #[inline]
467    fn into_values(self, decoder: &Dec) -> Option<impl IntoIterator<Item = u32>> {
468        decoder.decode(self)
469    }
470}
471
472/// The ISO/IEC 7064, MOD 11-2 pure system with a single check character.
473pub type Mod11_2 = System<1, accumulator::Mod11_2, charset::NumericX, charset::NumericX>;
474
475/// The ISO/IEC 7064, MOD 37-2 pure system with a single check character.
476pub type Mod37_2 =
477    System<1, accumulator::Mod37_2, charset::AlphanumericAst, charset::AlphanumericAst>;
478
479/// The ISO/IEC 7064, MOD 97-10 pure system with two check characters.
480pub type Mod97_10 = System<2, accumulator::Mod97_10, charset::Numeric, charset::Numeric>;
481
482/// The ISO/IEC 7064, MOD 661-26 pure system with two check characters.
483pub type Mod661_26 = System<2, accumulator::Mod661_26, charset::Alphabetic, charset::Alphabetic>;
484
485/// The ISO/IEC 7064, MOD 1271-36 pure system with two check characters.
486pub type Mod1271_36 =
487    System<2, accumulator::Mod1271_36, charset::Alphanumeric, charset::Alphanumeric>;
488
489/// The ISO/IEC 7064, MOD 11,10 hybrid system.
490pub type Mod11_10 = System<1, accumulator::Mod11_10, charset::Numeric, charset::Numeric>;
491
492/// The ISO/IEC 7064, MOD 27,26 hybrid system.
493pub type Mod27_26 = System<1, accumulator::Mod27_26, charset::Alphabetic, charset::Alphabetic>;
494
495/// The ISO/IEC 7064, MOD 37,36 hybrid system.
496pub type Mod37_36 = System<1, accumulator::Mod37_36, charset::Alphanumeric, charset::Alphanumeric>;
497
498/// An error returned when check character computation fails.
499#[derive(Debug)]
500pub struct ComputeError<T> {
501    val: T,
502    pos: usize,
503}
504
505impl<T: fmt::Debug> fmt::Display for ComputeError<T> {
506    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
507        let kind = VerifyErrorKind::NotInCharset;
508        write!(f, "{}: {:?} at {}", kind, self.val, self.pos)
509    }
510}
511
512impl<T: fmt::Debug> error::Error for ComputeError<T> {}
513
514/// An error returned when check character verification fails.
515#[derive(Debug)]
516pub struct VerifyError<T> {
517    val: T,
518    pos: usize,
519    kind: VerifyErrorKind,
520}
521
522impl<T: fmt::Debug> fmt::Display for VerifyError<T> {
523    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
524        write!(f, "{}: {:?} at {}", self.kind, self.val, self.pos)
525    }
526}
527
528impl<T: fmt::Debug> error::Error for VerifyError<T> {}
529
530/// The specific kind of a verification error.
531#[derive(Debug)]
532enum VerifyErrorKind {
533    /// A character in the input was not found in the character set.
534    NotInCharset,
535
536    /// A supplementary check character was found before the end of the input.
537    UnexpectedSuppl,
538}
539
540impl fmt::Display for VerifyErrorKind {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        match self {
543            Self::NotInCharset => f.write_str("char not in charset"),
544            Self::UnexpectedSuppl => f.write_str("suppl check char not at end"),
545        }
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552
553    #[cfg(feature = "alloc")]
554    #[test]
555    fn do_not_mutate_on_error() {
556        let mod1271_36 = Mod1271_36::default();
557        let mut buf = alloc::string::String::from("0 1 2 3");
558        assert!(mod1271_36.protect(&mut buf).is_err());
559        assert_eq!(buf, "0 1 2 3");
560    }
561
562    #[test]
563    fn reject_unexpected_suppl() {
564        let mod11_2 = Mod11_2::default();
565        assert!(mod11_2.compute("012X34").is_err());
566        assert!(mod11_2.compute("01234X").is_err());
567        assert!(mod11_2.verify("012X34").is_err());
568        assert!(mod11_2.verify("01234X").is_ok());
569    }
570
571    #[test]
572    fn ignore_unexpected_suppl() {
573        let mod11_2 = Mod11_2::default();
574        assert_eq!(mod11_2.compute_lax("32X37"), ['X']);
575        assert_eq!(mod11_2.compute_lax("3237X"), ['X']);
576        assert!(mod11_2.verify_lax("32X37X"));
577        assert!(mod11_2.verify_lax("3237XX"));
578        assert!(mod11_2.verify_lax("3237X"));
579    }
580
581    #[test]
582    fn decode_iban() {
583        let sys: System<2, accumulator::Mod97_10, _, _> =
584            System::with_charset(charset::Numeric, |c: char| {
585                c.to_digit(36).map(|v| match v {
586                    ..=9 => [v, 0].into_iter().take(1),
587                    10.. => [v / 10, v % 10].into_iter().take(2),
588                })
589            });
590
591        let iban = "IE06BOFI90008412345671";
592        let iter = iban[4..].chars().chain(iban[..4].chars());
593        assert!(sys.verify_from_chars(iter).unwrap());
594
595        let iter = iban[4..].chars().chain(iban[..2].chars());
596        assert!(
597            sys.compute_from_chars(iter)
598                .unwrap()
599                .into_iter()
600                .eq(iban[2..4].chars())
601        );
602    }
603}