pub trait Calculator<T>where
    T: Display + PartialEq,
{ fn name(&self) -> &'static str; fn calculate(&self, s: &str) -> Result<T, CheckDigitError>; fn number_of_check_digit_chars(&self) -> usize { ... } fn create(&self, s: &str) -> Result<String, CheckDigitError> { ... } fn validate<S>(&self, s: S) -> Result<(), CheckDigitError>
    where
        S: AsRef<str>
, { ... } fn is_valid<S>(&self, s: S) -> bool
    where
        S: AsRef<str>
, { ... } }
Expand description

ait for types that implement check digit algorithms.

Required Methods§

Return the name of this algorithm.

Calculate a check digit for the provided string.

Provided Methods§

Return the number of characters used as the check digit. Currently it is assumed that these are the n right-most characters in the input string.

Examples found in repository?
src/gs1.rs (line 126)
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
    fn calculate(&self, s: &str) -> Result<u8, CheckDigitError> {
        is_length_eq(s, self.length - self.number_of_check_digit_chars())?;
        is_ascii_numeric(s)?;
        let remainder: u16 = s
            .chars()
            .rev()
            .enumerate()
            .map(|(i, c)| gs1_multiply_even_character(i, c) as u16)
            .sum::<u16>()
            % 10;
        if remainder == 0 {
            Ok(0)
        } else {
            Ok(10 - remainder as u8)
        }
    }
More examples
Hide additional examples
src/lib.rs (line 125)
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    fn validate<S>(&self, s: S) -> Result<(), CheckDigitError>
    where
        S: AsRef<str>,
    {
        let s = s.as_ref();
        trace!(
            algorithm_name = self.name(),
            num_check_digits = self.number_of_check_digit_chars(),
            "Validating check digits for input {:?}",
            s
        );
        let check_digit_index = s.len() - self.number_of_check_digit_chars();
        let check = self.calculate(&s[0..check_digit_index])?;
        if s[check_digit_index..] == check.to_string() {
            Ok(())
        } else {
            Err(invalid_check_digit(&s[check_digit_index..], check))
        }
    }

Create a new string with the original data plus check digit.

Validate that the string is valid and that it contains a valid check digit.

Examples found in repository?
src/lib.rs (line 147)
143
144
145
146
147
148
    fn is_valid<S>(&self, s: S) -> bool
    where
        S: AsRef<str>,
    {
        self.validate(s).is_ok()
    }

Returns true if the provided string includes a valid check digit, else false. The default implementation relies on the validate method.

Implementors§