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
use std::error::Error;
use std::fmt::Formatter;
use std::fmt::{Debug, Display};
use std::str::FromStr;
use bstr::ByteSlice;
pub mod checksum;
use checksum::checksum_table;
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq)]
pub enum ParseError {
InvalidLength { was: usize },
InvalidCountryCode { was: [u8; 2] },
InvalidSecurityIdentifier { was: [u8; 9] },
InvalidCheckDigit { was: u8 },
IncorrectCheckDigit { was: u8, expected: u8 },
}
impl Debug for ParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ParseError::InvalidLength { was } => {
write!(f, "InvalidLength {{ was: {:?} }}", was)
}
ParseError::InvalidCountryCode { was } => match std::str::from_utf8(was) {
Ok(s) => {
write!(f, "InvalidCountryCode {{ was: {:?} }}", s)
}
Err(_) => {
write!(f, "InvalidCountryCode {{ was: (invalid UTF-8) {:?} }}", was)
}
},
ParseError::InvalidSecurityIdentifier { was } => match std::str::from_utf8(was) {
Ok(s) => {
write!(f, "InvalidSecurityIdentifier {{ was: {:?} }}", s)
}
Err(_) => {
write!(
f,
"InvalidSecurityIdentifier {{ was: (invalid UTF-8) {:?} }}",
was
)
}
},
ParseError::InvalidCheckDigit { was } => {
write!(f, "InvalidCheckDigit {{ was: {:?} }}", char::from(*was))
}
ParseError::IncorrectCheckDigit { was, expected } => {
write!(
f,
"IncorrectCheckDigit {{ was: {:?}, expected: {:?} }}",
char::from(*was),
char::from(*expected)
)
}
}
}
}
impl Display for ParseError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
ParseError::InvalidLength { was } => {
write!(f, "invalid length {} bytes when expecting 12", was)
}
ParseError::InvalidCountryCode { was } => match std::str::from_utf8(was) {
Ok(s) => {
write!(f,
"invalid country code {:?} is not two uppercase ASCII alphabetic characters",
s)
}
Err(_) => {
write!(f,
"invalid country code (invalid UTF-8) {:?} is not two uppercase ASCII alphabetic characters",
was)
}
},
ParseError::InvalidSecurityIdentifier { was } => match std::str::from_utf8(was) {
Ok(s) => {
write!(f,
"invalid security identifier {:?} is not nine uppercase ASCII alphanumeric characters",
s)
}
Err(_) => {
write!(f,
"invalid security identifier (invalid UTF-8) {:?} is not nine uppercase ASCII alphanumeric characters",
was)
}
},
ParseError::InvalidCheckDigit { was } => {
write!(
f,
"invalid check digit {:?} is not one ASCII decimal digit",
*was as char
)
}
ParseError::IncorrectCheckDigit { was, expected } => {
write!(
f,
"incorrect check digit {:?} when expecting {:?}",
char::from(*was),
char::from(*expected)
)
}
}
}
}
impl Error for ParseError {}
pub fn compute_check_digit(s: &[u8]) -> u8 {
let sum = checksum_table(s);
b'0' + sum
}
fn validate_country_code_format(cc: &[u8]) -> Result<(), ParseError> {
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(ParseError::InvalidCountryCode { was: cc_copy });
}
}
Ok(())
}
fn validate_security_id_format(si: &[u8]) -> Result<(), ParseError> {
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(ParseError::InvalidSecurityIdentifier { was: si_copy });
}
}
Ok(())
}
fn validate_check_digit_format(cd: u8) -> Result<(), ParseError> {
if !cd.is_ascii_digit() {
Err(ParseError::InvalidCheckDigit { was: cd })
} else {
Ok(())
}
}
pub fn parse_strict(value: &str) -> Result<ISIN, ParseError> {
let v: String = value.into();
if v.len() != 12 {
return Err(ParseError::InvalidLength { was: v.len() });
}
let b = v.as_bytes();
let cc: &[u8] = &b[0..2];
validate_country_code_format(cc)?;
let si: &[u8] = &b[2..11];
validate_security_id_format(si)?;
let cd = b[11];
validate_check_digit_format(cd)?;
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(ParseError::IncorrectCheckDigit {
was: cd,
expected: computed_check_digit,
});
}
let mut b = [0u8; 12];
b.copy_from_slice(v.as_bytes());
Ok(ISIN(b))
}
pub fn parse_loose(value: &str) -> Result<ISIN, ParseError> {
let uc = value.to_ascii_uppercase();
let temp = uc.trim();
parse_strict(temp)
}
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Hash, Debug)]
#[repr(transparent)]
pub struct ISIN([u8; 12]);
impl Display for ISIN {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let temp = unsafe { self.0[..].to_str_unchecked() };
write!(f, "{}", temp)
}
}
impl FromStr for ISIN {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_loose(s)
}
}
impl ISIN {
#[deprecated(since = "0.1.7", note = "please use `isin::parse_strict` instead")]
pub fn parse_strict<S>(value: S) -> Result<ISIN, ParseError>
where
S: Into<String>,
{
let v: String = value.into();
crate::parse_strict(&v)
}
#[deprecated(since = "0.1.7", note = "please use `isin::parse_loose` instead")]
pub fn parse_loose<S>(value: S) -> Result<ISIN, ParseError>
where
S: Into<String>,
{
let v: String = value.into();
crate::parse_loose(&v)
}
#[deprecated(since = "0.1.7", note = "please use `to_string` instead")]
pub fn value(&self) -> &str {
unsafe { self.0[..].to_str_unchecked() }
}
pub fn country_code(&self) -> &str {
unsafe { self.0[0..2].to_str_unchecked() }
}
pub fn security_identifier(&self) -> &str {
unsafe { self.0[2..11].to_str_unchecked() }
}
pub fn payload(&self) -> &str {
unsafe { self.0[0..11].to_str_unchecked() }
}
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_strict("US0378331005") {
Ok(isin) => {
assert_eq!(isin.to_string(), "US0378331005");
assert_eq!(isin.country_code(), "US");
assert_eq!(isin.security_identifier(), "037833100");
assert_eq!(isin.check_digit(), '5');
}
Err(_) => assert!(false, "Did not expect parsing to fail"),
}
}
#[test]
fn parse_isin_for_apple_loose() {
match parse_loose("\tus0378331005 ") {
Ok(isin) => {
assert_eq!(isin.to_string(), "US0378331005");
assert_eq!(isin.country_code(), "US");
assert_eq!(isin.security_identifier(), "037833100");
assert_eq!(isin.check_digit(), '5');
}
Err(_) => assert!(false, "Did not expect parsing to fail"),
}
}
#[test]
fn reject_empty_string() {
let res = parse_strict("");
assert!(res.is_err());
}
#[test]
fn reject_lowercase_country_code_if_strict() {
let res = parse_strict("us0378331005");
assert!(res.is_err());
}
#[test]
fn reject_lowercase_security_id_if_strict() {
let res = parse_strict("US09739d1000");
assert!(res.is_err());
}
#[test]
fn parse_isin_with_0_check_digit() {
parse_strict("US09739D1000").unwrap();
}
#[test]
fn parse_isin_with_1_check_digit() {
parse_strict("US4581401001").unwrap();
}
#[test]
fn parse_isin_with_2_check_digit() {
parse_strict("US98421M1062").unwrap();
}
#[test]
fn parse_isin_with_3_check_digit() {
parse_strict("US02376R1023").unwrap();
}
#[test]
fn parse_isin_with_4_check_digit() {
parse_strict("US9216591084").unwrap();
}
#[test]
fn parse_isin_with_5_check_digit() {
parse_strict("US0207721095").unwrap();
}
#[test]
fn parse_isin_with_6_check_digit() {
parse_strict("US71363P1066").unwrap();
}
#[test]
fn parse_isin_with_7_check_digit() {
parse_strict("US5915202007").unwrap();
}
#[test]
fn parse_isin_with_8_check_digit() {
parse_strict("US4570301048").unwrap();
}
#[test]
fn parse_isin_with_9_check_digit() {
parse_strict("US8684591089").unwrap();
}
#[test]
fn test_unicode_gibberish() {
assert_eq!(true, parse_strict("𑴈𐎟 0 A").is_err());
}
proptest! {
#[test]
#[allow(unused_must_use)]
fn doesnt_crash(s in "\\PC*") {
parse_strict(&s);
}
}
}