1use crate::{calendar::is_valid_gregorian_date, macros::string_newtype};
2
3string_newtype! {
4 pub struct Pinfl;
10 error = PinflError;
11 expecting = "a PINFL: exactly 14 digits";
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum Gender {
18 Male,
20 Female,
22}
23
24impl Pinfl {
25 pub const LEN: usize = 14;
27
28 const WEIGHTS: [u32; 3] = [7, 3, 1];
32
33 fn normalize(_: &mut str) {}
34
35 fn validate(s: &str) -> Result<(), PinflError> {
36 if !s.is_ascii() {
37 return Err(PinflError::Format);
38 }
39 if s.len() != Self::LEN {
40 return Err(PinflError::Length);
41 }
42 if !s.bytes().all(|b| b.is_ascii_digit()) {
43 return Err(PinflError::Format);
44 }
45 Ok(())
46 }
47
48 pub fn parse_strict(value: &str) -> Result<Self, PinflError> {
53 let pinfl = Self::parse(value)?;
54 if !pinfl.is_checksum_valid() {
55 return Err(PinflError::Checksum);
56 }
57 if pinfl.gender().is_none() || pinfl.birth_date_parts().is_none() {
58 return Err(PinflError::Structure);
59 }
60 Ok(pinfl)
61 }
62
63 #[inline]
64 fn digit(&self, index: usize) -> u32 {
65 u32::from(self.0.as_bytes()[index] - b'0')
66 }
67
68 #[must_use]
70 pub fn is_checksum_valid(&self) -> bool {
71 let sum: u32 = (0..Self::LEN - 1)
72 .map(|i| self.digit(i) * Self::WEIGHTS[i % 3])
73 .sum();
74 sum % 10 == self.digit(Self::LEN - 1)
75 }
76
77 #[must_use]
79 pub fn gender(&self) -> Option<Gender> {
80 match self.digit(0) {
81 1 | 3 | 5 => Some(Gender::Male),
82 2 | 4 | 6 => Some(Gender::Female),
83 _ => None,
84 }
85 }
86
87 #[must_use]
89 pub fn century(&self) -> Option<i32> {
90 match self.digit(0) {
91 1 | 2 => Some(1800),
92 3 | 4 => Some(1900),
93 5 | 6 => Some(2000),
94 _ => None,
95 }
96 }
97
98 #[must_use]
102 pub fn birth_date_parts(&self) -> Option<(i32, u32, u32)> {
103 let century = self.century()?;
104 let day = self.digit(1) * 10 + self.digit(2);
105 let month = self.digit(3) * 10 + self.digit(4);
106 let year = century + i32::try_from(self.digit(5) * 10 + self.digit(6)).ok()?;
107 is_valid_gregorian_date(year, month, day).then_some((year, month, day))
108 }
109
110 #[inline]
112 #[must_use]
113 pub fn region_code(&self) -> &str {
114 &self.0[7..10]
115 }
116
117 #[inline]
119 #[must_use]
120 pub fn serial(&self) -> &str {
121 &self.0[10..13]
122 }
123
124 #[cfg(feature = "date")]
130 #[must_use]
131 pub fn birth_date(&self) -> Option<crate::BirthDate> {
132 let (y, m, d) = self.birth_date_parts()?;
133 let date = chrono::NaiveDate::from_ymd_opt(y, m, d)?;
134 crate::BirthDate::from_naive_date(date).ok()
135 }
136
137 #[cfg(feature = "date")]
139 #[must_use]
140 pub fn birth_date_at(&self, today: chrono::NaiveDate) -> Option<crate::BirthDate> {
141 let (y, m, d) = self.birth_date_parts()?;
142 let date = chrono::NaiveDate::from_ymd_opt(y, m, d)?;
143 crate::BirthDate::from_naive_date_at(date, today).ok()
144 }
145}
146
147#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
149#[non_exhaustive]
150pub enum PinflError {
151 #[error("pinfl length is invalid, expected 14 digits")]
153 Length,
154 #[error("pinfl format is invalid, expected only digits")]
156 Format,
157 #[error("pinfl checksum is invalid")]
159 Checksum,
160 #[error("pinfl structure is invalid (gender/century digit or birth date)")]
162 Structure,
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 const OFFICIAL_1996: &str = "31210632040244";
171 const OFFICIAL_2022: &str = "31210932040247";
172 const OFFICIAL_2022_FEMALE: &str = "40201902050010";
173
174 #[test]
175 fn official_examples_pass_strict() {
176 for s in [OFFICIAL_1996, OFFICIAL_2022] {
177 let p = Pinfl::parse_strict(s).unwrap();
178 assert!(p.is_checksum_valid());
179 assert_eq!(p.gender(), Some(Gender::Male));
180 assert_eq!(p.century(), Some(1900));
181 assert_eq!(p.region_code(), "204");
182 assert_eq!(p.serial(), "024");
183 }
184 assert_eq!(
185 Pinfl::parse(OFFICIAL_1996).unwrap().birth_date_parts(),
186 Some((1963, 10, 12))
187 );
188 assert_eq!(
189 Pinfl::parse(OFFICIAL_2022).unwrap().birth_date_parts(),
190 Some((1993, 10, 12))
191 );
192
193 let female = Pinfl::parse_strict(OFFICIAL_2022_FEMALE).unwrap();
194 assert!(female.is_checksum_valid());
195 assert_eq!(female.gender(), Some(Gender::Female));
196 assert_eq!(female.century(), Some(1900));
197 assert_eq!(female.birth_date_parts(), Some((1990, 1, 2)));
198 assert_eq!(female.region_code(), "205");
199 assert_eq!(female.serial(), "001");
200 }
201
202 fn with_checksum(body: &str) -> String {
203 assert_eq!(body.len(), Pinfl::LEN - 1);
204 assert!(body.bytes().all(|byte| byte.is_ascii_digit()));
205
206 let sum: u32 = body
207 .bytes()
208 .enumerate()
209 .map(|(index, byte)| u32::from(byte - b'0') * Pinfl::WEIGHTS[index % 3])
210 .sum();
211 format!("{body}{}", sum % 10)
212 }
213
214 #[test]
215 fn strict_parse_requires_a_valid_gregorian_date() {
216 for body in ["3310290204024", "3310490204024", "3290200204024"] {
217 let value = with_checksum(body);
218 assert!(Pinfl::parse(&value).is_ok());
219 assert_eq!(Pinfl::parse_strict(&value), Err(PinflError::Structure));
220 }
221
222 let leap_day = with_checksum("5290200204024");
223 assert!(Pinfl::parse(&leap_day).is_ok());
224 assert!(Pinfl::parse_strict(&leap_day).is_ok());
225 assert_eq!(
226 Pinfl::parse(&leap_day).unwrap().birth_date_parts(),
227 Some((2000, 2, 29))
228 );
229 }
230
231 #[test]
232 fn structural_parse_is_lenient_strict_is_not() {
233 let zeros = "00000000000000";
234 assert!(Pinfl::parse(zeros).is_ok()); assert_eq!(Pinfl::parse_strict(zeros), Err(PinflError::Structure)); assert_eq!(
237 Pinfl::parse_strict("31210632040245"),
238 Err(PinflError::Checksum)
239 );
240 assert_eq!(Pinfl::parse("1234567890123"), Err(PinflError::Length));
241 assert_eq!(Pinfl::parse("123456789012345"), Err(PinflError::Length));
242 assert_eq!(Pinfl::parse("1234567890123a"), Err(PinflError::Format));
243 assert_eq!(Pinfl::parse("З1210632040247"), Err(PinflError::Format));
244 }
245
246 #[cfg(feature = "date")]
247 #[test]
248 fn birth_date_is_extracted() {
249 let p = Pinfl::parse(OFFICIAL_2022).unwrap();
250 assert_eq!(p.birth_date().unwrap().to_string(), "1993-10-12");
251 }
252
253 #[cfg(feature = "date")]
254 #[test]
255 fn birth_date_at_is_deterministic() {
256 let today = chrono::NaiveDate::from_ymd_opt(2026, 9, 3).unwrap();
257
258 let old = Pinfl::parse("11210632040244").unwrap();
261 assert_eq!(old.century(), Some(1800));
262 assert_eq!(
263 old.birth_date_at(today).unwrap().to_string(),
264 "1863-10-12" );
266
267 let future = Pinfl::parse("51210992040244").unwrap();
269 assert_eq!(future.birth_date_parts(), Some((2099, 10, 12)));
270 assert_eq!(future.birth_date_at(today), None);
271 }
272}