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
use crate::IbanLike;
use arrayvec::ArrayString;
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;
use thiserror::Error;
const MAX_IBAN_LEN: usize = 34;
const MAX_IBAN_LEN_PRETTY: usize = MAX_IBAN_LEN + MAX_IBAN_LEN / 4;
const MIN_IBAN_LEN: usize = 5;
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub struct BaseIban {
s: ArrayString<[u8; MAX_IBAN_LEN]>,
}
#[cfg(feature = "serde")]
impl Serialize for BaseIban {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
serializer.serialize_str(self.electronic_str())
}
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for BaseIban {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct IbanStringVisitor;
use serde::de;
impl<'vi> de::Visitor<'vi> for IbanStringVisitor {
type Value = BaseIban;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "an IBAN string")
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<BaseIban, E> {
value.parse::<BaseIban>().map_err(E::custom)
}
}
deserializer.deserialize_str(IbanStringVisitor)
}
}
impl IbanLike for BaseIban {
fn electronic_str(&self) -> &str {
self.s.as_str()
}
}
impl fmt::Debug for BaseIban {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.s.fmt(f)
}
}
impl fmt::Display for BaseIban {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut chars = self.electronic_str().chars().peekable();
loop {
for _ in 0..4 {
if let Some(c) = chars.next() {
write!(f, "{}", c)?;
} else {
return Ok(());
}
}
if chars.peek().is_some() {
write!(f, " ")?;
}
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Error)]
pub enum ParseBaseIbanError {
#[error("the string doesn't conform to the IBAN format")]
InvalidFormat,
#[error("the IBAN has an invalid checksum")]
InvalidChecksum,
}
impl BaseIban {
fn compute_checksum(address: &str) -> u8 {
address
.chars()
.cycle()
.skip(4)
.take(address.len())
.fold(0, |acc, c| {
let digit = c.to_digit(36).expect(
"An address was supplied to compute_checksum with an invalid \
character. Please file an issue at \
https://github.com/ThomasdenH/iban_validate.",
);
let multiplier = if digit > 9 { 100 } else { 10 };
(acc * multiplier + digit) % 97
}) as u8
}
fn try_form_string_from_electronic<T>(
mut chars: T,
) -> Result<ArrayString<[u8; MAX_IBAN_LEN]>, ParseBaseIbanError>
where
T: Iterator<Item = char>,
{
let mut address_no_spaces = ArrayString::<[u8; MAX_IBAN_LEN]>::new();
for _ in 0..2 {
let c = match chars.next() {
Some(c) if c.is_ascii_uppercase() => Ok(c),
_ => Err(ParseBaseIbanError::InvalidFormat),
}?;
address_no_spaces.try_push(c).expect(
"Could not push country code. Please create an issue at \
https://github.com/ThomasdenH/iban_validate.",
);
}
for _ in 0..2 {
let c = match chars.next() {
Some(c) if c.is_ascii_digit() => Ok(c),
_ => Err(ParseBaseIbanError::InvalidFormat),
}?;
address_no_spaces.try_push(c).expect(
"Could not push country code. Please create an issue at \
https://github.com/ThomasdenH/iban_validate.",
);
}
for c in chars {
if c.is_ascii_digit() || c.is_ascii_uppercase() {
address_no_spaces
.try_push(c)
.map_err(|_| ParseBaseIbanError::InvalidFormat)?;
} else {
return Err(ParseBaseIbanError::InvalidFormat);
}
}
Ok(address_no_spaces)
}
fn try_form_string_from_pretty_print(
s: &str,
) -> Result<ArrayString<[u8; MAX_IBAN_LEN]>, ParseBaseIbanError> {
s.chars()
.enumerate()
.find_map(|(i, c)| {
if i % 5 == 4 && c != ' ' {
Some(Err(ParseBaseIbanError::InvalidFormat))
} else {
None
}
})
.unwrap_or(Ok(()))?;
if s.ends_with(' ') {
return Err(ParseBaseIbanError::InvalidFormat);
}
BaseIban::try_form_string_from_electronic(
s.chars()
.enumerate()
.filter(|(i, _)| i % 5 != 4)
.map(|(_, c)| c),
)
}
}
impl FromStr for BaseIban {
type Err = ParseBaseIbanError;
fn from_str(address: &str) -> Result<Self, Self::Err> {
if address.len() < 5 || address.len() > MAX_IBAN_LEN_PRETTY {
return Err(ParseBaseIbanError::InvalidFormat);
}
let address_no_spaces = BaseIban::try_form_string_from_electronic(address.chars())
.or_else(|_| BaseIban::try_form_string_from_pretty_print(address))?;
if address_no_spaces.len() < MIN_IBAN_LEN {
return Err(ParseBaseIbanError::InvalidFormat);
}
if BaseIban::compute_checksum(&address_no_spaces) != 1 {
return Err(ParseBaseIbanError::InvalidChecksum);
}
Ok(BaseIban {
s: address_no_spaces,
})
}
}
impl<'a> TryFrom<&'a str> for BaseIban {
type Error = ParseBaseIbanError;
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
value.parse()
}
}