Trait codes_check_digits::Calculator
source · 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§
sourcefn calculate(&self, s: &str) -> Result<T, CheckDigitError>
fn calculate(&self, s: &str) -> Result<T, CheckDigitError>
Calculate a check digit for the provided string.
Provided Methods§
sourcefn number_of_check_digit_chars(&self) -> usize
fn number_of_check_digit_chars(&self) -> usize
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
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))
}
}sourcefn create(&self, s: &str) -> Result<String, CheckDigitError>
fn create(&self, s: &str) -> Result<String, CheckDigitError>
Create a new string with the original data plus check digit.