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
extern crate regex;
extern crate time;
#[macro_use]
extern crate lazy_static;
pub mod belfiore;
mod utils;
use belfiore::*;
use regex::Regex;
use std::collections::HashMap;
use utils::*;
#[derive(Debug, PartialEq)]
pub enum Error {
InvalidLength,
InvalidCheckChar,
InvalidName,
InvalidSurname,
InvalidBirthdate(Option<String>),
InvalidBelfioreCode,
}
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Gender {
M,
F,
}
#[derive(Debug, Clone, PartialEq)]
pub struct PersonData {
pub name: String,
pub surname: String,
pub birthdate: String,
pub gender: Gender,
pub place_of_birth: Municipality,
}
#[derive(Debug, Clone, PartialEq)]
struct CodiceFiscaleParts {
surname: String,
name: String,
birthyear: String,
birthmonth: char,
birthday: String,
birthdate: String,
place_of_birth: Municipality,
checkchar: char,
}
#[derive(Debug, PartialEq)]
pub struct CodiceFiscale {
person_data: PersonData,
codice: String,
codice_parts: CodiceFiscaleParts,
}
const CENTURY_BASE: i32 = 2000; const MONTHLETTERS: [char; 12] = ['A', 'B', 'C', 'D', 'E', 'H', 'L', 'M', 'P', 'R', 'S', 'T'];
const CHECKMODULI: [char; 26] = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
const DATE_FORMAT: &'static [time::format_description::FormatItem<'static>] = time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute] [offset_hour sign:mandatory]:[offset_minute]"
);
lazy_static! {
static ref CHECKCHARS: HashMap<char, (u8, u8)> = {
let mut m = HashMap::new();
m.insert('A', (1, 0));
m.insert('B', (0, 1));
m.insert('C', (5, 2));
m.insert('D', (7, 3));
m.insert('E', (9, 4));
m.insert('F', (13, 5));
m.insert('G', (15, 6));
m.insert('H', (17, 7));
m.insert('I', (19, 8));
m.insert('J', (21, 9));
m.insert('K', (2, 10));
m.insert('L', (4, 11));
m.insert('M', (18, 12));
m.insert('N', (20, 13));
m.insert('O', (11, 14));
m.insert('P', (3, 15));
m.insert('Q', (6, 16));
m.insert('R', (8, 17));
m.insert('S', (12, 18));
m.insert('T', (14, 19));
m.insert('U', (16, 20));
m.insert('V', (10, 21));
m.insert('W', (22, 22));
m.insert('X', (25, 23));
m.insert('Y', (24, 24));
m.insert('Z', (23, 25));
m.insert('0', (1, 0));
m.insert('1', (0, 1));
m.insert('2', (5, 2));
m.insert('3', (7, 3));
m.insert('4', (9, 4));
m.insert('5', (13, 5));
m.insert('6', (15, 6));
m.insert('7', (17, 7));
m.insert('8', (19, 8));
m.insert('9', (21, 9));
m
};
pub static ref BELFIORE_STORE: Belfiore = Belfiore::init();
}
impl CodiceFiscale {
pub fn check(codice: &str) -> Result<(), Error> {
CodiceFiscale::parse(codice)?;
Ok(())
}
pub fn new(initdata: &PersonData) -> Result<CodiceFiscale, Error> {
let mut cf = CodiceFiscale {
person_data: initdata.clone(),
codice: "".to_string(),
codice_parts: CodiceFiscaleParts {
surname: "".to_string(),
name: "".to_string(),
birthyear: "".to_string(),
birthmonth: '_',
birthday: "".to_string(),
birthdate: "".to_string(),
place_of_birth: Municipality::default(),
checkchar: '_',
},
};
let mut codice = "".to_string();
codice.push_str(cf.calc_surname());
codice.push_str(cf.calc_name());
codice.push_str(cf.calc_birthdate()?);
codice.push_str(cf.calc_belfiore()?);
cf.codice = codice.clone();
codice.push(cf.calc_checkchar());
cf.codice = codice;
Ok(cf)
}
pub fn parse(codice: &str) -> Result<CodiceFiscale, Error> {
let mut cf = CodiceFiscale {
person_data: PersonData {
name: "".to_string(),
surname: "".to_string(),
birthdate: "".to_string(),
gender: Gender::M,
place_of_birth: Municipality::default(),
},
codice: "".to_string(),
codice_parts: CodiceFiscaleParts {
surname: "".to_string(),
name: "".to_string(),
birthyear: "".to_string(),
birthmonth: '_',
birthday: "".to_string(),
birthdate: "".to_string(),
place_of_birth: Municipality::default(),
checkchar: '_',
},
};
if codice.len() != 16 {
return Err(Error::InvalidLength);
}
let mut codice_nolast = codice.to_uppercase();
let codice_checkchar = match codice_nolast.pop() {
Some(cc) => cc,
None => return Err(Error::InvalidCheckChar),
};
cf.codice = codice_nolast;
if cf.calc_checkchar() != codice_checkchar {
return Err(Error::InvalidCheckChar);
}
cf.codice_parts.surname = codice[0..3].to_string();
if !Regex::new("^[A-Z]{3}$")
.unwrap()
.is_match(&cf.codice_parts.surname)
{
return Err(Error::InvalidSurname);
}
cf.person_data.surname = cf.codice_parts.surname.clone();
cf.codice_parts.name = codice[3..6].to_string();
if !Regex::new("^[A-Z]{3}$")
.unwrap()
.is_match(&cf.codice_parts.name)
{
return Err(Error::InvalidName);
}
cf.person_data.name = cf.codice_parts.name.clone();
cf.codice_parts.birthyear = codice[6..8].to_string();
let birthyear_num = CENTURY_BASE
+ i32::from_str_radix(&cf.codice_parts.birthyear, 10)
.map_err(|_| Error::InvalidBirthdate(Some(cf.codice_parts.birthyear.clone())))?;
let tm_now_year = time::OffsetDateTime::now_utc().year();
let birthyear = if tm_now_year > birthyear_num {
birthyear_num
} else {
birthyear_num - 100
};
cf.codice_parts.birthmonth = codice.chars().nth(8).unwrap();
let birthday = codice[9..11].to_string();
let mut birthday: u8 = birthday
.parse()
.map_err(|_| Error::InvalidBirthdate(Some(birthday)))?;
if birthday > 40 {
cf.person_data.gender = Gender::F;
birthday -= 40;
}
cf.codice_parts.birthday = format!("{:02}", birthday);
let mut birthdate: String = format!("{:04}", birthyear);
birthdate.push('-');
let birthmonth = MONTHLETTERS
.binary_search(&cf.codice_parts.birthmonth)
.map_err(|_| Error::InvalidBirthdate(None))?;
birthdate.push_str(&format!("{:02}", (birthmonth + 1)));
birthdate.push('-');
birthdate.push_str(&cf.codice_parts.birthday);
match time::OffsetDateTime::parse(&(birthdate.clone() + " 00:00 +00:00"), DATE_FORMAT) {
Ok(_v) => cf.person_data.birthdate = birthdate,
Err(_e) => return Err(Error::InvalidBirthdate(Some(birthdate.clone()))),
};
cf.codice_parts.place_of_birth = match BELFIORE_STORE.lookup_belfiore(&codice[11..15]) {
Some(x) => x.clone(),
None => return Err(Error::InvalidBelfioreCode),
};
cf.person_data.place_of_birth = cf.codice_parts.place_of_birth.clone();
cf.codice.push(codice_checkchar);
Ok(cf)
}
pub fn get_codice(&self) -> &str {
&self.codice
}
pub fn get_person_data(&self) -> &PersonData {
&self.person_data
}
pub fn is_name_valid(&self, name: &str) -> bool {
calc_name_component(name) == self.codice_parts.name
}
pub fn is_surname_valid(&self, surname: &str) -> bool {
calc_surname_component(surname) == self.codice_parts.surname
}
fn calc_surname(&mut self) -> &str {
self.codice_parts.surname = calc_surname_component(&self.person_data.surname);
&self.codice_parts.surname
}
fn calc_name(&mut self) -> &str {
self.codice_parts.name = calc_name_component(&self.person_data.name);
&self.codice_parts.name
}
fn calc_birthdate(&mut self) -> Result<&str, Error> {
let tm_birthdate = match time::OffsetDateTime::parse(
&((&self).person_data.birthdate.clone() + " 00:00 +00:00"),
DATE_FORMAT,
) {
Ok(v) => v,
Err(_e) => return Err(Error::InvalidBirthdate(None)),
};
let tm_year = tm_birthdate.year();
self.codice_parts.birthyear = format!(
"{:02}",
if tm_year < CENTURY_BASE {
tm_year - 1900
} else {
tm_year - CENTURY_BASE
}
);
self.codice_parts.birthmonth = MONTHLETTERS[tm_birthdate.month() as usize - 1];
self.codice_parts.birthday = format!(
"{:02}",
if self.person_data.gender == Gender::F {
40 + tm_birthdate.day()
} else {
tm_birthdate.day()
}
);
self.codice_parts
.birthdate
.push_str(&self.codice_parts.birthyear);
self.codice_parts
.birthdate
.push(self.codice_parts.birthmonth);
self.codice_parts
.birthdate
.push_str(&self.codice_parts.birthday);
Ok(&self.codice_parts.birthdate)
}
fn calc_belfiore(&mut self) -> Result<&str, Error> {
self.codice_parts.place_of_birth = self.person_data.place_of_birth.clone();
Ok(&self.codice_parts.place_of_birth.belfiore_code)
}
fn calc_checkchar(&mut self) -> char {
let checksum: u8 = self.codice.char_indices().fold(0, |acc, x| {
acc + if x.0 % 2 == 0 {
CHECKCHARS[&x.1].0
} else {
CHECKCHARS[&x.1].1
}
});
self.codice_parts.checkchar = CHECKMODULI[(checksum % 26) as usize];
self.codice_parts.checkchar
}
}