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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#![warn(missing_docs)]
//! # isin
//!
//! `isin` provides an `ISIN` type for working with validated International Securities
//! Identification Numbers (ISINs) as defined in [ISO 6166:2021 Financial services — International securities
//! identification number (ISIN)](https://www.iso.org/standard/78502.html) ("The Standard").
//!
//! [The Association of National Numbering Agencies (ANNA)](https://www.anna-web.org/) has [a page
//! describing ISO 6166](https://www.anna-web.org/standards/isin-iso-6166/).
//!
//! An ISIN is comprised of 12 ASCII characters with the following parts, in order:
//!
//! 1. A two-letter _Prefix_ in uppercase, designating the issuer's country
//! of registration or legal domicile, or for OTC derivatives the special code `EZ`. Additional
//! codes may be allocated by subsequent revisions to The Standard. Country codes follow the
//! [ISO 3166](https://www.iso.org/iso-3166-country-codes.html) standard.
//! 2. A nine-character uppercase alphanumeric _Basic Code_ assigned by the corresponding
//! National Numbering Agency, zero-padded on the left if the underlying code is shorter than nine
//! characters.
//! 3. A single decimal digit representing the _Check Digit_ computed using what the standard calls
//! the "modulus 10 'double-add-double' check digit".
//!
//! Use the `parse()` or `parse_loose()` methods on the ISIN type to convert a string to a validated
//! ISIN.
//!
//! ## Related crates
//!
//! This crate is part of the Financial Identifiers series:
//!
//! * [CUSIP](https://crates.io/crates/cusip): Committee on Uniform Security Identification Procedures (ANSI X9.6-2020)
//! * [ISIN](https://crates.io/crates/isin): International Securities Identification Number (ISO 6166:2021)
//! * [LEI](https://crates.io/crates/lei): Legal Entity Identifier (ISO 17442:2020)
//!

use std::fmt;
use std::str::from_utf8_unchecked;
use std::str::FromStr;

pub mod checksum;

use checksum::checksum_table;

pub mod error;
pub use error::Error;

/// Type alias for backward compatibility. Do not use in new code.
#[deprecated(since = "0.1.8", note = "please use `Error` instead")]
pub type ParseError = Error;

/// Type alias for backward compatibility. Do not use in new code.
#[deprecated(since = "0.1.18", note = "please use `Error` instead")]
pub type ISINError = Error;

/// Compute the _check digit_ for an array of u8. No attempt is made to ensure the input string
/// is in the ISIN payload format or length. If an illegal character (not an ASCII digit and not
/// an ASCII uppercase letter) is encountered, this function will panic.
pub fn compute_check_digit(s: &[u8]) -> u8 {
    let sum = checksum_table(s);
    b'0' + sum
}

fn validate_prefix_format(cc: &[u8]) -> Result<(), Error> {
    for b in cc {
        if !(b.is_ascii_alphabetic() && b.is_ascii_uppercase()) {
            let mut cc_copy: [u8; 2] = [0; 2];
            cc_copy.copy_from_slice(cc);
            return Err(Error::InvalidPrefix { was: cc_copy });
        }
    }
    Ok(())
}

fn validate_basic_code_format(si: &[u8]) -> Result<(), Error> {
    for b in si {
        if !(b.is_ascii_digit() || (b.is_ascii_alphabetic() && b.is_ascii_uppercase())) {
            let mut si_copy: [u8; 9] = [0; 9];
            si_copy.copy_from_slice(si);
            return Err(Error::InvalidBasicCode { was: si_copy });
        }
    }
    Ok(())
}

fn validate_check_digit_format(cd: u8) -> Result<(), Error> {
    if !cd.is_ascii_digit() {
        Err(Error::InvalidCheckDigit { was: cd })
    } else {
        Ok(())
    }
}

/// Parse a string to a valid ISIN or an error message, requiring the string to already be only
/// uppercase alphanumerics with no leading or trailing whitespace in addition to being the
/// right length and format.
pub fn parse(value: &str) -> Result<ISIN, Error> {
    if value.len() != 12 {
        return Err(Error::InvalidLength { was: value.len() });
    }

    // We make the preliminary assumption that the string is pure ASCII, so we work with the
    // underlying bytes. If there is Unicode in the string, the bytes will be outside the
    // allowed range and format validations will fail.

    let b = value.as_bytes();

    // We slice out the three fields and validate their formats.

    let cc: &[u8] = &b[0..2];
    validate_prefix_format(cc)?;

    let si: &[u8] = &b[2..11];
    validate_basic_code_format(si)?;

    let cd = b[11];
    validate_check_digit_format(cd)?;

    // Now, we need to compute the correct check digit value from the "payload" (everything except
    // the check digit).

    let payload = &b[0..11];

    let computed_check_digit = compute_check_digit(payload);

    let incorrect_check_digit = cd != computed_check_digit;
    if incorrect_check_digit {
        return Err(Error::IncorrectCheckDigit {
            was: cd,
            expected: computed_check_digit,
        });
    }

    let mut bb = [0u8; 12];
    bb.copy_from_slice(b);

    Ok(ISIN(bb))
}

/// Forwards to `parse()` for backward compatibility. Do not use in new code.
#[deprecated(since = "0.1.7", note = "please use `isin::parse` instead")]
pub fn parse_strict(value: &str) -> Result<ISIN, Error> {
    parse(value)
}

/// Parse a string to a valid ISIN or an error, allowing the string to contain leading
/// or trailing whitespace and/or lowercase letters as long as it is otherwise the right length
/// and format.
pub fn parse_loose(value: &str) -> Result<ISIN, Error> {
    let uc = value.to_ascii_uppercase();
    let temp = uc.trim();
    parse(temp)
}

/// Build an ISIN from a _Payload_ (an already-concatenated _Prefix_ and _Basic Code_). The
/// _Check Digit is automatically computed.
pub fn build_from_payload(payload: &str) -> Result<ISIN, Error> {
    if payload.len() != 11 {
        return Err(Error::InvalidPayloadLength { was: payload.len() });
    }
    let b = &payload.as_bytes()[0..11];

    let prefix = &b[0..2];
    validate_prefix_format(prefix)?;

    let basic_code = &b[2..11];
    validate_basic_code_format(basic_code)?;

    let mut bb = [0u8; 12];

    bb[0..11].copy_from_slice(b);
    bb[11] = compute_check_digit(b);

    Ok(ISIN(bb))
}

/// Build an ISIN from its parts: an _Prefix_ and an _Basic Code_. The _Check Digit_ is
/// automatically computed.
pub fn build_from_parts(prefix: &str, basic_code: &str) -> Result<ISIN, Error> {
    if prefix.len() != 2 {
        return Err(Error::InvalidPrefixLength { was: prefix.len() });
    }
    let prefix: &[u8] = &prefix.as_bytes()[0..2];
    validate_prefix_format(prefix)?;

    if basic_code.len() != 9 {
        return Err(Error::InvalidBasicCodeLength {
            was: basic_code.len(),
        });
    }
    let basic_code: &[u8] = &basic_code.as_bytes()[0..9];
    validate_basic_code_format(basic_code)?;

    let mut bb = [0u8; 12];

    bb[0..2].copy_from_slice(prefix);
    bb[2..11].copy_from_slice(basic_code);
    bb[11] = compute_check_digit(&bb[0..11]);

    Ok(ISIN(bb))
}

/// Test whether or not the passed string is in valid ISIN format, without producing a ISIN struct
/// value.
pub fn validate(value: &str) -> bool {
    if value.len() != 12 {
        return false;
    }

    // We make the preliminary assumption that the string is pure ASCII, so we work with the
    // underlying bytes. If there is Unicode in the string, the bytes will be outside the
    // allowed range and format validations will fail.

    let b = value.as_bytes();

    // We slice out the three fields and validate their formats.

    let prefix: &[u8] = &b[0..2];
    if validate_prefix_format(prefix).is_err() {
        return false;
    }

    let basic_code: &[u8] = &b[2..11];
    if validate_basic_code_format(basic_code).is_err() {
        return false;
    }

    let cd = b[11];
    if validate_check_digit_format(cd).is_err() {
        return false;
    }

    let payload = &b[0..11];

    let computed_check_digit = compute_check_digit(payload);

    let incorrect_check_digit = cd != computed_check_digit;

    !incorrect_check_digit
}

#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;

/// An ISIN in confirmed valid format.
///
/// You cannot construct an ISIN value manually. This does not compile:
///
/// ```compile_fail
/// use isin;
/// let cannot_construct = isin::ISIN([0_u8; 12]);
/// ```
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Hash)]
#[repr(transparent)]
#[allow(clippy::upper_case_acronyms)]
pub struct ISIN([u8; 12]);

impl AsRef<str> for ISIN {
    fn as_ref(&self) -> &str {
        unsafe { from_utf8_unchecked(&self.0[..]) } // This is safe because we know it is ASCII
    }
}

impl fmt::Display for ISIN {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let temp = unsafe { from_utf8_unchecked(self.as_bytes()) }; // This is safe because we know it is ASCII
        write!(f, "{temp}")
    }
}

impl fmt::Debug for ISIN {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let temp = unsafe { from_utf8_unchecked(self.as_bytes()) }; // This is safe because we know it is ASCII
        write!(f, "ISIN({temp})")
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for ISIN {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor;

        impl serde::de::Visitor<'_> for Visitor {
            type Value = ISIN;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("an ISIN")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                crate::parse(v).map_err(E::custom)
            }
        }

        deserializer.deserialize_str(Visitor)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for ISIN {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_ref())
    }
}

impl FromStr for ISIN {
    type Err = Error;

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

impl ISIN {
    /// Internal convenience function for treating the ASCII characters as a byte-array slice.
    fn as_bytes(&self) -> &[u8] {
        &self.0[..]
    }

    /// Forwards to crate-level `parse()` for backward compatibility. Do not use in new code.
    #[deprecated(since = "0.1.7", note = "please use `isin::parse` instead")]
    pub fn parse_strict<S>(value: S) -> Result<ISIN, Error>
    where
        S: Into<String>,
    {
        let v: String = value.into();
        crate::parse(&v)
    }

    /// Forwards to crate-level `parse_loose()` for backward compatibility. Do not use in new code.
    #[deprecated(since = "0.1.7", note = "please use `isin::parse_loose` instead")]
    pub fn parse_loose<S>(value: S) -> Result<ISIN, Error>
    where
        S: Into<String>,
    {
        let v: String = value.into();
        crate::parse_loose(&v)
    }

    /// Return a string representation of the ISIN.
    #[deprecated(since = "0.1.7", note = "please use `to_string` instead")]
    pub fn value(&self) -> &str {
        unsafe { from_utf8_unchecked(&self.0[..]) } // This is safe because we know it is ASCII
    }

    /// Return just the _Prefix_ portion of the ISIN.
    pub fn prefix(&self) -> &str {
        unsafe { from_utf8_unchecked(&self.0[0..2]) } // This is safe because we know it is ASCII
    }

    /// Return just the _Prefix_ portion of the ISIN.
    #[deprecated(since = "0.1.8", note = "please use `prefix` instead")]
    pub fn country_code(&self) -> &str {
        self.prefix()
    }

    /// Return just the _Basic Code_ portion of the ISIN.
    pub fn basic_code(&self) -> &str {
        unsafe { from_utf8_unchecked(&self.0[2..11]) } // This is safe because we know it is ASCII
    }

    /// Return just the _Basic Code_ portion of the ISIN.
    #[deprecated(since = "0.1.8", note = "please use `basic_code` instead")]
    pub fn security_identifier(&self) -> &str {
        self.basic_code()
    }

    /// Return the _Payload_ &mdash; everything except the _Check Digit_.
    pub fn payload(&self) -> &str {
        unsafe { from_utf8_unchecked(&self.0[0..11]) } // This is safe because we know it is ASCII
    }

    /// Return just the _Check Digit_ portion of the ISIN.
    pub fn check_digit(&self) -> char {
        self.0[11] as char
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    #[test]
    fn parse_isin_for_apple_strict() {
        match parse("US0378331005") {
            Ok(isin) => {
                assert_eq!(isin.to_string(), "US0378331005");
                assert_eq!(isin.prefix(), "US");
                assert_eq!(isin.basic_code(), "037833100");
                assert_eq!(isin.check_digit(), '5');
            }
            Err(err) => panic!("Did not expect parsing to fail: {}", err),
        }
    }

    #[test]
    fn build_isin_for_apple_from_payload() {
        match build_from_payload("US037833100") {
            Ok(isin) => {
                assert_eq!(isin.to_string(), "US0378331005");
                assert_eq!(isin.prefix(), "US");
                assert_eq!(isin.basic_code(), "037833100");
                assert_eq!(isin.check_digit(), '5');
            }
            Err(err) => panic!("Did not expect building to fail: {}", err),
        }
    }

    #[test]
    fn build_isin_for_apple_from_parts() {
        match build_from_parts("US", "037833100") {
            Ok(isin) => {
                assert_eq!(isin.to_string(), "US0378331005");
                assert_eq!(isin.prefix(), "US");
                assert_eq!(isin.basic_code(), "037833100");
                assert_eq!(isin.check_digit(), '5');
            }
            Err(err) => panic!("Did not expect building to fail: {}", err),
        }
    }

    #[test]
    fn parse_isin_for_apple_loose() {
        match parse_loose("\tus0378331005    ") {
            Ok(isin) => {
                assert_eq!(isin.to_string(), "US0378331005");
                assert_eq!(isin.prefix(), "US");
                assert_eq!(isin.basic_code(), "037833100");
                assert_eq!(isin.check_digit(), '5');
            }
            Err(err) => panic!("Did not expect parsing to fail: {}", err),
        }
    }

    #[test]
    fn validate_examples_from_standard_annex_c() {
        assert!(validate("ES0SI0000005")); // Example 1, page 10: "IBEX 35"
        assert!(validate("JP3788600009")); // Example 2, page 11: "Hitachi Ltd. Shares"
        assert!(validate("DE000A0GNPZ3")); // Example 3, page 11: "Allianz Finance II 5 3/8% without expiration date"
    }

    #[test]
    fn validate_examples_from_standard_annex_e() {
        assert!(validate("JP3788600009")); // Page 13
        assert!(validate("US9047847093")); // Page 13
        assert!(validate("IE00BFXC1P95")); // Page 13
        assert!(validate("DE000A0GNPZ3")); // Page 13
        assert!(validate("XS2021448886")); // Page 13
        assert!(validate("US36962GXZ26")); // Page 13
        assert!(validate("FR0000571077")); // Page 13
        assert!(validate("US277847UB38")); // Page 13
        assert!(validate("US65412AEW80")); // Page 13
        assert!(validate("GB00BF0FCW58")); // Page 13
        assert!(validate("FR0000312928")); // Page 13
        assert!(validate("DE000DL3T7M1")); // Page 13

        assert!(validate("ES0A02234250")); // Page 14
        assert!(validate("EZR9HY1361L7")); // Page 14
        assert!(validate("CH0107166065")); // Page 14
        assert!(validate("XS0313614355")); // Page 14
        assert!(validate("DE000A0AE077")); // Page 14
        assert!(validate("CH0002813860")); // Page 14
        assert!(validate("TRLTCMB00045")); // Page 14
        assert!(validate("ES0SI0000005")); // Page 14
        assert!(validate("GB00B56Z6W79")); // Page 14
        assert!(validate("AU000000SKI7")); // Page 14
        assert!(validate("EU000A1RRN98")); // Page 14
        assert!(validate("LI0024807526")); // Page 14
    }

    #[test]
    fn reject_empty_string() {
        let res = parse("");
        assert!(res.is_err());
    }

    #[test]
    fn reject_lowercase_prefix_if_strict() {
        match parse("us0378331005") {
            Err(Error::InvalidPrefix { was: _ }) => {} // Ok
            Err(err) => {
                panic!(
                    "Expected Err(InvalidPrefix {{ ... }}), but got: Err({:?})",
                    err
                )
            }
            Ok(isin) => {
                panic!(
                    "Expected Err(InvalidPrefix {{ ... }}), but got: Ok({:?})",
                    isin
                )
            }
        }
    }

    #[test]
    fn reject_lowercase_basic_code_if_strict() {
        match parse("US09739d1000") {
            Err(Error::InvalidBasicCode { was: _ }) => {} // Ok
            Err(err) => {
                panic!(
                    "Expected Err(InvalidBasicCode {{ ... }}), but got: Err({:?})",
                    err
                )
            }
            Ok(isin) => {
                panic!(
                    "Expected Err(InvalidBasicCode {{ ... }}), but got: Ok({:?})",
                    isin
                )
            }
        }
    }

    #[test]
    fn parse_isin_with_0_check_digit() {
        parse("US09739D1000").unwrap(); // BCC aka Boise Cascade
    }

    #[test]
    fn parse_isin_with_1_check_digit() {
        parse("US4581401001").unwrap(); // INTC aka Intel
    }

    #[test]
    fn parse_isin_with_2_check_digit() {
        parse("US98421M1062").unwrap(); // XRX aka Xerox
    }

    #[test]
    fn parse_isin_with_3_check_digit() {
        parse("US02376R1023").unwrap(); // AAL aka American Airlines
    }

    #[test]
    fn parse_isin_with_4_check_digit() {
        parse("US9216591084").unwrap(); // VNDA aka Vanda Pharmaceuticals
    }

    #[test]
    fn parse_isin_with_5_check_digit() {
        parse("US0207721095").unwrap(); // APT aka AlphaProTec
    }

    #[test]
    fn parse_isin_with_6_check_digit() {
        parse("US71363P1066").unwrap(); // PRDO aka Perdoceo Education
    }

    #[test]
    fn parse_isin_with_7_check_digit() {
        parse("US5915202007").unwrap(); // MEI aka Methode Electronics
    }

    #[test]
    fn parse_isin_with_8_check_digit() {
        parse("US4570301048").unwrap(); // IMKTA aka Ingles Markets
    }

    #[test]
    fn parse_isin_with_9_check_digit() {
        parse("US8684591089").unwrap(); // SUPN aka Supernus Pharmaceuticals
    }

    #[test]
    fn test_unicode_gibberish() {
        assert!(parse("𑴈𐎟 0 A").is_err());
    }

    proptest! {
        #[test]
        #[allow(unused_must_use)]
        fn doesnt_crash(s in "\\PC*") {
            parse(&s);
        }
    }

    #[cfg(feature = "serde")]
    mod serde {
        use crate::ISIN;

        use proptest::{prop_assert, prop_assert_eq, proptest};
        use serde::de::value::{self, StrDeserializer};
        use serde::Deserialize as _;

        #[test]
        fn deserialize_apple() {
            let isin = ISIN::deserialize(StrDeserializer::<value::Error>::new("US0378331005"))
                .expect("successful deserialization");
            assert_eq!(isin.to_string(), "US0378331005");
            assert_eq!(isin.prefix(), "US");
            assert_eq!(isin.basic_code(), "037833100");
            assert_eq!(isin.check_digit(), '5');
        }

        #[test]
        fn reject_empty_string() {
            let _ = ISIN::deserialize(StrDeserializer::<value::Error>::new(""))
                .expect_err("unsuccessful deserialization");
        }

        #[test]
        fn reject_lowercase_prefix_if_strict() {
            let _ = ISIN::deserialize(StrDeserializer::<value::Error>::new("us0378331005"))
                .expect_err("unsuccessful deserialization");
        }

        #[test]
        fn reject_lowercase_basic_code_if_strict() {
            let _ = ISIN::deserialize(StrDeserializer::<value::Error>::new("US09739d1000"))
                .expect_err("unsuccessful deserialization");
        }

        proptest! {
            #[test]
            fn doesnt_crash(s in "\\PC*") {
                let _ = ISIN::deserialize(StrDeserializer::<value::Error>::new(&s));
            }

            #[test]
            fn matches_parse(s in "\\PC*") {
                let parse_result = crate::parse(&s);
                let deserialize_result = ISIN::deserialize(StrDeserializer::<value::Error>::new(&s));

                match (parse_result, deserialize_result)
                {
                    (Ok(parsed_isin), Ok(deserialized_isin)) => prop_assert_eq!(parsed_isin, deserialized_isin),
                    (Ok(_), Err(_)) | (Err(_), Ok(_)) => prop_assert!(false),
                    (Err(_), Err(_)) => {}
                 }
            }
        }
    }
}