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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! CNPJ (Cadastro Nacional da Pessoa Jurídica) — Brazil's national registry identifier for legal
//! entities, issued by the Receita Federal.
//!
//! This module provides the validated Rust representation ([`Cnpj`]) and the parsing, formatting,
//! validation, and error types that surround it. It accepts both the conventional punctuated
//! `AA.AAA.AAA/AAAA-DD` form and the compact 14-character form, normalizes ASCII case, and
//! guarantees that any constructed [`Cnpj`] satisfies the format and Módulo 11 checksum rules
//! described below. There is no partially-validated state: if you hold a [`Cnpj`], it is valid.
//!
//! # What this type represents
//!
//! A CNPJ has 14 meaningful characters, split into three logical segments:
//!
//! | Positions | Length | Segment | Meaning |
//! |-----------|--------|---------------------|-----------------------------------------------------------------|
//! | 1–8 | 8 | Root (raiz) | Identifies the entity itself; shared by the head office and every branch |
//! | 9–12 | 4 | Branch/order (ordem) | `"0001"` conventionally denotes the head office (matriz) |
//! | 13–14 | 2 | Verification digits | Computed from the first 12 characters via Módulo 11 |
//!
//! [`Cnpj`] stores those 14 characters as normalized uppercase ASCII and exposes borrowed
//! accessors for the root ([`Cnpj::root`]), the branch/order segment ([`Cnpj::branch_code`]), and
//! both the compact ([`Cnpj::as_str`]) and punctuated ([`Cnpj::formatted`]) renderings.
//!
//! # Numeric and alphanumeric formats
//!
//! The public format changed in 2026: the first 12 positions (root + branch/order) may now
//! contain uppercase letters as well as digits, while the final two verification digits remain
//! numeric. This crate follows `Nota Técnica Conjunta COCAD/SUARA/RFB nº 49/2024`, which keeps the
//! legacy numeric-only Módulo 11 calculation unchanged as a special case: each character
//! contributes its ASCII code minus `'0'` to the checksum (so `'A'` = 17, ..., `'Z'` = 42, and
//! digits contribute their own value), meaning a purely numeric CNPJ produces exactly the checksum
//! it always has.
//!
//! Older numeric-only CNPJs remain valid and are treated as a special case of the same
//! 14-character, same-checksum format — [`Cnpj`] represents both uniformly; there is no separate
//! legacy type, and no separate code path to keep in sync.
//!
//! # Validation rules
//!
//! Every fallible constructor runs the same rules, in order, and each maps to one [`CnpjError`]
//! variant:
//!
//! 1. **Length** — after formatting is stripped, the input must contain exactly 14 meaningful
//! characters ([`CnpjError::InvalidLength`]).
//! 2. **Character class** — positions 1–12 accept a digit or an uppercase letter; positions 13–14
//! accept only a digit ([`CnpjError::InvalidCharacter`]).
//! 3. **Not degenerate** — the 14 characters cannot all be identical, e.g. `"00000000000000"`
//! ([`CnpjError::RepeatedDigits`]). Such inputs are structurally well-formed, and can even
//! satisfy the checksum for certain repeated digits, but the Receita Federal never issues them;
//! they are reliably placeholder or data-entry artifacts.
//! 4. **Checksum** — both verification digits must match the Módulo 11 algorithm applied to the
//! preceding characters ([`CnpjError::InvalidCheckDigits`]).
//!
//! [`Cnpj::parse`] additionally strips conventional punctuation (`.`, `/`, `-`, ASCII spaces)
//! before these rules apply, and rejects empty input up front ([`CnpjError::Empty`]).
//! [`Cnpj::from_bytes`] skips the punctuation-stripping step but still enforces every rule above.
//!
//! # Design notes
//!
//! - **No invalid state is representable.** [`Cnpj`]'s only field is private; the only ways to
//! obtain one are [`Cnpj::parse`], [`Cnpj::new`], [`Cnpj::from_bytes`], [`FromStr`], and
//! [`TryFrom<&str>`] — every one of them runs full validation. There is no unchecked or
//! "trust me" constructor exposed publicly.
//! - **Zero allocation, `Copy`, `no_std`-friendly.** [`Cnpj`] is a 14-byte value type wrapping
//! `[u8; 14]`. Parsing, validating, formatting, and every accessor operate on the stack; nothing
//! in this module requires an allocator.
//! - **Ordering and hashing are byte-wise.** [`Cnpj`] derives [`Ord`] and [`Hash`] directly over
//! its underlying ASCII bytes, which matches [`str`] ordering on [`Cnpj::as_str`]. Because ASCII
//! digits (`'0'..='9'`) sort before uppercase letters (`'A'..='Z'`), a numeric-format CNPJ always
//! sorts before any alphanumeric CNPJ sharing the same leading digits. This is lexicographic
//! string order, not numeric order — don't read it as meaning "issued earlier" or
//! "smaller root number".
//! - **Safe to use as a map/set key.** [`Cnpj`] implements [`Eq`] and [`Hash`] consistently with
//! [`PartialEq`], so it works as a `HashMap`/`HashSet` key or a `BTreeMap`/`BTreeSet` key out of
//! the box.
//!
//! # Feature flags
//!
//! This module's optional integrations are off by default and purely additive — enabling one
//! never changes the behavior of [`Cnpj::parse`] or the validation rules above:
//!
//! - **`serde`** — (de)serializes [`Cnpj`] as its compact 14-character string (e.g.
//! `"12ABC34501DE35"`), never the punctuated form. Deserialization re-runs full validation, so an
//! untrusted payload can never produce an invalid [`Cnpj`].
//! - **`schemars`** — implements `JsonSchema` for [`Cnpj`], describing it as a pattern-constrained
//! string (`^[A-Z0-9]{12}[0-9]{2}$`). Implies `serde`.
//! - **`arbitrary`** — implements `Arbitrary` for [`Cnpj`], generating structurally valid,
//! checksum-correct values for fuzz targets.
//! - **`proptest`** — exposes reusable `proptest` strategies (`ftracker_identifiers::cnpj::proptest`,
//! when this feature is enabled) for generating checksum-valid [`Cnpj`] values and their
//! formatted string representations, so downstream property tests don't need to hand-roll a
//! generator.
//!
//! # Error handling
//!
//! Every fallible constructor returns [`CnpjError`], which is `Clone + PartialEq + Eq` and
//! implements [`core::error::Error`] and [`core::fmt::Display`], so it composes with `?` and with
//! error-aggregation crates alike. Match on it when you need to react to a specific failure mode
//! (for example, surfacing "which character was wrong" to a form field) rather than just the
//! human-readable message:
//!
//! ```
//! use ftracker_identifiers::{Cnpj, CnpjError};
//!
//! match Cnpj::parse("12.345.678/0001-XX") {
//! Ok(cnpj) => println!("valid: {cnpj}"),
//! Err(CnpjError::InvalidCheckDigits { expected, found, .. }) => {
//! println!("checksum mismatch: expected {expected}, found {found}");
//! }
//! Err(other) => println!("rejected: {other}"),
//! }
//! ```
//!
//! # Examples
//!
//! ```
//! use ftracker_identifiers::Cnpj;
//!
//! let numeric = Cnpj::parse("00.000.000/0001-91").unwrap();
//! assert!(numeric.is_root());
//! assert_eq!(numeric.as_str(), "00000000000191");
//! assert_eq!(numeric.formatted().as_str(), "00.000.000/0001-91");
//!
//! let alpha = Cnpj::parse("12ABC34501DE35").unwrap();
//! assert_eq!(alpha.branch_code(), "01DE");
//! assert_eq!(alpha.branch_number(), None);
//! ```
//!
//! Sorting and deduplicating a batch of CNPJs, e.g. after importing them from a spreadsheet:
//!
//! ```
//! use ftracker_identifiers::Cnpj;
//!
//! let mut cnpjs: Vec<Cnpj> = ["11.222.333/0002-62", "00.000.000/0001-91", "00.000.000/0001-91"]
//! .into_iter()
//! .map(|s| Cnpj::parse(s).unwrap())
//! .collect();
//! cnpjs.sort();
//! cnpjs.dedup();
//! assert_eq!(cnpjs.len(), 2);
//! ```
pub use CnpjError;
pub use FormattedCnpj;
use TryFrom;
use ;
/// 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`
///
/// | Constructor | Accepts |
/// |-----------------------------------|----------------------------------------------------------------|
/// | [`Cnpj::parse`] / [`Cnpj::new`] | Punctuated or compact strings, any ASCII case |
/// | [`Cnpj::from_bytes`] | Exactly 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](self) for the field layout, format history, and design rationale.