brids 0.5.1

Parse and generate random CPF and CNPJ, Brazil's ID numbers.
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
// cnpj.rs
//
// Copyright 2018 Ricardo Silva Veloso <ricvelozo@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT License
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: (MIT OR Apache-2.0)

use core::{
    convert::TryFrom,
    fmt::{self, Write},
    str::FromStr,
};

#[cfg(all(feature = "std", feature = "rand"))]
use rand::thread_rng;

#[cfg(feature = "rand")]
use rand::{
    distributions::{Distribution, Standard},
    Rng,
};

#[cfg(feature = "serde")]
use serde::*;

/// An error which can be returned when parsing an [`Cnpj`] number.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseCnpjError {
    Empty,
    InvalidCharacter(char, usize),
    InvalidNumber,
}

impl fmt::Display for ParseCnpjError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ParseCnpjError::*;
        match self {
            Empty => write!(f, "empty"),
            InvalidCharacter(ch, offset) => {
                write!(f, "invalid character `{ch}` at offset {offset}")
            }
            InvalidNumber => write!(f, "invalid CNPJ number"),
        }
    }
}

impl core::error::Error for ParseCnpjError {}

/// A valid CNPJ number. Parsing recognizes numbers with or without separators (dot, minus,
/// and slash).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Cnpj([u8; 14]);

impl Cnpj {
    /// Parses a byte slice of numbers as an CNPJ, guessing the missing parts.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// match Cnpj::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]) {
    ///     Ok(cnpj) => println!("{cnpj} is a valid number."),
    ///     Err(err) => eprintln!("Error: {err}"),
    /// }
    /// ```
    ///
    /// Guess the check digits:
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// match Cnpj::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 2, 7]) {
    ///     Ok(cnpj) => println!("{cnpj} is a valid number."),
    ///     Err(err) => eprintln!("Error: {err}"),
    /// }
    /// ```
    ///
    /// Guess the branch and check digits:
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// match Cnpj::from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]) {
    ///     Ok(cnpj) => println!("{cnpj} is a valid number."),
    ///     Err(err) => eprintln!("Error: {err}"),
    /// }
    /// ```
    pub fn from_slice(slice: &[u8]) -> Result<Self, ParseCnpjError> {
        let mut numbers = [0; 14];
        match slice.len() {
            0 => return Err(ParseCnpjError::Empty),
            len @ (8 | 12 | 14) => {
                numbers[..len].copy_from_slice(slice);
                if len == 8 {
                    numbers[11] = 1; // `0001` (company headquarters)
                }
            }
            _ => return Err(ParseCnpjError::InvalidNumber),
        }

        // 0..=9
        if numbers.iter().any(|&x| x > 9) {
            return Err(ParseCnpjError::InvalidNumber);
        }

        // Checks for repeated numbers
        let first_number = numbers[0];
        if slice.len() == 14 && numbers.iter().all(|&x| x == first_number) {
            return Err(ParseCnpjError::InvalidNumber);
        }

        for i in 0..=1 {
            let remainder = calc_remainder(numbers, i);
            let check_digit = numbers[12 + i];

            if slice.len() < 14 {
                numbers[12 + i] = remainder; // check digit
            } else if remainder != check_digit {
                return Err(ParseCnpjError::InvalidNumber);
            }
        }

        Ok(Cnpj(numbers))
    }

    /// Returns a byte slice of the numbers.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// let cnpj = "00.000.000/0001-91".parse::<Cnpj>().expect("Invalid CNPJ");
    /// let digits = cnpj.as_bytes();
    /// ```
    #[inline]
    pub fn as_bytes(&self) -> &[u8; 14] {
        &self.0
    }

    /// Returns the entity branch/subsidiary.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// let cnpj = "00.000.000/0001-91".parse::<Cnpj>().expect("Invalid CNPJ");
    /// let branch = cnpj.branch(); // 1
    /// ```
    #[inline]
    pub fn branch(&self) -> u16 {
        self.0[8..=11]
            .iter()
            .rev()
            .enumerate()
            .map(|(i, &x)| u16::from(x) * 10u16.pow(i as u32))
            .sum()
    }

    /// Generates a random number, using [`rand::thread_rng`] (requires `std` and `rand` features).
    /// To use a different generator, instantiate the generator directly. The random CNPJ will be
    /// the company headquarters.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use brids::Cnpj;
    ///
    /// let cnpj = Cnpj::generate();
    /// ```
    #[cfg(all(feature = "std", feature = "rand"))]
    #[inline]
    pub fn generate() -> Self {
        thread_rng().gen()
    }
}

impl AsRef<[u8]> for Cnpj {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl From<Cnpj> for [u8; 14] {
    #[inline]
    fn from(cnpj: Cnpj) -> [u8; 14] {
        cnpj.0
    }
}

impl TryFrom<&[u8]> for Cnpj {
    type Error = ParseCnpjError;

    #[inline]
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Self::from_slice(value)
    }
}

impl TryFrom<&[u8; 14]> for Cnpj {
    type Error = ParseCnpjError;

    #[inline]
    fn try_from(value: &[u8; 14]) -> Result<Self, Self::Error> {
        Self::from_slice(value)
    }
}

impl fmt::Debug for Cnpj {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Cnpj(\"{self}\")")
    }
}

impl fmt::Display for Cnpj {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, number) in self.0.iter().enumerate() {
            match i {
                2 | 5 => f.write_char('.')?,
                8 => f.write_char('/')?,
                12 => f.write_char('-')?,
                _ => (),
            }
            number.fmt(f)?;
        }
        Ok(())
    }
}

impl FromStr for Cnpj {
    type Err = ParseCnpjError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut numbers = [0; 14];

        if s.is_empty() {
            return Err(ParseCnpjError::Empty);
        }

        // Checks for invalid symbols and converts numbers to integers
        let mut i = 0;
        let mut has_dot = false;
        for (offset, ch) in s.chars().enumerate() {
            match (ch, offset) {
                ('0'..='9', _) => {
                    if i < 14 {
                        // SAFETY: Digit already matched
                        numbers[i] = unsafe { ch.to_digit(10).unwrap_unchecked() as u8 };
                        i += 1;
                    } else {
                        return Err(ParseCnpjError::InvalidNumber);
                    }
                }
                ('.', 2 | 6) => has_dot = true,
                ('/', 10) if has_dot => continue,
                ('/', 8) if !has_dot => continue,
                ('-', 15) if has_dot => continue,
                ('-', 13) if !has_dot => continue,
                _ => return Err(ParseCnpjError::InvalidCharacter(ch, offset)),
            }
        }

        // Checks the length
        if i != 14 {
            return Err(ParseCnpjError::InvalidNumber);
        }

        // Checks for repeated numbers
        let first_number = numbers[0];
        if numbers.iter().all(|&x| x == first_number) {
            return Err(ParseCnpjError::InvalidNumber);
        }

        for i in 0..=1 {
            let remainder = calc_remainder(numbers, i);
            let check_digit = numbers[12 + i];

            if remainder != check_digit {
                return Err(ParseCnpjError::InvalidNumber);
            }
        }

        Ok(Cnpj(numbers))
    }
}

#[cfg(feature = "rand")]
impl Distribution<Cnpj> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Cnpj {
        let mut numbers = [0; 14];
        for number in &mut numbers[..8] {
            *number = rng.gen_range(0..=9);
        }
        numbers[11] = 1; // `0001` (company headquarters)

        for i in 0..=1 {
            numbers[12 + i] = calc_remainder(numbers, i); // check digit
        }

        Cnpj(numbers)
    }
}

#[cfg(feature = "serde")]
impl Serialize for Cnpj {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.to_string())
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for Cnpj {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct CnpjStringVisitor;

        impl<'vi> de::Visitor<'vi> for CnpjStringVisitor {
            type Value = Cnpj;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                write!(formatter, "a CNPJ string")
            }

            fn visit_str<E: de::Error>(self, value: &str) -> Result<Cnpj, E> {
                value.parse().map_err(E::custom)
            }

            fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<Cnpj, E> {
                Cnpj::try_from(value).map_err(E::custom)
            }
        }

        deserializer.deserialize_str(CnpjStringVisitor)
    }
}

#[inline]
fn calc_remainder(numbers: impl IntoIterator<Item = u8>, i: usize) -> u8 {
    let remainder = numbers
        .into_iter()
        // Includes the first check digit in the second iteration
        .take(12 + i)
        // 5, 4, 3, 2, 9, 8, 7, ... 3, 2; and after: 6, 5, 4, 3, 2, 9, 8, 7, ... 3, 2
        .zip((2..=9).chain(2..=5 + i).rev())
        .map(|(x, y)| u32::from(x) * y as u32)
        .sum::<u32>()
        * 10
        % 11;

    match remainder {
        10 | 11 => 0,
        _ => remainder as u8,
    }
}

#[cfg(test)]
mod tests {
    #[cfg(not(feature = "std"))]
    use alloc::format;

    use super::*;

    #[test]
    fn from_slice() {
        let a = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 2, 7, 2, 4]);
        let c: [u8; 14] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5];
        let d: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1];
        let e: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
        let f: [u8; 12] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 2, 7];

        assert_eq!(a, Cnpj::from_slice(&c).unwrap());
        assert_eq!(a, Cnpj::from_slice(&d).unwrap());
        assert_eq!(a, Cnpj::from_slice(&e).unwrap());
        assert_eq!(b, Cnpj::from_slice(&f).unwrap());
    }

    #[test]
    fn as_bytes() {
        let a: [u8; 14] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5];
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);

        assert_eq!(&a, b.as_bytes());
    }

    #[test]
    fn branch() {
        let cnpj = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 2, 7, 2, 4]);
        assert_eq!(27, cnpj.branch());
    }

    #[cfg(feature = "rand")]
    #[test]
    fn generate() {
        let a = Cnpj::generate();
        let b = a.to_string().parse::<Cnpj>().unwrap();

        assert_eq!(a, b);
    }

    #[test]
    fn as_ref() {
        fn test_trait<T: AsRef<[u8]>>(b: T) {
            let a: [u8; 14] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5];
            assert_eq!(&a, b.as_ref());
        }

        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);

        test_trait(b);
    }

    #[test]
    fn from() {
        let a: [u8; 14] = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]).into();
        let b: [u8; 14] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5];

        assert_eq!(a, b);
    }

    #[test]
    fn try_from() {
        let a: [u8; 14] = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5];
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);

        assert_eq!(Cnpj::try_from(&a).unwrap(), b);
    }

    #[test]
    fn cmp() {
        let a = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 2, 7, 2, 4]);

        assert!(a < b);
    }

    #[test]
    fn debug() {
        let a = r#"Cnpj("12.345.678/0001-95")"#;
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);

        assert_eq!(a, format!("{b:?}"));
    }

    #[test]
    fn display() {
        let a = "12.345.678/0001-95";
        let b = Cnpj([1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 1, 9, 5]);

        assert_eq!(a, format!("{b}"));
    }

    #[test]
    fn from_str() {
        let a = "12.345.678/0001-95".parse::<Cnpj>().unwrap();
        let b = "12345678/0001-95".parse::<Cnpj>().unwrap();
        let c = "12345678000195".parse::<Cnpj>().unwrap();

        assert_eq!(a, b);
        assert_eq!(a, c);
        assert_eq!("".parse::<Cnpj>(), Err(ParseCnpjError::Empty));
        assert_eq!(
            "12-345-678/0001-95".parse::<Cnpj>(),
            Err(ParseCnpjError::InvalidCharacter('-', 2))
        );
        assert_eq!(
            "12.345.678/0001-96".parse::<Cnpj>(),
            Err(ParseCnpjError::InvalidNumber)
        );
        assert_eq!(
            "12.345.678/0001-995".parse::<Cnpj>(),
            Err(ParseCnpjError::InvalidNumber)
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serialize() {
        let cnpj_str = "12.345.678/0001-95";
        let cnpj = Cnpj::from_str(cnpj_str).unwrap();
        serde_test::assert_tokens(&cnpj, &[serde_test::Token::Str(cnpj_str)]);
    }
}