canboat 9.1.0

NMEA 2000 decoding, encoding and live-bus access: the CANboat PGN database as a library, plus the canboat CLI (convert / interface / server / tui).
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
461
462
463
464
465
466
467
468
469
470
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! Output formatters for `DecodedPgn`.
//!
//! Both formatters write to a `&mut dyn fmt::Write` — no I/O. The
//! caller decides whether that's stdout, a `String` buffer, or a
//! TCP socket.
//!
//! For v0, the formatters cover the canboat default outputs (text
//! and compact JSON). `-debug` byte/bit annotation, `-empty`,
//! `-nv`, and camelCase variants are option fields on the format
//! options structs that the formatters honor as they grow.

pub mod json;
pub mod text;

pub use json::{CamelCase, JsonOptions, write_json};
pub use text::{GeoFormat, TextOptions, write_text};

use crate::engine::format::timestamp::days_to_ymd;

/// Decimals for a scaled number with this resolution (canboat#969),
/// as canboat C's `decimalsForResolution`:
///
/// ```text
///   precision = 0
///   for r = resolution; 0 < r < 1.0; r *= 10:
///       precision++
///   if r is not a whole number: precision += 2
/// ```
///
/// A resolution that is a whole number of 10⁻ᵖ steps prints exactly with
/// p decimals: `0.01` → 2, `0.004` → 3, integers → 0. Any other one — a
/// binary fraction, a step divided by 60 or 3.6e6 by an SI conversion —
/// gets two more, so a value is off by under 1 % of a step instead of up
/// to half of one: 0.1 L/h in m³/s (2.78e-8) → 10.
pub(crate) fn precision_for(resolution: f64) -> usize {
    if !resolution.is_finite() || resolution <= 0.0 {
        return 0;
    }
    let mut p = 0usize;
    let mut r = resolution;
    while r > 0.0 && r < 1.0 {
        p += 1;
        r *= 10.0;
    }
    if (r - r.round()).abs() <= 1e-9 * r {
        p
    } else {
        p + 2
    }
}

/// Decimals for a TIME or DURATION's seconds: one per factor of ten in
/// its resolution, as canboat C's `fieldPrintTime` takes them from the
/// units per second. A time ignores a field's display precision.
pub(crate) fn time_precision_for(resolution: Option<f64>) -> usize {
    let resolution = resolution.unwrap_or(1.0);
    if !resolution.is_finite() || resolution <= 0.0 {
        return 0;
    }
    let mut p = 0usize;
    let mut r = resolution;
    while r > 0.0 && r < 1.0 {
        p += 1;
        r *= 10.0;
    }
    p
}

/// Effective precision for a decoded field: honors the load-time
/// override from canboat's unit fix-up when non-zero, otherwise
/// derives it from the resolution.
pub(crate) fn effective_precision(precision: u8, resolution: Option<f64>) -> usize {
    if precision > 0 {
        precision as usize
    } else {
        precision_for(resolution.unwrap_or(1.0))
    }
}

/// Format `v` as `{:.precision$}` without going through
/// `core::fmt::float::float_to_decimal_common_exact`, which the
/// profiler had as the single biggest leaf in `write_field_value`.
///
/// Scale + round + split-int-and-frac is the standard fast path for
/// fixed-precision output (the algorithm Ryu/lexical-write-float
/// would internally degrade to once you ask for a precision instead
/// of shortest-round-trip). The integer halves go through
/// `lexical-write-integer`, which beats `core::fmt::Display` for
/// `u64` by a wide margin and lets us write straight into a
/// stack-local byte buffer.
///
/// `min_width` adds left padding with spaces — needed by the LAT/LON
/// `%10.7f` path which produces ` 5.1815566` for short longitudes.
/// Pass `0` to disable.
pub(crate) fn write_fixed_float<W: std::fmt::Write>(
    w: &mut W,
    v: f64,
    precision: usize,
    min_width: usize,
) -> std::fmt::Result {
    // Fall back to core::fmt for NaN / inf and for values where
    // `v * 10^precision` would exceed the integer-exact range of f64
    // (2^53). That covers the AIS "Altitude unknown" sentinel
    // (~9.2e12) which canboat C formats via `%.*f` directly, and the
    // many-decimal fields (GPS almanac rates, resolution ~1e-11).
    const EXACT: f64 = 9_007_199_254_740_992.0; // 2^53
    if !v.is_finite() || v.abs() >= 1e12 || v.abs() * 10f64.powi(precision as i32) >= EXACT {
        return write!(
            w,
            "{:>width$.prec$}",
            v,
            width = min_width,
            prec = precision
        );
    }
    // Preserve the sign of the original value — `-0.0001` with
    // precision 1 rounds to integer 0 but `core::fmt` (and canboat C)
    // still emit it as `-0.0`. Use `is_sign_negative` to catch that
    // along with proper negatives.
    let neg = v.is_sign_negative();
    // Scaling by 10^precision can land exactly on .5 for a value that is
    // not really a tie: `5 * 0.0001` is 0.000500000000000000010408…, above
    // the tie, but multiplying by 1000 rounds the product to exactly 0.5 and
    // the information is gone. printf never scales — it rounds off the
    // double's own decimal expansion — so PGN 126208's `Air pressure offset`
    // came out 0.000 where canboat prints 0.001.
    //
    // Hand an exact .5 to core::fmt, which is correctly rounded from the
    // original value: a real tie (127489's 1.890625, a dyadic fraction)
    // still goes to even, and a near-tie goes the way its true value points.
    // Rare, so the fast path below keeps the common case.
    fn lands_on_a_tie(v: f64, precision: usize) -> bool {
        let scaled = v * 10f64.powi(precision as i32);
        scaled.fract().abs() == 0.5
    }
    if lands_on_a_tie(v, precision) {
        return write!(
            w,
            "{:>width$.prec$}",
            v,
            width = min_width,
            prec = precision
        );
    }
    if precision == 0 {
        // Whole-number path: integer fmt. Ties go to even, see below.
        let rounded = v.round_ties_even() as i64;
        let mut buf = itoa::Buffer::new();
        let s = buf.format(rounded.unsigned_abs());
        let signed_len = (if neg && rounded != 0 { 1 } else { 0 }) + s.len();
        for _ in 0..min_width.saturating_sub(signed_len) {
            w.write_char(' ')?;
        }
        if neg && rounded != 0 {
            w.write_char('-')?;
        }
        return w.write_str(s);
    }
    // Scale, round to integer, then emit integer + decimal point + zero-
    // padded fractional digits — no float formatter on the hot path.
    let scale = 10f64.powi(precision as i32);
    let scaled = v * scale;
    // Ties go to EVEN, not away from zero. canboat prints through printf,
    // which rounds under the current FP mode -- FE_TONEAREST, i.e. half to
    // even. `f64::round` rounds half away from zero, so an exact tie came out
    // one ulp high: 127489's Power factor is 30976/16384 = 1.890625 exactly,
    // scaling to 189062.5 at precision 5, and printed 1.89063 where canboat
    // prints 1.89062.
    let rounded = scaled.round_ties_even() as i128;
    let abs = rounded.unsigned_abs();
    let pow = 10u128.pow(precision as u32);
    let int_part = (abs / pow) as u64;
    let frac_part = (abs % pow) as u64;
    let mut int_buf = itoa::Buffer::new();
    let int_str = int_buf.format(int_part);
    let mut frac_buf = itoa::Buffer::new();
    let frac_str = frac_buf.format(frac_part);
    let total_len = (if neg { 1 } else { 0 }) + int_str.len() + 1 + precision;
    for _ in 0..min_width.saturating_sub(total_len) {
        w.write_char(' ')?;
    }
    if neg {
        w.write_char('-')?;
    }
    w.write_str(int_str)?;
    w.write_char('.')?;
    for _ in 0..precision.saturating_sub(frac_str.len()) {
        w.write_char('0')?;
    }
    w.write_str(frac_str)
}

/// C `printf("%g")` — how canboat prints FLOAT fields
/// (`fieldPrintFloat`, print.c).
///
/// Six significant digits: `%e` when the decimal exponent is below -4
/// or at least 6, `%f` otherwise, then trailing fractional zeros and a
/// bare `.` are stripped. C's exponent always carries a sign and at
/// least two digits, which Rust's `{:e}` does not.
///
/// This is not the same function as Rust's `{}`, which prints the
/// shortest string that round-trips. The two diverge exactly where a
/// FLOAT field is a widened `f32`: Garmin's `Heading to Steer` is
/// `2.7274` under `%g` and `2.7273988723754883` under `{}`.
///
/// Allocates, unlike the rest of this module — but only on the FLOAT
/// path, which a handful of PGNs use.
pub(crate) fn write_c_g<W: std::fmt::Write>(w: &mut W, v: f64) -> std::fmt::Result {
    const PRECISION: i32 = 6;

    if v.is_nan() {
        return w.write_str("nan");
    }
    if v.is_infinite() {
        return w.write_str(if v > 0.0 { "inf" } else { "-inf" });
    }

    // Take the exponent from the rounded `%e` form rather than from
    // `log10`, so a value that rounds up into the next decade (9.9999995
    // → 1e+01) picks the exponent it will actually be printed with.
    let sci = format!("{:.*e}", (PRECISION - 1) as usize, v);
    let (mantissa, exp_str) = sci.split_once('e').expect("{:e} always emits an 'e'");
    let exp: i32 = exp_str
        .parse()
        .expect("{:e} always emits an integer exponent");

    fn trim(s: &str) -> &str {
        match s.split_once('.') {
            Some(_) => s.trim_end_matches('0').trim_end_matches('.'),
            None => s,
        }
    }

    // Spelled as C's own condition rather than a range test, so it
    // reads against the standard's wording for %g.
    #[allow(clippy::manual_range_contains)]
    let scientific = exp < -4 || exp >= PRECISION;
    if scientific {
        w.write_str(trim(mantissa))?;
        write!(w, "e{}{:02}", if exp < 0 { '-' } else { '+' }, exp.abs())
    } else {
        let decimals = (PRECISION - 1 - exp).max(0) as usize;
        w.write_str(trim(&format!("{v:.decimals$}")))
    }
}

/// Format days-since-1970-01-01 as `YYYY.MM.DD` (canboat text style).
pub fn format_date(days: u16, w: &mut dyn std::fmt::Write) -> std::fmt::Result {
    let (y, m, d) = days_to_ymd(days as i64);
    write!(w, "{:04}.{:02}.{:02}", y, m, d)
}

/// A TIME / DURATION value read back as seconds, as leniently as
/// canboat ever wrote it: a number of seconds (`"300"`, `"-1.5"`), or a
/// clock `[-]HH:MM`, `[-]HH:MM:SS` or `[-]HH:MM:SS.ffff`.
pub fn parse_time(s: &str) -> Option<f64> {
    let s = s.trim();
    if let Ok(seconds) = s.parse::<f64>() {
        return seconds.is_finite().then_some(seconds);
    }
    // A negative duration ("-00:05:00.000") is negative as a whole.
    let (sign, clock) = match s.strip_prefix('-') {
        Some(rest) => (-1.0, rest),
        None => (1.0, s),
    };
    let part = |x: &str| {
        x.parse::<f64>()
            .ok()
            .filter(|v| v.is_finite() && !x.starts_with(['-', '+']))
    };
    let mut it = clock.split(':');
    let h = part(it.next()?)?;
    let m = part(it.next()?)?;
    let sec = match it.next() {
        Some(x) => part(x)?,
        None => 0.0,
    };
    if it.next().is_some() {
        return None;
    }
    let total = sign * (h * 3600.0 + m * 60.0 + sec);
    total.is_finite().then_some(total)
}

/// Format seconds-since-midnight as `HH:MM:SS[.fff]`. Fractional
/// digits follow `precision`. When `trim_zero_fraction` is set and
/// the fractional part is zero, the `.fff` suffix is omitted — this
/// matches canboat's text-mode `fieldPrintTime`, where the JSON path
/// always shows the fraction and the text path skips it when zero.
pub fn format_time(
    seconds: f64,
    precision: usize,
    trim_zero_fraction: bool,
    w: &mut dyn std::fmt::Write,
) -> std::fmt::Result {
    if !seconds.is_finite() {
        return w.write_str("00:00:00");
    }
    // Negative values render as DURATION-style negatives (canboat does
    // the same for DURATION_FIX*_MS-typed fields, e.g. a B&G key-value
    // Race Timer at "-00:05:00.000").
    let neg = seconds < 0.0;
    let abs = seconds.abs();
    let sign = if neg { "-" } else { "" };
    let whole = abs.trunc() as u64;
    let h = whole / 3600;
    let m = (whole / 60) % 60;
    let s = whole % 60;
    if precision == 0 {
        return write!(w, "{sign}{:02}:{:02}:{:02}", h, m, s);
    }
    let frac = (abs - whole as f64) * 10f64.powi(precision as i32);
    let frac_rounded = frac.round() as u64;
    if trim_zero_fraction && frac_rounded == 0 {
        write!(w, "{sign}{:02}:{:02}:{:02}", h, m, s)
    } else {
        write!(
            w,
            "{sign}{:02}:{:02}:{:02}.{:0width$}",
            h,
            m,
            s,
            frac_rounded,
            width = precision
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn precision_matches_canboat() {
        assert_eq!(precision_for(1.0), 0);
        assert_eq!(precision_for(0.1), 1);
        assert_eq!(precision_for(0.01), 2);
        assert_eq!(precision_for(0.001), 3);
        assert_eq!(precision_for(0.0001), 4);
        // Resolutions >= 1 round to 0 decimals.
        assert_eq!(precision_for(10.0), 0);
        // Edge: zero or negative.
        assert_eq!(precision_for(0.0), 0);
        assert_eq!(precision_for(-1.0), 0);
        // A whole number of 10^-p steps keeps p decimals.
        assert_eq!(precision_for(0.004), 3);
        assert_eq!(precision_for(0.05), 2);
        assert_eq!(precision_for(180.0), 0);
        // Any other resolution gets two more (canboat#969).
        assert_eq!(precision_for(0.03125), 4);
        assert_eq!(precision_for(0.25 / 60.0), 5);
        assert_eq!(precision_for(0.1 / 3.6e6), 10);
        // No cap: canboat C keeps counting, and so must we.
        assert_eq!(precision_for(2f64.powi(-38)), 14);
        assert_eq!(precision_for(2f64.powi(-38) * std::f64::consts::PI), 13);
    }

    #[test]
    fn date_round_trips_known_dates() {
        assert_eq!(days_to_ymd(0), (1970, 1, 1));
        assert_eq!(days_to_ymd(1), (1970, 1, 2));
        // 2022-09-10 → 19245 days since epoch.
        assert_eq!(days_to_ymd(19245), (2022, 9, 10));
        // Leap day 2024-02-29.
        assert_eq!(days_to_ymd(19782), (2024, 2, 29));
    }

    #[test]
    fn time_formats() {
        let mut out = String::new();
        format_time(3661.0, 0, false, &mut out).unwrap();
        assert_eq!(out, "01:01:01");
        let mut out = String::new();
        format_time(3661.5, 3, false, &mut out).unwrap();
        assert_eq!(out, "01:01:01.500");
    }

    #[test]
    fn many_decimals_match_printf() {
        // Precisions past 10 come from resolutions near 1e-11 (GPS almanac
        // rates); `printf("%.*f")` prints those exactly as written here.
        let fixed = |v: f64, p: usize| {
            let mut out = String::new();
            write_fixed_float(&mut out, v, p, 0).unwrap();
            out
        };
        assert_eq!(fixed(-3.1415926535e-7, 11), "-0.00000031416");
        assert_eq!(fixed(-1.0000076e-7, 12), "-0.000000100001");
        assert_eq!(fixed(123.456789012345, 12), "123.456789012345");
    }
}

#[cfg(test)]
mod c_g_tests {
    use super::write_c_g;

    fn g(v: f32) -> String {
        let mut s = String::new();
        write_c_g(&mut s, v as f64).unwrap();
        s
    }

    #[test]
    fn matches_c_printf_g() {
        // Expected strings produced by a C program printing `%g` of the
        // same `(double)` promotions, compiled and run on this platform.
        let cases: &[(f32, &str)] = &[
            (2.727_398_9, "2.7274"), // Garmin Heading to Steer
            (0.0, "0"),
            (-0.0, "-0"),
            (1.0, "1"),
            (10.0, "10"),
            (100_000.0, "100000"),  // last %f exponent
            (1_000_000.0, "1e+06"), // first %e exponent
            (1_234_567.0, "1.23457e+06"),
            (0.0001, "0.0001"), // last %f exponent going down
            (0.00001, "1e-05"), // first %e exponent going down
            (9.999_999, "10"),  // rounds up into the next decade
            (-core::f32::consts::PI, "-3.14159"),
            (123_456.0, "123456"),
            (0.5, "0.5"),
            (1e-10, "1e-10"),
            (1e20, "1e+20"),
            (65535.0, "65535"),
            (2.5e-5, "2.5e-05"),
            (999_999.5, "1e+06"),
            (1e6, "1e+06"),
            (0.000_123_456, "0.000123456"),
        ];
        for (v, want) in cases {
            assert_eq!(&g(*v), want, "%g of {v}");
        }
    }

    #[test]
    fn rounds_a_near_tie_the_way_printf_does() {
        use super::write_fixed_float;
        fn f(v: f64, p: usize) -> String {
            let mut s = String::new();
            write_fixed_float(&mut s, v, p, 0).unwrap();
            s
        }
        // 5 * 0.0001 is 0.000500000000000000010408…, just *above* the
        // tie, so printf rounds it up. Scaling by 1000 collapses the
        // product onto exactly 0.5 and loses that. PGN 126208's
        // `Air pressure offset` in samples/scx20-setting-tool-offsets.raw.
        assert_eq!(f(5.0 * 0.0001, 3), "0.001");
        // A genuine tie — 30976/16384 is exactly 1.890625 — still goes
        // to even, as printf does under FE_TONEAREST. PGN 127489.
        assert_eq!(f(30976.0 / 16384.0, 5), "1.89062");
        // …and the even-side tie rounds up to the even digit.
        assert_eq!(f(0.125, 2), "0.12");
        assert_eq!(f(0.375, 2), "0.38");
    }

    #[test]
    fn handles_non_finite() {
        let mut s = String::new();
        write_c_g(&mut s, f64::NAN).unwrap();
        assert_eq!(s, "nan");
        s.clear();
        write_c_g(&mut s, f64::INFINITY).unwrap();
        assert_eq!(s, "inf");
        s.clear();
        write_c_g(&mut s, f64::NEG_INFINITY).unwrap();
        assert_eq!(s, "-inf");
    }
}