Crate brids

source ·
Expand description

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

Usage

Add the following to your Cargo.toml:

[dependencies]
brids = "0.4"

Dependencies

The rand crate is an optional dependency enabled by default. To disable, use:

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

The serde crate is an optional dependency disabled by default. To enable, use:

[dependencies]
brids = { version = "0.4", features = ["serde"] }

Examples

Parse and format:

use brids::Cpf;
use std::io::{stdin, stdout, Write};

fn main() {
    print!("Input a CPF/ICN number: ");
    stdout().flush().ok();

    let mut input = String::with_capacity(14);
    stdin().read_line(&mut input).ok();

    match input.trim().parse::<Cpf>() {
        Ok(cpf) => println!("{} is a valid number.", cpf),
        Err(err) => println!("Error: {}", err),
    }
}

Generate random CNPJ and CPF/ICN numbers:

use brids::{Cnpj, Cpf};

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

Using a different generator:

use brids::{Cnpj, Cpf};
use rand::prelude::*;

fn main() {
    let mut rng = SmallRng::seed_from_u64(123);
    println!("Random CNPJ number: {}", rng.gen::<Cnpj>());
    println!("Random CPF/ICN number: {}", rng.gen::<Cpf>());
}

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

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

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

fn main() {
    let company1 = Company {
        name: "ACME",
        cnpj: Cnpj::generate(),
    };

    // Serializes the struct into JSON
    let json = serde_json::to_string(&company1).unwrap();
    println!("{}", json);

    // Deserializes the struct back
    let company2: Company = serde_json::from_str(&json).unwrap();
    assert_eq!(company1, company2);
}

Structs

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

Enums

An error which can be returned when parsing an CNPJ number.
An error which can be returned when parsing an CPF/ICN number.

Type Definitions