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
//! ISIN (International Securities Identification Number) — the ISO 6166 identifier for a fungible
//! financial security.
//!
//! This module provides the validated Rust representation ([`Isin`]) and the parsing, validation,
//! and error types that surround it. It accepts the canonical 12-character form (optionally
//! surrounded by whitespace, in any ASCII case), normalizes it, and guarantees that any constructed
//! [`Isin`] satisfies the structural rules and the Luhn check digit described below. There is no
//! partially-validated state: if you hold an [`Isin`], it is valid.
//!
//! # What this type represents
//!
//! An ISIN has 12 characters, split into three segments:
//!
//! | Positions | Length | Segment | Meaning |
//! |-----------|--------|---------------|-------------------------------------------------------------------|
//! | 1–2 | 2 | Country code | ISO 3166-1 alpha-2 prefix of the issuing national numbering agency |
//! | 3–11 | 9 | NSIN | National Securities Identifying Number, alphanumeric |
//! | 12 | 1 | Check digit | Luhn (modulus 10) digit computed over the first 11 characters |
//!
//! ```text
//! ┌──────────────────────────────────────────────────────┐
//! │ CC │ NSIN (9 chars) │ Check (1) │
//! │ A A │ N N N N N N N N N │ D │
//! └──────────────────────────────────────────────────────┘
//! ```
//!
//! [`Isin`] stores those 12 characters as normalized uppercase ASCII and exposes borrowed accessors
//! for the country code ([`Isin::country_code`]), the NSIN ([`Isin::nsin`]), the check digit
//! ([`Isin::check_digit`]), and the whole value ([`Isin::as_str`]).
//!
//! # Validation rules
//!
//! Every fallible constructor runs the same rules, in order, and each maps to one [`IsinError`]
//! variant:
//!
//! 1. **Length** — after surrounding whitespace is trimmed, the input must contain exactly 12
//! characters ([`IsinError::InvalidLength`]). [`Isin::parse`] rejects empty input up front
//! ([`IsinError::Empty`]).
//! 2. **Character class** — positions 1–2 accept an uppercase letter, positions 3–11 accept a digit
//! or an uppercase letter, and position 12 accepts only a digit ([`IsinError::InvalidCharacter`]).
//! 3. **Check digit** — position 12 must match the ISO 6166 Luhn digit computed from the first 11
//! characters ([`IsinError::InvalidCheckDigit`]).
//!
//! The country code is validated *structurally* (two uppercase letters); this crate deliberately
//! does not check it against the live ISO 3166-1 country registry, which changes over time and is
//! out of scope for a checksum-oriented value type.
//!
//! # Design notes
//!
//! - **No invalid state is representable.** [`Isin`]'s only field is private; the only ways to
//! obtain one — [`Isin::parse`], [`Isin::new`], [`Isin::from_bytes`], [`FromStr`], and
//! [`TryFrom<&str>`] — all run full validation. There is no unchecked constructor.
//! - **Zero allocation, `Copy`, `no_std`-friendly.** [`Isin`] is a 12-byte value type wrapping
//! `[u8; 12]`. Parsing, validating, and every accessor operate on the stack.
//! - **Ordering and hashing are byte-wise.** [`Isin`] derives [`Ord`] and [`Hash`] directly over
//! its ASCII bytes, which matches [`str`] ordering on [`Isin::as_str`]. This is lexicographic
//! string order, not any notion of issuance order.
//! - **Safe to use as a map/set key.** [`Isin`] implements [`Eq`] and [`Hash`] consistently with
//! [`PartialEq`], so it works as a `HashMap`/`HashSet` or `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 [`Isin::parse`] or the validation rules above:
//!
//! - **`serde`** — (de)serializes [`Isin`] as its 12-character string (e.g. `"US0378331005"`).
//! Deserialization re-runs full validation, so an untrusted payload can never produce an invalid
//! [`Isin`].
//! - **`schemars`** — implements `JsonSchema` for [`Isin`], describing it as a pattern-constrained
//! string (`^[A-Z]{2}[A-Z0-9]{9}[0-9]$`). Implies `serde`.
//! - **`arbitrary`** — implements `Arbitrary` for [`Isin`], generating structurally valid,
//! checksum-correct values for fuzz targets.
//! - **`proptest`** — exposes reusable `proptest` strategies (`ftracker_identifiers::isin::proptest`,
//! when this feature is enabled) for generating checksum-valid [`Isin`] values.
//!
//! # Error handling
//!
//! Every fallible constructor returns [`IsinError`], which is `Clone + PartialEq + Eq` and
//! implements [`core::error::Error`] and [`core::fmt::Display`], so it composes with `?` and with
//! error-aggregation crates alike:
//!
//! ```
//! use ftracker_identifiers::{Isin, IsinError};
//!
//! match Isin::parse("US0378331006") {
//! Ok(isin) => println!("valid: {isin}"),
//! Err(IsinError::InvalidCheckDigit { expected, found }) => {
//! println!("checksum mismatch: expected {expected}, found {found}");
//! }
//! Err(other) => println!("rejected: {other}"),
//! }
//! ```
//!
//! # Examples
//!
//! ```
//! use ftracker_identifiers::Isin;
//!
//! let apple = Isin::parse("US0378331005").unwrap();
//! assert_eq!(apple.country_code(), "US");
//! assert_eq!(apple.nsin(), "037833100");
//! assert_eq!(apple.check_digit(), 5);
//! assert_eq!(apple.as_str(), "US0378331005");
//! ```
//!
//! Sorting and deduplicating a batch of ISINs, e.g. after importing them from a spreadsheet:
//!
//! ```
//! use ftracker_identifiers::Isin;
//!
//! let mut isins: Vec<Isin> = ["US0231351067", "US0378331005", "US0378331005"]
//! .into_iter()
//! .map(|s| Isin::parse(s).unwrap())
//! .collect();
//! isins.sort();
//! isins.dedup();
//! assert_eq!(isins.len(), 2);
//! ```
pub use IsinError;
use TryFrom;
use ;
/// A validated ISIN (International Securities Identification Number, ISO 6166).
///
/// `Isin` is a 12-byte, `Copy`, allocation-free value object. Once constructed, it is guaranteed to
/// satisfy the structural rules and Luhn check digit required by ISO 6166 — there is no way to
/// obtain an `Isin` that hasn't passed validation.
///
/// Internally, the identifier is stored as raw uppercase ASCII bytes (`'0'..='9'` or `'A'..='Z'`).
///
/// # Constructing an `Isin`
///
/// | Constructor | Accepts |
/// |----------------------------------|-----------------------------------------------------|
/// | [`Isin::parse`] / [`Isin::new`] | 12-character strings, any ASCII case, trimmed |
/// | [`Isin::from_bytes`] | Exactly 12 pre-normalized uppercase ASCII bytes |
/// | [`FromStr`] / [`TryFrom<&str>`] | Same as `parse`, for use in generic code |
///
/// All of them run the same validation and return [`IsinError`] on failure. See the [module-level
/// documentation](self) for the segment layout and design rationale.