mb_vin 0.8.0

A zero-copy parsing and validating vehicle identification numbers (VINs).
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
//! mb-vin - A lightweight VIN parser and validator
//!
//! This crate provides efficient parsing and validation of VIN (Vehicle
//! Identification Number).
//!
//! Features:
//!
//! - No allocations (zero-copy)
//! - Parse and validate VINs (length, character set, check digit)
//! - Extract WMI (World Manufacturer Identifier), VDS, VIS
//! - Lookup manufacturer and country from WMI
//! - Infer manufacturing year from VIN
//! - Optional `serde` support with serialization and deserialization
//! - Optional `simd` to fast batch parse
//!
//! # Examples
//!
//! ```
//! use mb_vin::Vin;
//!
//! // Parse a valid VIN
//! let vin = Vin::parse(b"5GZCZ43D13S812715").unwrap();
//!
//! // Access VIN components
//! println!("WMI (manufacturer): {}", vin.wmi());
//! println!("VDS (vehicle attributes): {}", vin.vds());
//! println!("VIS (vehicle identifier): {}", vin.vis());
//! println!("Check digit: {}", vin.check_digit());
//!
//! if let Some(info) = vin.lookup_wmi_info() {
//!     println!("Country: {}", info.country);
//!     println!("Manufacturer: {}", info.manufacturer);
//!     println!("Region: {}", info.region);
//! }
//!
//! if let Some(year) = vin.year_of_manufacture() {
//!     println!("Year: {}", year);
//! }
//! ```
//!
//! ## Optional Serde Support
//!
//! Enable the `serde` feature in your `Cargo.toml`:
//!
//! ```toml
//! mb-vin = { version = "0.8.0", features = ["serde"] }
//! ```
//!
//! The crate provides two approaches for serialization/deserialization:
//!
//! 1. `OwnedVin` - Uses owned strings, recommended for most cases.
//! 2. `Vin<'a>` - For advanced use cases with custom deserializers that preserve
//!    input lifetimes.
//!
//! ### Using `OwnedVin` (recommended for most cases)
//!
//! ```
//! # #[cfg(feature = "serde")]
//! # {
//! use mb_vin::OwnedVin;
//! use serde_json;
//!
//! // Deserialize from JSON
//! let vin: OwnedVin = serde_json::from_str("\"5GZCZ43D13S812715\"").unwrap();
//!
//! // Access components
//! assert_eq!(vin.wmi, "5GZ");
//! assert_eq!(vin.vds, "CZ43D1");
//!
//! // Convert to a borrowed Vin if needed
//! let borrowed = vin.as_vin();
//!
//! // Serialize back to JSON
//! let json = serde_json::to_string(&vin).unwrap();
//! assert_eq!(json, "\"5GZCZ43D13S812715\"");
//! # }
//! ```
//!
//! ### Using with structures
//!
//! ```
//! # #[cfg(feature = "serde")]
//! # {
//! use mb_vin::OwnedVin;
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, Debug)]
//! struct Vehicle {
//!     vin: OwnedVin,
//!     make: String,
//!     model: String,
//!     year: u16,
//! }
//!
//! // Create from JSON
//! let json = r#"{
//!     "vin": "5GZCZ43D13S812715",
//!     "make": "General Motors",
//!     "model": "Suburban",
//!     "year": 2003
//! }"#;
//!
//! let vehicle: Vehicle = serde_json::from_str(json).unwrap();
//! assert_eq!(vehicle.vin.wmi, "5GZ");
//! # }
//! ```
//!
//! ### Advanced: Using borrowed `Vin<'a>`
//!
//! The `Vin<'a>` struct implements `Deserialize<'de>` for advanced use cases
//! where you need zero-copy deserialization with custom deserializers that
//! preserve input lifetimes. This is rarely needed for typical applications.
//
// Copyright (c) 2025 murilo ijanc' <mbsd@m0x.ru>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//

#![warn(
    missing_debug_implementations,
    missing_docs,
    clippy::all,
    clippy::todo,
    future_incompatible,
    nonstandard_style
)]
#![forbid(unsafe_code)]

/// Errors that may occur during VIN parsing and validation
#[derive(Debug)]
pub enum Error {
    /// VIN must be exactly 17 characters
    /// This error occurs when the input bytes length is not 17
    InvalidLength,

    /// VIN contains an invalid character
    /// Valid characters are alphanumeric excluding I, O, and Q
    /// The character that caused the error is included
    InvalidCharacter(char),

    /// VIN must only contain uppercase characters
    /// This error occurs when a lowercase letter is found
    InvalidLowercaseCharacter,

    /// The check digit is invalid
    InvalidCheckDigit {
        /// The check digit that was expected based on calculation
        expected: char,

        /// The check digit that was actually found in the VIN
        found: char,
    },
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::InvalidLength => {
                write!(
                    f,
                    "VIN must be exactly {} characters",
                    crate::MAX_LENGTH
                )
            }
            Error::InvalidCharacter(c) => {
                write!(f, "VIN contains invalid character: '{}' (valid characters are alphanumeric excluding I, O, and Q)", c)
            }
            Error::InvalidLowercaseCharacter => {
                write!(f, "VIN must only contain uppercase characters")
            }
            Error::InvalidCheckDigit { expected, found } => {
                write!(
                    f,
                    "VIN has invalid check digit: expected '{}', found '{}'",
                    expected, found
                )
            }
        }
    }
}

impl std::error::Error for Error {}

////////////////////////////////////////////////////////////////////////////////
// WMI
////////////////////////////////////////////////////////////////////////////////
/// Information about a World Manufacturer Identifier (WMI)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WmiInfo {
    /// The manufacturer name
    pub manufacturer: &'static str,

    /// The country of origin
    pub country: &'static str,

    /// The region code (first character of WMI)
    pub region: &'static str,
}

#[cfg(not(feature = "phf"))]
use std::collections::HashMap;
#[cfg(not(feature = "phf"))]
use std::sync::LazyLock;

#[cfg(not(feature = "phf"))]
static REGIONS: LazyLock<HashMap<char, &'static str>> = LazyLock::new(|| {
    let mut r = HashMap::new();
    r.insert('1', "North America");
    r.insert('2', "North America");
    r.insert('3', "North America");
    r.insert('4', "North America");
    r.insert('5', "North America");
    r.insert('J', "Asia (Japan)");
    r.insert('K', "Asia (Korea)");
    r.insert('L', "Asia (China)");
    r.insert('S', "Europe (UK, Germany)");
    r.insert('T', "Europe (Switzerland, Czech Republic)");
    r.insert('V', "Europe (Austria, France)");
    r.insert('W', "Europe (Germany)");
    r.insert('Y', "Europe (Sweden, Finland)");
    r.insert('Z', "Europe (Italy)");
    r
});

#[cfg(not(feature = "phf"))]
#[rustfmt::skip]
static WMI_DATA: LazyLock<HashMap<&'static [u8], WmiInfo>> = LazyLock::new(|| {
    let mut m = HashMap::new();
    m.insert(b"1G".as_ref(), WmiInfo {
        manufacturer: "General Motors",
        country: "United States",
        region: "North America",
    });
    m.insert(b"1H".as_ref(), WmiInfo {
        manufacturer: "Honda".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"1J".as_ref(), WmiInfo {
        manufacturer: "Jeep".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"1N".as_ref(), WmiInfo {
        manufacturer: "Nissan".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"1V".as_ref(), WmiInfo {
        manufacturer: "Volkswagen".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"1Y".as_ref(), WmiInfo {
        manufacturer: "General Motors".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"2G".as_ref(), WmiInfo {
        manufacturer: "General Motors Canada".as_ref(),
        country: "Canada".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"2T".as_ref(), WmiInfo {
        manufacturer: "Toyota".as_ref(),
        country: "Canada".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"3G".as_ref(), WmiInfo {
        manufacturer: "General Motors Mexico".as_ref(),
        country: "Mexico".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"3H".as_ref(), WmiInfo {
        manufacturer: "Honda Mexico".as_ref(),
        country: "Mexico".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"3N".as_ref(), WmiInfo {
        manufacturer: "Nissan Mexico".as_ref(),
        country: "Mexico".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"3V".as_ref(), WmiInfo {
        manufacturer: "Volkswagen Mexico".as_ref(),
        country: "Mexico".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"4F".as_ref(), WmiInfo {
        manufacturer: "Mazda".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"4S".as_ref(), WmiInfo {
        manufacturer: "Subaru-Isuzu Automotive".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"4T".as_ref(), WmiInfo {
        manufacturer: "Toyota".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"5G".as_ref(), WmiInfo {
        manufacturer: "General Motors".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"5GZ".as_ref(), WmiInfo {
        manufacturer: "General Motors".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"5L".as_ref(), WmiInfo {
        manufacturer: "Lincoln".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"5N".as_ref(), WmiInfo {
        manufacturer: "Hyundai".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    m.insert(b"5T".as_ref(), WmiInfo {
        manufacturer: "Toyota".as_ref(),
        country: "United States".as_ref(),
        region: "North America".as_ref(),
    });
    // Europe
    m.insert(b"WA".as_ref(), WmiInfo {
        manufacturer: "Audi".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WB".as_ref(), WmiInfo {
        manufacturer: "BMW".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WD".as_ref(), WmiInfo {
        manufacturer: "Mercedes-Benz".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WF".as_ref(), WmiInfo {
        manufacturer: "Ford Germany".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WP".as_ref(), WmiInfo {
        manufacturer: "Porsche".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WV".as_ref(), WmiInfo {
        manufacturer: "Volkswagen".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"WVW".as_ref(), WmiInfo {
        manufacturer: "Volkswagen".as_ref(),
        country: "Germany".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"YV".as_ref(), WmiInfo {
        manufacturer: "Volvo".as_ref(),
        country: "Sweden".as_ref(),
        region: "Europe".as_ref(),
    });
    m.insert(b"ZFA".as_ref(), WmiInfo {
        manufacturer: "Fiat".as_ref(),
        country: "Italy".as_ref(),
        region: "Europe".as_ref(),
    });
    // Asia
    m.insert(b"JH".as_ref(), WmiInfo {
        manufacturer: "Honda".as_ref(),
        country: "Japan".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"JM".as_ref(), WmiInfo {
        manufacturer: "Mazda".as_ref(),
        country: "Japan".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"JN".as_ref(), WmiInfo {
        manufacturer: "Nissan".as_ref(),
        country: "Japan".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"JS".as_ref(), WmiInfo {
        manufacturer: "Suzuki".as_ref(),
        country: "Japan".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"JT".as_ref(), WmiInfo {
        manufacturer: "Toyota".as_ref(),
        country: "Japan".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"KL".as_ref(), WmiInfo {
        manufacturer: "Daewoo".as_ref(),
        country: "South Korea".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"KM".as_ref(), WmiInfo {
        manufacturer: "Hyundai".as_ref(),
        country: "South Korea".as_ref(),
        region: "Asia".as_ref(),
    });
    m.insert(b"KN".as_ref(), WmiInfo {
        manufacturer: "Kia".as_ref(),
        country: "South Korea".as_ref(),
        region: "Asia".as_ref(),
    });
    m
});

// Static mapping of WMI codes to their information
#[cfg(feature = "phf")]
static WMI_DATA: phf::Map<&'static [u8], WmiInfo> = phf::phf_map! {
    // North America
    b"1G" => WmiInfo {
        manufacturer: "General Motors",
        country: "United States",
        region: "North America",
    },
    b"1H" => WmiInfo {
        manufacturer: "Honda",
        country: "United States",
        region: "North America",
    },
    b"1J" => WmiInfo {
        manufacturer: "Jeep",
        country: "United States",
        region: "North America",
    },
    b"1N" => WmiInfo {
        manufacturer: "Nissan",
        country: "United States",
        region: "North America",
    },
    b"1V" => WmiInfo {
        manufacturer: "Volkswagen",
        country: "United States",
        region: "North America",
    },
    b"1Y" => WmiInfo {
        manufacturer: "General Motors",
        country: "United States",
        region: "North America",
    },
    b"2G" => WmiInfo {
        manufacturer: "General Motors Canada",
        country: "Canada",
        region: "North America",
    },
    b"2T" => WmiInfo {
        manufacturer: "Toyota",
        country: "Canada",
        region: "North America",
    },
    b"3G" => WmiInfo {
        manufacturer: "General Motors Mexico",
        country: "Mexico",
        region: "North America",
    },
    b"3H" => WmiInfo {
        manufacturer: "Honda Mexico",
        country: "Mexico",
        region: "North America",
    },
    b"3N" => WmiInfo {
        manufacturer: "Nissan Mexico",
        country: "Mexico",
        region: "North America",
    },
    b"3V" => WmiInfo {
        manufacturer: "Volkswagen Mexico",
        country: "Mexico",
        region: "North America",
    },
    b"4F" => WmiInfo {
        manufacturer: "Mazda",
        country: "United States",
        region: "North America",
    },
    b"4S" => WmiInfo {
        manufacturer: "Subaru-Isuzu Automotive",
        country: "United States",
        region: "North America",
    },
    b"4T" => WmiInfo {
        manufacturer: "Toyota",
        country: "United States",
        region: "North America",
    },
    b"5G" => WmiInfo {
        manufacturer: "General Motors",
        country: "United States",
        region: "North America",
    },
    b"5GZ" => WmiInfo {
        manufacturer: "General Motors",
        country: "United States",
        region: "North America",
    },
    b"5L" => WmiInfo {
        manufacturer: "Lincoln",
        country: "United States",
        region: "North America",
    },
    b"5N" => WmiInfo {
        manufacturer: "Hyundai",
        country: "United States",
        region: "North America",
    },
    b"5T" => WmiInfo {
        manufacturer: "Toyota",
        country: "United States",
        region: "North America",
    },
    // Europe
    b"WA" => WmiInfo {
        manufacturer: "Audi",
        country: "Germany",
        region: "Europe",
    },
    b"W" => WmiInfo {
        manufacturer: "BMW",
        country: "Germany",
        region: "Europe",
    },
    b"WD" => WmiInfo {
        manufacturer: "Mercedes-Benz",
        country: "Germany",
        region: "Europe",
    },
    b"WF" => WmiInfo {
        manufacturer: "Ford Germany",
        country: "Germany",
        region: "Europe",
    },
    b"WP" => WmiInfo {
        manufacturer: "Porsche",
        country: "Germany",
        region: "Europe",
    },
    b"WV" => WmiInfo {
        manufacturer: "Volkswagen",
        country: "Germany",
        region: "Europe",
    },
    b"WVW" => WmiInfo {
        manufacturer: "Volkswagen",
        country: "Germany",
        region: "Europe",
    },
    b"YV" => WmiInfo {
        manufacturer: "Volvo",
        country: "Sweden",
        region: "Europe",
    },
    b"ZFA" => WmiInfo {
        manufacturer: "Fiat",
        country: "Italy",
        region: "Europe",
    },
    // Asia
    b"JH" => WmiInfo {
        manufacturer: "Honda",
        country: "Japan",
        region: "Asia",
    },
    b"JM" => WmiInfo {
        manufacturer: "Mazda",
        country: "Japan",
        region: "Asia",
    },
    b"JN" => WmiInfo {
        manufacturer: "Nissan",
        country: "Japan",
        region: "Asia",
    },
    b"JS" => WmiInfo {
        manufacturer: "Suzuki",
        country: "Japan",
        region: "Asia",
    },
    b"JT" => WmiInfo {
        manufacturer: "Toyota",
        country: "Japan",
        region: "Asia",
    },
    b"KL" => WmiInfo {
        manufacturer: "Daewoo",
        country: "South Korea",
        region: "Asia",
    },
    b"KM" => WmiInfo {
        manufacturer: "Hyundai",
        country: "South Korea",
        region: "Asia",
    },
    b"KN" => WmiInfo {
        manufacturer: "Kia",
        country: "South Korea",
        region: "Asia",
    },
};

// Regions based on first digit/character
#[cfg(feature = "phf")]
static REGIONS: phf::Map<char, &'static str> = phf::phf_map! {
    '1' => "North America",
    '2' => "North America",
    '3' => "North America",
    '4' => "North America",
    '5' => "North America",
    'J' => "Asia (Japan)",
    'K' => "Asia (Korea)",
    'L' => "Asia (China)",
    'S' => "Europe (UK, Germany)",
    'T' => "Europe (Switzerland, Czech Republic)",
    'V' => "Europe (Austria, France)",
    'W' => "Europe (Germany)",
    'Y' => "Europe (Sweden, Finland)",
    'Z' => "Europe (Italy)",
};

impl WmiInfo {
    /// Lookup WMI information from a WMI code
    ///
    /// Returns the manufacturer and country information if found in the database.
    ///
    /// # Arguments
    ///
    /// * `wmi` - A WMI code bytes (typically the first 3 characters of a VIN)
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// use mb_vin::WmiInfo;
    ///
    /// let wmi = b"WVW";
    ///
    /// if let Some(info) = WmiInfo::lookup(wmi) {
    ///     println!("Manufacturer: {}", info.manufacturer);
    ///     println!("Country: {}", info.country);
    /// }
    /// ```
    pub fn lookup(wmi: &[u8]) -> Option<&'static WmiInfo> {
        // Try looking up the full WMI first (for specific models)
        if let Some(info) = WMI_DATA.get(wmi) {
            return Some(info);
        }

        // Try looking up just the first two characters (more common)
        if wmi.len() >= 2 {
            let prefix = &wmi[0..2];
            if let Some(info) = WMI_DATA.get(prefix) {
                return Some(info);
            }
        }

        None
    }

    /// Get the region information from the first character of a WMI
    ///
    /// # Arguments
    ///
    /// * `wmi_char` - The first character of a WMI
    pub fn region_from_char(wmi_char: char) -> Option<&'static str> {
        REGIONS.get(&wmi_char).copied()
    }
}

////////////////////////////////////////////////////////////////////////////////
// VIN
////////////////////////////////////////////////////////////////////////////////
const WEIGHTS: [u32; 17] = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];

const CURRENT_YEAR: u16 = 2025;

/// Max vehicle identification number length.
pub const MAX_LENGTH: usize = 17;

/// Combined validation and transliteration table
/// 0xFF indicates invalid character
/// Other values are transliteration values
static VIN_CHAR_TABLE: [u8; 256] = {
    let mut table = [0xFF; 256]; // Initialize all as invalid

    // Set digits
    table[b'0' as usize] = 0;
    table[b'1' as usize] = 1;
    table[b'2' as usize] = 2;
    table[b'3' as usize] = 3;
    table[b'4' as usize] = 4;
    table[b'5' as usize] = 5;
    table[b'6' as usize] = 6;
    table[b'7' as usize] = 7;
    table[b'8' as usize] = 8;
    table[b'9' as usize] = 9;

    // Set valid letters with their transliteration values
    table[b'A' as usize] = 1;
    table[b'B' as usize] = 2;
    table[b'C' as usize] = 3;
    table[b'D' as usize] = 4;
    table[b'E' as usize] = 5;
    table[b'F' as usize] = 6;
    table[b'G' as usize] = 7;
    table[b'H' as usize] = 8;
    table[b'J' as usize] = 1;
    table[b'K' as usize] = 2;
    table[b'L' as usize] = 3;
    table[b'M' as usize] = 4;
    table[b'N' as usize] = 5;
    table[b'P' as usize] = 7;
    table[b'R' as usize] = 9;
    table[b'S' as usize] = 2;
    table[b'T' as usize] = 3;
    table[b'U' as usize] = 4;
    table[b'V' as usize] = 5;
    table[b'W' as usize] = 6;
    table[b'X' as usize] = 7;
    table[b'Y' as usize] = 8;
    table[b'Z' as usize] = 9;

    table
};

#[inline]
fn check_and_transliterate(byte: u8) -> Result<u8, Error> {
    let value = VIN_CHAR_TABLE[byte as usize];
    if value == 0xFF {
        Err(Error::InvalidCharacter(byte as char))
    } else {
        Ok(value)
    }
}

/// Represents a parsed and validated Vehicle Identification Number
#[derive(Debug)]
pub struct Vin<'a> {
    /// The original raw VIN bytes
    #[allow(dead_code)]
    raw: &'a [u8],

    /// Check digit (character 9)
    /// Used to detect errors in VIN transcription
    check_digit: char,

    /// World Manufacturer Identifier (WMI), characters 1–3
    /// Identifies the manufacturer and country of origin
    wmi: &'a [u8],

    /// Vehicle Descriptor Section (VDS), characters 4–9
    /// Contains vehicle attributes like model, body type, engine, etc.
    vds: &'a [u8],

    /// Vehicle Identifier Section (VIS), characters 10–17
    /// Contains specific vehicle information including production year and
    /// plant
    vis: &'a [u8],
}

impl<'a> Vin<'a> {
    /// Attempts to infer the year of manufacture from the VIN.
    ///
    /// This method uses the 10th character of the VIN (first character of the VIS)
    /// to determine the model year according to the standard coding pattern.
    ///
    /// Since the year codes repeat in a 30-year cycle, this method attempts to
    /// resolve ambiguity by selecting the most likely year based on the current date.
    ///
    /// # Returns
    /// * `Some(year)` - The inferred manufacturing year
    /// * `None` - If the year could not be determined
    ///
    /// # Examples
    /// ```
    /// # use mb_vin::Vin;
    /// let vin = Vin::parse(b"5GZCZ43D13S812715").unwrap();
    /// let year = vin.year_of_manufacture();
    /// assert_eq!(year, Some(2003)); // The '3' in position 10 indicates 2003
    /// ```
    #[must_use]
    pub fn year_of_manufacture(&self) -> Option<u16> {
        // Use current year as reference (could be replaced with time-based
        // logic if needed)
        self.year_of_manufacture_with_base(CURRENT_YEAR)
    }

    /// Attempts to infer the year of manufacture from the VIN using a custom base year.
    ///
    /// This method is similar to `year_of_manufacture` but allows the caller to specify
    /// the reference year used to resolve ambiguities in the 30-year cycle.
    ///
    /// # Parameters
    /// * `base_year` - The reference year to use for resolving ambiguities
    ///
    /// # Returns
    /// * `Some(year)` - The inferred manufacturing year
    /// * `None` - If the year could not be determined
    ///
    /// # Examples
    /// ```
    /// # use mb_vin::Vin;
    /// let vin = Vin::parse(b"5GZCZ43D13S812715").unwrap();
    ///
    /// // Using different base years may produce different results
    /// // for ambiguous VINs manufactured 30+ years apart
    /// let year_2023 = vin.year_of_manufacture_with_base(2023);
    /// let year_1995 = vin.year_of_manufacture_with_base(1995);
    /// ```
    #[must_use]
    pub fn year_of_manufacture_with_base(&self, base_year: u16) -> Option<u16> {
        let year_char = self.vis[0] as char; // self.vis.chars().next()?;

        #[rustfmt::skip]
        static YEAR_MAP: &[(char, u16)] = &[
            // 1980–2009
            ('A', 1980), ('B', 1981), ('C', 1982), ('D', 1983), ('E', 1984),
            ('F', 1985), ('G', 1986), ('H', 1987), ('J', 1988), ('K', 1989),
            ('L', 1990), ('M', 1991), ('N', 1992), ('P', 1993), ('R', 1994),
            ('S', 1995), ('T', 1996), ('V', 1997), ('W', 1998), ('X', 1999),
            ('Y', 2000), ('1', 2001), ('2', 2002), ('3', 2003), ('4', 2004),
            ('5', 2005), ('6', 2006), ('7', 2007), ('8', 2008), ('9', 2009),

            // 2010–2039
            ('A', 2010), ('B', 2011), ('C', 2012), ('D', 2013), ('E', 2014),
            ('F', 2015), ('G', 2016), ('H', 2017), ('J', 2018), ('K', 2019),
            ('L', 2020), ('M', 2021), ('N', 2022), ('P', 2023), ('R', 2024),
            ('S', 2025), ('T', 2026), ('V', 2027), ('W', 2028), ('X', 2029),
            ('Y', 2030), ('1', 2031), ('2', 2032), ('3', 2033), ('4', 2034),
            ('5', 2035), ('6', 2036), ('7', 2037), ('8', 2038), ('9', 2039),
        ];

        let mut candidates: Vec<u16> = YEAR_MAP
            .iter()
            .filter(|(c, _)| *c == year_char)
            .map(|(_, year)| *year)
            .collect();

        // Seleciona o valor mais próximo sem ultrapassar base_year + 1
        candidates.retain(|&y| y <= base_year + 1);
        candidates.into_iter().max()
    }

    /// Look up manufacturer and country information from the WMI
    ///
    /// Returns information about the manufacturer, country, and region if found.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mb_vin::Vin;
    /// let vin = Vin::parse(b"5GZCZ43D13S812715").unwrap();
    /// if let Some(info) = vin.lookup_wmi_info() {
    ///     println!("Manufacturer: {}", info.manufacturer);
    ///     println!("Country: {}", info.country);
    ///     println!("Region: {}", info.region);
    /// }
    /// ```
    pub fn lookup_wmi_info(&self) -> Option<&'static crate::WmiInfo> {
        crate::WmiInfo::lookup(self.wmi)
    }

    /// Help
    #[inline]
    pub fn vds(&self) -> &str {
        std::str::from_utf8(self.vds).unwrap()
    }

    /// Help
    #[inline]
    pub fn vis(&self) -> &str {
        std::str::from_utf8(self.vis).unwrap()
    }

    /// Help
    #[inline]
    pub fn wmi(&self) -> &str {
        std::str::from_utf8(self.wmi).unwrap()
    }

    /// Help
    #[inline]
    pub fn check_digit(&self) -> &char {
        &self.check_digit
    }

    /// Attempts to parse and validate a VIN from a raw bytes.
    ///
    /// # Validation steps:
    /// 1. Checks that the input is exactly 17 characters
    /// 2. Verifies all characters are valid (alphanumeric excluding I, O, Q)
    /// 3. Confirms all letters are uppercase
    /// 4. Validates the check digit (9th character)
    ///
    /// # Errors
    /// Returns an error if any validation step fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mb_vin::Vin;
    /// let valid_vin = Vin::parse(b"5GZCZ43D13S812715");
    /// assert!(valid_vin.is_ok());
    ///
    /// let invalid_vin = Vin::parse(b"INVALID");
    /// assert!(invalid_vin.is_err());
    /// ```
    pub fn parse(raw: &'a [u8]) -> Result<Self, Error> {
        if raw.len() != MAX_LENGTH {
            return Err(Error::InvalidLength);
        }

        // let bytes = raw.as_bytes();
        let expected = raw[8] as char;
        let mut sum: u32 = 0;

        for i in 0..MAX_LENGTH {
            let b = raw[i];

            if is_lowercase_alpha(b) {
                return Err(Error::InvalidLowercaseCharacter);
            }

            // Validate and get transliteration value
            let value = match check_and_transliterate(b) {
                Ok(v) => v as u32,
                Err(e) => return Err(e),
            };

            if i != 8 {
                sum += value * WEIGHTS[i];
            }
        }

        let result = sum % 11;
        let found = if result == 10 {
            'X'
        } else {
            std::char::from_digit(result, 10).unwrap()
        };

        if expected != found {
            return Err(Error::InvalidCheckDigit { expected, found });
        }

        Ok(Self {
            raw,
            check_digit: expected,
            wmi: &raw[0..3],
            vds: &raw[3..9],
            vis: &raw[9..],
        })
    }

    /// Attempts to parse and validate a VIN from a raw string.
    ///
    /// # Validation steps:
    /// 1. Checks that the input is exactly 17 characters
    /// 2. Verifies all characters are valid (alphanumeric excluding I, O, Q)
    /// 3. Confirms all letters are uppercase
    /// 4. Validates the check digit (9th character)
    ///
    /// # Errors
    /// Returns an error if any validation step fails.
    ///
    /// # Examples
    ///
    /// ```
    /// # use mb_vin::Vin;
    /// let valid_vin = Vin::parse_str("5GZCZ43D13S812715");
    /// assert!(valid_vin.is_ok());
    ///
    /// let invalid_vin = Vin::parse_str("INVALID");
    /// assert!(invalid_vin.is_err());
    /// ```
    pub fn parse_str(input: &'a str) -> Result<Self, Error> {
        Self::parse(input.as_bytes())
    }

    /// Parses a VIN with minimal validation
    ///
    /// # Safety
    ///
    /// This function assumes the input is well-formed (17 characters, uppercase,
    /// valid charset).
    /// It only validates the check digit. Use with caution.
    pub fn parse_trusted(raw: &'a [u8]) -> Result<Self, Error> {
        let found = raw[8] as char;
        let mut sum: u32 = 0;

        for i in 0..MAX_LENGTH {
            if i != 8 {
                let value = VIN_CHAR_TABLE[raw[i] as usize] as u32;
                sum += value * WEIGHTS[i];
            }
        }

        let result = sum % 11;
        let expected = if result == 10 {
            'X'
        } else {
            std::char::from_digit(result, 10).unwrap()
        };

        if expected != found {
            return Err(Error::InvalidCheckDigit { expected, found });
        }

        Ok(Self {
            raw,
            check_digit: expected,
            wmi: &raw[0..3],
            vds: &raw[3..9],
            vis: &raw[9..],
        })
    }

    /// Process a batch str of VINs efficiently
    #[cfg(not(feature = "simd"))]
    pub fn parse_batch(vins: &[&'a &str]) -> Vec<Result<Vin<'a>, Error>> {
        vins.iter().map(|&vin| Self::parse_str(vin)).collect()
    }

    /// Process a batch of VINs using SIMD (Single Instruction, Multiple Data) parallelism
    ///
    /// This function efficiently validates and parses multiple VINs by leveraging SIMD
    /// instructions to process multiple bytes simultaneously. It uses the `wide` crate's
    /// SIMD types to accelerate the check digit calculation.
    ///
    /// # Implementation Details
    ///
    /// The SIMD optimization primarily focuses on the weighted sum calculation used to verify
    /// the check digit:
    ///
    /// 1. Character validation is still performed sequentially, as error handling
    ///    cannot be easily vectorized
    /// 2. The check digit calculation uses SIMD to process bytes in two batches:
    ///    - First 8 bytes (positions 0-7)
    ///    - Last 8 bytes (positions 9-16)
    ///    - Position 8 (the check digit itself) is skipped in the calculation
    /// 3. SIMD parallelism allows multiplication and addition operations to be
    ///    performed on multiple values simultaneously
    ///
    /// # Performance Considerations
    ///
    /// - This function is most efficient when processing many VINs at once
    /// - The SIMD operations provide greatest benefit for the weighted sum calculation
    /// - CPU must support the SIMD instruction set used by the `wide` crate
    ///
    /// # Examples
    ///
    /// ```
    /// # use mb_vin::Vin;
    /// let vins = ["5GZCZ43D13S812715", "1M8GDM9AXKP042788", "WVWZZZ1KZAW180599"];
    /// let vins: Vec<&[u8]> = vins.iter().map(|v| v.as_bytes()).collect();
    /// let results = Vin::parse_batch(&vins);
    ///
    /// // Check results
    /// for result in &results {
    ///     match result {
    ///         Ok(vin) => println!("Valid VIN: {}", vin),
    ///         Err(e) => println!("Invalid VIN: {}", e),
    ///     }
    /// }
    /// ```
    ///
    /// # Requirements
    ///
    /// Requires the `simd` feature to be enabled in your Cargo.toml:
    /// ```toml
    /// mb-vin = { version = "0.8.0", features = ["simd"] }
    /// ```
    #[cfg(feature = "simd")]
    pub fn parse_batch(vins: &[&'a [u8]]) -> Vec<Result<Vin<'a>, Error>> {
        use wide::{u32x8, u8x16};

        vins.iter()
            .map(|&vin_bytes| {
                if vin_bytes.len() != MAX_LENGTH {
                    return Err(Error::InvalidLength);
                }

                if is_any_lowercase_simd(vin_bytes) {
                    return Err(Error::InvalidLowercaseCharacter);
                }

                // Validate characters first (we need to do this individually)
                for &b in vin_bytes {
                    if VIN_CHAR_TABLE[b as usize] == 0xFF {
                        return Err(Error::InvalidCharacter(b as char));
                    }
                }

                // Now use SIMD for the check digit calculation
                let found = vin_bytes[8] as char;

                // Process 16 bytes at once with SIMD, but we'll need to handle the missing byte (8th)
                let mut sum: u32 = 0;

                // First 8 bytes (skipping the check digit at position 8)
                {
                    // Transliterate first 8 bytes
                    let values = u8x16::from([
                        VIN_CHAR_TABLE[vin_bytes[0] as usize],
                        VIN_CHAR_TABLE[vin_bytes[1] as usize],
                        VIN_CHAR_TABLE[vin_bytes[2] as usize],
                        VIN_CHAR_TABLE[vin_bytes[3] as usize],
                        VIN_CHAR_TABLE[vin_bytes[4] as usize],
                        VIN_CHAR_TABLE[vin_bytes[5] as usize],
                        VIN_CHAR_TABLE[vin_bytes[6] as usize],
                        VIN_CHAR_TABLE[vin_bytes[7] as usize],
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0, // Padding
                    ]);

                    // Load weights for first 8 bytes
                    let weights = u32x8::from([
                        WEIGHTS[0], WEIGHTS[1], WEIGHTS[2], WEIGHTS[3],
                        WEIGHTS[4], WEIGHTS[5], WEIGHTS[6], WEIGHTS[7],
                    ]);

                    // Convert values to u32 (we'll use only 8 of the 16 lanes)
                    let values_u32 = u32x8::from([
                        values.as_array_ref()[0] as u32,
                        values.as_array_ref()[1] as u32,
                        values.as_array_ref()[2] as u32,
                        values.as_array_ref()[3] as u32,
                        values.as_array_ref()[4] as u32,
                        values.as_array_ref()[5] as u32,
                        values.as_array_ref()[6] as u32,
                        values.as_array_ref()[7] as u32,
                    ]);

                    // Multiply values by weights
                    let products = values_u32 * weights;

                    // Sum the products
                    sum += products.as_array_ref().iter().sum::<u32>();
                }

                // Last 8 bytes (skipping the check digit - we already skipped it above)
                {
                    // Transliterate last 8 bytes
                    let values = u8x16::from([
                        VIN_CHAR_TABLE[vin_bytes[9] as usize],
                        VIN_CHAR_TABLE[vin_bytes[10] as usize],
                        VIN_CHAR_TABLE[vin_bytes[11] as usize],
                        VIN_CHAR_TABLE[vin_bytes[12] as usize],
                        VIN_CHAR_TABLE[vin_bytes[13] as usize],
                        VIN_CHAR_TABLE[vin_bytes[14] as usize],
                        VIN_CHAR_TABLE[vin_bytes[15] as usize],
                        VIN_CHAR_TABLE[vin_bytes[16] as usize],
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0,
                        0, // Padding
                    ]);

                    // Load weights for last 8 bytes
                    let weights = u32x8::from([
                        WEIGHTS[9],
                        WEIGHTS[10],
                        WEIGHTS[11],
                        WEIGHTS[12],
                        WEIGHTS[13],
                        WEIGHTS[14],
                        WEIGHTS[15],
                        WEIGHTS[16],
                    ]);

                    // Convert values to u32 (we'll use only 8 of the 16 lanes)
                    let values_u32 = u32x8::from([
                        values.as_array_ref()[0] as u32,
                        values.as_array_ref()[1] as u32,
                        values.as_array_ref()[2] as u32,
                        values.as_array_ref()[3] as u32,
                        values.as_array_ref()[4] as u32,
                        values.as_array_ref()[5] as u32,
                        values.as_array_ref()[6] as u32,
                        values.as_array_ref()[7] as u32,
                    ]);

                    // Multiply values by weights
                    let products = values_u32 * weights;

                    // Sum the products
                    sum += products.as_array_ref().iter().sum::<u32>();
                }

                // Calculate check digit
                let result = sum % 11;
                let expected = if result == 10 {
                    'X'
                } else {
                    std::char::from_digit(result, 10).unwrap()
                };

                if expected != found {
                    return Err(Error::InvalidCheckDigit { expected, found });
                }

                Ok(Vin {
                    raw: vin_bytes,
                    check_digit: expected,
                    wmi: &vin_bytes[0..3],
                    vds: &vin_bytes[3..9],
                    vis: &vin_bytes[9..],
                })
            })
            .collect()
    }
}

#[cfg(feature = "simd")]
#[inline]
fn is_any_lowercase_simd(bytes: &[u8]) -> bool {
    use wide::{i8x16, CmpGt, CmpLt};

    if bytes.len() >= 16 {
        let mut chunk = [0i8; 16];
        for i in 0..16 {
            chunk[i] = bytes[i] as i8;
        }
        let v = i8x16::from(chunk);

        let a = i8x16::splat(b'a' as i8);
        let z = i8x16::splat(b'z' as i8);

        let ge_a = v.cmp_gt(a);
        let le_z = v.cmp_lt(z);

        let is_lower = ge_a & le_z;
        if is_lower.any() {
            return true;
        }

        return bytes[16..].iter().any(|&b| b.is_ascii_lowercase());
    }

    bytes.iter().any(|&b| b.is_ascii_lowercase())
}

#[inline]
fn is_lowercase_alpha(byte: u8) -> bool {
    byte.is_ascii_lowercase()
}

impl<'a> std::fmt::Display for Vin<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Format: WMI-VDS-VIS (e.g., 5GZ-CZ43D1-3S812715)
        // This makes it more readable by grouping the VIN components
        write!(f, "{}-{}-{}", self.wmi(), self.vds(), self.vis())
    }
}

////////////////////////////////////////////////////////////////////////////////
// SERDE
////////////////////////////////////////////////////////////////////////////////
#[cfg(feature = "serde")]
mod serde_impl {

    use super::{Error, Vin};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::marker::PhantomData;

    /// An owned version of Vin for serialization and deserialization
    #[derive(Debug, Clone)]
    pub struct OwnedVin {
        /// The original raw VIN string
        pub raw: String,

        /// Check digit (character 9)
        pub check_digit: char,

        /// World Manufacturer Identifier (WMI), characters 1–3
        pub wmi: String,

        /// Vehicle Descriptor Section (VDS), characters 4–9
        pub vds: String,

        /// Vehicle Identifier Section (VIS), characters 10–17
        pub vis: String,
    }

    impl OwnedVin {
        /// Create a new OwnedVin from a string
        pub fn new(vin_str: &str) -> Result<Self, Error> {
            // First validate with the existing parser
            let vin = Vin::parse_str(vin_str)?;

            // Then convert to owned strings
            Ok(OwnedVin {
                raw: vin_str.to_string(),
                check_digit: vin.check_digit,
                wmi: vin.wmi().to_string(),
                vds: vin.vds().to_string(),
                vis: vin.vis().to_string(),
            })
        }

        /// Convert to a borrowed Vin
        pub fn as_vin(&self) -> Vin<'_> {
            // This is safe because we've already validated the VIN
            Vin {
                raw: self.raw.as_bytes(),
                check_digit: self.check_digit,
                wmi: self.wmi.as_bytes(),
                vds: self.vds.as_bytes(),
                vis: self.vis.as_bytes(),
            }
        }
    }

    impl<'a> Serialize for Vin<'a> {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_bytes(self.raw)
        }
    }

    impl Serialize for OwnedVin {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.serialize_str(&self.raw)
        }
    }

    impl<'de> Deserialize<'de> for OwnedVin {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            // Deserialize to a string first
            let s = String::deserialize(deserializer)?;

            // Then use our constructor that takes a &str
            OwnedVin::new(&s).map_err(serde::de::Error::custom)
        }
    }

    // For Vin<'de>, we need to handle lifetimes differently
    impl<'de> Deserialize<'de> for Vin<'de> {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            struct VinVisitor<'de>(PhantomData<&'de str>);

            impl<'de> VinVisitor<'de> {
                fn new() -> Self {
                    VinVisitor(PhantomData)
                }
            }

            impl<'de> serde::de::Visitor<'de> for VinVisitor<'de> {
                type Value = Vin<'de>;

                fn expecting(
                    &self,
                    formatter: &mut std::fmt::Formatter,
                ) -> std::fmt::Result {
                    formatter.write_str("a valid VIN string")
                }

                // This is called for non-borrowed strings
                fn visit_str<E>(self, _value: &str) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    // We can't use value directly due to lifetime issues
                    Err(E::custom("Cannot deserialize Vin from non-borrowed data. Use OwnedVin instead."))
                }

                // This is called for borrowed strings with matching lifetime
                fn visit_borrowed_str<E>(
                    self,
                    value: &'de str,
                ) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    Vin::parse_str(value).map_err(serde::de::Error::custom)
                }
            }

            // Use standard deserialize_str, but our visitor will handle the lifetimes
            deserializer.deserialize_str(VinVisitor::new())
        }
    }

    #[cfg(test)]
    fn deserialize_borrowed_vin<'a>(
        s: &'a str,
    ) -> Result<Vin<'a>, serde_json::Error> {
        // This function properly preserves lifetimes for tests
        struct BorrowedStrDeserializer<'a>(&'a str);

        impl<'de, 'a> Deserializer<'de> for BorrowedStrDeserializer<'a>
        where
            'a: 'de,
        {
            type Error = serde_json::Error;

            // Implement the deserialize_str method to pass the borrowed string
            fn deserialize_str<V>(
                self,
                visitor: V,
            ) -> Result<V::Value, Self::Error>
            where
                V: serde::de::Visitor<'de>,
            {
                // Strip quotes if present (simple JSON string handling)
                let s = self.0.trim();
                let s =
                    if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
                        &s[1..s.len() - 1]
                    } else {
                        s
                    };

                visitor.visit_borrowed_str(s)
            }

            // Implement other required methods with default error behavior
            serde::forward_to_deserialize_any! {
                bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char string
                bytes byte_buf option unit unit_struct newtype_struct seq tuple
                tuple_struct map struct enum identifier ignored_any
            }

            fn deserialize_any<V>(
                self,
                _visitor: V,
            ) -> Result<V::Value, Self::Error>
            where
                V: serde::de::Visitor<'de>,
            {
                Err(serde::de::Error::custom(
                    "This deserializer only supports strings",
                ))
            }
        }

        // Create a deserializer that preserves the lifetime
        let deserializer = BorrowedStrDeserializer(s);
        Vin::deserialize(deserializer)
    }

    #[cfg(all(test, feature = "serde"))]
    mod serde_tests {
        use serde::{Deserialize, Serialize};
        use serde_json;

        use super::*;

        #[test]
        fn serialize_vin() {
            let vin_bytes = b"5GZCZ43D13S812715";
            let vin = Vin::parse(vin_bytes).unwrap();
            let json = serde_json::to_string(&vin).unwrap();
            // assert_eq!(json, "\"5GZCZ43D13S812715\"");
            assert_eq!(
                json,
                "[53,71,90,67,90,52,51,68,49,51,83,56,49,50,55,49,53]"
            );
        }

        #[test]
        fn deserialize_owned_vin() {
            let vin: OwnedVin =
                serde_json::from_str("\"5GZCZ43D13S812715\"").unwrap();
            assert_eq!(vin.wmi, "5GZ");
            assert_eq!(vin.vds, "CZ43D1");
            assert_eq!(vin.vis, "3S812715");
        }

        #[test]
        fn borrowed_vin_deserialization() {
            // Use our special test helper function that properly handles lifetimes
            let input = "\"5GZCZ43D13S812715\"";
            let vin = deserialize_borrowed_vin(input).unwrap();
            assert_eq!(vin.wmi, b"5GZ");
        }

        #[test]
        fn invalid_vin_deserialize() {
            let result: Result<OwnedVin, _> =
                serde_json::from_str("\"INVALID\"");
            assert!(result.is_err());
        }

        #[test]
        fn in_struct() {
            #[derive(Serialize, Deserialize, Debug)]
            struct Vehicle {
                vin: OwnedVin,
                make: String,
                year: u16,
            }

            let json = r#"{
                "vin": "5GZCZ43D13S812715",
                "make": "General Motors",
                "year": 2003
            }"#;

            let vehicle: Vehicle = serde_json::from_str(json).unwrap();
            assert_eq!(vehicle.vin.wmi, "5GZ");
            assert_eq!(vehicle.year, 2003);

            // Test serialization
            let serialized = serde_json::to_string(&vehicle).unwrap();
            let deserialized: Vehicle =
                serde_json::from_str(&serialized).unwrap();
            assert_eq!(deserialized.vin.raw, "5GZCZ43D13S812715");
        }

        #[test]
        fn owned_vin_methods() {
            let vin_str = "5GZCZ43D13S812715";
            let owned = OwnedVin::new(vin_str).unwrap();

            // Test as_vin() conversion
            let borrowed = owned.as_vin();
            assert_eq!(borrowed.wmi(), "5GZ");
            // assert_eq!(borrowed.raw(), vin_str);

            // Test direct access
            assert_eq!(owned.wmi, "5GZ");
            assert_eq!(owned.raw, vin_str);
        }
    }
}

// Export the OwnedVin type when the serde feature is enabled
#[cfg(feature = "serde")]
pub use self::serde_impl::OwnedVin;

#[cfg(test)]
mod tests {
    use std::error::Error as StdError;

    use super::*;

    #[test]
    fn year_of_manufacture() {
        let test_cases = [
            // VIN, Expected Year
            (b"5GZCZ43D13S812715", Some(2003)), // '3' => 2003
            (b"1M8GDM9AXKP042788", Some(2019)), // 'K' => 2019
            (b"WVWZZZ1K8AW180599", Some(2010)), // 'A' => 2010
            (b"JN1DA31A82T216982", Some(2002)), // '2' => 2002
            (b"1HGCM82613A004351", Some(2003)), // '3' => 2003
            (b"WDBNG70J42A225892", Some(2002)), // '2' => 2002
            (b"SAJDA32C214F28662", Some(2001)), // '1' => 2001
            (b"4T1BE32K45U678742", Some(2005)), // '5' => 2005
            (b"1FAFP34N57W207249", Some(2007)), // '7' => 2007
        ];

        for (vin_bytes, expected_year) in test_cases {
            let vin = Vin::parse(vin_bytes).unwrap();
            assert_eq!(
                vin.year_of_manufacture(),
                expected_year,
                "Failed for VIN {:?}",
                vin_bytes
            );
        }
    }

    #[test]
    fn year_of_manufacture_with_base() {
        let vin_bytes = b"5GZCZ43D13S812715"; // '3' => 2003
        let vin = Vin::parse(vin_bytes).unwrap();

        // Correto com base atual
        assert_eq!(vin.year_of_manufacture_with_base(2025), Some(2003));
        // Com base antiga, ainda considera 2003 pois não retrocede
        assert_eq!(vin.year_of_manufacture_with_base(1995), None);
        // Com base futura, pega 2033
        assert_eq!(vin.year_of_manufacture_with_base(2055), Some(2033));
    }

    #[test]
    fn years_at_cycle_boundaries() {
        let test_cases = [
            (b"1FTYR10U2YPB32455", 1995, None), // 'Y' => 2000
            (b"1FTYR10U2YPB32455", 2025, Some(2000)), // mesmo resultado
            (b"1FADP3F2XAL278143", 1995, Some(1980)), // 'A' => 1980
            (b"1FADP3F2XAL278143", 2025, Some(2010)), // 'A' => 2010
            (b"5NMSG73P89H303658", 1995, None), // '9' => 2009
            (b"5NMSG73P89H303658", 2025, Some(2009)), // mesmo resultado
        ];

        for (vin_bytes, base_year, expected_year) in test_cases {
            let vin = Vin::parse(vin_bytes).unwrap();
            assert_eq!(
                vin.year_of_manufacture_with_base(base_year),
                expected_year,
                "Failed for VIN {:?} with base year {}",
                vin_bytes,
                base_year
            );
        }
    }

    #[test]
    fn invalid_year_character() {
        struct MockVin {
            vis: String,
        }

        impl MockVin {
            fn year_char_to_year(&self) -> Option<u16> {
                let year_char = self.vis.chars().next()?;
                match year_char {
                    'I' | 'O' | 'Q' => None,
                    _ => Some(2000),
                }
            }
        }

        let invalid_chars = ['I', 'O', 'Q'];
        for &c in &invalid_chars {
            let mock_vin = MockVin { vis: format!("{}ABCDEFG", c) };
            assert_eq!(mock_vin.year_char_to_year(), None);
        }
    }

    #[test]
    fn wmi_lookup() {
        let vin_bytes = b"5GZCZ43D13S812715";
        let vin = Vin::parse(vin_bytes).unwrap();

        let info = vin.lookup_wmi_info().unwrap();
        assert_eq!(info.manufacturer, "General Motors");
        assert_eq!(info.country, "United States");
        assert_eq!(info.region, "North America");
    }

    #[test]
    fn parse_trusted_valid() {
        let vin_bytes = b"5GZCZ43D13S812715";
        let vin =
            Vin::parse_trusted(vin_bytes).expect("should parse successfully");
        assert_eq!(vin.check_digit, '1');
        assert_eq!(vin.wmi(), "5GZ");
        assert_eq!(vin.vds(), "CZ43D1");
        assert_eq!(vin.vis(), "3S812715");
    }

    #[test]
    fn parse_trusted_invalid_check_digit() {
        let vin_bytes = b"1HGCM82633A004351";
        let err = Vin::parse_trusted(vin_bytes).unwrap_err();
        match err {
            Error::InvalidCheckDigit { expected, found } => {
                assert_eq!(expected, '1');
                assert_eq!(found, '3');
            }
            _ => panic!("unexpected error type"),
        }
    }

    #[cfg(not(feature = "simd"))]
    #[test]
    fn parse_batch_all_valid() {
        let vins =
            ["5GZCZ43D13S812715", "1M8GDM9AXKP042788", "WVWZZZ1K8AW180599"];

        let vins: Vec<&[u8]> = vins.iter().map(|v| v.as_bytes()).collect();
        let results = Vin::parse_batch(&vins);

        assert_eq!(results.len(), 3);
        for result in &results {
            assert!(result.is_ok());
        }

        // Check specific values
        let first_vin = &results[0].as_ref().unwrap();
        assert_eq!(first_vin.wmi(), "5GZ");

        let second_vin = &results[1].as_ref().unwrap();
        assert_eq!(second_vin.check_digit, 'X');
    }

    #[cfg(not(feature = "simd"))]
    #[test]
    fn parse_batch_with_invalid() {
        let vins = [
            "5GZCZ43D13S812715", // valid
            "INVALID",           // invalid length
            "1HGCM82633A004351", // invalid check digit
        ];

        let vins: Vec<&[u8]> = vins.iter().map(|v| v.as_bytes()).collect();
        let results = Vin::parse_batch(&vins);

        assert_eq!(results.len(), 3);
        assert!(results[0].is_ok());

        match &results[1] {
            Err(Error::InvalidLength) => (),
            _ => panic!("Expected InvalidLength error"),
        }

        match &results[2] {
            Err(Error::InvalidCheckDigit { expected, found }) => {
                assert_eq!(*expected, '3');
                assert_eq!(*found, '1');
            }
            _ => panic!("Expected InvalidCheckDigit error"),
        }
    }

    #[cfg(feature = "simd")]
    #[test]
    fn parse_batch_simd_all_valid() {
        let vins =
            ["5GZCZ43D13S812715", "1M8GDM9AXKP042788", "WVWZZZ1K8AW180599"];

        let vins: Vec<&[u8]> = vins.iter().map(|v| v.as_bytes()).collect();

        let results = Vin::parse_batch(&vins);

        assert_eq!(results.len(), 3);
        for result in &results {
            assert!(result.is_ok());
        }

        // Check specific values
        let first_vin = &results[0].as_ref().unwrap();
        assert_eq!(first_vin.wmi(), "5GZ");

        let second_vin = &results[1].as_ref().unwrap();
        assert_eq!(second_vin.check_digit, 'X');
    }

    #[cfg(feature = "simd")]
    #[test]
    fn parse_batch_simd_with_invalid() {
        let vins = [
            "5GZCZ43D13S812715", // valid
            "INVALID",           // invalid length
            "1HGCM82633A004351", // invalid check digit
        ];
        let vins: Vec<&[u8]> = vins.iter().map(|v| v.as_bytes()).collect();

        let results = Vin::parse_batch(&vins);

        assert_eq!(results.len(), 3);
        assert!(results[0].is_ok());

        match &results[1] {
            Err(Error::InvalidLength) => (),
            _ => panic!("Expected InvalidLength error"),
        }

        match &results[2] {
            Err(Error::InvalidCheckDigit { expected, found }) => {
                assert_eq!(*expected, '1');
                assert_eq!(*found, '3');
            }
            _ => panic!("Expected InvalidCheckDigit error"),
        }
    }

    #[test]
    fn vin_display() {
        let vin_bytes = b"5GZCZ43D13S812715";
        let vin = Vin::parse(vin_bytes).expect("should parse successfully");

        assert_eq!(vin.to_string(), "5GZ-CZ43D1-3S812715");
    }

    #[test]
    fn vin_display_with_x_check_digit() {
        let vin_bytes = b"1M8GDM9AXKP042788";
        let vin = Vin::parse(vin_bytes).expect("should parse successfully");

        assert_eq!(vin.to_string(), "1M8-GDM9AX-KP042788");
    }

    #[test]
    fn invalid_length_display() {
        let err = Error::InvalidLength;
        assert_eq!(
            err.to_string(),
            format!("VIN must be exactly {} characters", MAX_LENGTH)
        );
    }

    #[test]
    fn invalid_character_display() {
        let err = Error::InvalidCharacter('*');
        assert_eq!(
            err.to_string(),
            "VIN contains invalid character: '*' (valid characters are alphanumeric excluding I, O, and Q)"
        );
    }

    #[test]
    fn invalid_lowercase_character_display() {
        let err = Error::InvalidLowercaseCharacter;
        assert_eq!(
            err.to_string(),
            "VIN must only contain uppercase characters"
        );
    }

    #[test]
    fn invalid_check_digit_display() {
        let err = Error::InvalidCheckDigit { expected: '3', found: '1' };
        assert_eq!(
            err.to_string(),
            "VIN has invalid check digit: expected '3', found '1'"
        );
    }

    #[test]
    fn error_is_std_error() {
        fn is_error<T: StdError>(_: T) -> bool {
            true
        }

        assert!(is_error(Error::InvalidLength));
        assert!(is_error(Error::InvalidCharacter('!')));
        assert!(is_error(Error::InvalidLowercaseCharacter));
        assert!(is_error(Error::InvalidCheckDigit {
            expected: 'X',
            found: '0',
        }));
    }

    #[test]
    fn parse_valid_vin() {
        let vin_bytes = b"5GZCZ43D13S812715";
        let vin = Vin::parse(vin_bytes).expect("should parse successfully");
        assert_eq!(vin.check_digit, '1');
        assert_eq!(vin.wmi(), "5GZ");
        assert_eq!(vin.vds(), "CZ43D1");
        assert_eq!(vin.vis(), "3S812715");
    }

    #[test]
    fn valid_check_digit_x() {
        // check digit 'X'
        let vin_bytes = b"1M8GDM9AXKP042788";
        let vin = Vin::parse(vin_bytes).unwrap();
        assert_eq!(vin.check_digit, 'X');
    }

    #[test]
    fn invalid_check_digit() {
        // check digit is '3' but here is '1'
        let vin_bytes = b"1HGCM82633A004351";
        let err = Vin::parse(vin_bytes).unwrap_err();
        match err {
            Error::InvalidCheckDigit { expected, found } => {
                assert_eq!(expected, '3');
                assert_eq!(found, '1');
            }
            _ => panic!("unexpected error type"),
        }
    }

    #[test]
    fn with_invalid_lowercase_char() {
        let vin_bytes = b"HHGCM82633a00435A";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidLowercaseCharacter));
    }

    #[test]
    fn with_invalid_alphanumeric_char() {
        let vin_bytes = b"/HGCM82633A00435A";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidCharacter('/')));
    }

    #[test]
    fn with_invalid_char_i() {
        let vin_bytes = b"1HGCM82633A00435I";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidCharacter('I')));
    }

    #[test]
    fn with_invalid_char_o() {
        let vin_bytes = b"1HGCM82633A00435O";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidCharacter('O')));
    }

    #[test]
    fn with_invalid_char_q() {
        let vin_bytes = b"1HGCM82633A00435Q";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidCharacter('Q')));
    }

    #[test]
    fn invalid_length_less() {
        let vin_bytes = b"123456789";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidLength));
    }

    #[test]
    fn invalid_length_greater() {
        let vin_bytes = b"1HGCM82633A00435A1HGCM82633A00435A";
        let err = Vin::parse(vin_bytes).unwrap_err();
        assert!(matches!(err, Error::InvalidLength));
    }

    #[test]
    fn lookup_exact_match() {
        let info = WmiInfo::lookup(b"5GZ").unwrap();
        assert_eq!(info.manufacturer, "General Motors");
        assert_eq!(info.country, "United States");
    }

    #[test]
    fn lookup_prefix_match() {
        let info = WmiInfo::lookup(b"5G1").unwrap();
        assert_eq!(info.manufacturer, "General Motors");
    }

    #[test]
    fn unknown_wmi() {
        assert!(WmiInfo::lookup(b"XXX").is_none());
    }

    #[test]
    fn region_lookup() {
        assert_eq!(WmiInfo::region_from_char('W'), Some("Europe (Germany)"));
        assert_eq!(WmiInfo::region_from_char('J'), Some("Asia (Japan)"));
    }
}