hamcty 0.5.0

Load and search country data for ham radio callsigns in the CTY database
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
//! Load and search in a CTY database
//!
//! licensed under CC BY-SA 4.0,
//! To view a copy of this license, visit <http://creativecommons.org/licenses/by-sa/4.0/>
//!
//! Author: Andreas, <df1asc@darc.de>
//!
//! # Example
//!
//! ```
//! use hamcty::{CountryDatabase, CtyType, load_recent_cty};
//!
//! fn main() {
//!     // Use crate internal data (maybe not up to date)...
//!     let cdb = CountryDatabase::new();
//!     // ...or load recent CTY and load data from path (you decide about the version)
//!     load_recent_cty("cty.csv", CtyType::Cty).expect("Could not load recent CTY");
//!     let cdb = CountryDatabase::from_path("cty.csv").expect("Could not load cty data");
//!
//!     let call = "DF1ASC";
//!     assert_eq!(cdb.country(call).unwrap().code, "DL");
//!     assert_eq!(cdb.prefix(call), Ok("DF".to_string()));
//!  }
//! ```

#[cfg(feature = "load_cty")]
pub mod load_cty;
#[cfg(feature = "load_cty")]
pub use load_cty::{CtyType, load_recent_cty};

pub mod error;

use csv::StringRecord;
use error::Error;
use regex::Regex;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
use std::fs;
use std::sync::LazyLock;

pub const NAME: &str = env!("CARGO_PKG_NAME");
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Ham radio country code
pub type CountryCode = String;

/// Continents
#[derive(Debug, Clone, PartialEq)]
pub enum Continent {
    NorthAmerica,
    SouthAmerica,
    Europe,
    Africa,
    Oceania,
    Asia,
    Antarctica,
    Unknown(String),
}

impl From<&str> for Continent {
    /// Converts two letter continent codes to `Continent`
    fn from(value: &str) -> Self {
        match value.to_uppercase().as_str() {
            "NA" => Continent::NorthAmerica,
            "SA" => Continent::SouthAmerica,
            "EU" => Continent::Europe,
            "AF" => Continent::Africa,
            "OC" => Continent::Oceania,
            "AS" => Continent::Asia,
            "AN" => Continent::Antarctica,
            _ => Continent::Unknown(value.to_string()),
        }
    }
}

impl Display for Continent {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Continent::NorthAmerica => "NA",
                Continent::SouthAmerica => "SA",
                Continent::Europe => "EU",
                Continent::Africa => "AF",
                Continent::Oceania => "OC",
                Continent::Asia => "AS",
                Continent::Antarctica => "AN",
                Continent::Unknown(cont) => cont,
            }
        )
    }
}

/// DXCC entity code
pub type DXCCEntity = u16;

/// CQ zone number
pub type CQZone = u8;

/// ITU zone number
pub type ITUZone = u8;

/// Coordinates for a location
#[derive(Debug, Clone, PartialEq)]
pub struct Location {
    /// Latitude: positive for north, negative for south.
    pub lat: f32,
    /// Longitude: positive for east, negative for west.
    pub lon: f32,
}

impl TryFrom<&str> for Location {
    type Error = Error;

    /// Converts string e.g. 12.0/-3.0 to `Location{lat: 12.0, lon: 3.0}`
    fn try_from(value: &str) -> Result<Location, Self::Error> {
        let mut loc = value.split("/");
        if let (Some(Ok(lat)), Some(Ok(lon))) = (
            loc.next().map(|v| v.parse::<f32>()),
            loc.next().map(|v| v.parse::<f32>()),
        ) {
            Ok(Location { lat, lon: -lon })
        } else {
            Err(Error::ParseError("unable to parse location".to_string()))
        }
    }
}

/// UTC time offset
pub type TimeOffset = f32;

/// Holds a country information set
#[derive(Debug, Clone, PartialEq)]
pub struct Country {
    /// Ham radio country code
    pub code: CountryCode,
    /// English country name
    pub name: String,
    /// DXCC country code
    pub dxcc: DXCCEntity,
    /// The continent
    pub continent: Continent,
    /// CQ Zone number
    pub cq: CQZone,
    /// ITU Zone number
    pub itu: ITUZone,
    /// Latitude and longitude of country center
    pub location: Location,
    /// Time offset from UTC
    pub time_off: TimeOffset,
    /// If the country does not have an own DXCC
    pub not_dxcc: bool,
}

impl Display for Country {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Maps the Ham radio country code to the country information
pub type CountryMap = HashMap<CountryCode, Country>;

/// Holds mapping data to mapping prefixes or calls to a country
#[derive(Debug, Clone, PartialEq)]
struct OverrideData {
    /// Ham radio country code
    code: CountryCode,
    /// CQ Zone Override
    cq: Option<CQZone>,
    /// ITU Zone override
    itu: Option<ITUZone>,
    /// Location override
    loc: Option<Location>,
    /// Continent override
    cnt: Option<Continent>,
    /// TZ override
    tz: Option<TimeOffset>,
}

static RE_OVERRIDES: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"([A-Z0-9/=]+)",              // Prefix or exact match
        r"(?:\((\d+)\))?",             // CQ override
        r"(?:\[(\d+)\])?",             // ITU override
        r"(?:<(-?\d+.\d/-?\d+.\d)>)?", // Location override
        r"(?:\{(\w+)\})?",             // Continent override
        r"(?:~(-?\d+.\d)~)?",          // TZ override
        r".*"
    ))
    .unwrap()
});

/// Holds the complete country database
#[derive(Debug, PartialEq)]
pub struct CountryDatabase {
    /// Mapping for country code to country
    countries: CountryMap,
    /// Mapping for callsign prefixes to country code
    prefix_overrides: HashMap<String, OverrideData>,
    /// Prefixes as sorted list
    prefixes: Vec<String>,
    /// Mapping for callsign overrides to country code
    call_overrides: HashMap<String, OverrideData>,
    /// The data version
    version: String,
}

impl CountryDatabase {
    /// Create a country database from included CTY data
    pub fn new() -> Self {
        // This should not fail, because it is tested to load
        Self::load(include_str!("../cty/cty.csv").as_bytes()).unwrap()
    }

    /// Loads a cty.csv (either normal or big) from a path
    pub fn from_path(path: impl AsRef<str>) -> Result<Self, Error> {
        Self::load(
            fs::read(path.as_ref())
                .map_err(|e| Error::CtyFileError(e.to_string()))?
                .as_ref(),
        )
    }

    /// Load CTY CSV data
    fn load(data: &[u8]) -> Result<Self, Error> {
        let mut countries = CountryMap::new();
        let mut prefix_overrides: HashMap<String, OverrideData> = HashMap::new();
        let mut call_overrides: HashMap<String, OverrideData> = HashMap::new();
        let mut version = String::new();

        let mut reader = csv::ReaderBuilder::new()
            .delimiter(b',')
            .has_headers(false)
            .from_reader(data);

        for res in reader.records() {
            let record = res.map_err(|e| Error::CSVError(e.to_string()))?;
            Self::parse_record(
                &mut countries,
                &mut prefix_overrides,
                &mut call_overrides,
                &mut version,
                record,
            )?;
        }

        if version.is_empty() {
            return Err(Error::VersionNotFound);
        }

        // Preprocess prefixes to speed up searching
        let mut prefixes = prefix_overrides
            .keys()
            .map(|pfx| pfx.to_string())
            .collect::<Vec<String>>();
        prefixes.sort(); // No need to dedupe as these are hashmap keys

        Ok(Self {
            countries,
            prefix_overrides,
            prefixes,
            call_overrides,
            version,
        })
    }

    /// Parse a CSV record data
    /// e.g. `1A,Sov Mil Order of Malta,246,EU,15,28,41.90,-12.43,-1.0,1A;`
    fn parse_record(
        countries: &mut HashMap<CountryCode, Country>,
        prefix_overrides: &mut HashMap<String, OverrideData>,
        call_overrides: &mut HashMap<String, OverrideData>,
        version: &mut String,
        record: StringRecord,
    ) -> Result<(), Error> {
        let code = record.get(0).unwrap_or_default();
        let not_dxcc = code.starts_with("*");
        let code = code.replace("*", "");

        countries.insert(
            code.to_string(),
            Country {
                code: code.to_string(),
                name: record.get(1).unwrap_or_default().to_string(),
                dxcc: record
                    .get(2)
                    .unwrap_or_default()
                    .parse()
                    .map_err(|_| Error::ParseError(format!("DXCC for country code '{code}'")))?,
                continent: record.get(3).unwrap_or_default().into(),
                cq: record
                    .get(4)
                    .unwrap_or_default()
                    .parse()
                    .map_err(|_| Error::ParseError(format!("CQ zone for country code '{code}'")))?,
                itu: record.get(5).unwrap_or_default().parse().map_err(|_| {
                    Error::ParseError(format!("ITU zone for country code '{code}'"))
                })?,
                location: Location {
                    lat: record.get(6).unwrap_or_default().parse().map_err(|_| {
                        Error::ParseError(format!("latitude for country code '{code}'"))
                    })?,
                    lon: record
                        .get(7)
                        .unwrap_or_default()
                        .parse::<f32>()
                        .map(|val| -val)
                        .map_err(|_| {
                            Error::ParseError(format!("longitude for country code '{code}'"))
                        })?,
                },
                time_off: record.get(8).unwrap_or_default().parse().map_err(|_| {
                    Error::ParseError(format!("time offset for country code '{code}'"))
                })?,
                not_dxcc,
            },
        );

        record
            .get(9)
            .unwrap_or_default()
            .replace(";", "")
            .split(" ")
            .for_each(|pfx| {
                Self::parse_prefix_data(prefix_overrides, call_overrides, version, &code, pfx)
            });
        Ok(())
    }

    /// Parses the prefix data part
    fn parse_prefix_data(
        prefix_overrides: &mut HashMap<String, OverrideData>,
        call_overrides: &mut HashMap<String, OverrideData>,
        version: &mut String,
        code: impl AsRef<str>,
        pfx: impl AsRef<str>,
    ) {
        let (pfx, cq, itu, loc, cnt, tz) =
            if let Some(cap) = Regex::captures(&RE_OVERRIDES, pfx.as_ref()) {
                (
                    cap.get(1).map(|v| v.as_str().to_string()),
                    cap.get(2).map(|v| v.as_str().parse::<CQZone>().unwrap()),
                    cap.get(3).map(|v| v.as_str().parse::<ITUZone>().unwrap()),
                    cap.get(4)
                        .map(|v| Location::try_from(v.as_str()).ok().unwrap()),
                    cap.get(5).map(|v| Continent::from(v.as_str())),
                    cap.get(6)
                        .map(|v| v.as_str().parse::<TimeOffset>().unwrap()),
                )
            } else {
                (None, None, None, None, None, None)
            };

        let Some(pfx) = pfx else { return };

        if let Some(pfx) = pfx.strip_prefix("=") {
            if code.as_ref() == "VE" && pfx.starts_with("VER") {
                version.push_str(pfx);
                return;
            }
            if !call_overrides.contains_key(pfx) {
                call_overrides.insert(
                    pfx.to_string(),
                    OverrideData {
                        code: code.as_ref().to_string(),
                        cq,
                        itu,
                        loc,
                        cnt,
                        tz,
                    },
                );
            }
        } else {
            prefix_overrides.insert(
                pfx,
                OverrideData {
                    code: code.as_ref().to_string(),
                    cq,
                    itu,
                    loc,
                    cnt,
                    tz,
                },
            );
        }
    }

    /// Returns the database version.
    pub fn version(&self) -> &String {
        &self.version
    }

    /// Returns the version entity for verification purpose.
    pub fn version_entity(&self) -> Result<(CountryCode, String), Error> {
        let cty = self
            .country("VERSION")
            .map_err(|_| Error::VersionEntityNotFound)?;
        Ok((cty.code, cty.name))
    }

    /// Finds the prefix for a callsign
    pub fn prefix(&self, call: impl AsRef<str>) -> Result<String, Error> {
        let mut pfx = String::new();

        let call = call.as_ref().to_uppercase();
        (1..call.chars().count() + 1).for_each(|i| {
            if let Ok(_) = self.prefixes.binary_search(&call[..i].to_string()) {
                pfx = call[..i].to_string()
            }
        });

        if !pfx.is_empty() {
            Ok(pfx)
        } else {
            Err(Error::PrefixNotFound)
        }
    }

    /// Searches the country code and override data for a callsign.
    /// If data is not found in callsigns, the data is searched in prefixes.
    fn country_code(&self, call: impl AsRef<str>) -> Result<&OverrideData, Error> {
        if let Some(ord) = self.call_overrides.get(&call.as_ref().to_uppercase()) {
            return Ok(ord);
        }

        self.prefix_overrides
            .get(&self.prefix(call).map_err(|_| Error::CountryCodeNotFound)?)
            .ok_or(Error::CountryCodeNotFound)
    }

    /// Fetches the `Country` data for a callsign.
    pub fn country(&self, call: impl AsRef<str>) -> Result<Country, Error> {
        let data = self.country_code(&call)?.clone();

        self.countries
            .get(&data.code)
            .ok_or(Error::CountryNotFound)
            .map(|cty| Country {
                cq: if let Some(cq) = data.cq { cq } else { cty.cq },
                itu: if let Some(itu) = data.itu {
                    itu
                } else {
                    cty.itu
                },
                location: if let Some(loc) = data.loc {
                    loc
                } else {
                    cty.location.clone()
                },
                continent: if let Some(cnt) = data.cnt {
                    cnt
                } else {
                    cty.continent.clone()
                },
                time_off: if let Some(tz) = data.tz {
                    tz
                } else {
                    cty.time_off
                },
                ..cty.clone()
            })
    }
}

impl Default for CountryDatabase {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use std::collections::HashSet;

    // The tests will only work with cty.csv from 3 June 2026 (CTY-3620)
    // VER20260603, Version entity is Kingdom of Eswatini, 3DA
    fn setup() -> CountryDatabase {
        CountryDatabase::from_path("test_data/cty.csv").expect("error loading test data")
    }

    #[test]
    fn test_100_version() {
        let cdb = setup();

        assert_eq!(cdb.version(), "VER20260603");
        assert_eq!(
            cdb.version_entity(),
            Ok(("3DA".to_string(), "Kingdom of Eswatini".to_string()))
        );
    }

    // Test that the correct version is included in the binary
    // Adapt this to the version and entity of the data provided in `cty`
    #[test]
    fn test_101_cur_version() {
        let cdb = CountryDatabase::default();

        assert_eq!(cdb.version(), "VER20260915");
        assert_eq!(
            cdb.version_entity(),
            Ok(("3D2/r".to_string(), "Rotuma Island".to_string()))
        );
    }

    #[test]
    fn test_105_prefixes_state() {
        let cdb = setup();
        assert_eq!(true, cdb.prefixes.is_sorted());

        // Check if prefixes has only unique elements
        let mut helper_set = HashSet::new();
        assert_eq!(
            true,
            cdb.prefixes
                .clone()
                .into_iter()
                .all(|x| helper_set.insert(x))
        );
    }

    #[test]
    fn test_110_prefix() {
        let cdb = setup();

        assert_eq!(cdb.prefix("DF1ASC"), Ok("DF".to_string()));
        assert_eq!(cdb.prefix("DK50K32MR"), Ok("DK".to_string()));
        assert_eq!(cdb.prefix("XX1XX"), Err(Error::PrefixNotFound));
    }

    #[test]
    fn test_120_search() {
        let cdb = setup();

        let cty = cdb.country("DF1ASC").unwrap();
        assert_eq!(cty.code, "DL");
        assert_eq!(cty.continent, Continent::Europe);
        assert_eq!(
            cty.location,
            Location {
                lat: 51.00,
                lon: 10.00
            }
        );
        assert_eq!(false, cty.not_dxcc);

        let cty = cdb.country("N4ABC").unwrap();
        assert_eq!(cty.code, "K");
        assert_eq!(cty.continent, Continent::NorthAmerica);
        assert_eq!(false, cty.not_dxcc);

        let cty = cdb.country("IH9ABC").unwrap();
        assert_eq!(true, cty.not_dxcc);

        let calls = vec![
            ("LU1DD", "LU"),    // LU prefix
            ("LU1ZB", "CE9"),   // LU1Z prefix
            ("LU1ZA", "VP8/o"), // Exact match override
            ("LU1ZAW", "CE9"),  // LU1Z prefix
        ];

        for (call, cc) in calls {
            let cty = cdb.country(call).unwrap();
            assert_eq!(cty.code, cc);
        }

        assert_eq!(cdb.country("XX1XX"), Err(Error::CountryCodeNotFound));
    }

    #[test]
    fn test_125_search_prefix() {
        let cdb = setup();

        let cty = cdb.country("PA/DF1ASC").unwrap();
        assert_eq!(cty.code, "PA");

        let cty = cdb.country("DO/K4ABC").unwrap();
        assert_eq!(cty.code, "DL");

        let cty = cdb.country("DK/ZS3ASD").unwrap();
        assert_eq!(cty.code, "DL");
    }

    #[test]
    fn test_130_search_w_override() {
        let cdb = setup();

        // Override country for call
        let cty = cdb.country("LU1ZA").unwrap();
        assert_eq!(cty.code, "VP8/o");
        assert_eq!(cty.continent, Continent::SouthAmerica);

        // Override ITU and CQ for call
        let cty = cdb.country("4U1WB").unwrap();
        assert_eq!(cty.code, "K");
        assert_eq!(cty.continent, Continent::NorthAmerica);
        assert_eq!(cty.cq, 5);
        assert_eq!(cty.itu, 8);

        // Override ITU for prefix
        let cty = cdb.country("PP6XX").unwrap();
        assert_eq!(cty.code, "PY");
        assert_eq!(cty.continent, Continent::SouthAmerica);
        assert_eq!(cty.itu, 13);
        assert_eq!(cty.cq, 11);
    }

    #[test]
    fn test_135_search_w_override() {
        let row = String::from(
            "K,United States,291,NA,5,8,37.60,91.87,5.0,AA AB AC<2.0/3.5> AD{SA} AE~-3.0~ \
                AF AG AI AJ AK(3)[24] K N W =4U1WB(5)[8] =AH0AB(13)[16] =AH0AJ(5) =AH0AM[8] \
                =AH0AX(7)[6]<-12.0/23.5>{AF}~2.0~ =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;\n\
                VE,Canada,1,NA,5,9,44.35,78.75,5.0,CF CG CJ CK =VER20260603 =VA2VVV(2)[4];",
        );
        let cdb = CountryDatabase::load(row.as_bytes()).unwrap();

        // All overrides for call
        let cty = cdb.country("AH0AX").unwrap();
        assert_eq!("K", cty.code);
        assert_eq!(7, cty.cq);
        assert_eq!(6, cty.itu);
        assert_eq!(
            Location {
                lat: -12.0,
                lon: -23.5
            },
            cty.location
        );
        assert_eq!(Continent::Africa, cty.continent);
        assert_eq!(2.0, cty.time_off)
    }

    #[test]
    fn test_200_error() {
        assert_eq!(Error::PrefixNotFound.to_string(), "PrefixNotFound");
    }

    #[test]
    fn test_300_continent() {
        assert_eq!(<&str as Into<Continent>>::into("AN"), Continent::Antarctica);
        assert_eq!(
            <&str as Into<Continent>>::into("BB"),
            Continent::Unknown("BB".to_string())
        );
    }

    #[test]
    fn test_310_cont_disp() {
        assert_eq!(Continent::Unknown("XX".to_string()).to_string(), "XX");
        assert_eq!(Continent::NorthAmerica.to_string(), "NA");
        assert_eq!(Continent::SouthAmerica.to_string(), "SA");
        assert_eq!(Continent::Europe.to_string(), "EU");
        assert_eq!(Continent::Africa.to_string(), "AF");
        assert_eq!(Continent::Oceania.to_string(), "OC");
        assert_eq!(Continent::Asia.to_string(), "AS");
        assert_eq!(Continent::Antarctica.to_string(), "AN");
    }

    #[test]
    fn test_320_country_disp() {
        let country = Country {
            code: "XY".to_string(),
            name: "Xy".to_string(),
            dxcc: 100,
            continent: Continent::Antarctica,
            cq: 101,
            itu: 102,
            location: Location {
                lat: 10.1,
                lon: 5.5,
            },
            time_off: -2.0,
            not_dxcc: false,
        };
        assert_eq!(
            country.to_string(),
            "Country { \
                code: \"XY\", \
                name: \"Xy\", \
                dxcc: 100, \
                continent: Antarctica, \
                cq: 101, \
                itu: 102, \
                location: Location { lat: 10.1, lon: 5.5 }, \
                time_off: -2.0, \
                not_dxcc: false \
            }"
        )
    }

    #[test]
    fn test_400_parse_ok() {
        let row = String::from(
            "K,United States,29,NA,5,8,37.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;\n\
                VE,Canada,1,NA,5,9,44.35,78.75,5.0,CF CG CJ CK =VER20260603 =VA2VVV(2)[4];",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(true, res.is_ok());
    }

    #[test]
    fn test_410_parse_errors() {
        let row = String::from(
            "K,United States,291,NA,5,8,37.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(res, Err(Error::VersionNotFound));

        // DXCC
        let row = String::from(
            "K,United States,29a,NA,5,8,37.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError("DXCC for country code 'K'".to_string()))
        );

        // CQ zone
        let row = String::from(
            "K,United States,291,NA,a,8,37.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError(
                "CQ zone for country code 'K'".to_string()
            ))
        );

        // ITU zone
        let row = String::from(
            "K,United States,291,NA,5,a,37.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError(
                "ITU zone for country code 'K'".to_string()
            ))
        );

        // lat/long
        let row = String::from(
            "K,United States,291,NA,5,8,a.60,91.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError(
                "latitude for country code 'K'".to_string()
            ))
        );
        let row = String::from(
            "K,United States,291,NA,5,8,37.60,a.87,5.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError(
                "longitude for country code 'K'".to_string()
            ))
        );

        // Time offset
        let row = String::from(
            "K,United States,291,NA,5,8,37.60,91.87,a.0,AA AB AC AD AE AF AG AI AJ AK K N W \
                =4U1WB(5)[8] =AH0AB(3)[6] =AH0AJ(5)[8] =AH0AM(4)[8] =AH0AX(5)[8] =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;",
        );
        let res = CountryDatabase::load(row.as_bytes());
        assert_eq!(
            res,
            Err(Error::ParseError(
                "time offset for country code 'K'".to_string()
            ))
        );
    }

    #[test]
    fn test_420_parse_override() {
        let row = String::from(
            "K,United States,291,NA,5,8,37.60,91.87,5.0,AA AB AC<2.0/3.5> AD{SA} AE~-3.0~ \
                AF AG AI AJ AK(3)[24] K N W =4U1WB(5)[8] =AH0AB(13)[16] =AH0AJ(5) =AH0AM[8] \
                =AH0AX(7)[6]<-12.0/23.5>{AF}~2.0~ =AH0BR(5)[8];\n\
                3DA,Kingdom of Eswatini,468,AF,38,57,-26.65,-31.48,-2.0,3DA =VERSION;\n\
                VE,Canada,1,NA,5,9,44.35,78.75,5.0,CF CG CJ CK =VER20260603 =VA2VVV(2)[4];",
        );
        let cdb = CountryDatabase::load(row.as_bytes()).unwrap();

        assert_eq!(None, cdb.prefix_overrides["AA"].cq);
        assert_eq!(None, cdb.prefix_overrides["AA"].itu);
        assert_eq!(None, cdb.prefix_overrides["AA"].loc);
        assert_eq!(None, cdb.prefix_overrides["AA"].cnt);
        assert_eq!(None, cdb.prefix_overrides["AA"].tz);

        assert_eq!(None, cdb.prefix_overrides["AC"].cq);
        assert_eq!(None, cdb.prefix_overrides["AC"].itu);
        assert_eq!(
            Some(Location {
                lat: 2.0,
                lon: -3.5
            }),
            cdb.prefix_overrides["AC"].loc
        );
        assert_eq!(None, cdb.prefix_overrides["AC"].cnt);
        assert_eq!(None, cdb.prefix_overrides["AC"].tz);

        assert_eq!(None, cdb.prefix_overrides["AD"].cq);
        assert_eq!(None, cdb.prefix_overrides["AD"].itu);
        assert_eq!(None, cdb.prefix_overrides["AD"].loc);
        assert_eq!(
            Some(Continent::SouthAmerica),
            cdb.prefix_overrides["AD"].cnt
        );
        assert_eq!(None, cdb.prefix_overrides["AD"].tz);

        assert_eq!(None, cdb.prefix_overrides["AE"].cq);
        assert_eq!(None, cdb.prefix_overrides["AE"].itu);
        assert_eq!(None, cdb.prefix_overrides["AE"].loc);
        assert_eq!(None, cdb.prefix_overrides["AE"].cnt);
        assert_eq!(Some(-3.0), cdb.prefix_overrides["AE"].tz);

        assert_eq!(Some(3), cdb.prefix_overrides["AK"].cq);
        assert_eq!(Some(24), cdb.prefix_overrides["AK"].itu);
        assert_eq!(None, cdb.prefix_overrides["AK"].loc);
        assert_eq!(None, cdb.prefix_overrides["AK"].cnt);
        assert_eq!(None, cdb.prefix_overrides["AK"].tz);

        assert_eq!(Some(7), cdb.call_overrides["AH0AX"].cq);
        assert_eq!(Some(6), cdb.call_overrides["AH0AX"].itu);
        assert_eq!(
            Some(Location {
                lat: -12.0,
                lon: -23.5
            }),
            cdb.call_overrides["AH0AX"].loc
        );
        assert_eq!(Some(Continent::Africa), cdb.call_overrides["AH0AX"].cnt);
        assert_eq!(Some(2.0), cdb.call_overrides["AH0AX"].tz);
    }
}