#validating #formatting #brazil #brasil #parser #numbers #brazilian

no-std cnpj

Brazilian CNPJ parsing, validating and formatting library

4 releases (2 breaking)

0.2.2 Jun 12, 2021
0.2.1 May 22, 2021
0.1.4 Apr 17, 2021
0.0.1 Apr 12, 2021

#340 in No standard library

MIT license

15KB
251 lines

cnpj-rs

Brazilian CNPJ parsing, validating and formatting library.

use cnpj::Cnpj;

// Use the `valid` function if all you need is validating a CNPJ number
assert!(cnpj::valid("96.769.900/0001-77"));
assert!(cnpj::valid("96769900000177"));
assert!(!cnpj::valid("00.000.000/0000-00"));

// Parse into a Cnpj struct if you need formatting or other metadata
let cnpj: Cnpj = "96769900000177".parse()?;
assert_eq!(format!("{}", cnpj), "96.769.900/0001-77");
assert_eq!(cnpj.digits(), [9, 6, 7, 6, 9, 9, 0, 0, 0, 0, 0, 1, 7, 7]);

// Note that the Cnpj struct is guaranteed to always be valid
assert!("00.000.000/0000-00".parse::<Cnpj>().is_err());
assert!(cnpj::valid("96.769.900/0001-77".parse::<Cnpj>()?));

no_std support

The library makes no dinamic allocation and can be used on no_std environments by disabling the std flag:

[dependencies]
cnpj = { version = "0.2", default-features = false }

Random CNPJ generation support

The rand feature flag enables random CNPJ generation:

[dependencies]
cnpj = { version = "0.2", features = ["rand"] }
rand = "0.8"
use cnpj::Cnpj;
use rand;
use rand::Rng;

let cnpj: Cnpj = rand::thread_rng().gen();

Dependencies

~72KB