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
use super::{ValidResult, Validate};
use error::Error;

/// This structure describes taxpayer identification number
/// and allows to obtain information about its properties.
/// To check whether it is correct.
///
/// # Examples
///
/// ```rust
///
/// use government_id::*;
/// let tin: TaxpayerIdentificationNumber = "7827004526".to_owned().into();
/// assert!(tin.is_valid().unwrap());
///
/// ```
///
pub struct TaxpayerIdentificationNumber {
    value: String,
}

impl TaxpayerIdentificationNumber {
    const RATIO: [u32; 11] = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8];
    /// Creates a new `TaxpayerIdentificationNumber`
    pub fn new(input: &str) -> Self {
        TaxpayerIdentificationNumber {
            value: input.into(),
        }
    }

    /// Verifies the tax ID of the individual entrepreneur.
    fn check_len12(&self) -> bool {
        let calc_num1 = self.check_digit(&TaxpayerIdentificationNumber::RATIO[1..]);
        let calc_num2 = self.check_digit(&TaxpayerIdentificationNumber::RATIO[..]);

        calc_num1 == get_digit(&self.value, 10) && calc_num2 == get_digit(&self.value, 11)
    }

    /// Verifies the identity of the taxpayer legal entity.
    fn check_len10(&self) -> bool {
        let calc_num = self.check_digit(&TaxpayerIdentificationNumber::RATIO[2..]);

        calc_num == get_digit(&self.value, 9)
    }

    /// Calculates check digit.
    fn check_digit(&self, r: &[u32]) -> u32 {
        let mut sum = 0;

        for i in 0..r.len() {
            let num = get_digit(&self.value, i);
            sum += num * r[i];
        }
        sum % 11 % 10
    }
}

/// Gets number from string by index.
fn get_digit(input: &str, n: usize) -> u32 {
    match input.chars().nth(n) {
        Some(ch) => match ch.to_digit(10) {
            Some(d) => d,
            None => 0,
        },
        None => 0,
    }
}

impl Validate for TaxpayerIdentificationNumber {
    fn is_valid(&self) -> ValidResult {
        if self.value.is_empty() {
            return Err(Error::Empty);
        }

        if !super::only_digits(&self.value) {
            return Err(Error::ExpectedNumbersOnly);
        }

        match self.value.len() {
            12 => Ok(self.check_len12()),
            10 => Ok(self.check_len10()),
            1...9 => Err(Error::WrongLength { length: 10 }),
            11 => Err(Error::WrongLength { length: 12 }),
            _ => Err(Error::WrongLength { length: 12 }),
        }
    }
}

impl From<String> for TaxpayerIdentificationNumber {
    fn from(other: String) -> TaxpayerIdentificationNumber {
        TaxpayerIdentificationNumber { value: other }
    }
}

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

    fn create_taxpayer_identification_number(s: &str) -> TaxpayerIdentificationNumber {
        TaxpayerIdentificationNumber::new(s)
    }

    #[test]
    fn test_empty_taxpayer_identification_number() {
        assert!(match create_taxpayer_identification_number("").is_valid() {
            Err(error::Error::Empty) => true,
            _ => false,
        });
    }

    #[test]
    fn test_invalid_taxpayer_identification_number_9_zeros() {
        match create_taxpayer_identification_number("000000000").is_valid() {
            Err(error::Error::WrongLength { length: _ }) => assert!(true),
            _ => assert!(false),
        };
    }

    #[test]
    fn test_valid_taxpayer_identification_number_10zeros() {
        assert!(
            create_taxpayer_identification_number("0000000000")
                .is_valid()
                .unwrap()
        );
    }

    #[test]
    fn test_invalid_taxpayer_identification_number_11zeros() {
        match create_taxpayer_identification_number("00000000000").is_valid() {
            Err(error::Error::WrongLength { length: _ }) => assert!(true),
            _ => assert!(false),
        };
    }

    #[test]
    fn test_valid_taxpayer_identification_number_12zeros() {
        assert!(
            create_taxpayer_identification_number("000000000000")
                .is_valid()
                .unwrap()
        );
    }

    #[test]
    fn test_invalid_taxpayer_identification_number_too_short() {
        match create_taxpayer_identification_number("772053").is_valid() {
            Err(error::Error::WrongLength { length: _ }) => assert!(true),
            _ => assert!(false),
        };
    }

    #[test]
    fn test_valid_taxpayer_identification_number_10_numbers() {
        assert!(
            create_taxpayer_identification_number("7827004526")
                .is_valid()
                .unwrap()
        );
    }

    #[test]
    fn test_invalid_check_digit_taxpayer_identification_number_10_numbers() {
        assert!(
            create_taxpayer_identification_number("7827004527")
                .is_valid()
                .unwrap() == false
        );
    }

    #[test]
    fn test_valid_taxpayer_identification_number_12_numbers() {
        assert!(
            create_taxpayer_identification_number("760307073214")
                .is_valid()
                .unwrap()
        );
    }

    #[test]
    fn test_invalid_check_digit_taxpayer_identification_number_12_numbers() {
        assert!(
            create_taxpayer_identification_number("760307073217")
                .is_valid()
                .unwrap() == false
        );
    }

    #[test]
    fn test_invalid_taxpayer_identification_number_with_litters() {
        match create_taxpayer_identification_number("782f004526").is_valid() {
            Err(error::Error::ExpectedNumbersOnly) => assert!(true),
            _ => assert!(false),
        };
    }

    #[test]
    fn test_convert_from_string() {
        let tin: TaxpayerIdentificationNumber = "7827004526".to_owned().into();
        assert!(match tin.is_valid() {
            Ok(true) => true,
            _ => false,
        })
    }
}