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#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn reader_char() {
232        let fields = &["T", "", "AB"];
233        let mut r = FieldReader::new(fields);
234        assert_eq!(r.char(), Some('T'));
235        assert_eq!(r.char(), None);
236        assert_eq!(r.char(), Some('A')); // takes first char
237    }
238
239    #[test]
240    fn reader_f32() {
241        let fields = &["270.0", "", "abc"];
242        let mut r = FieldReader::new(fields);
243        assert_eq!(r.f32(), Some(270.0));
244        assert_eq!(r.f32(), None);
245        assert_eq!(r.f32(), None); // invalid
246    }
247
248    #[test]
249    fn reader_past_end() {
250        let fields: &[&str] = &[];
251        let mut r = FieldReader::new(fields);
252        assert_eq!(r.f32(), None);
253        assert_eq!(r.char(), None);
254    }
255
256    #[test]
257    fn reader_skip() {
258        let fields = &["10.0", "T", "20.0"];
259        let mut r = FieldReader::new(fields);
260        assert_eq!(r.f32(), Some(10.0));
261        r.skip();
262        assert_eq!(r.f32(), Some(20.0));
263    }
264
265    #[test]
266    fn reader_string() {
267        let fields = &["DEST", ""];
268        let mut r = FieldReader::new(fields);
269        assert_eq!(r.string(), Some("DEST".to_string()));
270        assert_eq!(r.string(), None);
271    }
272
273    #[test]
274    fn writer_roundtrip() {
275        let mut w = FieldWriter::new();
276        w.f32(Some(270.0));
277        w.fixed('T');
278        w.f32(None);
279        w.fixed('M');
280        let fields = w.finish();
281        assert_eq!(fields, vec!["270", "T", "", "M"]);
282    }
283}