use crate::checkdigit;
use crate::country;
use crate::errors::ValidationError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Isin {
bytes: [u8; Self::LENGTH],
}
impl Isin {
pub const LENGTH: usize = 12;
pub fn parse(s: &str) -> Result<Self, ValidationError> {
let found = s.chars().count();
if found != Self::LENGTH {
return Err(ValidationError::WrongLength {
expected: Self::LENGTH,
found,
});
}
for (i, ch) in s.chars().enumerate() {
let legal = if i == Self::LENGTH - 1 {
ch.is_ascii_digit()
} else {
ch.is_ascii_digit() || ch.is_ascii_uppercase()
};
if !legal {
return Err(ValidationError::InvalidCharacter {
position: i + 1,
found: ch,
});
}
}
let mut bytes = [0u8; Self::LENGTH];
bytes.copy_from_slice(s.as_bytes());
let prefix = core::str::from_utf8(&bytes[0..2]).unwrap_or("");
if !country::is_isin_prefix(prefix) {
return Err(ValidationError::InvalidCountryCode);
}
let body = core::str::from_utf8(&bytes[0..11]).unwrap_or("");
let expected = checkdigit::isin_check_digit(body)?;
let supplied = char::from(bytes[11]);
if expected != supplied {
return Err(ValidationError::BadCheckDigit {
expected,
found: supplied,
});
}
Ok(Self { bytes })
}
pub fn validate(s: &str) -> Result<(), ValidationError> {
Self::parse(s).map(|_| ())
}
#[must_use]
pub const fn from_bytes_unchecked(bytes: [u8; Self::LENGTH]) -> Self {
Self { bytes }
}
#[must_use]
#[inline]
pub fn as_str(&self) -> &str {
core::str::from_utf8(&self.bytes).unwrap_or("")
}
#[must_use]
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
#[inline]
pub fn country_code(&self) -> &str {
core::str::from_utf8(&self.bytes[0..2]).unwrap_or("")
}
#[must_use]
#[inline]
pub fn nsin(&self) -> &str {
core::str::from_utf8(&self.bytes[2..11]).unwrap_or("")
}
#[must_use]
#[inline]
pub fn check_digit(&self) -> char {
char::from(self.bytes[11])
}
}
impl core::fmt::Display for Isin {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl core::str::FromStr for Isin {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::parse(s)
}
}
impl AsRef<str> for Isin {
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::display;
use core::str::FromStr;
const GOLDEN: &[&str] = &[
"US0378331005", "US5949181045", "GB0002634946", "DE000BAY0017", "FR0000131104", "NL0011794037", ];
#[test]
fn parses_golden_isins() {
for &s in GOLDEN {
let isin = Isin::parse(s).unwrap_or_else(|e| panic!("{s} should parse: {e}"));
assert_eq!(isin.as_str(), s);
}
}
#[test]
fn segment_accessors() {
let isin = Isin::parse("US0378331005").unwrap();
assert_eq!(isin.country_code(), "US");
assert_eq!(isin.nsin(), "037833100");
assert_eq!(isin.check_digit(), '5');
assert_eq!(isin.as_bytes(), b"US0378331005");
assert_eq!(Isin::LENGTH, 12);
}
#[test]
fn accepts_substitute_prefix() {
let isin = Isin::parse("XS0000000009").unwrap();
assert_eq!(isin.country_code(), "XS");
}
#[test]
fn rejects_bad_check_digit() {
assert_eq!(
Isin::parse("US0378331004"),
Err(ValidationError::BadCheckDigit {
expected: '5',
found: '4',
})
);
}
#[test]
fn rejects_wrong_length() {
assert_eq!(
Isin::parse("US037833100"),
Err(ValidationError::WrongLength {
expected: 12,
found: 11,
})
);
assert_eq!(
Isin::parse(""),
Err(ValidationError::WrongLength {
expected: 12,
found: 0,
})
);
}
#[test]
fn rejects_lower_case() {
assert!(matches!(
Isin::parse("us0378331005"),
Err(ValidationError::InvalidCharacter { position: 1, .. })
));
}
#[test]
fn rejects_non_digit_check_position() {
assert!(matches!(
Isin::parse("US037833100X"),
Err(ValidationError::InvalidCharacter { position: 12, .. })
));
}
#[test]
fn rejects_unknown_country_code() {
assert_eq!(
Isin::parse("ZZ0378331005"),
Err(ValidationError::InvalidCountryCode)
);
}
#[test]
fn rejects_non_ascii_without_panic() {
assert!(Isin::parse("US037833100é").is_err());
assert!(Isin::parse("ÉS0378331005").is_err());
}
#[test]
fn round_trips_through_str() {
for &s in GOLDEN {
assert_eq!(Isin::parse(s).unwrap().as_str(), s);
}
}
#[test]
fn from_str_matches_parse() {
assert_eq!(Isin::from_str("US0378331005"), Isin::parse("US0378331005"));
assert!(Isin::from_str("nonsense").is_err());
}
#[test]
fn display_renders_identifier() {
let isin = Isin::parse("US0378331005").unwrap();
assert_eq!(display(isin).as_str(), "US0378331005");
}
#[test]
fn as_ref_str() {
let isin = Isin::parse("US0378331005").unwrap();
let s: &str = isin.as_ref();
assert_eq!(s, "US0378331005");
}
#[test]
fn from_bytes_unchecked_round_trip() {
let isin = Isin::from_bytes_unchecked(*b"US0378331005");
assert_eq!(isin, Isin::parse("US0378331005").unwrap());
}
#[test]
fn is_copy_and_eq_and_hashable() {
let a = Isin::parse("US0378331005").unwrap();
let b = a; assert_eq!(a, b);
assert_ne!(a, Isin::parse("US5949181045").unwrap());
let keys = [a, b];
assert_eq!(keys[0], keys[1]);
}
}