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
use std::{fmt::Display, ops::{Deref, DerefMut}};

use chrono::{Datelike, Timelike, Utc};
use indexmap::IndexMap;

#[derive(Debug)]
pub struct SerializeError {
    pub message: String,
    pub offender: String,
}

impl Display for SerializeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}. Offending value: {}", self.message, self.offender)
    }
}

/// Supported datatypes for representing ADIF data
#[derive(Debug, Clone, PartialEq)]
pub enum AdifType {
    /// Basic string type
    Str(String),

    /// Basic boolean type
    Boolean(bool),

    /// Basic number type
    Number(f64),

    /// 8 Digits representing a UTC date in `YYYYMMDD` format, where
    ///  - YYYY is a 4-Digit year specifier, where 1930 <= YYYY
    ///  - MM is a 2-Digit month specifier, where 1 <= MM <= 12
    ///  - DD is a 2-Digit day specifier, where 1 <= DD <= DaysInMonth(MM)
    Date(chrono::Date<Utc>),

    /// 6 Digits representing a UTC time in HHMMSS format
    /// or 4 Digits representing a time in HHMM format, where:
    ///  - HH is a 2-Digit hour specifier, where 0 <= HH <= 23
    ///  - MM is a 2-Digit minute specifier, where 0 <= MM <= 59
    ///  - SS is a 2-Digit second specifier, where 0 <= SS <= 59
    Time(chrono::NaiveTime),
}

impl AdifType {
    /// Get the single-char indicator used to specify a type
    pub fn get_data_type_indicator(&self) -> Option<char> {
        match self {
            AdifType::Str(_) => None,
            AdifType::Boolean(_) => Some('B'),
            AdifType::Number(_) => Some('N'),
            AdifType::Date(_) => Some('D'),
            AdifType::Time(_) => Some('T'),
        }
    }

    /// Serialize into a single value
    pub fn serialize(&self, key_name: &str) -> Result<String, SerializeError> {
        // Convert enum value into a usable string
        let value: Result<String, SerializeError> = match self {
            AdifType::Str(val) => {
                // String cannot contain linebreaks, and must be ASCII
                if val.contains('\n') {
                    return Err(SerializeError {
                        message: "String cannot contain linebreaks".to_string(),
                        offender: val.to_string(),
                    });
                }
                if !val.is_ascii() {
                    return Err(SerializeError {
                        message: "String must be ASCII".to_string(),
                        offender: val.to_string(),
                    });
                }

                Ok(val.to_string())
            }
            AdifType::Boolean(val) => Ok(match val {
                true => "Y",
                false => "N",
            }
            .to_string()),
            AdifType::Number(val) => Ok(val.to_string()),
            AdifType::Date(val) => {
                // Date must be after 1929
                if val.year() < 1930 {
                    return Err(SerializeError {
                        message: "Date must be >= 1930".to_string(),
                        offender: val.to_string(),
                    });
                }

                Ok(format!("{}{:02}{:02}", val.year(), val.month(), val.day()))
            }
            AdifType::Time(val) => Ok(format!(
                "{:02}{:02}{:02}",
                val.hour(),
                val.minute(),
                val.second()
            )),
        };
        let value: &str = &(value?);

        // Format the result
        Ok(format!(
            "<{}:{}{}>{}",
            key_name.to_uppercase().replace(' ', "_"),
            value.len(),
            match self.get_data_type_indicator() {
                Some(id) => format!(":{}", id),
                None => String::new(),
            },
            value
        ))
    }
}

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

/// A single ADIF record, consisting of many values
#[derive(Debug, Clone, PartialEq)]
pub struct AdifRecord(IndexMap<String, AdifType>);

impl AdifRecord {
    /// Serialize into a full record string
    pub fn serialize(&self) -> Result<String, SerializeError> {
        let mut output = self
            .0
            .iter()
            .map(|(key, value)| value.serialize(&key))
            .collect::<Result<Vec<String>, SerializeError>>()?
            .join("");
        output.push_str("<eor>");
        Ok(output)
    }
}

impl From<IndexMap<String, AdifType>> for AdifRecord {
    fn from(map: IndexMap<String, AdifType>) -> Self {
        Self { 0: map }
    }
}

impl<'a> From<IndexMap<&'a str, AdifType>> for AdifRecord {
    fn from(map: IndexMap<&'a str, AdifType>) -> Self {
        Self {
            0: map
                .iter()
                .map(|(key, value)| (key.to_string(), value.clone()))
                .collect(),
        }
    }
}

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

impl Deref for AdifRecord {
    type Target = IndexMap<String, AdifType>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for AdifRecord {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}


/// An ADIF file header, consisting of many values
#[derive(Debug, Clone, PartialEq)]
pub struct AdifHeader(IndexMap<String, AdifType>);

impl AdifHeader {
    /// Serialize into a full header string
    pub fn serialize(&self) -> Result<String, SerializeError> {
        let mut output = self
            .0
            .iter()
            .map(|(key, value)| value.serialize(&key))
            .collect::<Result<Vec<String>, SerializeError>>()?
            .join("\n");
        output.push_str("\n");
        output.push_str("<EOH>");
        Ok(output)
    }
}

impl From<IndexMap<String, AdifType>> for AdifHeader {
    fn from(map: IndexMap<String, AdifType>) -> Self {
        Self { 0: map }
    }
}

impl<'a> From<IndexMap<&'a str, AdifType>> for AdifHeader {
    fn from(map: IndexMap<&'a str, AdifType>) -> Self {
        Self {
            0: map
                .iter()
                .map(|(key, value)| (key.to_string(), value.clone()))
                .collect(),
        }
    }
}

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

impl Deref for AdifHeader {
    type Target = IndexMap<String, AdifType>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for AdifHeader {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Defines an entire file of ADIF data
#[derive(Debug, Clone, PartialEq)]
pub struct AdifFile {
    pub header: AdifHeader,
    pub body: Vec<AdifRecord>,
}

impl AdifFile {

    /// Serialize into text data to be written to a file
    pub fn serialize(&self) -> Result<String, SerializeError> {
        Ok(format!(
            "{}\n{}",
            self.header.serialize()?,
            self.body
                .iter()
                .map(|record| record.serialize())
                .collect::<Result<Vec<String>, SerializeError>>()?
                .join("\n")
        ))
    }
}

#[cfg(test)]
mod types_tests {
    use chrono::{Date, NaiveDate, NaiveTime};

    use super::*;

    #[test]
    pub fn test_ser_string() {
        assert_eq!(
            AdifType::Str("Hello, world!".to_string()).serialize("test").unwrap(),
            "<TEST:13>Hello, world!"
        );
    }

    #[test]
    pub fn test_ser_bool() {
        assert_eq!(
            AdifType::Boolean(true).serialize("test").unwrap(),
            "<TEST:1:B>Y"
        );
        assert_eq!(
            AdifType::Boolean(false).serialize("test").unwrap(),
            "<TEST:1:B>N"
        );
    }

    #[test]
    pub fn test_ser_num() {
        assert_eq!(
            AdifType::Number(3.5).serialize("test").unwrap(),
            "<TEST:3:N>3.5"
        );
        assert_eq!(
            AdifType::Number(-3.5).serialize("test").unwrap(),
            "<TEST:4:N>-3.5"
        );
        assert_eq!(
            AdifType::Number(-12.0).serialize("test").unwrap(),
            "<TEST:3:N>-12"
        );
    }

    #[test]
    pub fn test_ser_date() {
        assert_eq!(
            AdifType::Date(Date::from_utc(NaiveDate::from_ymd(2020, 2, 24), Utc))
                .serialize("test")
                .unwrap(),
            "<TEST:8:D>20200224"
        );
        assert!(
            AdifType::Date(Date::from_utc(NaiveDate::from_ymd(1910, 2, 2), Utc))
                .serialize("test")
                .is_err()
        );
    }

    #[test]
    pub fn test_ser_time() {
        assert_eq!(
            AdifType::Time(NaiveTime::from_hms(23, 2, 5))
                .serialize("test")
                .unwrap(),
            "<TEST:6:T>230205"
        );
    }
}

#[cfg(test)]
mod record_tests {

    use indexmap::indexmap;

    use super::*;

    #[test]
    pub fn test_ser_record() {
        let test_record: AdifRecord = indexmap! {
            "a number" => AdifType::Number(15.5),
            "test string" => AdifType::Str("Heyo rusty friends!".to_string()),
        }
        .into();

        assert_eq!(
            test_record.serialize().unwrap(),
            "<A_NUMBER:4:N>15.5<TEST_STRING:19>Heyo rusty friends!<eor>"
        );
    }

    #[test]
    pub fn test_ser_header() {
        let test_header: AdifHeader = indexmap! {
            "a number" => AdifType::Number(15.5),
            "test string" => AdifType::Str("Heyo rusty friends!".to_string()),
        }
        .into();

        assert_eq!(
            test_header.serialize().unwrap(),
            "<A_NUMBER:4:N>15.5\n<TEST_STRING:19>Heyo rusty friends!\n<EOH>"
        );
    }
}