ocpi-tariffs 0.46.0

OCPI tariff calculations
Documentation
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! An ISO 3166-1 country code.
//!
//! Use `CodeSet` to parse a `Code` from JSON.

#[cfg(test)]
pub(crate) mod test;

use std::fmt;

use crate::{
    json,
    warning::{self, GatherWarnings as _, IntoCaveat as _},
    Verdict,
};

const RESERVED_PREFIX: u8 = b'x';
const ALPHA_2_LEN: usize = 2;
const ALPHA_3_LEN: usize = 3;

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
    /// Neither the timezone or country field require char escape codes.
    ContainsEscapeCodes,

    /// The field at the path could not be decoded.
    Decode(json::decode::Warning),

    /// The `country` is not a valid ISO 3166-1 country code because it's not uppercase.
    PreferUpperCase,

    /// The `country` is not a valid ISO 3166-1 country code.
    InvalidCode,

    /// The JSON value given is not a string.
    InvalidType { type_found: json::ValueKind },

    /// The `country` is not a valid ISO 3166-1 country code because it's not 2 or 3 chars in length.
    InvalidLength,

    /// The `country` is not a valid ISO 3166-1 country code because it's all codes beginning with 'X' are reserved.
    InvalidReserved,
}

impl Warning {
    fn invalid_type(elem: &json::Element<'_>) -> Self {
        Self::InvalidType {
            type_found: elem.value().kind(),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ContainsEscapeCodes => f.write_str("The value contains escape codes but it does not need them"),
            Self::Decode(warning) => fmt::Display::fmt(warning, f),
            Self::PreferUpperCase => f.write_str("The country-code follows the ISO 3166-1 standard which states: the chars should be uppercase."),
            Self::InvalidCode => f.write_str("The country-code is not a valid ISO 3166-1 code."),
            Self::InvalidType { type_found } => {
                write!(f, "The value should be a string but is `{type_found}`")
            }
            Self::InvalidLength => f.write_str("The country-code follows the ISO 3166-1 which states that the code should be 2 or 3 chars in length."),
            Self::InvalidReserved => f.write_str("The country-code follows the ISO 3166-1 standard which states: all codes beginning with 'X' are reserved."),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
            Self::Decode(kind) => kind.id(),
            Self::PreferUpperCase => warning::Id::from_static("prefer_upper_case"),
            Self::InvalidCode => warning::Id::from_static("invalid_code"),
            Self::InvalidType { .. } => warning::Id::from_static("invalid_type"),
            Self::InvalidLength => warning::Id::from_static("invalid_length"),
            Self::InvalidReserved => warning::Id::from_static("invalid_reserved"),
        }
    }
}

/// An alpha-2 or alpha-3 `Code`.
///
/// The caller can decide if they want to warn or fail if the wrong variant is parsed.
#[derive(Debug)]
pub(crate) enum CodeSet {
    /// An alpha-2 country code was parsed.
    Alpha2(Code),

    /// An alpha-3 country code was parsed.
    Alpha3(Code),
}

impl From<json::decode::Warning> for Warning {
    fn from(warn_kind: json::decode::Warning) -> Self {
        Self::Decode(warn_kind)
    }
}

impl json::FromJson<'_> for CodeSet {
    type Warning = Warning;

    fn from_json(elem: &json::Element<'_>) -> Verdict<CodeSet, Self::Warning> {
        let mut warnings = warning::Set::new();
        let value = elem.as_value();

        let Some(s) = value.to_raw_str() else {
            return warnings.bail(Warning::invalid_type(elem), elem);
        };

        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);

        let s = match pending_str {
            json::decode::PendingStr::NoEscapes(s) => s,
            json::decode::PendingStr::HasEscapes(_) => {
                return warnings.bail(Warning::ContainsEscapeCodes, elem);
            }
        };

        let bytes = s.as_bytes();

        if let [a, b, c] = bytes {
            let triplet: [u8; ALPHA_3_LEN] = [
                a.to_ascii_uppercase(),
                b.to_ascii_uppercase(),
                c.to_ascii_uppercase(),
            ];

            if triplet != bytes {
                warnings.insert(Warning::PreferUpperCase, elem);
            }

            if a.eq_ignore_ascii_case(&RESERVED_PREFIX) {
                warnings.insert(Warning::InvalidReserved, elem);
            }

            let Some(code) = Code::from_alpha_3(triplet) else {
                return warnings.bail(Warning::InvalidCode, elem);
            };

            Ok(CodeSet::Alpha3(code).into_caveat(warnings))
        } else if let [a, b] = bytes {
            let pair: [u8; ALPHA_2_LEN] = [a.to_ascii_uppercase(), b.to_ascii_uppercase()];

            if pair != bytes {
                warnings.insert(Warning::PreferUpperCase, elem);
            }

            if a.eq_ignore_ascii_case(&RESERVED_PREFIX) {
                warnings.insert(Warning::InvalidReserved, elem);
            }

            let Some(code) = Code::from_alpha_2(pair) else {
                return warnings.bail(Warning::InvalidCode, elem);
            };

            Ok(CodeSet::Alpha2(code).into_caveat(warnings))
        } else {
            warnings.bail(Warning::InvalidLength, elem)
        }
    }
}

impl fmt::Display for Code {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.into_alpha_2_str())
    }
}

/// Macro to specify a list of valid ISO 3166-1 alpha-2 and alpha-3 country codes strings
macro_rules! country_codes {
    [$(($name:ident, $alph2:literal, $alph3:literal)),*] => {
        /// An ISO 3166-1 alpha-2 country code.
        ///
        /// The impl is designed to be converted from `json::RawValue`.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash,  PartialOrd, Ord)]
        pub enum Code {
            $($name),*
        }

        impl Code {
            /// Try creating a `Code` from two upper ASCII bytes.
            const fn from_alpha_2(code: [u8; 2]) -> Option<Self> {
                match &code {
                    $($alph2 => Some(Self::$name),)*
                    _ => None
                }
            }

            /// Try creating a `Code` from three upper ASCII bytes.
            const fn from_alpha_3(code: [u8; 3]) -> Option<Self> {
                match &code {
                    $($alph3 => Some(Self::$name),)*
                    _ => None
                }
            }

            /// Return enum as two byte uppercase `&str`.
            pub fn into_alpha_2_str(self) -> &'static str {
                let bytes = match self {
                    $(Self::$name => $alph2),*
                };
                std::str::from_utf8(bytes).expect("The country code bytes are known to be valid UTF8 as they are embedded into the binary")
            }

            /// Return enum as three byte uppercase `&str`.
            pub fn into_alpha_3_str(self) -> &'static str {
                let bytes = match self {
                    $(Self::$name => $alph3),*
                };
                std::str::from_utf8(bytes).expect("The country code bytes are known to be valid UTF8 as they are embedded into the binary")
            }
        }
    };
}

country_codes![
    (Ad, b"AD", b"AND"),
    (Ae, b"AE", b"ARE"),
    (Af, b"AF", b"AFG"),
    (Ag, b"AG", b"ATG"),
    (Ai, b"AI", b"AIA"),
    (Al, b"AL", b"ALB"),
    (Am, b"AM", b"ARM"),
    (Ao, b"AO", b"AGO"),
    (Aq, b"AQ", b"ATA"),
    (Ar, b"AR", b"ARG"),
    (As, b"AS", b"ASM"),
    (At, b"AT", b"AUT"),
    (Au, b"AU", b"AUS"),
    (Aw, b"AW", b"ABW"),
    (Ax, b"AX", b"ALA"),
    (Az, b"AZ", b"AZE"),
    (Ba, b"BA", b"BIH"),
    (Bb, b"BB", b"BRB"),
    (Bd, b"BD", b"BGD"),
    (Be, b"BE", b"BEL"),
    (Bf, b"BF", b"BFA"),
    (Bg, b"BG", b"BGR"),
    (Bh, b"BH", b"BHR"),
    (Bi, b"BI", b"BDI"),
    (Bj, b"BJ", b"BEN"),
    (Bl, b"BL", b"BLM"),
    (Bm, b"BM", b"BMU"),
    (Bn, b"BN", b"BRN"),
    (Bo, b"BO", b"BOL"),
    (Bq, b"BQ", b"BES"),
    (Br, b"BR", b"BRA"),
    (Bs, b"BS", b"BHS"),
    (Bt, b"BT", b"BTN"),
    (Bv, b"BV", b"BVT"),
    (Bw, b"BW", b"BWA"),
    (By, b"BY", b"BLR"),
    (Bz, b"BZ", b"BLZ"),
    (Ca, b"CA", b"CAN"),
    (Cc, b"CC", b"CCK"),
    (Cd, b"CD", b"COD"),
    (Cf, b"CF", b"CAF"),
    (Cg, b"CG", b"COG"),
    (Ch, b"CH", b"CHE"),
    (Ci, b"CI", b"CIV"),
    (Ck, b"CK", b"COK"),
    (Cl, b"CL", b"CHL"),
    (Cm, b"CM", b"CMR"),
    (Cn, b"CN", b"CHN"),
    (Co, b"CO", b"COL"),
    (Cr, b"CR", b"CRI"),
    (Cu, b"CU", b"CUB"),
    (Cv, b"CV", b"CPV"),
    (Cw, b"CW", b"CUW"),
    (Cx, b"CX", b"CXR"),
    (Cy, b"CY", b"CYP"),
    (Cz, b"CZ", b"CZE"),
    (De, b"DE", b"DEU"),
    (Dj, b"DJ", b"DJI"),
    (Dk, b"DK", b"DNK"),
    (Dm, b"DM", b"DMA"),
    (Do, b"DO", b"DOM"),
    (Dz, b"DZ", b"DZA"),
    (Ec, b"EC", b"ECU"),
    (Ee, b"EE", b"EST"),
    (Eg, b"EG", b"EGY"),
    (Eh, b"EH", b"ESH"),
    (Er, b"ER", b"ERI"),
    (Es, b"ES", b"ESP"),
    (Et, b"ET", b"ETH"),
    (Fi, b"FI", b"FIN"),
    (Fj, b"FJ", b"FJI"),
    (Fk, b"FK", b"FLK"),
    (Fm, b"FM", b"FSM"),
    (Fo, b"FO", b"FRO"),
    (Fr, b"FR", b"FRA"),
    (Ga, b"GA", b"GAB"),
    (Gb, b"GB", b"GBR"),
    (Gd, b"GD", b"GRD"),
    (Ge, b"GE", b"GEO"),
    (Gf, b"GF", b"GUF"),
    (Gg, b"GG", b"GGY"),
    (Gh, b"GH", b"GHA"),
    (Gi, b"GI", b"GIB"),
    (Gl, b"GL", b"GRL"),
    (Gm, b"GM", b"GMB"),
    (Gn, b"GN", b"GIN"),
    (Gp, b"GP", b"GLP"),
    (Gq, b"GQ", b"GNQ"),
    (Gr, b"GR", b"GRC"),
    (Gs, b"GS", b"SGS"),
    (Gt, b"GT", b"GTM"),
    (Gu, b"GU", b"GUM"),
    (Gw, b"GW", b"GNB"),
    (Gy, b"GY", b"GUY"),
    (Hk, b"HK", b"HKG"),
    (Hm, b"HM", b"HMD"),
    (Hn, b"HN", b"HND"),
    (Hr, b"HR", b"HRV"),
    (Ht, b"HT", b"HTI"),
    (Hu, b"HU", b"HUN"),
    (Id, b"ID", b"IDN"),
    (Ie, b"IE", b"IRL"),
    (Il, b"IL", b"ISR"),
    (Im, b"IM", b"IMN"),
    (In, b"IN", b"IND"),
    (Io, b"IO", b"IOT"),
    (Iq, b"IQ", b"IRQ"),
    (Ir, b"IR", b"IRN"),
    (Is, b"IS", b"ISL"),
    (It, b"IT", b"ITA"),
    (Je, b"JE", b"JEY"),
    (Jm, b"JM", b"JAM"),
    (Jo, b"JO", b"JOR"),
    (Jp, b"JP", b"JPN"),
    (Ke, b"KE", b"KEN"),
    (Kg, b"KG", b"KGZ"),
    (Kh, b"KH", b"KHM"),
    (Ki, b"KI", b"KIR"),
    (Km, b"KM", b"COM"),
    (Kn, b"KN", b"KNA"),
    (Kp, b"KP", b"PRK"),
    (Kr, b"KR", b"KOR"),
    (Kw, b"KW", b"KWT"),
    (Ky, b"KY", b"CYM"),
    (Kz, b"KZ", b"KAZ"),
    (La, b"LA", b"LAO"),
    (Lb, b"LB", b"LBN"),
    (Lc, b"LC", b"LCA"),
    (Li, b"LI", b"LIE"),
    (Lk, b"LK", b"LKA"),
    (Lr, b"LR", b"LBR"),
    (Ls, b"LS", b"LSO"),
    (Lt, b"LT", b"LTU"),
    (Lu, b"LU", b"LUX"),
    (Lv, b"LV", b"LVA"),
    (Ly, b"LY", b"LBY"),
    (Ma, b"MA", b"MAR"),
    (Mc, b"MC", b"MCO"),
    (Md, b"MD", b"MDA"),
    (Me, b"ME", b"MNE"),
    (Mf, b"MF", b"MAF"),
    (Mg, b"MG", b"MDG"),
    (Mh, b"MH", b"MHL"),
    (Mk, b"MK", b"MKD"),
    (Ml, b"ML", b"MLI"),
    (Mm, b"MM", b"MMR"),
    (Mn, b"MN", b"MNG"),
    (Mo, b"MO", b"MAC"),
    (Mp, b"MP", b"MNP"),
    (Mq, b"MQ", b"MTQ"),
    (Mr, b"MR", b"MRT"),
    (Ms, b"MS", b"MSR"),
    (Mt, b"MT", b"MLT"),
    (Mu, b"MU", b"MUS"),
    (Mv, b"MV", b"MDV"),
    (Mw, b"MW", b"MWI"),
    (Mx, b"MX", b"MEX"),
    (My, b"MY", b"MYS"),
    (Mz, b"MZ", b"MOZ"),
    (Na, b"NA", b"NAM"),
    (Nc, b"NC", b"NCL"),
    (Ne, b"NE", b"NER"),
    (Nf, b"NF", b"NFK"),
    (Ng, b"NG", b"NGA"),
    (Ni, b"NI", b"NIC"),
    (Nl, b"NL", b"NLD"),
    (No, b"NO", b"NOR"),
    (Np, b"NP", b"NPL"),
    (Nr, b"NR", b"NRU"),
    (Nu, b"NU", b"NIU"),
    (Nz, b"NZ", b"NZL"),
    (Om, b"OM", b"OMN"),
    (Pa, b"PA", b"PAN"),
    (Pe, b"PE", b"PER"),
    (Pf, b"PF", b"PYF"),
    (Pg, b"PG", b"PNG"),
    (Ph, b"PH", b"PHL"),
    (Pk, b"PK", b"PAK"),
    (Pl, b"PL", b"POL"),
    (Pm, b"PM", b"SPM"),
    (Pn, b"PN", b"PCN"),
    (Pr, b"PR", b"PRI"),
    (Ps, b"PS", b"PSE"),
    (Pt, b"PT", b"PRT"),
    (Pw, b"PW", b"PLW"),
    (Py, b"PY", b"PRY"),
    (Qa, b"QA", b"QAT"),
    (Re, b"RE", b"REU"),
    (Ro, b"RO", b"ROU"),
    (Rs, b"RS", b"SRB"),
    (Ru, b"RU", b"RUS"),
    (Rw, b"RW", b"RWA"),
    (Sa, b"SA", b"SAU"),
    (Sb, b"SB", b"SLB"),
    (Sc, b"SC", b"SYC"),
    (Sd, b"SD", b"SDN"),
    (Se, b"SE", b"SWE"),
    (Sg, b"SG", b"SGP"),
    (Sh, b"SH", b"SHN"),
    (Si, b"SI", b"SVN"),
    (Sj, b"SJ", b"SJM"),
    (Sk, b"SK", b"SVK"),
    (Sl, b"SL", b"SLE"),
    (Sm, b"SM", b"SMR"),
    (Sn, b"SN", b"SEN"),
    (So, b"SO", b"SOM"),
    (Sr, b"SR", b"SUR"),
    (Ss, b"SS", b"SSD"),
    (St, b"ST", b"STP"),
    (Sv, b"SV", b"SLV"),
    (Sx, b"SX", b"SXM"),
    (Sy, b"SY", b"SYR"),
    (Sz, b"SZ", b"SWZ"),
    (Tc, b"TC", b"TCA"),
    (Td, b"TD", b"TCD"),
    (Tf, b"TF", b"ATF"),
    (Tg, b"TG", b"TGO"),
    (Th, b"TH", b"THA"),
    (Tj, b"TJ", b"TJK"),
    (Tk, b"TK", b"TKL"),
    (Tl, b"TL", b"TLS"),
    (Tm, b"TM", b"TKM"),
    (Tn, b"TN", b"TUN"),
    (To, b"TO", b"TON"),
    (Tr, b"TR", b"TUR"),
    (Tt, b"TT", b"TTO"),
    (Tv, b"TV", b"TUV"),
    (Tw, b"TW", b"TWN"),
    (Tz, b"TZ", b"TZA"),
    (Ua, b"UA", b"UKR"),
    (Ug, b"UG", b"UGA"),
    (Um, b"UM", b"UMI"),
    (Us, b"US", b"USA"),
    (Uy, b"UY", b"URY"),
    (Uz, b"UZ", b"UZB"),
    (Va, b"VA", b"VAT"),
    (Vc, b"VC", b"VCT"),
    (Ve, b"VE", b"VEN"),
    (Vg, b"VG", b"VGB"),
    (Vi, b"VI", b"VIR"),
    (Vn, b"VN", b"VNM"),
    (Vu, b"VU", b"VUT"),
    (Wf, b"WF", b"WLF"),
    (Ws, b"WS", b"WSM"),
    (Ye, b"YE", b"YEM"),
    (Yt, b"YT", b"MYT"),
    (Za, b"ZA", b"ZAF"),
    (Zm, b"ZM", b"ZMB"),
    (Zw, b"ZW", b"ZWE")
];