Skip to main content

Cnpj

Struct Cnpj 

Source
pub struct Cnpj { /* private fields */ }
Expand description

A validated CNPJ (Cadastro Nacional da Pessoa Jurídica).

Cnpj is a 14-byte, Copy, allocation-free value object. Once constructed, it is guaranteed to satisfy the structural rules and Módulo 11 checksum required by the crate — there is no way to obtain a Cnpj that hasn’t passed validation.

Internally, the identifier is stored as raw uppercase ASCII bytes ('0'...='9' or 'A'...='Z'). This keeps the compact representation lossless and makes borrowed access to the normalized form cheap.

§Constructing a Cnpj

ConstructorAccepts
Cnpj::parse / Cnpj::newPunctuated or compact strings, any ASCII case
Cnpj::from_bytesExactly 14 pre-normalized ASCII bytes, no punctuation
FromStr / TryFrom<&str>Same as parse, for use in generic code

All of them run the same validation and return CnpjError on failure. See the module-level documentation for the field layout, format history, and design rationale.

Implementations§

Source§

impl Cnpj

Source

pub fn parse(input: &str) -> Result<Self, CnpjError>

Parses a CNPJ from a string.

The parser accepts the conventional AA.AAA.AAA/AAAA-DD form as well as the compact 14-character form. It also tolerates surrounding and embedded ASCII spaces and folds ASCII letters to uppercase before validation.

This is the primary constructor; Cnpj::new, FromStr, and TryFrom<&str> all delegate to it.

§Errors

Returns CnpjError if the input is empty, does not contain exactly 14 meaningful characters after formatting is removed, contains a character invalid for its position, consists of a single repeated character, or fails the checksum.

§Examples
use ftracker_identifiers::Cnpj;

assert!(Cnpj::parse("00.000.000/0001-91").is_ok());
assert!(Cnpj::parse("00000000000191").is_ok());
assert!(Cnpj::parse("12abc34501de35").is_ok()); // lowercase is folded automatically
assert!(Cnpj::parse("not-a-cnpj").is_err());
Source

pub fn new(input: &str) -> Result<Self, CnpjError>

Alias for Cnpj::parse.

§Errors

See Cnpj::parse.

§Examples
use ftracker_identifiers::Cnpj;

assert_eq!(Cnpj::new("00000000000191"), Cnpj::parse("00000000000191"));
Source

pub fn from_bytes(bytes: [u8; 14]) -> Result<Self, CnpjError>

Constructs a Cnpj directly from 14 raw ASCII bytes.

Each byte must already be an ASCII digit, and for the first 12 positions may also be an uppercase ASCII letter. Use Cnpj::parse if the input might contain punctuation or lowercase letters.

Numeric-only CNPJs remain fully supported. Pass ASCII digit bytes (b'0'...=b'9'), not raw numeric values.

§Errors

Returns CnpjError under the same conditions as Cnpj::parse, except that length is guaranteed by the [u8; 14] type itself: CnpjError::InvalidLength cannot occur here.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::from_bytes(*b"00000000000191").unwrap();
assert_eq!(cnpj.as_str(), "00000000000191");

// A malformed checksum is rejected just like it would be through `parse`.
assert!(Cnpj::from_bytes(*b"00000000000192").is_err());
Source

pub fn as_bytes(&self) -> &[u8; 14]

Returns the 14 raw ASCII bytes backing this CNPJ.

The returned bytes are in compact form, without punctuation (for example, b"12ABC34501DE35").

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("00000000000191").unwrap();
assert_eq!(cnpj.as_bytes(), b"00000000000191");
Source

pub fn as_str(&self) -> &str

Returns the compact CNPJ as a &str.

This never allocates: the bytes are guaranteed to be valid ASCII by construction.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("00.000.000/0001-91").unwrap();
assert_eq!(cnpj.as_str(), "00000000000191");
Source

pub fn formatted(&self) -> FormattedCnpj

Renders the punctuated AA.AAA.AAA/AAAA-DD form without heap allocation.

See FormattedCnpj. Cnpj’s own Display implementation delegates to this, so cnpj.to_string() and cnpj.formatted().to_string() are equivalent.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("00000000000191").unwrap();
assert_eq!(cnpj.formatted().as_str(), "00.000.000/0001-91");
assert_eq!(cnpj.to_string(), cnpj.formatted().as_str());
Source

pub fn root(&self) -> &str

Returns the 8-character root segment.

This identifies the entity itself and is shared by the company and all of its branches.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("00000000000191").unwrap();
assert_eq!(cnpj.root(), "00000000");
Source

pub fn branch_code(&self) -> &str

Returns the 4-character branch/order segment.

"0001" conventionally denotes the head office (matriz); see Cnpj::is_root.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("11.222.333/0002-62").unwrap();
assert_eq!(cnpj.branch_code(), "0002");
Source

pub fn is_root(&self) -> bool

Returns true when the branch/order segment is "0001".

§Examples
use ftracker_identifiers::Cnpj;

assert!(Cnpj::parse("00000000000191").unwrap().is_root());
assert!(!Cnpj::parse("11.222.333/0002-62").unwrap().is_root());
Source

pub fn branch_number(&self) -> Option<u16>

Returns the branch/order segment as a number when it is purely numeric.

Returns None when the segment contains a letter, which is only possible for alphanumeric-format CNPJs. Numeric CNPJs, including the conventional matriz marker ("0001"), always parse successfully.

§Examples
use ftracker_identifiers::Cnpj;

let matriz = Cnpj::parse("00000000000191").unwrap();
assert_eq!(matriz.branch_number(), Some(1));

let alphanumeric_branch = Cnpj::parse("12ABC34501DE35").unwrap();
assert_eq!(alphanumeric_branch.branch_code(), "01DE");
assert_eq!(alphanumeric_branch.branch_number(), None);
Source

pub fn check_digits(&self) -> (u8, u8)

Returns the two verification digits as numeric values.

§Examples
use ftracker_identifiers::Cnpj;

let cnpj = Cnpj::parse("00000000000191").unwrap();
assert_eq!(cnpj.check_digits(), (9, 1));

Trait Implementations§

Source§

impl<'a> Arbitrary<'a> for Cnpj

Source§

fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self>

Generate an arbitrary value of Self from the given unstructured data. Read more
Source§

fn arbitrary_take_rest(u: Unstructured<'a>) -> Result<Self, Error>

Generate an arbitrary value of Self from the entirety of the given unstructured data. Read more
Source§

fn size_hint(depth: usize) -> (usize, Option<usize>)

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

fn try_size_hint( depth: usize, ) -> Result<(usize, Option<usize>), MaxRecursionReached>

Get a size hint for how many bytes out of an Unstructured this type needs to construct itself. Read more
Source§

impl AsRef<[u8]> for Cnpj

Source§

fn as_ref(&self) -> &[u8]

Equivalent to Cnpj::as_bytes, borrowed as a slice.

Source§

impl AsRef<str> for Cnpj

Source§

fn as_ref(&self) -> &str

Equivalent to Cnpj::as_str.

Source§

impl Clone for Cnpj

Source§

fn clone(&self) -> Cnpj

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Cnpj

Source§

impl Debug for Cnpj

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Cnpj

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Cnpj

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Cnpj

Source§

impl FromStr for Cnpj

Source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Delegates to Cnpj::parse, enabling input.parse::<Cnpj>() and use in generic code bounded by FromStr.

Source§

type Err = CnpjError

The associated error which can be returned from parsing.
Source§

impl Hash for Cnpj

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl JsonSchema for Cnpj

Source§

fn schema_name() -> Cow<'static, str>

The name of the generated JSON Schema. Read more
Source§

fn json_schema(_: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn inline_schema() -> bool

Whether JSON Schemas generated for this type should be included directly in parent schemas, rather than being re-used where possible using the $ref keyword. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

impl Ord for Cnpj

Source§

fn cmp(&self, other: &Cnpj) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for Cnpj

Source§

fn eq(&self, other: &Cnpj) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<&str> for Cnpj

Source§

fn eq(&self, other: &&str) -> bool

Compares against a string slice by its compact 14 character representation (not the punctuated form).

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Cnpj> for str

Source§

fn eq(&self, other: &Cnpj) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Cnpj> for &str

Source§

fn eq(&self, other: &Cnpj) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<str> for Cnpj

Source§

fn eq(&self, other: &str) -> bool

Compares against a string slice by its compact 14 character representation (not the punctuated form).

1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Cnpj

Source§

fn partial_cmp(&self, other: &Cnpj) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for Cnpj

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Cnpj

Source§

impl TryFrom<&[u8]> for Cnpj

Source§

fn try_from(value: &[u8]) -> Result<Self, Self::Error>

Validates a byte slice as a CNPJ. The slice must be exactly 14 pre normalized ASCII bytes, without punctuation; any other length yields CnpjError::InvalidLength. Once the length is confirmed, this behaves like Cnpj::from_bytes.

Source§

type Error = CnpjError

The type returned in the event of a conversion error.
Source§

impl TryFrom<&str> for Cnpj

Source§

fn try_from(value: &str) -> Result<Self, Self::Error>

Delegates to Cnpj::parse, enabling Cnpj::try_from(input) and use in generic code bounded by TryFrom<&str>.

Source§

type Error = CnpjError

The type returned in the event of a conversion error.
Source§

impl TryFrom<[u8; 14]> for Cnpj

Source§

fn try_from(value: [u8; 14]) -> Result<Self, Self::Error>

Delegates to Cnpj::from_bytes. The bytes must already be pre normalized ASCII, without punctuation.

Source§

type Error = CnpjError

The type returned in the event of a conversion error.

Auto Trait Implementations§

§

impl Freeze for Cnpj

§

impl RefUnwindSafe for Cnpj

§

impl Send for Cnpj

§

impl Sync for Cnpj

§

impl Unpin for Cnpj

§

impl UnsafeUnpin for Cnpj

§

impl UnwindSafe for Cnpj

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V