rfham-core 0.1.1

Core data types for RF-Ham libraries.
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
//! Amateur radio callsign parsing and validation.
//!
//! A callsign follows the ITU pattern `[ancillary-prefix/]PREFIX N SUFFIX[/ancillary-suffix]`:
//!
//! - **Prefix** — one to three letters (or digit + letters), e.g. `K`, `VE`, `OE3`
//! - **Separator** — a single digit `0`–`9`
//! - **Suffix** — one to ten alphanumeric characters ending in a letter
//! - **Ancillary prefix/suffix** — optional portable / operating-context qualifiers
//!
//! ## Ancillary suffixes
//!
//! | Suffix | Meaning |
//! |--------|---------|
//! | `/P`   | Portable |
//! | `/M`   | Mobile |
//! | `/AM`  | Aeronautical mobile |
//! | `/MM`  | Maritime mobile |
//! | `/A`   | Alternate location |
//! | `/QRP` | Low-power (≤5 W) operation |
//! | `/AG`, `/AE` | FCC licence pending upgrade |
//!
//! # Examples
//!
//! ```rust
//! use rfham_core::callsign::CallSign;
//!
//! let cs: CallSign = "K7SKJ".parse().unwrap();
//! assert_eq!(cs.prefix(), "K");
//! assert_eq!(cs.separator_numeral(), 7);
//! assert_eq!(cs.suffix(), "SKJ");
//! assert!(!cs.is_mobile());
//! ```
//!
//! Ancillary qualifiers round-trip through `Display`:
//!
//! ```rust
//! use rfham_core::callsign::CallSign;
//!
//! let cs: CallSign = "LM9L40Y/P".parse().unwrap();
//! assert!(cs.is_portable());
//! assert_eq!(cs.to_string(), "LM9L40Y/P");
//! ```
//!
//! Invalid callsigns return an error:
//!
//! ```rust
//! use rfham_core::callsign::CallSign;
//!
//! assert!(CallSign::is_valid("K7SKJ"));
//! assert!(!CallSign::is_valid("NODIGIT"));
//! assert!("NODIGIT".parse::<CallSign>().is_err());
//! ```

use crate::error::CoreError;
use regex::Regex;
use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::{fmt::Display, str::FromStr, sync::LazyLock};

// ------------------------------------------------------------------------------------------------
// Public Macros
// ------------------------------------------------------------------------------------------------

// ------------------------------------------------------------------------------------------------
// Public Types
// ------------------------------------------------------------------------------------------------

/// In general an amateur radio callsign is of one of these forms where:
///
/// * *P* – prefix character (letter or numeral, subject to exclusions below). Prefixes can be
///   formed using one-letter, two-letters, a digit and a letter, a letter and a digit, or in
///   rare cases a digit and two letters. There is no ITU allocation of digit-only prefixes.
///   Letter-digit-letter prefixes are possible but there are no known cases of them being
///   issued by national bodies.
/// * *N* – a single numeral which separates prefix from suffix (any digit from 0 to 9).
///   Often a cross-hatched Ø is used for the numeral zero to distinguish it from the letter O.
/// * *S* – suffix character (letter or numeral, last character must be a letter). Digits are
///   in practise used sparingly in suffixes and almost always for special events. This avoids
///   confusion with separating numerals and digits in prefixes in regularly issued call signs.
///
///   From [Wikipedia](https://en.wikipedia.org/wiki/Amateur_radio_call_signs)
#[derive(Clone, Debug, PartialEq, Eq, DeserializeFromStr, SerializeDisplay)]
pub struct CallSign {
    ancillary_prefix: Option<String>,
    prefix: String,
    separator: u8,
    suffix: String,
    ancillary_suffix: Option<String>,
}

// ------------------------------------------------------------------------------------------------
// Implementations
// ------------------------------------------------------------------------------------------------

static CALLSIGN_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?x)
    ^
        (?:(?<aprefix>[A-Z0-9]+)\/)?
        (?<prefix>(?:[A-Z][0-9][A-Z]?)|(?:[0-9][A-Z]{0,2})|(?:[A-Z]{1,3}))
        (?<sep>[0-9])
        (?<suffix>[A-Z0-9]{1,10})
        (?:\/(?<asuffix>[A-Z0-9]+))?
    $",
    )
    .unwrap()
});

const ODD_CALLSIGN_PREFIXES: &[&str; 16] = &[
    "1A", // is used by the Sovereign Military Order of Malta
    "1B", // is used by the Turkish Republic of Northern Cyprus
    "1C", "1X", // are occasionally used by separatists in the Chechnya
    "1S", // is sometimes used on the Spratly Islands in the South China Sea
    "1Z", // has been used in Kawthoolei, an unrecognized breakaway region of Myanmar
    "D0",
    "1C",  // were used in 2014, allegedly from the unrecognized Donetsk People's Republic
    "S0",  // is a prefix used in the Western Sahara
    "S1A", // is used by the Principality of Sealand
    "T1",  // has appeared as a callsign from Transnistria
    "T0", "0S", "1P",
    "T89", // have occasionally been used by operators in the Principality of Seborga
    "Z6",  // was chosen by the Telecommunications Regulatory Authority of the Republic of Kosovo
];

// ------------------------------------------------------------------------------------------------

impl Display for CallSign {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}{}{}{}{}",
            if let Some(ancillary_prefix) = &self.ancillary_prefix {
                format!("{ancillary_prefix}/")
            } else {
                String::default()
            },
            self.prefix,
            self.separator,
            self.suffix,
            if let Some(ancillary_suffix) = &self.ancillary_suffix {
                format!("/{ancillary_suffix}")
            } else {
                String::default()
            },
        )
    }
}

impl FromStr for CallSign {
    type Err = CoreError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let captures = CALLSIGN_REGEX.captures(s);
        if let Some(captures) = captures {
            let result = CallSign::new(
                captures.name("prefix").unwrap().as_str(),
                u8::from_str(captures.name("sep").unwrap().as_str())
                    .map_err(|_| CoreError::InvalidValueFromStr(s.to_string(), "CallSign"))?,
                captures.name("suffix").unwrap().as_str(),
            );
            let result = if let Some(a_prefix) = captures.name("aprefix") {
                result.with_ancillary_prefix(a_prefix.as_str())
            } else {
                result
            };
            let result = if let Some(a_suffix) = captures.name("asuffix") {
                result.with_ancillary_suffix(a_suffix.as_str())
            } else {
                result
            };
            Ok(result)
        } else {
            Err(CoreError::InvalidValueFromStr(s.to_string(), "CallSign"))
        }
    }
}

impl CallSign {
    pub fn new<S1: Into<String>, N: Into<u8>, S2: Into<String>>(
        prefix: S1,
        separator: N,
        suffix: S2,
    ) -> Self {
        Self {
            ancillary_prefix: None,
            prefix: prefix.into(),
            separator: separator.into(),
            suffix: suffix.into(),
            ancillary_suffix: None,
        }
    }

    pub fn with_ancillary_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
        self.ancillary_prefix = Some(prefix.into());
        self
    }

    pub fn with_ancillary_suffix<S: Into<String>>(mut self, suffix: S) -> Self {
        self.ancillary_suffix = Some(suffix.into());
        self
    }

    pub fn ancillary_prefix(&self) -> Option<&String> {
        self.ancillary_prefix.as_ref()
    }

    pub fn prefix(&self) -> &String {
        &self.prefix
    }

    pub fn separator_numeral(&self) -> u8 {
        self.separator
    }

    pub fn suffix(&self) -> &String {
        &self.suffix
    }

    pub fn ancillary_suffix(&self) -> Option<&String> {
        self.ancillary_suffix.as_ref()
    }

    /// Returns `true` if `s` matches the ITU callsign pattern.
    pub fn is_valid(s: &str) -> bool {
        CALLSIGN_REGEX.is_match(s)
    }

    /// Returns `true` if this is a special-event or commemorative callsign — i.e. the suffix
    /// is longer than four characters or ends with a digit.
    pub fn is_special(&self) -> bool {
        self.suffix.len() > 4 || self.suffix.chars().last().unwrap().is_ascii_digit()
    }

    /// Returns `true` if the prefix appears in the list of non-standard or
    /// unrecognised-entity prefixes tracked by this library.
    pub fn is_prefix_non_standard(&self) -> bool {
        ODD_CALLSIGN_PREFIXES.contains(&self.prefix.as_str())
    }

    /// Returns `true` when the `/A` ancillary suffix indicates operation from an alternate
    /// licensed location.
    pub fn is_at_alternate_location(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("A"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/P` ancillary suffix indicates portable operation.
    pub fn is_portable(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("P"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/M` ancillary suffix indicates mobile operation.
    pub fn is_mobile(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("M"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/AM` ancillary suffix indicates aeronautical mobile operation.
    pub fn is_aeronautical_mobile(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("AM"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/MM` ancillary suffix indicates maritime mobile operation.
    pub fn is_maritime_mobile(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("MM"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/QRP` ancillary suffix indicates the station is operating
    /// at QRP power levels (typically ≤5 W).
    pub fn is_operating_qrp(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("QRP"))
            .unwrap_or_default()
    }

    /// Returns `true` when the `/AG` or `/AE` ancillary suffix indicates a pending FCC
    /// licence upgrade.
    pub fn is_fcc_license_pending(&self) -> bool {
        self.ancillary_suffix()
            .map(|s| s.eq_ignore_ascii_case("AG") || s.eq_ignore_ascii_case("AE"))
            .unwrap_or_default()
    }
}

// ------------------------------------------------------------------------------------------------
// Unit Tests
// ------------------------------------------------------------------------------------------------

#[cfg(test)]
mod test {
    use crate::callsigns::CallSign;
    use pretty_assertions::assert_eq;
    use std::str::FromStr;

    const VALID: &[&str] = &[
        "3DA0RS",
        "4D71/N0NM",
        "4X130RISHON",
        "4X4AAA",
        "9N38",
        "A22A",
        "AX3GAMES",
        "B2AA",
        "BV100",
        "DA2MORSE",
        "DB50FIRAC",
        "DL50FRANCE",
        "FBC5AGB",
        "FBC5CWU",
        "FBC5LMJ",
        "FBC5NOD",
        "FBC5YJ",
        "FBC6HQP",
        "GB50RSARS",
        "HA80MRASZ",
        "HB9STEVE",
        "HG5FIRAC",
        "HG80MRASZ",
        "HL1AA",
        "I2OOOOX",
        "II050SCOUT",
        "IP1METEO",
        "J42004A",
        "J42004Q",
        "K4X",
        "LM1814",
        "LM2T70Y",
        "LM9L40Y",
        "LM9L40Y/P",
        "M0A",
        "N2ASD",
        "OEM2BZL",
        "OEM3SGU",
        "OEM3SGU/3",
        "OEM6CLD",
        "OEM8CIQ",
        "OM2011GOOOLY",
        "ON1000NOTGER",
        "ON70REDSTAR",
        "PA09SHAPE",
        "PA65VERON",
        "PA90CORUS",
        "PG50RNARS",
        "PG540BUFFALO",
        "S55CERKNO",
        "TM380",
        // How is this valid => "TX9",
        "TYA11",
        "U5ARTEK/A",
        "V6T1",
        "VB3Q70",
        "VI2AJ2010",
        "VI2FG30",
        "VI4WIP50",
        "VU3DJQF1",
        "VX31763",
        // How is this valid => "WD4",
        "XUF2B",
        "YI9B4E",
        "YO1000LEANY",
        "ZL4RUGBY",
        "ZS9MADIBA",
        "C6AFO",   // Bahamian
        "C6AGB",   // Bahamian
        "VE9COAL", // Canadian commemorative event
    ];

    #[test]
    fn test_callsign_components() {
        let callsign = CallSign::from_str("K7SKJ/M").unwrap();
        assert_eq!(None, callsign.ancillary_prefix());
        assert_eq!("K", callsign.prefix().as_str());
        assert_eq!(7, callsign.separator_numeral());
        assert_eq!("SKJ", callsign.suffix().as_str());
        assert_eq!(Some("M"), callsign.ancillary_suffix().map(|s| s.as_str()));
        assert!(!callsign.is_special());
    }

    #[test]
    fn test_callsign_mobile_qualifiers() {
        assert!("K7SKJ/M".parse::<CallSign>().unwrap().is_mobile());
        assert!("K7SKJ/P".parse::<CallSign>().unwrap().is_portable());
        assert!(
            "K7SKJ/AM"
                .parse::<CallSign>()
                .unwrap()
                .is_aeronautical_mobile()
        );
        assert!("K7SKJ/MM".parse::<CallSign>().unwrap().is_maritime_mobile());
        assert!(
            "K7SKJ/A"
                .parse::<CallSign>()
                .unwrap()
                .is_at_alternate_location()
        );
        assert!("K7SKJ/QRP".parse::<CallSign>().unwrap().is_operating_qrp());
    }

    #[test]
    fn test_callsign_fcc_pending() {
        assert!(
            "K7SKJ/AG"
                .parse::<CallSign>()
                .unwrap()
                .is_fcc_license_pending()
        );
        assert!(
            "K7SKJ/AE"
                .parse::<CallSign>()
                .unwrap()
                .is_fcc_license_pending()
        );
        assert!(
            !"K7SKJ/P"
                .parse::<CallSign>()
                .unwrap()
                .is_fcc_license_pending()
        );
    }

    #[test]
    fn test_callsign_special() {
        assert!("GB50RSARS".parse::<CallSign>().unwrap().is_special()); // long suffix
        assert!(!"K7SKJ".parse::<CallSign>().unwrap().is_special()); // normal suffix
    }

    #[test]
    fn test_callsign_no_qualifier_flags_false() {
        let cs: CallSign = "K7SKJ".parse().unwrap();
        assert!(!cs.is_mobile());
        assert!(!cs.is_portable());
        assert!(!cs.is_aeronautical_mobile());
        assert!(!cs.is_maritime_mobile());
        assert!(!cs.is_at_alternate_location());
        assert!(!cs.is_operating_qrp());
        assert!(!cs.is_fcc_license_pending());
    }

    #[test]
    fn test_invalid_callsigns() {
        assert!(!CallSign::is_valid("NODIGIT")); // no separator digit
        assert!(!CallSign::is_valid("")); // empty
        assert!(!CallSign::is_valid("K7SK!")); // invalid character
        assert!("NODIGIT".parse::<CallSign>().is_err());
    }

    #[test]
    fn test_callsign_display_roundtrip() {
        for s in VALID {
            assert_eq!(s.to_string(), CallSign::from_str(s).unwrap().to_string());
        }
    }
}