Crate brids

Source
Expand description

Parse and generate random CPF and CNPJ, Brazil’s ID numbers.

§Usage

Add the following to your Cargo.toml:

[dependencies]
brids = "0.5"

§Features

All dependencies are optional and disabled by default:

  • rand - enable to generate random numbers
  • serde - enable to (de)serialize numbers

§no_std mode

To enable no_std mode, just disable the default features:

[dependencies]
brids = { version = "0.5", default-features = false }

§Examples

Parse and format:

use brids::Cpf;

let maybe_valid = "123.456.789-09".parse::<Cpf>();
assert!(maybe_valid.is_ok()); // Checks validity

let old_format = "123.456.789/09".parse::<Cpf>();
assert!(old_format.is_ok()); // Accepts the old format too

let unformatted = "12345678909".parse::<Cpf>().expect("Invalid CPF");
let formatted = unformatted.to_string(); // Formats
println!("CPF: {unformatted}"); // Formats too

Generate random CNPJ and CPF numbers (you must enable the rand feature):

use brids::{Cnpj, Cpf};

println!("Random CNPJ number: {}", Cnpj::generate());
println!("Random CPF number: {}", Cpf::generate());

If you are using the no_std mode, the ::generate() methods are unavailable; instantiate the generator directly instead:

use brids::{Cnpj, Cpf};
use rand::{rngs::StdRng, Rng, SeedableRng};

let mut rng = StdRng::seed_from_u64(123); // Available in `no_std` mode
println!("Random CNPJ number: {}", rng.gen::<Cnpj>());
println!("Random CPF number: {}", rng.gen::<Cpf>());

Serialize and deserialize (you must enable the serde feature):

use brids::Cnpj;
use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Company<'a> {
    name: &'a str,
    cnpj: Cnpj,
}

let company1 = Company {
    name: "Banco do Brasil S/A",
    cnpj: "00.000.000/0001-91".parse().expect("Invalid CNPJ"),
};

// Serializes the struct into JSON
let json = serde_json::to_string(&company1).expect("Failed to serialize");
println!("{json}");

// Deserializes the struct back
let company2: Company = serde_json::from_str(&json).expect("Failed to deserialize");
assert_eq!(company1, company2);

Structs§

Cnpj
A valid CNPJ number. Parsing recognizes numbers with or without separators (dot, minus, and slash).
Cpf
A valid CPF number. Parsing recognizes numbers with or without separators (dot, minus, and slash).

Enums§

ParseCnpjError
An error which can be returned when parsing an Cnpj number.
ParseCpfError
An error which can be returned when parsing an Cpf number.