nmea0183-parser 0.3.2

A zero-allocation NMEA 0183 parser that separates message framing from content parsing
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
use nom::{
    AsBytes, AsChar, Compare, Input, Offset, ParseTo, Parser,
    character::complete::{anychar, char},
    combinator::opt,
    error::ParseError,
    multi::many0,
    sequence::preceded,
};

use crate::{Error, IResult};

/// Trait for parsing types from NMEA 0183 sentence fields.
///
/// The `NmeaParse` trait provides a generic interface for parsing values from NMEA 0183-style
/// content, supporting both primitive and composite types. Implementations are provided for
/// primitive types, `Option<T>`, `Vec<T>`, and more types, and you can implement this trait
/// for your own types to enable custom parsing logic.
///
/// # Examples
///
/// ```rust
/// use nmea0183_parser::{NmeaParse, IResult};
///
/// // Parsing a single integer field
/// let input = "42";
/// let result: IResult<_, _> = u8::parse(input);
/// assert_eq!(result, Ok(("", 42)));
///
/// // Parsing an optional field (empty string yields None)
/// let input = "";
/// let result: IResult<_, _> = Option::<u8>::parse(input);
/// assert_eq!(result, Ok(("", None)));
///
/// // Parsing a comma-separated list of integers
/// let input = "1,2,3";
/// let result: IResult<_, _> = Vec::<u8>::parse(input);
/// assert_eq!(result, Ok(("", vec![1, 2, 3])));
/// ```
///
/// # Implementing for Custom Types
///
/// To support custom types, implement `NmeaParse` and define how your type should be parsed from
/// the input. You can compose existing parsers for fields within your type.
///
/// ```rust
/// use nmea0183_parser::{IResult, NmeaParse};
/// use nom::{AsChar, Input, Parser, character::complete::char, error::ParseError};
///
/// struct MyData {
///     a: u8,
///     b: Option<u32>,
/// }
///
/// impl<I, E> NmeaParse<I, E> for MyData
/// where
///     I: Input,
///     <I as Input>::Item: AsChar,
///     E: ParseError<I>,
/// {
///     fn parse(i: I) -> IResult<I, Self, E> {
///         let (i, a) = u8::parse(i)?;
///         let (i, _) = char(',').parse(i)?;
///         let (i, b) = Option::<u32>::parse(i)?;
///
///         Ok((i, MyData { a, b }))
///     }
/// }
/// ```
///
/// This trait provides another method `parse_preceded` that allows you to define how to
/// parse a value that is preceded by a separator, such as a comma in NMEA sentences.
/// This is useful for parsing fields that are separated by specific characters.
///
/// When possible, prefer using `parse_preceded` to handle separators, as it usually provides
/// a cleaner and more efficient way (especially for lists or optional fields) to parse values
/// that are separated by a specific separator.
///
/// The above example could also be implemented using `parse_preceded` to handle the separator:
///
/// ```rust
/// use nmea0183_parser::{IResult, NmeaParse};
/// use nom::{AsChar, Input, Parser, character::complete::char, error::ParseError};
///
/// struct MyData {
///     a: u8,
///     b: Option<u32>,
/// }
///
/// impl<I, E> NmeaParse<I, E> for MyData
/// where
///     I: Input,
///     <I as Input>::Item: AsChar,
///     E: ParseError<I>,
/// {
///     fn parse(i: I) -> IResult<I, Self, E> {
///         let (i, a) = u8::parse(i)?;
///         let (i, b) = Option::<u32>::parse_preceded(char(',')).parse(i)?;
///
///         Ok((i, MyData { a, b }))
///     }
/// }
/// ```
pub trait NmeaParse<I, E = nom::error::Error<I>>
where
    I: Input,
    E: ParseError<I>,
    Self: Sized,
{
    /// Parses the input and returns a result.
    ///
    /// # Arguments
    ///
    /// * `input` - The input to parse into `Self`.
    ///
    /// # Returns
    ///
    /// Returns an [`IResult`] containing:
    /// - On success: A tuple of `(remaining_input, parsed_value)`, where `remaining_input`
    ///   is the unparsed portion of the input and `parsed_value` is the successfully parsed
    ///   instance of `Self`.
    /// - On failure: An [`Error`] indicating the parsing error.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(feature = "nmea-content")] {
    /// use nmea0183_parser::{IResult, NmeaParse, nmea_content::NmeaSentence};
    ///
    /// // Parse complete sentence content (including talker ID and sentence type)
    /// let content = "GPGGA,123456.00,4916.29,N,12311.76,W,1,08,0.9,545.4,M,46.9,M,,";
    /// let result: IResult<_, _> = NmeaSentence::parse(content);
    /// assert!(result.is_ok());
    /// # }
    /// ```
    fn parse(i: I) -> IResult<I, Self, E>;

    /// Returns a parser that first consumes a separator, then parses the value.
    /// This is useful for parsing fields that are separated by a specific character,
    /// such as a comma in NMEA sentences.
    ///
    /// # Arguments
    ///
    /// * `separator` - A parser that matches the separator character(s) before the value.
    ///
    /// # Returns
    ///
    /// Returns a parser that consumes the separator and then parses the value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmea0183_parser::{NmeaParse, IResult};
    /// use nom::{Parser, character::complete::char};
    ///
    /// let result: IResult<_, _> = u8::parse_preceded(char(',')).parse(",42");
    /// assert_eq!(result, Ok(("", 42)));
    /// ```
    fn parse_preceded<S>(separator: S) -> impl Parser<I, Output = Self, Error = Error<I, E>>
    where
        S: Parser<I, Error = Error<I, E>>,
    {
        preceded(separator, Self::parse)
    }
}

macro_rules! impl_uints_type {
    ($($t:tt),*) => ($(
        impl<I, E> NmeaParse<I, E> for $t
        where
            I: Input,
            <I as Input>::Item: AsChar,
            E: ParseError<I>,
        {
            fn parse(i: I) -> IResult<I, Self, E> {
                nom::character::complete::$t.parse(i)
            }
        }
    )*)
}

macro_rules! impl_ints_type {
    ($($t:tt),*) => ($(
        impl<I, E> NmeaParse<I, E> for $t
        where
            I: Input + for<'a> Compare<&'a [u8]>,
            <I as Input>::Item: AsChar,
            E: ParseError<I>,
        {
            fn parse(i: I) -> IResult<I, Self, E> {
                nom::character::complete::$t.parse(i)
            }
        }

    )*)
}

impl_uints_type!(u8, u16, u32, u64, u128, usize);
impl_ints_type!(i8, i16, i32, i64, i128, isize);

macro_rules! impl_float_type {
    ($($t:ty, $p:ident),*) => ($(
        impl<I, E> NmeaParse<I, E> for $t
        where
            I: Input + Offset + ParseTo<$t> + AsBytes,
            I: Compare<&'static str> + for<'a> Compare<&'a [u8]>,
            <I as Input>::Item: AsChar,
            <I as Input>::Iter: Clone,
            E: ParseError<I>,
        {
            fn parse(i: I) -> IResult<I, Self, E> {
                nom::number::complete::$p.parse(i)
            }
        }
    )*)
}

impl_float_type!(f32, float, f64, double);

impl<I, E> NmeaParse<I, E> for char
where
    I: Input,
    <I as Input>::Item: AsChar,
    E: ParseError<I>,
{
    fn parse(i: I) -> IResult<I, Self, E> {
        anychar.parse(i)
    }
}

impl<T, I, E> NmeaParse<I, E> for Option<T>
where
    T: NmeaParse<I, E>,
    I: Input,
    E: ParseError<I>,
{
    fn parse(i: I) -> IResult<I, Self, E> {
        opt(T::parse).parse(i)
    }

    fn parse_preceded<S>(separator: S) -> impl Parser<I, Output = Self, Error = Error<I, E>>
    where
        S: Parser<I, Error = Error<I, E>>,
    {
        let mut separator = separator;
        move |i: I| {
            let input = i.clone();
            let (i, _) = separator.parse(i)?;
            match T::parse.parse(i.clone()) {
                Ok((i, value)) => Ok((i, Some(value))),
                Err(_) => {
                    if let Ok((_, _)) = separator.parse(i.clone()) {
                        // Input was ",," → return (",", None)
                        Ok((i, None))
                    } else if i.input_len() == 0 {
                        // Input was "," → return ("", None)
                        Ok((i, None))
                    } else {
                        Err(nom::Err::Error(nom::error::make_error(
                            input,
                            nom::error::ErrorKind::Verify,
                        )))
                    }
                }
            }
        }
    }
}

impl<T, I, E, const N: usize> NmeaParse<I, E> for [T; N]
where
    T: NmeaParse<I, E> + Default + Copy,
    I: Input,
    <I as Input>::Item: AsChar,
    E: ParseError<I>,
{
    fn parse(i: I) -> IResult<I, Self, E> {
        let mut elems = [T::default(); N];
        let mut i = i;

        match T::parse(i.clone()) {
            Ok((i1, first)) => {
                elems[0] = first;
                i = i1;
            }
            Err(nom::Err::Error(_)) => {
                return Err(nom::Err::Error(nom::error::make_error(
                    i,
                    nom::error::ErrorKind::Count,
                )));
            }
            Err(nom::Err::Failure(e)) => return Err(nom::Err::Failure(e)),
            Err(nom::Err::Incomplete(e)) => return Err(nom::Err::Incomplete(e)),
        }

        for elem in &mut elems[1..] {
            match preceded(char(','), T::parse).parse(i.clone()) {
                Ok((i1, next)) => {
                    *elem = next;
                    i = i1;
                }
                Err(nom::Err::Error(_)) => {
                    return Err(nom::Err::Error(nom::error::make_error(
                        i,
                        nom::error::ErrorKind::Count,
                    )));
                }
                Err(e) => return Err(e),
            };
        }

        Ok((i, elems))
    }

    fn parse_preceded<S>(separator: S) -> impl Parser<I, Output = Self, Error = Error<I, E>>
    where
        S: Parser<I, Error = Error<I, E>>,
    {
        let mut parser = T::parse_preceded(separator);
        move |i: I| {
            let mut i = i;
            let mut elems = [T::default(); N];

            for elem in &mut elems {
                match parser.parse(i.clone()) {
                    Ok((i1, next)) => {
                        *elem = next;
                        i = i1;
                    }
                    Err(nom::Err::Error(_)) => {
                        return Err(nom::Err::Error(nom::error::make_error(
                            i,
                            nom::error::ErrorKind::Count,
                        )));
                    }
                    Err(e) => return Err(e),
                };
            }

            Ok((i, elems))
        }
    }
}

impl<T, I, E> NmeaParse<I, E> for Vec<T>
where
    T: NmeaParse<I, E>,
    I: Clone + Input,
    <I as Input>::Item: AsChar,
    E: ParseError<I>,
{
    fn parse(i: I) -> IResult<I, Self, E> {
        let mut elems = Vec::with_capacity(4);
        let mut i = i;

        match T::parse(i.clone()) {
            Ok((i1, first)) => {
                // infinite loop check: the parser must always consume
                if i1.input_len() == i.input_len() {
                    return Err(nom::Err::Error(nom::error::make_error(
                        i,
                        nom::error::ErrorKind::Many0,
                    )));
                }

                elems.push(first);
                i = i1;
            }
            Err(nom::Err::Error(_)) => {
                return Ok((i, elems));
            }
            Err(e) => return Err(e),
        }

        loop {
            let len = i.input_len();
            match T::parse_preceded(char(',')).parse(i.clone()) {
                Ok((i1, next)) => {
                    // infinite loop check: the parser must always consume
                    if i1.input_len() == len {
                        return Err(nom::Err::Error(nom::error::make_error(
                            i,
                            nom::error::ErrorKind::Many0,
                        )));
                    }

                    elems.push(next);
                    i = i1;
                }
                Err(nom::Err::Error(_)) => return Ok((i, elems)),
                Err(e) => return Err(e),
            };
        }
    }

    fn parse_preceded<S>(separator: S) -> impl Parser<I, Output = Self, Error = Error<I, E>>
    where
        S: Parser<I, Error = Error<I, E>>,
    {
        many0(<T>::parse_preceded(separator))
    }
}

#[cfg(test)]
mod tests {
    use crate::{IResult, NmeaParse};
    use nom::{Parser, character::complete::char};

    #[test]
    fn test_parse_vec() {
        let input = "1,2,,4";
        let expected: Vec<Option<u8>> = vec![Some(1), Some(2), None, Some(4)];
        let result: IResult<_, _> = Vec::<Option<u8>>::parse(input);
        assert_eq!(result, Ok(("", expected)));

        let input = ",1,2,,4";
        let expected: Vec<Option<u8>> = vec![Some(1), Some(2), None, Some(4)];
        let result: IResult<_, _> = Vec::<Option<u8>>::parse_preceded(char(',')).parse(input);
        assert_eq!(result, Ok(("", expected)));
    }
}