Skip to main content

nmea_kit/nmea/
field.rs

1//! Field parsing and formatting helpers for NMEA sentence fields.
2//!
3//! [`FieldReader`] reads fields sequentially from a parsed frame.
4//! [`FieldWriter`] builds fields sequentially for encoding.
5
6/// Sequential field reader for NMEA sentence parsing.
7///
8/// Wraps a slice of `&str` fields and reads them in order,
9/// advancing an internal index after each read.
10pub struct FieldReader<'a> {
11    fields: &'a [&'a str],
12    idx: usize,
13}
14
15impl<'a> FieldReader<'a> {
16    pub fn new(fields: &'a [&'a str]) -> Self {
17        Self { fields, idx: 0 }
18    }
19
20    /// Read an optional f32 and advance.
21    pub fn f32(&mut self) -> Option<f32> {
22        let val = self.fields.get(self.idx).and_then(|f| {
23            if f.is_empty() {
24                None
25            } else {
26                f.parse::<f32>().ok()
27            }
28        });
29        self.idx += 1;
30        val
31    }
32
33    /// Read an optional f64 and advance.
34    pub fn f64(&mut self) -> Option<f64> {
35        let val = self.fields.get(self.idx).and_then(|f| {
36            if f.is_empty() {
37                None
38            } else {
39                f.parse::<f64>().ok()
40            }
41        });
42        self.idx += 1;
43        val
44    }
45
46    /// Read an optional u8 and advance.
47    pub fn u8(&mut self) -> Option<u8> {
48        let val = self.fields.get(self.idx).and_then(|f| {
49            if f.is_empty() {
50                None
51            } else {
52                f.parse::<u8>().ok()
53            }
54        });
55        self.idx += 1;
56        val
57    }
58
59    /// Read an optional u32 and advance.
60    pub fn u32(&mut self) -> Option<u32> {
61        let val = self.fields.get(self.idx).and_then(|f| {
62            if f.is_empty() {
63                None
64            } else {
65                f.parse::<u32>().ok()
66            }
67        });
68        self.idx += 1;
69        val
70    }
71
72    /// Read an optional i8 and advance.
73    pub fn i8(&mut self) -> Option<i8> {
74        let val = self.fields.get(self.idx).and_then(|f| {
75            if f.is_empty() {
76                None
77            } else {
78                f.parse::<i8>().ok()
79            }
80        });
81        self.idx += 1;
82        val
83    }
84
85    /// Read an optional single character and advance.
86    pub fn char(&mut self) -> Option<char> {
87        let val = self
88            .fields
89            .get(self.idx)
90            .and_then(|f| f.chars().next().filter(|_| !f.is_empty()));
91        self.idx += 1;
92        val
93    }
94
95    /// Read an optional non-empty string and advance.
96    pub fn string(&mut self) -> Option<String> {
97        let val = self.fields.get(self.idx).and_then(|f| {
98            if f.is_empty() {
99                None
100            } else {
101                Some((*f).to_string())
102            }
103        });
104        self.idx += 1;
105        val
106    }
107
108    /// Skip one field (fixed indicator) and advance.
109    pub fn skip(&mut self) {
110        self.idx += 1;
111    }
112}
113
114/// Sequential field writer for NMEA sentence encoding.
115///
116/// Builds a `Vec<String>` of field values in wire order.
117pub struct FieldWriter {
118    fields: Vec<String>,
119}
120
121impl FieldWriter {
122    pub fn new() -> Self {
123        Self { fields: Vec::new() }
124    }
125
126    /// Write an optional f32. `None` → empty field.
127    pub fn f32(&mut self, value: Option<f32>) {
128        self.fields.push(match value {
129            Some(v) => format!("{v}"),
130            None => String::new(),
131        });
132    }
133
134    /// Write an optional f64. `None` → empty field.
135    pub fn f64(&mut self, value: Option<f64>) {
136        self.fields.push(match value {
137            Some(v) => format!("{v}"),
138            None => String::new(),
139        });
140    }
141
142    /// Write an optional u8. `None` → empty field.
143    pub fn u8(&mut self, value: Option<u8>) {
144        self.fields.push(match value {
145            Some(v) => v.to_string(),
146            None => String::new(),
147        });
148    }
149
150    /// Write an optional i8. `None` → empty field.
151    pub fn i8(&mut self, value: Option<i8>) {
152        self.fields.push(match value {
153            Some(v) => v.to_string(),
154            None => String::new(),
155        });
156    }
157
158    /// Write an optional u32. `None` → empty field.
159    pub fn u32(&mut self, value: Option<u32>) {
160        self.fields.push(match value {
161            Some(v) => v.to_string(),
162            None => String::new(),
163        });
164    }
165
166    /// Write an optional char. `None` → empty field.
167    pub fn char(&mut self, value: Option<char>) {
168        self.fields.push(match value {
169            Some(c) => c.to_string(),
170            None => String::new(),
171        });
172    }
173
174    /// Write a fixed indicator character (always emitted).
175    pub fn fixed(&mut self, c: char) {
176        self.fields.push(c.to_string());
177    }
178
179    /// Write an optional string. `None` → empty field.
180    pub fn string(&mut self, value: Option<&str>) {
181        self.fields.push(value.unwrap_or("").to_string());
182    }
183
184    /// Consume and return the built field list.
185    pub fn finish(self) -> Vec<String> {
186        self.fields
187    }
188}
189
190impl Default for FieldWriter {
191    fn default() -> Self {
192        Self::new()
193    }
194}
195
196/// Trait for NMEA sentence types that can be encoded to wire format.
197///
198/// Provides `SENTENCE_TYPE` and `encode()` — the `to_sentence()` default
199/// method combines them with [`encode_frame()`](crate::encode_frame) to
200/// produce a complete NMEA sentence with checksum.
201///
202/// # Example
203///
204/// ```
205/// use nmea_kit::nmea::{NmeaEncodable, sentences::Dpt};
206///
207/// let dpt = Dpt { depth: Some(4.1), offset: Some(0.0), rangescale: None };
208/// let sentence = dpt.to_sentence("II");
209/// assert!(sentence.starts_with("$IIDPT,"));
210/// ```
211pub trait NmeaEncodable {
212    /// The 3-character sentence type identifier (e.g. `"MWD"`, `"RMC"`).
213    const SENTENCE_TYPE: &str;
214
215    /// Encode fields into a `Vec` of strings in wire order.
216    fn encode(&self) -> Vec<String>;
217
218    /// Encode into a complete NMEA 0183 sentence with checksum and `\r\n`.
219    fn to_sentence(&self, talker: &str) -> String {
220        let fields = self.encode();
221        let field_refs: Vec<&str> = fields.iter().map(|s| s.as_str()).collect();
222        crate::encode_frame('$', talker, Self::SENTENCE_TYPE, &field_refs)
223    }
224}
225
226/// Convert an NMEA `DDMM.MMMM` coordinate to decimal degrees.
227///
228/// NMEA sentences encode latitude as `DDMM.MMMM` (degrees + minutes) and
229/// longitude as `DDDMM.MMMM`. AIS and most application code use decimal degrees.
230/// The sign (N/S, E/W) is not part of `ddmm` — apply it after conversion.
231///
232/// # Example
233///
234/// ```
235/// use nmea_kit::nmea::ddmm_to_decimal;
236///
237/// // 4807.038 → 48°07.038′ → 48.1173°
238/// let lat = ddmm_to_decimal(4807.038);
239/// assert!((lat - 48.1173).abs() < 0.0001);
240/// ```
241pub fn ddmm_to_decimal(ddmm: f64) -> f64 {
242    let degrees = (ddmm / 100.0).floor();
243    let minutes = ddmm - degrees * 100.0;
244    degrees + minutes / 60.0
245}
246
247/// Convert decimal degrees to an NMEA `DDMM.MMMM` coordinate.
248///
249/// This is the inverse of [`ddmm_to_decimal`]. The sign is not encoded —
250/// strip it before calling and re-apply the N/S or E/W indicator separately.
251///
252/// # Example
253///
254/// ```
255/// use nmea_kit::nmea::decimal_to_ddmm;
256///
257/// // 48.1173° → 48°07.038′ → 4807.038
258/// let ddmm = decimal_to_ddmm(48.1173);
259/// assert!((ddmm - 4807.038).abs() < 0.001);
260/// ```
261pub fn decimal_to_ddmm(decimal: f64) -> f64 {
262    let degrees = decimal.floor();
263    let minutes = (decimal - degrees) * 60.0;
264    degrees * 100.0 + minutes
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn reader_char() {
273        let fields = &["T", "", "AB"];
274        let mut r = FieldReader::new(fields);
275        assert_eq!(r.char(), Some('T'));
276        assert_eq!(r.char(), None);
277        assert_eq!(r.char(), Some('A')); // takes first char
278    }
279
280    #[test]
281    fn reader_f32() {
282        let fields = &["270.0", "", "abc"];
283        let mut r = FieldReader::new(fields);
284        assert_eq!(r.f32(), Some(270.0));
285        assert_eq!(r.f32(), None);
286        assert_eq!(r.f32(), None); // invalid
287    }
288
289    #[test]
290    fn reader_past_end() {
291        let fields: &[&str] = &[];
292        let mut r = FieldReader::new(fields);
293        assert_eq!(r.f32(), None);
294        assert_eq!(r.char(), None);
295    }
296
297    #[test]
298    fn reader_skip() {
299        let fields = &["10.0", "T", "20.0"];
300        let mut r = FieldReader::new(fields);
301        assert_eq!(r.f32(), Some(10.0));
302        r.skip();
303        assert_eq!(r.f32(), Some(20.0));
304    }
305
306    #[test]
307    fn reader_string() {
308        let fields = &["DEST", ""];
309        let mut r = FieldReader::new(fields);
310        assert_eq!(r.string(), Some("DEST".to_string()));
311        assert_eq!(r.string(), None);
312    }
313
314    #[test]
315    fn writer_roundtrip() {
316        let mut w = FieldWriter::new();
317        w.f32(Some(270.0));
318        w.fixed('T');
319        w.f32(None);
320        w.fixed('M');
321        let fields = w.finish();
322        assert_eq!(fields, vec!["270", "T", "", "M"]);
323    }
324
325    #[test]
326    fn ddmm_to_decimal_lat() {
327        // 4807.038 → 48°07.038′ → 48.1173°
328        let result = ddmm_to_decimal(4807.038);
329        assert!((result - 48.1173).abs() < 0.0001);
330    }
331
332    #[test]
333    fn ddmm_to_decimal_lon() {
334        // 01131.000 → 11°31.000′ → 11.5167°
335        let result = ddmm_to_decimal(1131.0);
336        assert!((result - 11.5167).abs() < 0.0001);
337    }
338
339    #[test]
340    fn decimal_to_ddmm_lat() {
341        // 48.1173° → 4807.038
342        let result = decimal_to_ddmm(48.1173);
343        assert!((result - 4807.038).abs() < 0.001);
344    }
345
346    #[test]
347    fn decimal_to_ddmm_roundtrip() {
348        let original = 5132.5200_f64;
349        let roundtrip = decimal_to_ddmm(ddmm_to_decimal(original));
350        assert!((roundtrip - original).abs() < 0.0001);
351    }
352}