Skip to main content

serial_mcp/framing/
config.rs

1//! Framing and parser configuration types, defaults, and protocol presets.
2//!
3//! RX framing configuration (`RxFramingConfig`/`RxFramingMode`/`LineEnding`),
4//! TX framing configuration (`TxFramingConfig`/`TxFramingMode`/`TxLineEnding`),
5//! parser configuration (`ParserConfig`/`ParserType`), the shared
6//! `Endianness` type, and the `ProtocolPreset` expansion functions.
7
8use crate::match_config::PatternEncoding;
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12// ---- RX framing configuration ----------------------------------------------
13
14/// RX framing configuration applied by `read`, the `transact` read half, and `capture_boot`.
15/// Specifies how to split the byte stream into frames and optionally parse
16/// each frame's content.
17///
18/// The mode fields are flattened into the config struct so the JSON shape is:
19/// `{"type": "line", "ending": "auto"}` rather than
20/// `{"mode": {"type": "line"}}`.
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
22pub struct RxFramingConfig {
23    /// Frame boundary detection mode. Flattened: its `type` discriminator and
24    /// variant fields appear at the top level of the `rx_framing` object.
25    #[serde(flatten)]
26    pub mode: RxFramingMode,
27    /// Maximum number of frames to collect before stopping (read only).
28    /// When set, the read stops after collecting this many frames regardless
29    /// of timeout. Default: no limit.
30    #[serde(default)]
31    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
32    pub max_frames: Option<usize>,
33    /// Include terminators/delimiters in the frame `data` field.
34    /// Default: false (terminators are stripped).
35    #[serde(default)]
36    pub include_terminators: bool,
37    /// Skip frames whose data is empty or whitespace-only (ASCII whitespace).
38    /// Default: false. When true, empty/whitespace-only frames are not emitted
39    /// and do not increment the frame index. Applies to all framing modes.
40    /// The `ndjson` preset sets this true (NDJSON spec: skip blank lines).
41    #[serde(default)]
42    pub skip_empty: bool,
43}
44
45impl Default for RxFramingConfig {
46    fn default() -> Self {
47        Self {
48            mode: RxFramingMode::Line {
49                ending: LineEnding::Auto,
50            },
51            max_frames: None,
52            include_terminators: false,
53            skip_empty: false,
54        }
55    }
56}
57
58/// How frame boundaries are detected in the byte stream.
59/// Flattened into [`RxFramingConfig`] via `#[serde(flatten)]`.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
61#[serde(rename_all = "snake_case", tag = "type")]
62pub enum RxFramingMode {
63    /// Split on line endings. Supports `auto` (LF or CRLF), `lf`, `cr`, `crlf`.
64    #[serde(rename_all = "snake_case")]
65    Line {
66        /// Line ending style. Default: `auto` (recognizes LF and CRLF, strips
67        /// preceding `\r` when splitting on `\n`).
68        #[serde(default)]
69        ending: LineEnding,
70    },
71    /// Split on a user-supplied byte delimiter sequence.
72    #[serde(rename_all = "snake_case")]
73    Delimiter {
74        /// The delimiter as a string (decoded per `delimiter_encoding`).
75        delimiter: String,
76        /// How to decode the delimiter string into bytes.
77        #[serde(default = "default_encoding")]
78        delimiter_encoding: PatternEncoding,
79    },
80    /// Split based on a length prefix field at the start of each frame.
81    #[serde(rename_all = "snake_case")]
82    LengthPrefixed {
83        /// Size of the length prefix field in bytes: 1, 2, or 4.
84        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
85        prefix_size: u8,
86        /// Byte order of the length prefix.
87        #[serde(default)]
88        endianness: Endianness,
89        /// Optional: reading starts at an offset from the beginning of the stream.
90        /// When Some(N), the first N bytes are skipped before reading the first
91        /// length prefix.
92        #[serde(default)]
93        #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
94        initial_offset: Option<usize>,
95    },
96    /// Split based on start and end marker byte sequences.
97    /// `start` is a list of marker strings; RX matches ANY of them
98    /// (finds the earliest one). TX uses `start[0]`.
99    #[serde(rename_all = "snake_case")]
100    StartEnd {
101        /// Start marker(s) (decoded per `marker_encoding`).
102        /// RX matches any marker in the list (earliest match wins).
103        /// TX uses the first marker (`start[0]`).
104        start: Vec<String>,
105        /// End marker (decoded per `marker_encoding`).
106        end: String,
107        /// How to decode the marker strings into bytes.
108        #[serde(default = "default_encoding")]
109        marker_encoding: PatternEncoding,
110        /// Include the markers in frame data. Default: false.
111        #[serde(default)]
112        include_markers: bool,
113    },
114    /// SLIP (RFC 1055) framing. Byte-stuffed payloads between END (0xC0) markers.
115    #[serde(rename_all = "snake_case")]
116    Slip,
117    /// COBS (Consistent Overhead Byte Stuffing) framing. Byte-stuffed payloads
118    /// delimited by 0x00 (plain COBS, Cheshire/Baker). The delimiter never
119    /// appears inside an encoded block. The PPP-COBS draft variant (0x7E) is
120    /// not supported.
121    #[serde(rename_all = "snake_case")]
122    Cobs,
123}
124
125/// Line ending style for RX line framing.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
127#[serde(rename_all = "snake_case")]
128pub enum LineEnding {
129    /// Adaptive: starts as LF/CRLF (splits on `\n`, strips preceding `\r`).
130    /// When a bare `\r` is detected (no `\n` follows in the same chunk), the
131    /// decoder enters a pending state. If the next received byte is `\n`, the
132    /// `\r\n` is treated as CRLF and decoding continues in LF/CRLF mode. If
133    /// the next byte is anything else (including end-of-stream), the `\r` is
134    /// confirmed as a bare CR line ending, the pending line is emitted, and
135    /// the decoder promotes to CR-split mode for the remainder of the call.
136    /// Promotion is per-call (resets on the next read).
137    #[default]
138    Auto,
139    /// Split on `\n` only. Do NOT strip a preceding `\r`.
140    Lf,
141    /// Split on bare `\r` only.
142    Cr,
143    /// Split on exact `\r\n` only.
144    Crlf,
145}
146
147fn default_encoding() -> PatternEncoding {
148    PatternEncoding::Utf8
149}
150
151// ---- Protocol presets --------------------------------------------------------
152
153/// Built-in protocol preset. A named bundle of framing/parser primitives
154/// that a single `protocol` field expands into on `write`, `read`, `transact`, and `capture_boot`.
155#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
156#[serde(rename_all = "snake_case", tag = "type")]
157pub enum ProtocolPreset {
158    /// AT-command modem protocol. TX appends `\r`, RX splits on line
159    /// endings (auto), RX frames are parsed as AT command responses/URCs.
160    AtCommand,
161    /// SLIP (RFC 1055) byte-stuffed framing, raw payload (no parser).
162    Slip,
163    /// One JSON value per line (line framing + JSON-lines parser).
164    JsonLines,
165    /// COBS (Consistent Overhead Byte Stuffing, plain 0x00-delimited) framing,
166    /// raw payload (no parser).
167    Cobs,
168    /// NDJSON (newline-delimited JSON). Line framing (`auto` RX, `lf` TX) +
169    /// JSON-lines parser, skipping empty/whitespace-only lines per the NDJSON
170    /// spec. Differs from `json_lines` only in `skip_empty`.
171    Ndjson,
172    /// NMEA-0183 marine sentence protocol. StartEnd framing (start markers
173    /// $ / !, end \r\n) + Nmea parser with checksum validation.
174    Nmea0183,
175    /// Modbus ASCII mode. StartEnd framing (: start, \r\n end) + ModbusAscii
176    /// parser with LRC validation.
177    ModbusAscii,
178}
179
180/// The TX framing implied by a protocol preset.
181pub fn preset_tx_framing(p: ProtocolPreset) -> TxFramingConfig {
182    match p {
183        ProtocolPreset::AtCommand => TxFramingConfig {
184            mode: TxFramingMode::Line {
185                ending: TxLineEnding::Cr,
186            },
187        },
188        ProtocolPreset::Slip => TxFramingConfig {
189            mode: TxFramingMode::Slip,
190        },
191        ProtocolPreset::JsonLines | ProtocolPreset::Ndjson => TxFramingConfig {
192            mode: TxFramingMode::Line {
193                ending: TxLineEnding::Lf,
194            },
195        },
196        ProtocolPreset::Cobs => TxFramingConfig {
197            mode: TxFramingMode::Cobs,
198        },
199        ProtocolPreset::Nmea0183 => TxFramingConfig {
200            mode: TxFramingMode::Nmea,
201        },
202        ProtocolPreset::ModbusAscii => TxFramingConfig {
203            mode: TxFramingMode::StartEnd {
204                start: vec![":".into()],
205                end: "\r\n".into(),
206                marker_encoding: PatternEncoding::Utf8,
207            },
208        },
209    }
210}
211
212/// The RX framing implied by a protocol preset.
213pub fn preset_rx_framing(p: ProtocolPreset) -> RxFramingConfig {
214    let (mode, skip_empty) = match p {
215        ProtocolPreset::AtCommand | ProtocolPreset::JsonLines => (
216            RxFramingMode::Line {
217                ending: LineEnding::Auto,
218            },
219            false,
220        ),
221        ProtocolPreset::Slip => (RxFramingMode::Slip, false),
222        ProtocolPreset::Cobs => (RxFramingMode::Cobs, false),
223        ProtocolPreset::Ndjson => (
224            RxFramingMode::Line {
225                ending: LineEnding::Auto,
226            },
227            true,
228        ),
229        ProtocolPreset::Nmea0183 => (
230            RxFramingMode::StartEnd {
231                start: vec!["$".into(), "!".into()],
232                end: "\r\n".into(),
233                marker_encoding: PatternEncoding::Utf8,
234                include_markers: false,
235            },
236            false,
237        ),
238        ProtocolPreset::ModbusAscii => (
239            RxFramingMode::StartEnd {
240                start: vec![":".into()],
241                end: "\r\n".into(),
242                marker_encoding: PatternEncoding::Utf8,
243                include_markers: false,
244            },
245            false,
246        ),
247    };
248    RxFramingConfig {
249        mode,
250        max_frames: None,
251        include_terminators: false,
252        skip_empty,
253    }
254}
255
256/// The RX parser implied by a protocol preset.
257pub fn preset_rx_parser(p: ProtocolPreset) -> ParserConfig {
258    let (parser_type, validate) = match p {
259        ProtocolPreset::AtCommand => (ParserType::AtCommand, false),
260        ProtocolPreset::Slip | ProtocolPreset::Cobs => (ParserType::Raw, false),
261        ProtocolPreset::JsonLines | ProtocolPreset::Ndjson => (ParserType::JsonLines, false),
262        ProtocolPreset::Nmea0183 => (ParserType::Nmea, true),
263        ProtocolPreset::ModbusAscii => (ParserType::ModbusAscii, true),
264    };
265    ParserConfig {
266        parser_type,
267        custom_prompt: None,
268        validate,
269    }
270}
271
272// ---- TX framing configuration -----------------------------------------------
273
274/// TX framing configuration for `write`.
275/// Mirrors the RX modes but directionally appropriate.
276#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
277pub struct TxFramingConfig {
278    /// TX frame boundary mode. Flattened: its `type` discriminator and
279    /// variant fields appear at the top level of the `tx_framing` object.
280    #[serde(flatten)]
281    pub mode: TxFramingMode,
282}
283
284/// How TX frames are constructed around a payload.
285/// Flattened into [`TxFramingConfig`] via `#[serde(flatten)]`.
286#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
287#[serde(rename_all = "snake_case", tag = "type")]
288pub enum TxFramingMode {
289    /// Append a line terminator. No `auto` — agents must be explicit.
290    #[serde(rename_all = "snake_case")]
291    Line {
292        /// Line ending to append: `lf`, `cr`, or `crlf`.
293        ending: TxLineEnding,
294    },
295    /// Append a delimiter byte sequence after the payload.
296    #[serde(rename_all = "snake_case")]
297    Delimiter {
298        /// The delimiter as a string (decoded per `delimiter_encoding`).
299        delimiter: String,
300        /// How to decode the delimiter string into bytes.
301        #[serde(default = "default_encoding")]
302        delimiter_encoding: PatternEncoding,
303    },
304    /// Prepend a length prefix encoding the payload length, then the payload.
305    #[serde(rename_all = "snake_case")]
306    LengthPrefixed {
307        /// Size of the length prefix field in bytes: 1, 2, or 4.
308        #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
309        prefix_size: u8,
310        /// Byte order of the length prefix.
311        #[serde(default)]
312        endianness: Endianness,
313    },
314    /// Write start marker, payload, end marker.
315    #[serde(rename_all = "snake_case")]
316    StartEnd {
317        /// Start marker(s) (decoded per `marker_encoding`).
318        /// TX uses the first marker (`start[0]`).
319        start: Vec<String>,
320        /// End marker (decoded per `marker_encoding`).
321        end: String,
322        /// How to decode the marker strings into bytes.
323        #[serde(default = "default_encoding")]
324        marker_encoding: PatternEncoding,
325    },
326    /// SLIP (RFC 1055) framing. Encodes as `END [stuffed payload] END`.
327    #[serde(rename_all = "snake_case")]
328    Slip,
329    /// COBS (Consistent Overhead Byte Stuffing) framing. Byte-stuffed payload
330    /// followed by 0x00 delimiter (plain COBS). The delimiter never appears
331    /// inside an encoded block. The PPP-COBS draft variant (0x7E) is not
332    /// supported.
333    #[serde(rename_all = "snake_case")]
334    Cobs,
335    /// NMEA-0183 sentence framing: `$<payload>*XX\r\n` with the `*XX` XOR
336    /// checksum auto-appended over the payload bytes. Used by the `nmea0183`
337    /// preset TX path. If the payload already ends in `*HH` (two hex chars
338    /// after a `*`), the existing checksum is validated and a mismatch
339    /// errors (no double-append). If the payload already starts with `$` or
340    /// `!`, that leading char is used (AIS `!` sentences); otherwise `$` is
341    /// prepended.
342    #[serde(rename_all = "snake_case")]
343    Nmea,
344}
345
346/// Line ending for TX framing. No `auto` — agents must pick one.
347#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
348#[serde(rename_all = "snake_case")]
349pub enum TxLineEnding {
350    /// Append `\n` (LF).
351    Lf,
352    /// Append `\r` (CR).
353    Cr,
354    /// Append `\r\n` (CRLF).
355    Crlf,
356}
357
358// ---- Shared types -----------------------------------------------------------
359
360/// Byte order for length-prefixed framing.
361#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
362#[serde(rename_all = "snake_case")]
363pub enum Endianness {
364    #[default]
365    Big,
366    Little,
367}
368
369/// Parser configuration — what to do with each frame's content.
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
371pub struct ParserConfig {
372    /// Which parser to use.
373    #[serde(rename = "type")]
374    pub parser_type: ParserType,
375    /// Optional custom prompt pattern for shell prompt parser.
376    /// Accepts a regex pattern as a string.
377    #[serde(default)]
378    pub custom_prompt: Option<String>,
379    /// Whether to enforce a protocol checksum when present. Default: false.
380    /// When true, a protocol parser that defines a checksum (currently NMEA's
381    /// *XX XOR, Modbus ASCII LRC) drops mismatched frames instead of emitting
382    /// them. The dropped frame is counted in `PushOutcome.frames_dropped` and
383    /// does NOT halt the read (stream-fatal errors like SLIP
384    /// malformed escapes still stop the decode). When false, the frame is
385    /// emitted with `checksum_valid: Some(false)` (no-op for the caller).
386    /// A sentence/message WITHOUT a checksum is accepted regardless.
387    #[serde(default)]
388    pub validate: bool,
389}
390
391/// Supported parser types.
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
393#[serde(rename_all = "snake_case")]
394pub enum ParserType {
395    /// Parse AT command responses and URCs.
396    AtCommand,
397    /// Parse each frame as a JSON object.
398    JsonLines,
399    /// Detect shell prompt patterns.
400    ShellPrompt,
401    /// No parsing — frames are returned as raw data.
402    Raw,
403    /// Parse NMEA-0183 sentences: talker ID + sentence type + comma fields,
404    /// with optional *XX XOR checksum validation.
405    Nmea,
406    /// Parse Modbus ASCII frames: hex-decode the body, validate the LRC,
407    /// expose address + function code + data bytes.
408    ModbusAscii,
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414
415    // ── Line ending default: `auto` when `ending` omitted ────────────────
416
417    #[test]
418    fn line_ending_default_is_auto() {
419        // When Line is constructed without `ending`, it should default to Auto.
420        let val = serde_json::json!({"type": "line"});
421        let mode: RxFramingMode = serde_json::from_value(val).unwrap();
422        assert!(matches!(
423            mode,
424            RxFramingMode::Line {
425                ending: LineEnding::Auto
426            }
427        ));
428    }
429
430    // ── Protocol preset tests (table-driven) ────────────────────────────────
431
432    /// Assert that a ProtocolPreset variant round-trips through the tagged-object
433    /// JSON shape `{"type": "<variant_str>"}` and rejects the bare-string form.
434    fn assert_preset_roundtrip(variant_str: &str, expected: ProtocolPreset) {
435        let val = serde_json::json!({ "type": variant_str });
436        let p: ProtocolPreset = serde_json::from_value(val.clone()).unwrap();
437        assert_eq!(p, expected);
438        assert_eq!(serde_json::to_value(p).unwrap(), val);
439        assert!(
440            serde_json::from_value::<ProtocolPreset>(serde_json::json!(variant_str)).is_err(),
441            "bare string form {variant_str:?} must be rejected (tagged-object shape required)"
442        );
443    }
444
445    /// One row per protocol preset: expected framing/parser expansions + roundtrip label.
446    struct PresetTestRow {
447        preset: ProtocolPreset,
448        wire_name: &'static str,
449        expected_tx: TxFramingConfig,
450        expected_rx: RxFramingConfig,
451        expected_parser: ParserConfig,
452        /// `None` = run the equivalence check. `Some(reason)` = skip (documented
453        /// exemption for presets whose expansion cannot be expressed as a single
454        /// bare framing/parser config).
455        equivalence_skip: Option<&'static str>,
456    }
457
458    fn preset_test_table() -> Vec<PresetTestRow> {
459        vec![
460            PresetTestRow {
461                preset: ProtocolPreset::AtCommand,
462                wire_name: "at_command",
463                expected_tx: TxFramingConfig {
464                    mode: TxFramingMode::Line {
465                        ending: TxLineEnding::Cr,
466                    },
467                },
468                expected_rx: RxFramingConfig {
469                    mode: RxFramingMode::Line {
470                        ending: LineEnding::Auto,
471                    },
472                    max_frames: None,
473                    include_terminators: false,
474                    skip_empty: false,
475                },
476                expected_parser: ParserConfig {
477                    parser_type: ParserType::AtCommand,
478                    custom_prompt: None,
479                    validate: false,
480                },
481                equivalence_skip: None,
482            },
483            PresetTestRow {
484                preset: ProtocolPreset::Slip,
485                wire_name: "slip",
486                expected_tx: TxFramingConfig {
487                    mode: TxFramingMode::Slip,
488                },
489                expected_rx: RxFramingConfig {
490                    mode: RxFramingMode::Slip,
491                    max_frames: None,
492                    include_terminators: false,
493                    skip_empty: false,
494                },
495                expected_parser: ParserConfig {
496                    parser_type: ParserType::Raw,
497                    custom_prompt: None,
498                    validate: false,
499                },
500                equivalence_skip: None,
501            },
502            PresetTestRow {
503                preset: ProtocolPreset::JsonLines,
504                wire_name: "json_lines",
505                expected_tx: TxFramingConfig {
506                    mode: TxFramingMode::Line {
507                        ending: TxLineEnding::Lf,
508                    },
509                },
510                expected_rx: RxFramingConfig {
511                    mode: RxFramingMode::Line {
512                        ending: LineEnding::Auto,
513                    },
514                    max_frames: None,
515                    include_terminators: false,
516                    skip_empty: false,
517                },
518                expected_parser: ParserConfig {
519                    parser_type: ParserType::JsonLines,
520                    custom_prompt: None,
521                    validate: false,
522                },
523                equivalence_skip: None,
524            },
525            PresetTestRow {
526                preset: ProtocolPreset::Cobs,
527                wire_name: "cobs",
528                expected_tx: TxFramingConfig {
529                    mode: TxFramingMode::Cobs,
530                },
531                expected_rx: RxFramingConfig {
532                    mode: RxFramingMode::Cobs,
533                    max_frames: None,
534                    include_terminators: false,
535                    skip_empty: false,
536                },
537                expected_parser: ParserConfig {
538                    parser_type: ParserType::Raw,
539                    custom_prompt: None,
540                    validate: false,
541                },
542                equivalence_skip: None,
543            },
544            PresetTestRow {
545                preset: ProtocolPreset::Ndjson,
546                wire_name: "ndjson",
547                expected_tx: TxFramingConfig {
548                    mode: TxFramingMode::Line {
549                        ending: TxLineEnding::Lf,
550                    },
551                },
552                expected_rx: RxFramingConfig {
553                    mode: RxFramingMode::Line {
554                        ending: LineEnding::Auto,
555                    },
556                    max_frames: None,
557                    include_terminators: false,
558                    skip_empty: true,
559                },
560                expected_parser: ParserConfig {
561                    parser_type: ParserType::JsonLines,
562                    custom_prompt: None,
563                    validate: false,
564                },
565                equivalence_skip: None,
566            },
567            PresetTestRow {
568                preset: ProtocolPreset::Nmea0183,
569                wire_name: "nmea0183",
570                expected_tx: TxFramingConfig {
571                    mode: TxFramingMode::Nmea,
572                },
573                expected_rx: RxFramingConfig {
574                    mode: RxFramingMode::StartEnd {
575                        start: vec!["$".into(), "!".into()],
576                        end: "\r\n".into(),
577                        marker_encoding: PatternEncoding::Utf8,
578                        include_markers: false,
579                    },
580                    max_frames: None,
581                    include_terminators: false,
582                    skip_empty: false,
583                },
584                expected_parser: ParserConfig {
585                    parser_type: ParserType::Nmea,
586                    custom_prompt: None,
587                    validate: true,
588                },
589                equivalence_skip: None,
590            },
591            PresetTestRow {
592                preset: ProtocolPreset::ModbusAscii,
593                wire_name: "modbus_ascii",
594                expected_tx: TxFramingConfig {
595                    mode: TxFramingMode::StartEnd {
596                        start: vec![":".into()],
597                        end: "\r\n".into(),
598                        marker_encoding: PatternEncoding::Utf8,
599                    },
600                },
601                expected_rx: RxFramingConfig {
602                    mode: RxFramingMode::StartEnd {
603                        start: vec![":".into()],
604                        end: "\r\n".into(),
605                        marker_encoding: PatternEncoding::Utf8,
606                        include_markers: false,
607                    },
608                    max_frames: None,
609                    include_terminators: false,
610                    skip_empty: false,
611                },
612                expected_parser: ParserConfig {
613                    parser_type: ParserType::ModbusAscii,
614                    custom_prompt: None,
615                    validate: true,
616                },
617                equivalence_skip: None,
618            },
619        ]
620    }
621
622    #[test]
623    fn preset_tx_framing_matches_table() {
624        for row in preset_test_table() {
625            let cfg = preset_tx_framing(row.preset);
626            assert_eq!(cfg.mode, row.expected_tx.mode);
627        }
628    }
629
630    #[test]
631    fn preset_rx_framing_matches_table() {
632        for row in preset_test_table() {
633            let cfg = preset_rx_framing(row.preset);
634            assert_eq!(cfg.mode, row.expected_rx.mode);
635            assert_eq!(cfg.skip_empty, row.expected_rx.skip_empty);
636        }
637    }
638
639    #[test]
640    fn preset_rx_parser_matches_table() {
641        for row in preset_test_table() {
642            let cfg = preset_rx_parser(row.preset);
643            assert_eq!(cfg.parser_type, row.expected_parser.parser_type);
644            assert_eq!(cfg.validate, row.expected_parser.validate);
645        }
646    }
647
648    #[test]
649    fn protocol_preset_tagged_object_roundtrips() {
650        for row in preset_test_table() {
651            assert_preset_roundtrip(row.wire_name, row.preset);
652        }
653    }
654
655    #[test]
656    fn presets_equivalent_to_bare_configs() {
657        for row in preset_test_table() {
658            if let Some(reason) = row.equivalence_skip {
659                // Documented exemption, not a missing test.
660                eprintln!("skipping equivalence for {}: {}", row.wire_name, reason);
661                continue;
662            }
663            let preset_tx = preset_tx_framing(row.preset);
664            assert_eq!(preset_tx, row.expected_tx, "{} TX", row.wire_name);
665
666            let preset_rx = preset_rx_framing(row.preset);
667            assert_eq!(preset_rx, row.expected_rx, "{} RX", row.wire_name);
668
669            let preset_parser = preset_rx_parser(row.preset);
670            assert_eq!(
671                preset_parser, row.expected_parser,
672                "{} parser",
673                row.wire_name
674            );
675        }
676    }
677
678    #[test]
679    fn skip_empty_default_is_false() {
680        assert!(!RxFramingConfig::default().skip_empty);
681    }
682
683    #[test]
684    fn skip_empty_off_by_default_in_preset_json_lines() {
685        assert!(!preset_rx_framing(ProtocolPreset::JsonLines).skip_empty);
686    }
687
688    #[test]
689    fn skip_empty_on_in_preset_ndjson() {
690        assert!(preset_rx_framing(ProtocolPreset::Ndjson).skip_empty);
691    }
692}