From 8f87263c78f220d6b12bb125b288dac4e3978feb Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Sat, 14 Nov 2026 23:38:03 +0100 Subject: [PATCH 1/4] feat(cli): --format csv, stdin streams via '-', and telecommand inspection Telemetry decoding often feeds analysis pipelines, spreadsheets, and stream processors, where plain text table and JSON lines require extra parsing or do not stream into CSV consumers cleanly. xtce was also strictly file-bound, failing if piped input used the standard '-' convention. * `--format csv` outputs tabular parameter values per packet: `packet,container,parameter,eng` (and an optional `,raw` column with `--raw`). RFC 4180 escaping is applied when strings contain commas, double quotes, or newlines. * `--no-summary` suppresses the trailing timing and packet count lines, leaving stdout clean for piping directly into downstream tools (`xsv`, `jq`, Pandas). * Reading from standard input (`-`) is now supported across the CLI: `xtce decode` accepts `-` for either the packet stream or the definition, and `xtce info`, `xtce codegen` and `xtce bench` accept `-` for definition files. * `xtce info --verbose` now lists the telecommands section, showing each command, inheritance, backing container, and declared argument types. Tests added for CSV string escaping, float formatting, and tabular output. All 9 differential cases match the reference, fmt and clippy clean. --- Cargo.lock | 12 +- crates/xtce-cli/src/decode.rs | 301 +++++++++++++++++++++++++++++++--- crates/xtce-cli/src/info.rs | 48 +++++- crates/xtce-cli/src/main.rs | 193 +++++++++++++--------- 4 files changed, 445 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 79a8b0e..e1dd06f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -915,7 +915,7 @@ checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" [[package]] name = "xtask" -version = "0.1.0" +version = "0.1.1" dependencies = [ "clap", "serde_json", @@ -925,7 +925,7 @@ dependencies = [ [[package]] name = "xtce-cli" -version = "0.1.0" +version = "0.1.1" dependencies = [ "clap", "xtce-codegen", @@ -935,7 +935,7 @@ dependencies = [ [[package]] name = "xtce-codegen" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "prettyplease", @@ -949,7 +949,7 @@ dependencies = [ [[package]] name = "xtce-codegen-e2e" -version = "0.1.0" +version = "0.1.1" dependencies = [ "xtce-codegen", "xtce-decode", @@ -958,7 +958,7 @@ dependencies = [ [[package]] name = "xtce-decode" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "proptest", @@ -968,7 +968,7 @@ dependencies = [ [[package]] name = "xtce-model" -version = "0.1.0" +version = "0.1.1" dependencies = [ "criterion", "proptest", diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index 18de97a..dde4556 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -1,6 +1,6 @@ //! `xtce decode` — run a packet stream through a definition and print the values. -use std::io::Write; +use std::io::{Read, Write}; use std::path::Path; use std::time::Instant; @@ -14,6 +14,8 @@ pub enum Format { Table, /// One JSON object per packet, one packet per line. Jsonl, + /// Comma-separated values (CSV) with packet, container, and parameter columns. + Csv, /// Nothing per packet; only the summary. Quiet, } @@ -28,6 +30,62 @@ pub struct Options<'a> { pub only: &'a [String], pub format: Format, pub show_raw: bool, + pub no_summary: bool, +} + +fn load_stream(packets: &Path) -> std::io::Result> { + if packets.as_os_str() == "-" { + let mut bytes = Vec::new(); + std::io::stdin().read_to_end(&mut bytes)?; + Ok(bytes) + } else { + std::fs::read(packets) + } +} + +fn load_definition(definition: &Path) -> Result> { + if definition.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + Ok(XtceDb::from_xml(&xml)?) + } else { + Ok(XtceDb::from_path(definition)?) + } +} + +struct Summary { + total: usize, + decoded: usize, + unrecognised: usize, + failed: usize, + trailing: usize, + load_elapsed: std::time::Duration, + decode_elapsed: std::time::Duration, +} + +fn print_summary(out: &mut impl Write, summary: &Summary) -> std::io::Result<()> { + writeln!(out)?; + writeln!( + out, + "{} packet(s): {} decoded, {} not described, {} failed", + summary.total, summary.decoded, summary.unrecognised, summary.failed + )?; + if summary.trailing > 0 { + // Worth surfacing: the definition and the packets disagree about length, which + // usually means a container is missing entries rather than that anything is corrupt. + writeln!( + out, + "{} packet(s) had bits no entry claimed — the definition may be incomplete", + summary.trailing + )?; + } + writeln!( + out, + "load {:.2} ms, decode {:.2} ms ({:.1} packets/s)", + summary.load_elapsed.as_secs_f64() * 1e3, + summary.decode_elapsed.as_secs_f64() * 1e3, + summary.decoded as f64 / summary.decode_elapsed.as_secs_f64().max(f64::MIN_POSITIVE), + ) } /// Decodes a stream and writes the result. @@ -39,8 +97,12 @@ pub struct Options<'a> { /// not well-framed. A packet that fails to *decode* is reported and counted, not fatal: one /// malformed frame in a downlink should not end the run. pub fn run(options: &Options<'_>) -> Result<(), Box> { + if options.definition.as_os_str() == "-" && options.packets.as_os_str() == "-" { + return Err("cannot read both definition and packets from standard input".into()); + } + let load_start = Instant::now(); - let db = XtceDb::from_path(options.definition)?; + let db = load_definition(options.definition)?; let load_elapsed = load_start.elapsed(); check_only(&db, options.only)?; @@ -50,7 +112,7 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { None => Decoder::new(&db)?, }; - let stream = std::fs::read(options.packets)?; + let stream = load_stream(options.packets)?; let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); @@ -63,6 +125,14 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { // One packet buffer for the whole stream: after the first packet this allocates nothing. let mut packet = decoder.new_packet(&stream); + if options.format == Format::Csv { + if options.show_raw { + writeln!(out, "packet,container,parameter,eng,raw")?; + } else { + writeln!(out, "packet,container,parameter,eng")?; + } + } + let decode_start = Instant::now(); for (index, framed) in PacketIter::new(&stream, options.skip_header_bytes).enumerate() { if options.limit.is_some_and(|limit| total >= limit) { @@ -80,46 +150,49 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { match options.format { Format::Table => write_table(&mut out, index, &packet, options)?, Format::Jsonl => write_jsonl(&mut out, index, &packet, options)?, + Format::Csv => write_csv(&mut out, index, &packet, options)?, Format::Quiet => {} } } Err(DecodeError::UnrecognizedPacket { container, .. }) => { unrecognised += 1; - if options.format != Format::Quiet { + if options.format == Format::Table { writeln!( out, "packet {index}: not described by this definition (no inheritor of {container} matches)" )?; + } else if options.format != Format::Quiet { + eprintln!( + "packet {index}: not described by this definition (no inheritor of {container} matches)" + ); } } Err(error) => { failed += 1; - writeln!(out, "packet {index}: {error}")?; + if options.format == Format::Table { + writeln!(out, "packet {index}: {error}")?; + } else { + eprintln!("packet {index}: {error}"); + } } } } let decode_elapsed = decode_start.elapsed(); - writeln!(out)?; - writeln!( - out, - "{total} packet(s): {decoded_count} decoded, {unrecognised} not described, {failed} failed" - )?; - if trailing > 0 { - // Worth surfacing: the definition and the packets disagree about length, which - // usually means a container is missing entries rather than that anything is corrupt. - writeln!( - out, - "{trailing} packet(s) had bits no entry claimed — the definition may be incomplete" + if !options.no_summary { + print_summary( + &mut out, + &Summary { + total, + decoded: decoded_count, + unrecognised, + failed, + trailing, + load_elapsed, + decode_elapsed, + }, )?; } - writeln!( - out, - "load {:.2} ms, decode {:.2} ms ({:.1} packets/s)", - load_elapsed.as_secs_f64() * 1e3, - decode_elapsed.as_secs_f64() * 1e3, - decoded_count as f64 / decode_elapsed.as_secs_f64().max(f64::MIN_POSITIVE), - )?; out.flush()?; if failed > 0 { @@ -382,6 +455,94 @@ fn write_json_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { Ok(()) } +fn write_csv( + out: &mut impl Write, + index: usize, + packet: &xtce_decode::DecodedPacket<'_, '_>, + options: &Options<'_>, +) -> std::io::Result<()> { + let db = packet.db(); + let container = db + .container(packet.container()) + .map_or("?", |container| db.name(container.name)); + for (name, value) in packet.iter_named() { + if !wanted(options.only, name) { + continue; + } + write!(out, "{index},")?; + write_csv_string(out, container)?; + write!(out, ",")?; + write_csv_string(out, name)?; + write!(out, ",")?; + write_csv_eng(out, &value.eng)?; + if options.show_raw { + write!(out, ",")?; + write_csv_raw(out, &value.raw)?; + } + writeln!(out)?; + } + Ok(()) +} + +fn write_csv_eng(out: &mut impl Write, value: &EngValue<'_, '_>) -> std::io::Result<()> { + match value { + EngValue::Unsigned(number) => write!(out, "{number}"), + EngValue::Signed(number) => write!(out, "{number}"), + EngValue::Float(number) => write_csv_float(out, *number), + EngValue::Bool(flag) => write!(out, "{flag}"), + EngValue::Label(text) => write_csv_string(out, text), + EngValue::Text(text) => write_csv_string(out, text.as_ref()), + EngValue::Bytes(bytes) => write_hex_raw(out, bytes), + } +} + +fn write_csv_raw(out: &mut impl Write, value: &RawValue<'_>) -> std::io::Result<()> { + match value { + RawValue::Unsigned(number) => write!(out, "{number}"), + RawValue::Signed(number) => write!(out, "{number}"), + RawValue::Float(number) => write_csv_float(out, *number), + RawValue::Bytes(bytes) => write_hex_raw(out, bytes), + } +} + +fn write_csv_float(out: &mut impl Write, value: f64) -> std::io::Result<()> { + if value.is_nan() { + write!(out, "NaN") + } else if value.is_infinite() { + if value.is_sign_positive() { + write!(out, "Infinity") + } else { + write!(out, "-Infinity") + } + } else { + write!(out, "{value}") + } +} + +fn write_hex_raw(out: &mut impl Write, bytes: &[u8]) -> std::io::Result<()> { + for byte in bytes { + write!(out, "{byte:02x}")?; + } + Ok(()) +} + +fn write_csv_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { + if text.contains([',', '"', '\n', '\r']) { + out.write_all(b"\"")?; + for ch in text.chars() { + if ch == '"' { + out.write_all(b"\"\"")?; + } else { + let mut buf = [0u8; 4]; + out.write_all(ch.encode_utf8(&mut buf).as_bytes())?; + } + } + out.write_all(b"\"") + } else { + out.write_all(text.as_bytes()) + } +} + #[cfg(test)] mod tests { use super::{check_only, edit_distance, glob_matches, suggest, wanted}; @@ -568,4 +729,98 @@ mod tests { // Two characters apart is still two edits: only *adjacent* swaps are one. assert_eq!(edit_distance("ABCD", "CBAD"), 2); } + + #[test] + fn csv_string_escapes_only_when_needed() { + let mut out = Vec::new(); + super::write_csv_string(&mut out, "plain_identifier").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "plain_identifier"); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "comma, separated").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "\"comma, separated\""); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "contains \"quotes\" inside").unwrap(); + assert_eq!( + String::from_utf8(out).unwrap(), + "\"contains \"\"quotes\"\" inside\"" + ); + + let mut out = Vec::new(); + super::write_csv_string(&mut out, "line1\nline2").unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "\"line1\nline2\""); + } + + #[test] + fn csv_float_formats_special_values() { + let mut out = Vec::new(); + super::write_csv_float(&mut out, 42.5).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "42.5"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::NAN).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "NaN"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::INFINITY).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "Infinity"); + + let mut out = Vec::new(); + super::write_csv_float(&mut out, f64::NEG_INFINITY).unwrap(); + assert_eq!(String::from_utf8(out).unwrap(), "-Infinity"); + } + + #[test] + fn csv_formatting_writes_headers_and_rows() { + let db = db(); + let decoder = xtce_decode::Decoder::new(&db).expect("decoder creates"); + let data = [0x00, 0x00, 0x00, 0x2A]; + let mut packet = decoder.new_packet(&data); + decoder.decode_into(&mut packet, &data).expect("decodes"); + + let mut out = Vec::new(); + let options = super::Options { + definition: std::path::Path::new("dummy.xml"), + packets: std::path::Path::new("dummy.bin"), + root: None, + skip_header_bytes: 0, + limit: None, + only: &[], + format: super::Format::Csv, + show_raw: false, + no_summary: false, + }; + + super::write_csv(&mut out, 0, &packet, &options).expect("writes csv"); + let text = String::from_utf8(out).expect("utf8"); + assert_eq!(text, "0,PKT,ADGPSPOSX,42\n"); + + let mut out = Vec::new(); + let options_raw = super::Options { + show_raw: true, + ..options + }; + super::write_csv(&mut out, 0, &packet, &options_raw).expect("writes csv raw"); + let text_raw = String::from_utf8(out).expect("utf8"); + assert_eq!(text_raw, "0,PKT,ADGPSPOSX,42,42\n"); + } + + #[test] + fn print_summary_writes_formatted_counts() { + let mut out = Vec::new(); + let summary = super::Summary { + total: 10, + decoded: 8, + unrecognised: 1, + failed: 1, + trailing: 2, + load_elapsed: std::time::Duration::from_millis(5), + decode_elapsed: std::time::Duration::from_millis(15), + }; + super::print_summary(&mut out, &summary).expect("prints summary"); + let text = String::from_utf8(out).expect("utf8"); + assert!(text.contains("10 packet(s): 8 decoded, 1 not described, 1 failed")); + assert!(text.contains("2 packet(s) had bits no entry claimed")); + } } diff --git a/crates/xtce-cli/src/info.rs b/crates/xtce-cli/src/info.rs index 6e5b62c..e9a49ef 100644 --- a/crates/xtce-cli/src/info.rs +++ b/crates/xtce-cli/src/info.rs @@ -9,7 +9,7 @@ pub fn report(db: &XtceDb, elapsed: Duration, verbose: bool) { let stats = db.stats(); let source = db .source() - .map_or_else(|| "".to_owned(), |path| path.display().to_string()); + .map_or_else(|| "".to_owned(), |path| path.display().to_string()); println!("{source}"); println!( @@ -97,6 +97,7 @@ pub fn report(db: &XtceDb, elapsed: Duration, verbose: bool) { if verbose { print_containers(db); + print_commands(db); } println!(); } @@ -263,3 +264,48 @@ fn print_containers(db: &XtceDb) { } } } + +fn print_commands(db: &XtceDb) { + if db.meta_commands().is_empty() { + return; + } + println!(" telecommands:"); + for command in db.meta_commands() { + let base = command + .base + .and_then(|base| db.meta_command(base)) + .map(|base| format!(" extends {}", db.name(base.name))) + .unwrap_or_default(); + let container = command + .container + .and_then(|c| db.container(c)) + .map(|c| format!(" -> {}", db.name(c.name))) + .unwrap_or_default(); + println!( + " {}{}{}{}", + db.name(command.name), + if command.is_abstract { + " (abstract)" + } else { + "" + }, + base, + container + ); + for ¶m_id in &command.arguments { + let Some(param) = db.parameter(param_id) else { + continue; + }; + let ty = db.type_of(param_id); + let bits = ty + .and_then(xtce_model::ParameterType::fixed_size_in_bits) + .map_or_else(|| "var".to_owned(), |bits| format!("{bits}b")); + println!( + " {:<28} {:<16} {}", + db.name(param.name), + ty.map_or("?", |ty| ty.kind.label()), + bits + ); + } + } +} diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index f1e5230..274d5ce 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -11,7 +11,8 @@ #![allow(clippy::doc_markdown)] #![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used, clippy::panic))] -use std::path::PathBuf; +use std::io::Read; +use std::path::{Path, PathBuf}; use std::process::ExitCode; use std::time::Instant; @@ -32,7 +33,7 @@ struct Cli { enum Command { /// Summarise one or more XTCE files: space systems, counts, and anything not decodable. Info { - /// XTCE files to inspect. + /// XTCE files to inspect. Use '-' to read from standard input. #[arg(required = true)] files: Vec, @@ -43,10 +44,10 @@ enum Command { /// Decode a CCSDS packet stream against an XTCE definition. Decode { - /// XTCE definition. + /// XTCE definition. Use '-' to read from standard input. definition: PathBuf, - /// File of concatenated CCSDS packets. + /// File of concatenated CCSDS packets. Use '-' to read from standard input. packets: PathBuf, /// Container to start from. Defaults to CCSDSPacket, CCSDSTelemetryPacket, or the @@ -74,11 +75,15 @@ enum Command { /// Also show the raw value alongside the engineering value. #[arg(long)] raw: bool, + + /// Suppress the final summary (load and decode timing, packet counts). + #[arg(long)] + no_summary: bool, }, /// Compile a definition into a static Rust decoder. Codegen { - /// XTCE definition. + /// XTCE definition. Use '-' to read from standard input. definition: PathBuf, /// Container to start from. @@ -92,7 +97,7 @@ enum Command { /// Time loading an XTCE file. Bench { - /// XTCE file to load. + /// XTCE file to load. Use '-' to read from standard input. file: PathBuf, /// Number of load iterations to time. @@ -116,26 +121,19 @@ fn main() -> ExitCode { } } +fn load_db(path: &Path) -> Result> { + if path.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + Ok(XtceDb::from_xml(&xml)?) + } else { + Ok(XtceDb::from_path(path)?) + } +} + fn run(cli: Cli) -> Result<(), Box> { match cli.command { - Command::Info { files, verbose } => { - let mut failures = 0; - for file in &files { - let started = Instant::now(); - match XtceDb::from_path(file) { - Ok(db) => info::report(&db, started.elapsed(), verbose), - Err(error) => { - failures += 1; - eprintln!("{}: {error}", file.display()); - } - } - } - if failures > 0 { - return Err(format!("{failures} of {} file(s) failed to load", files.len()).into()); - } - Ok(()) - } - + Command::Info { files, verbose } => run_info(&files, verbose), Command::Decode { definition, packets, @@ -145,6 +143,7 @@ fn run(cli: Cli) -> Result<(), Box> { params, format, raw, + no_summary, } => decode::run(&decode::Options { definition: &definition, packets: &packets, @@ -154,69 +153,105 @@ fn run(cli: Cli) -> Result<(), Box> { only: ¶ms, format, show_raw: raw, + no_summary, }), - Command::Codegen { definition, root, out, - } => { - let db = XtceDb::from_path(&definition)?; - let source = xtce_codegen::generate( - &db, - &xtce_codegen::Options { - root, - source_label: Some(definition.display().to_string()), - }, - )?; - match out { - Some(path) => { - std::fs::write(&path, source)?; - eprintln!("wrote {}", path.display()); - eprintln!( - "include it inside a module carrying the lint allowances generated \ - code needs; the file's header shows how" - ); - } - None => print!("{source}"), + } => run_codegen(&definition, root, out), + Command::Bench { file, iterations } => run_bench(&file, iterations), + } +} + +fn run_info(files: &[PathBuf], verbose: bool) -> Result<(), Box> { + let mut failures = 0; + for file in files { + let started = Instant::now(); + match load_db(file) { + Ok(db) => info::report(&db, started.elapsed(), verbose), + Err(error) => { + failures += 1; + eprintln!("{}: {error}", file.display()); } - Ok(()) } + } + if failures > 0 { + return Err(format!("{failures} of {} file(s) failed to load", files.len()).into()); + } + Ok(()) +} - Command::Bench { file, iterations } => { - let bytes = std::fs::metadata(&file).map_or(0, |meta| meta.len()); - let mut timings = Vec::with_capacity(iterations as usize); - let mut last = None; - for _ in 0..iterations.max(1) { - let started = Instant::now(); - let db = XtceDb::from_path(&file)?; - timings.push(started.elapsed()); - last = Some(db); - } - timings.sort_unstable(); - let median = timings.get(timings.len() / 2).copied().unwrap_or_default(); - let best = timings.first().copied().unwrap_or_default(); - - println!("{}", file.display()); - println!(" size {:>10.1} KiB", bytes as f64 / 1024.0); - println!(" load median {:>10.3} ms", median.as_secs_f64() * 1e3); - println!(" load best {:>10.3} ms", best.as_secs_f64() * 1e3); - if let Some(db) = last { - let stats = db.stats(); - println!( - " throughput {:>10.1} MiB/s", - (bytes as f64 / (1024.0 * 1024.0)) - / median.as_secs_f64().max(f64::MIN_POSITIVE) - ); - println!( - " model {} parameters, {} containers, {} interned names ({:.1} KiB)", - stats.parameters, - stats.containers, - stats.interned_names, - stats.interned_bytes as f64 / 1024.0 - ); - } - Ok(()) +fn run_codegen( + definition: &Path, + root: Option, + out: Option, +) -> Result<(), Box> { + let db = load_db(definition)?; + let source_label = if definition.as_os_str() == "-" { + Some("".to_owned()) + } else { + Some(definition.display().to_string()) + }; + let source = xtce_codegen::generate(&db, &xtce_codegen::Options { root, source_label })?; + match out { + Some(path) => { + std::fs::write(&path, source)?; + eprintln!("wrote {}", path.display()); + eprintln!( + "include it inside a module carrying the lint allowances generated \ + code needs; the file's header shows how" + ); } + None => print!("{source}"), + } + Ok(()) +} + +fn run_bench(file: &Path, iterations: u32) -> Result<(), Box> { + let (bytes, xml_data) = if file.as_os_str() == "-" { + let mut xml = String::new(); + std::io::stdin().read_to_string(&mut xml)?; + (xml.len() as u64, Some(xml)) + } else { + (std::fs::metadata(file).map_or(0, |meta| meta.len()), None) + }; + let mut timings = Vec::with_capacity(iterations as usize); + let mut last = None; + for _ in 0..iterations.max(1) { + let started = Instant::now(); + let db = match &xml_data { + Some(xml) => XtceDb::from_xml(xml)?, + None => XtceDb::from_path(file)?, + }; + timings.push(started.elapsed()); + last = Some(db); + } + timings.sort_unstable(); + let median = timings.get(timings.len() / 2).copied().unwrap_or_default(); + let best = timings.first().copied().unwrap_or_default(); + + if file.as_os_str() == "-" { + println!(""); + } else { + println!("{}", file.display()); + } + println!(" size {:>10.1} KiB", bytes as f64 / 1024.0); + println!(" load median {:>10.3} ms", median.as_secs_f64() * 1e3); + println!(" load best {:>10.3} ms", best.as_secs_f64() * 1e3); + if let Some(db) = last { + let stats = db.stats(); + println!( + " throughput {:>10.1} MiB/s", + (bytes as f64 / (1024.0 * 1024.0)) / median.as_secs_f64().max(f64::MIN_POSITIVE) + ); + println!( + " model {} parameters, {} containers, {} interned names ({:.1} KiB)", + stats.parameters, + stats.containers, + stats.interned_names, + stats.interned_bytes as f64 / 1024.0 + ); } + Ok(()) } From 84a53b7d2627785fb62067f109ec32e6fbd3927f Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Tue, 17 Nov 2026 15:46:42 +0100 Subject: [PATCH 2/4] feat(decode): stream packets via PacketReader without buffering whole streams Add PacketReader to stream CCSDS space packets sequentially from any std::io::Read source into an internal reusable buffer bounded at 64 KiB, eliminating unbounded memory consumption on large telemetry streams or live stdin feeds. Update xtce decode to stream packets on the fly via PacketReader, and add tests for streaming framing, wrappers, and stdin conflict rejection. --- crates/xtce-cli/src/decode.rs | 48 ++++-- crates/xtce-decode/src/ccsds.rs | 265 ++++++++++++++++++++++++++++++++ crates/xtce-decode/src/lib.rs | 2 +- 3 files changed, 300 insertions(+), 15 deletions(-) diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index dde4556..2d567a9 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -4,7 +4,7 @@ use std::io::{Read, Write}; use std::path::Path; use std::time::Instant; -use xtce_decode::{DecodeError, Decoder, EngValue, PacketIter, RawValue}; +use xtce_decode::{DecodeError, Decoder, EngValue, PacketReader, RawValue}; use xtce_model::XtceDb; /// How to render each packet. @@ -33,13 +33,12 @@ pub struct Options<'a> { pub no_summary: bool, } -fn load_stream(packets: &Path) -> std::io::Result> { +fn open_packet_source(packets: &Path) -> std::io::Result> { if packets.as_os_str() == "-" { - let mut bytes = Vec::new(); - std::io::stdin().read_to_end(&mut bytes)?; - Ok(bytes) + Ok(Box::new(std::io::BufReader::new(std::io::stdin()))) } else { - std::fs::read(packets) + let file = std::fs::File::open(packets)?; + Ok(Box::new(std::io::BufReader::new(file))) } } @@ -112,7 +111,8 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { None => Decoder::new(&db)?, }; - let stream = load_stream(options.packets)?; + let source = open_packet_source(options.packets)?; + let mut reader = PacketReader::new(source, options.skip_header_bytes); let stdout = std::io::stdout(); let mut out = std::io::BufWriter::new(stdout.lock()); @@ -122,9 +122,6 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { let mut trailing = 0usize; let mut total = 0usize; - // One packet buffer for the whole stream: after the first packet this allocates nothing. - let mut packet = decoder.new_packet(&stream); - if options.format == Format::Csv { if options.show_raw { writeln!(out, "packet,container,parameter,eng,raw")?; @@ -134,15 +131,15 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { } let decode_start = Instant::now(); - for (index, framed) in PacketIter::new(&stream, options.skip_header_bytes).enumerate() { + let mut index = 0usize; + while let Some(framed) = reader.next_packet()? { if options.limit.is_some_and(|limit| total >= limit) { break; } total += 1; - let framed = framed?; - match decoder.decode_into(&mut packet, framed.bytes()) { - Ok(()) => { + match decoder.decode(framed.bytes()) { + Ok(packet) => { decoded_count += 1; if packet.trailing_bits() != 0 { trailing += 1; @@ -176,6 +173,7 @@ pub fn run(options: &Options<'_>) -> Result<(), Box> { } } } + index += 1; } let decode_elapsed = decode_start.elapsed(); @@ -823,4 +821,26 @@ mod tests { assert!(text.contains("10 packet(s): 8 decoded, 1 not described, 1 failed")); assert!(text.contains("2 packet(s) had bits no entry claimed")); } + + #[test] + fn run_rejects_stdin_conflict_for_definition_and_packets() { + let options = super::Options { + definition: std::path::Path::new("-"), + packets: std::path::Path::new("-"), + root: None, + skip_header_bytes: 0, + limit: None, + only: &[], + format: super::Format::Quiet, + show_raw: false, + no_summary: true, + }; + let result = super::run(&options); + assert!(result.is_err()); + let err = result.unwrap_err(); + assert_eq!( + err.to_string(), + "cannot read both definition and packets from standard input" + ); + } } diff --git a/crates/xtce-decode/src/ccsds.rs b/crates/xtce-decode/src/ccsds.rs index fc36219..74ee34a 100644 --- a/crates/xtce-decode/src/ccsds.rs +++ b/crates/xtce-decode/src/ccsds.rs @@ -8,6 +8,7 @@ //! steps over it. The SUDA test file in this repository needs four. use std::fmt; +use std::io::Read; /// Size of the CCSDS primary header. pub const PRIMARY_HEADER_BYTES: usize = 6; @@ -199,6 +200,194 @@ impl<'a> Iterator for PacketIter<'a> { } } +/// An error encountered while reading a packet stream. +#[derive(Debug, thiserror::Error)] +pub enum PacketReadError { + /// A malformed packet frame in the stream. + #[error(transparent)] + Framing(#[from] FramingError), + + /// An I/O error reading from the underlying stream. + #[error("I/O error at stream offset {offset}: {source}")] + Io { + /// Byte offset in the stream where the error occurred. + offset: usize, + /// The underlying I/O error. + #[source] + source: std::io::Error, + }, +} + +/// Reads CCSDS space packets sequentially from an I/O source. +/// +/// Unlike [`PacketIter`], which borrows from an in-memory byte slice, `PacketReader` +/// streams packets from any [`Read`] source into an internal reusable buffer, +/// allocating at most one maximum-length packet buffer (up to 64 KiB) regardless of stream +/// size. +/// +/// ```no_run +/// # fn main() -> Result<(), Box> { +/// use std::fs::File; +/// use std::io::BufReader; +/// use xtce_decode::ccsds::PacketReader; +/// +/// let file = File::open("telemetry.bin")?; +/// let mut reader = PacketReader::new(BufReader::new(file), 0); +/// while let Some(packet) = reader.next_packet()? { +/// println!("APID: {}", packet.apid()); +/// } +/// # Ok(()) +/// # } +/// ``` +pub struct PacketReader { + reader: R, + offset: usize, + skip_header_bytes: usize, + buffer: Vec, + finished: bool, +} + +impl fmt::Debug for PacketReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PacketReader") + .field("offset", &self.offset) + .field("skip_header_bytes", &self.skip_header_bytes) + .field("buffer_len", &self.buffer.len()) + .field("finished", &self.finished) + .finish_non_exhaustive() + } +} + +impl PacketReader { + /// Creates a new `PacketReader` reading from `reader`, skipping `skip_header_bytes` before each packet. + #[must_use] + pub const fn new(reader: R, skip_header_bytes: usize) -> Self { + Self { + reader, + offset: 0, + skip_header_bytes, + buffer: Vec::new(), + finished: false, + } + } + + /// Current byte offset in the underlying stream. + #[must_use] + pub const fn offset(&self) -> usize { + self.offset + } + + /// Consumes the `PacketReader`, returning the underlying reader. + #[must_use] + pub fn into_inner(self) -> R { + self.reader + } + + /// Reads the next CCSDS packet from the stream into an internal buffer. + /// + /// Returns `Ok(Some(packet))` on success, `Ok(None)` on clean EOF, or `Err(...)` on framing or I/O error. + /// + /// # Errors + /// + /// Yields [`PacketReadError::Framing`] if the stream ends mid-packet, or + /// [`PacketReadError::Io`] if an I/O error occurs on the reader. + pub fn next_packet(&mut self) -> Result>, PacketReadError> { + if self.finished { + return Ok(None); + } + + // 1. Skip wrapper bytes if configured. + let mut skipped = 0; + let mut skip_buf = [0u8; 64]; + while skipped < self.skip_header_bytes { + let to_read = (self.skip_header_bytes - skipped).min(skip_buf.len()); + match self.reader.read(&mut skip_buf[..to_read]) { + Ok(0) => { + self.offset += skipped; + self.finished = true; + return Ok(None); + } + Ok(n) => { + skipped += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: self.offset + skipped, + source, + }); + } + } + } + self.offset += skipped; + + let start_offset = self.offset; + + // 2. Read the primary CCSDS header (6 bytes). + self.buffer.resize(PRIMARY_HEADER_BYTES, 0); + let mut header_read = 0; + while header_read < PRIMARY_HEADER_BYTES { + match self + .reader + .read(&mut self.buffer[header_read..PRIMARY_HEADER_BYTES]) + { + Ok(0) => { + self.finished = true; + if header_read == 0 { + return Ok(None); + } + return Err(PacketReadError::Framing(FramingError::ShortHeader { + offset: start_offset, + remaining: header_read, + })); + } + Ok(n) => { + header_read += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: start_offset + header_read, + source, + }); + } + } + } + + // 3. Parse length and read packet payload. + let count = u16::from_be_bytes([self.buffer[4], self.buffer[5]]); + let total = PRIMARY_HEADER_BYTES + usize::from(count) + 1; + + self.buffer.resize(total, 0); + let mut total_read = PRIMARY_HEADER_BYTES; + while total_read < total { + match self.reader.read(&mut self.buffer[total_read..total]) { + Ok(0) => { + self.finished = true; + return Err(PacketReadError::Framing(FramingError::ShortPacket { + offset: start_offset, + declared: total, + remaining: total_read, + })); + } + Ok(n) => { + total_read += n; + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(source) => { + return Err(PacketReadError::Io { + offset: start_offset + total_read, + source, + }); + } + } + } + + self.offset = start_offset + total; + Ok(Some(SpacePacketBytes::new(&self.buffer))) + } +} + #[cfg(test)] mod tests { use super::*; @@ -286,4 +475,80 @@ mod tests { assert_eq!(packet.sequence_count(), 0x1234); assert_eq!(packet.data_length(), 1); } + + #[test] + fn packet_reader_splits_a_stream_into_packets() { + let mut stream = packet(11, 10); + stream.extend(packet(42, 4)); + + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 0); + let p1 = reader.next_packet().expect("packet 1").expect("some"); + assert_eq!(p1.apid(), 11); + assert_eq!(p1.bytes().len(), 16); + assert_eq!(p1.user_data().len(), 10); + assert!(p1.secondary_header_flag()); + + let p2 = reader.next_packet().expect("packet 2").expect("some"); + assert_eq!(p2.apid(), 42); + assert_eq!(p2.bytes().len(), 10); + + assert!(reader.next_packet().expect("eof").is_none()); + assert_eq!(reader.offset(), 26); + } + + #[test] + fn packet_reader_skips_per_packet_wrappers() { + let mut stream = vec![0xDE, 0xAD, 0xBE, 0xEF]; + stream.extend(packet(7, 3)); + stream.extend([0xDE, 0xAD, 0xBE, 0xEF]); + stream.extend(packet(8, 3)); + + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 4); + let p1 = reader.next_packet().expect("packet 1").expect("some"); + assert_eq!(p1.apid(), 7); + + let p2 = reader.next_packet().expect("packet 2").expect("some"); + assert_eq!(p2.apid(), 8); + + assert!(reader.next_packet().expect("eof").is_none()); + } + + #[test] + fn packet_reader_reports_truncated_tails() { + let mut stream = packet(11, 10); + stream.truncate(12); + let mut reader = PacketReader::new(std::io::Cursor::new(stream), 0); + let err = reader.next_packet().expect_err("truncated payload"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortPacket { + offset: 0, + declared: 16, + remaining: 12, + }) + )); + + let stub = [0u8; 3]; + let mut reader = PacketReader::new(std::io::Cursor::new(stub), 0); + let err = reader.next_packet().expect_err("truncated header"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortHeader { + offset: 0, + remaining: 3, + }) + )); + } + + #[test] + fn packet_reader_empty_stream_yields_nothing() { + let mut reader = PacketReader::new(std::io::Cursor::new([]), 0); + assert!(reader.next_packet().expect("ok").is_none()); + + let mut reader_wrapped = PacketReader::new(std::io::Cursor::new([0xAA; 4]), 4); + assert!(reader_wrapped.next_packet().expect("ok").is_none()); + + let mut reader_partial_wrap = PacketReader::new(std::io::Cursor::new([0xAA; 2]), 4); + assert!(reader_partial_wrap.next_packet().expect("ok").is_none()); + } } diff --git a/crates/xtce-decode/src/lib.rs b/crates/xtce-decode/src/lib.rs index 2bb5896..2881167 100644 --- a/crates/xtce-decode/src/lib.rs +++ b/crates/xtce-decode/src/lib.rs @@ -69,7 +69,7 @@ pub mod error; pub mod value; pub use bits::{BitCursor, BitError}; -pub use ccsds::{FramingError, PacketIter, SpacePacketBytes}; +pub use ccsds::{FramingError, PacketIter, PacketReadError, PacketReader, SpacePacketBytes}; pub use decoder::Decoder; pub use error::DecodeError; pub use value::{DecodedPacket, EngValue, ParameterValue, RawValue}; From 62d25d8ad51f2868dc4a8cf420a320b729b988f7 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Tue, 17 Nov 2026 16:09:17 +0100 Subject: [PATCH 3/4] perf(cli): optimize CSV string escaping and bound stdin definition reads Emit byte slices instead of per-character writes in write_csv_string to avoid repeated I/O calls when escaping CSV fields. Cap standard input XML definition reads at 256 MiB to guard against unbounded stream inputs without impacting legitimate definitions. --- crates/xtce-cli/src/decode.rs | 20 +++++++++++++------- crates/xtce-cli/src/main.rs | 10 ++++++++-- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/crates/xtce-cli/src/decode.rs b/crates/xtce-cli/src/decode.rs index 2d567a9..a0c0ebb 100644 --- a/crates/xtce-cli/src/decode.rs +++ b/crates/xtce-cli/src/decode.rs @@ -42,10 +42,14 @@ fn open_packet_source(packets: &Path) -> std::io::Result> { } } +const MAX_DEFINITION_BYTES: u64 = 256 * 1024 * 1024; + fn load_definition(definition: &Path) -> Result> { if definition.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; Ok(XtceDb::from_xml(&xml)?) } else { Ok(XtceDb::from_path(definition)?) @@ -527,14 +531,16 @@ fn write_hex_raw(out: &mut impl Write, bytes: &[u8]) -> std::io::Result<()> { fn write_csv_string(out: &mut impl Write, text: &str) -> std::io::Result<()> { if text.contains([',', '"', '\n', '\r']) { out.write_all(b"\"")?; - for ch in text.chars() { - if ch == '"' { - out.write_all(b"\"\"")?; - } else { - let mut buf = [0u8; 4]; - out.write_all(ch.encode_utf8(&mut buf).as_bytes())?; + let bytes = text.as_bytes(); + let mut last = 0; + for (i, &b) in bytes.iter().enumerate() { + if b == b'"' { + out.write_all(&bytes[last..=i])?; + out.write_all(b"\"")?; + last = i + 1; } } + out.write_all(&bytes[last..])?; out.write_all(b"\"") } else { out.write_all(text.as_bytes()) diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 274d5ce..38f5f5a 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -121,10 +121,14 @@ fn main() -> ExitCode { } } +const MAX_DEFINITION_BYTES: u64 = 256 * 1024 * 1024; + fn load_db(path: &Path) -> Result> { if path.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; Ok(XtceDb::from_xml(&xml)?) } else { Ok(XtceDb::from_path(path)?) @@ -211,7 +215,9 @@ fn run_codegen( fn run_bench(file: &Path, iterations: u32) -> Result<(), Box> { let (bytes, xml_data) = if file.as_os_str() == "-" { let mut xml = String::new(); - std::io::stdin().read_to_string(&mut xml)?; + std::io::stdin() + .take(MAX_DEFINITION_BYTES) + .read_to_string(&mut xml)?; (xml.len() as u64, Some(xml)) } else { (std::fs::metadata(file).map_or(0, |meta| meta.len()), None) From f9fb0678d46e345ff6cb66e67b3695d85fa4cdb0 Mon Sep 17 00:00:00 2001 From: Maciej Myszkiewicz Date: Wed, 18 Nov 2026 13:57:22 +0100 Subject: [PATCH 4/4] feat(cli): add Wireshark Lua dissector generator and PCAP converter Add 'xtce wireshark' to compile an XTCE definition into a standalone Wireshark Lua dissector script covering container inheritance, restriction criteria, bit-level field extraction, enumerations, and polynomial calibration. Add 'xtce pcap' to stream concatenated CCSDS space packets into a standard libpcap (.pcap) capture file (DLT_USER0 = 147) with constant O(1) memory usage. --- crates/xtce-cli/src/main.rs | 73 ++++ crates/xtce-cli/src/pcap.rs | 247 ++++++++++++ crates/xtce-cli/src/wireshark.rs | 634 +++++++++++++++++++++++++++++++ 3 files changed, 954 insertions(+) create mode 100644 crates/xtce-cli/src/pcap.rs create mode 100644 crates/xtce-cli/src/wireshark.rs diff --git a/crates/xtce-cli/src/main.rs b/crates/xtce-cli/src/main.rs index 38f5f5a..13fb308 100644 --- a/crates/xtce-cli/src/main.rs +++ b/crates/xtce-cli/src/main.rs @@ -21,6 +21,8 @@ use xtce_model::XtceDb; mod decode; mod info; +mod pcap; +mod wireshark; #[derive(Parser)] #[command(name = "xtce", version, about, long_about = None)] @@ -95,6 +97,42 @@ enum Command { out: Option, }, + /// Compile a definition into a Wireshark Lua dissector script (.lua). + Wireshark { + /// XTCE definition. Use '-' to read from standard input. + definition: PathBuf, + + /// Container to start from. + #[arg(long)] + root: Option, + + /// Write here instead of standard output. + #[arg(long, short)] + out: Option, + + /// Also register the dissector on this UDP port in addition to DLT_USER0 (147). + #[arg(long)] + udp_port: Option, + }, + + /// Wrap a raw CCSDS packet stream in a libpcap (.pcap) capture file for Wireshark. + Pcap { + /// File of concatenated CCSDS packets. Use '-' to read from standard input. + packets: PathBuf, + + /// Write here instead of standard output. + #[arg(long, short)] + out: Option, + + /// Bytes of per-packet wrapper to skip before each CCSDS header. + #[arg(long, default_value_t = 0)] + skip_header_bytes: usize, + + /// Stop after this many packets. + #[arg(long)] + limit: Option, + }, + /// Time loading an XTCE file. Bench { /// XTCE file to load. Use '-' to read from standard input. @@ -164,10 +202,45 @@ fn run(cli: Cli) -> Result<(), Box> { root, out, } => run_codegen(&definition, root, out), + Command::Wireshark { + definition, + root, + out, + udp_port, + } => run_wireshark(&definition, root.as_deref(), out.as_deref(), udp_port), + Command::Pcap { + packets, + out, + skip_header_bytes, + limit, + } => pcap::run(&pcap::Options { + packets: &packets, + out: out.as_deref(), + skip_header_bytes, + limit, + }), Command::Bench { file, iterations } => run_bench(&file, iterations), } } +fn run_wireshark( + definition: &Path, + root: Option<&str>, + out: Option<&Path>, + udp_port: Option, +) -> Result<(), Box> { + let db = load_db(definition)?; + wireshark::run_with_db( + &db, + &wireshark::Options { + definition, + root, + out, + udp_port, + }, + ) +} + fn run_info(files: &[PathBuf], verbose: bool) -> Result<(), Box> { let mut failures = 0; for file in files { diff --git a/crates/xtce-cli/src/pcap.rs b/crates/xtce-cli/src/pcap.rs new file mode 100644 index 0000000..3354755 --- /dev/null +++ b/crates/xtce-cli/src/pcap.rs @@ -0,0 +1,247 @@ +//! `xtce pcap` — wrap a CCSDS space packet stream in a libpcap (`.pcap`) capture file. +//! +//! Wireshark and `tshark` dissect raw space packets over the `USER0` data-link type +//! (`DLT_USER0 = 147`). Writing a standard 24-byte global header and a 16-byte record header +//! around each framed CCSDS packet lets an engineer open any telemetry recording directly in +//! Wireshark alongside the Lua dissector produced by `xtce wireshark`. + +use std::io::{Read, Write}; +use std::path::Path; + +use xtce_decode::{PacketReadError, PacketReader}; + +/// Standard libpcap magic number for microsecond-resolution little-endian captures. +#[cfg(test)] +pub const PCAP_MAGIC_LE: u32 = 0xA1B2_C3D4; + +/// `DLT_USER0` (147), the conventional link-layer header type for raw CCSDS packets. +#[cfg(test)] +pub const LINKTYPE_USER0: u32 = 147; + +/// Maximum packet length advertised in the PCAP global header. +const SNAPLEN: u32 = 65_535; + +/// Pre-encoded 24-byte little-endian PCAP global header (version 2.4, `LINKTYPE_USER0`). +const GLOBAL_HEADER: [u8; 24] = [ + 0xD4, 0xC3, 0xB2, 0xA1, // magic_number: 0xa1b2c3d4 + 0x02, 0x00, // version_major: 2 + 0x04, 0x00, // version_minor: 4 + 0x00, 0x00, 0x00, 0x00, // thiszone: 0 + 0x00, 0x00, 0x00, 0x00, // sigfigs: 0 + 0xFF, 0xFF, 0x00, 0x00, // snaplen: 65535 + 0x93, 0x00, 0x00, 0x00, // network: 147 (LINKTYPE_USER0) +]; + +/// Configuration for `xtce pcap`. +pub struct Options<'a> { + pub packets: &'a Path, + pub out: Option<&'a Path>, + pub skip_header_bytes: usize, + pub limit: Option, +} + +/// Summary of packets written to a PCAP stream. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Stats { + pub packets: usize, + pub payload_bytes: u64, +} + +fn open_packet_source(packets: &Path) -> std::io::Result> { + if packets.as_os_str() == "-" { + Ok(Box::new(std::io::BufReader::new(std::io::stdin()))) + } else { + let file = std::fs::File::open(packets)?; + Ok(Box::new(std::io::BufReader::new(file))) + } +} + +/// Streams packets from `reader` into `out` formatted as a libpcap capture. +/// +/// Synthetic timestamps advance by 1 millisecond per packet so that Wireshark I/O graphs and +/// timeline filters have a monotonic time axis even when the raw recording carries no ground +/// receipt timestamps. +/// +/// # Errors +/// +/// Returns [`PacketReadError::Framing`] if the input stream ends mid-packet, or +/// [`PacketReadError::Io`] if reading or writing fails. +pub fn write_stream( + reader: &mut PacketReader, + out: &mut W, + limit: Option, +) -> Result { + out.write_all(&GLOBAL_HEADER) + .map_err(|source| PacketReadError::Io { offset: 0, source })?; + + let mut stats = Stats::default(); + + while let Some(framed) = reader.next_packet()? { + if limit.is_some_and(|max| stats.packets >= max) { + break; + } + + let bytes = framed.bytes(); + let pkt_len = u32::try_from(bytes.len()).unwrap_or(u32::MAX); + let index_u32 = u32::try_from(stats.packets).unwrap_or(u32::MAX); + let seconds = index_u32 / 1_000; + let micros = (index_u32 % 1_000) * 1_000; + + let s = seconds.to_le_bytes(); + let u = micros.to_le_bytes(); + let inc = pkt_len.min(SNAPLEN).to_le_bytes(); + let orig = pkt_len.to_le_bytes(); + + let record_header: [u8; 16] = [ + s[0], s[1], s[2], s[3], u[0], u[1], u[2], u[3], inc[0], inc[1], inc[2], inc[3], + orig[0], orig[1], orig[2], orig[3], + ]; + + let write_len = (pkt_len.min(SNAPLEN)) as usize; + out.write_all(&record_header) + .and_then(|()| out.write_all(&bytes[..write_len])) + .map_err(|source| PacketReadError::Io { + offset: reader.offset(), + source, + })?; + + stats.packets += 1; + stats.payload_bytes += write_len as u64; + } + + Ok(stats) +} + +/// Executes `xtce pcap`. +/// +/// # Errors +/// +/// Returns an error if the packet source or output destination cannot be opened, or if the +/// packet stream is malformed. +pub fn run(options: &Options<'_>) -> Result<(), Box> { + let source = open_packet_source(options.packets)?; + let mut reader = PacketReader::new(source, options.skip_header_bytes); + + match options.out { + Some(path) if path.as_os_str() != "-" => { + let file = std::fs::File::create(path)?; + let mut out = std::io::BufWriter::new(file); + let stats = write_stream(&mut reader, &mut out, options.limit)?; + out.flush()?; + eprintln!( + "wrote {} packet(s) ({} payload bytes) to {}", + stats.packets, + stats.payload_bytes, + path.display() + ); + } + _ => { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + let stats = write_stream(&mut reader, &mut out, options.limit)?; + out.flush()?; + eprintln!( + "wrote {} packet(s) ({} payload bytes) to ", + stats.packets, stats.payload_bytes + ); + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::io::Cursor; + + use xtce_decode::{FramingError, PacketReadError, PacketReader}; + + use super::{GLOBAL_HEADER, LINKTYPE_USER0, PCAP_MAGIC_LE, write_stream}; + + fn make_packet(apid: u16, payload: &[u8]) -> Vec { + let mut pkt = Vec::with_capacity(6 + payload.len()); + let word0 = 0x0800 | (apid & 0x07FF); + pkt.extend_from_slice(&word0.to_be_bytes()); + pkt.extend_from_slice(&0xC000u16.to_be_bytes()); + let len_field = u16::try_from(payload.len().saturating_sub(1)).unwrap_or(0); + pkt.extend_from_slice(&len_field.to_be_bytes()); + pkt.extend_from_slice(payload); + pkt + } + + #[test] + fn writes_valid_pcap_global_and_packet_headers() { + let mut raw = make_packet(0x10, &[1, 2, 3, 4]); + raw.extend(make_packet(0x20, &[5, 6])); + + let mut reader = PacketReader::new(Cursor::new(raw), 0); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, None).expect("pcap writes"); + + assert_eq!(stats.packets, 2); + assert_eq!(stats.payload_bytes, 18); + assert_eq!(out.len(), 24 + (16 + 10) + (16 + 8)); + + let magic = u32::from_le_bytes(out[0..4].try_into().unwrap()); + let linktype = u32::from_le_bytes(out[20..24].try_into().unwrap()); + assert_eq!(magic, PCAP_MAGIC_LE); + assert_eq!(linktype, LINKTYPE_USER0); + + // First packet record header at offset 24: ts_sec=0, ts_usec=0, incl_len=10, orig_len=10 + assert_eq!(u32::from_le_bytes(out[24..28].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[28..32].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[32..36].try_into().unwrap()), 10); + assert_eq!(u32::from_le_bytes(out[36..40].try_into().unwrap()), 10); + + // Second packet record header at offset 50: ts_sec=0, ts_usec=1000, incl_len=8, orig_len=8 + assert_eq!(u32::from_le_bytes(out[50..54].try_into().unwrap()), 0); + assert_eq!(u32::from_le_bytes(out[54..58].try_into().unwrap()), 1_000); + assert_eq!(u32::from_le_bytes(out[58..62].try_into().unwrap()), 8); + assert_eq!(u32::from_le_bytes(out[62..66].try_into().unwrap()), 8); + } + + #[test] + fn respects_packet_limit_and_skip_header_bytes() { + let mut raw = vec![0xAA, 0xBB, 0xCC, 0xDD]; + raw.extend(make_packet(1, &[0x11, 0x22])); + raw.extend([0xAA, 0xBB, 0xCC, 0xDD]); + raw.extend(make_packet(2, &[0x33, 0x44])); + + let mut reader = PacketReader::new(Cursor::new(raw), 4); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, Some(1)).expect("limited pcap"); + + assert_eq!(stats.packets, 1); + assert_eq!(stats.payload_bytes, 8); + assert_eq!(out.len(), 24 + 16 + 8); + } + + #[test] + fn empty_stream_writes_only_global_header() { + let mut reader = PacketReader::new(Cursor::new(Vec::::new()), 0); + let mut out = Vec::new(); + let stats = write_stream(&mut reader, &mut out, None).expect("empty pcap"); + + assert_eq!(stats.packets, 0); + assert_eq!(stats.payload_bytes, 0); + assert_eq!(out.as_slice(), &GLOBAL_HEADER); + } + + #[test] + fn truncated_packet_surfaces_framing_error() { + let mut raw = make_packet(1, &[1, 2, 3, 4]); + raw.truncate(8); + + let mut reader = PacketReader::new(Cursor::new(raw), 0); + let mut out = Vec::new(); + let err = write_stream(&mut reader, &mut out, None).expect_err("truncated"); + assert!(matches!( + err, + PacketReadError::Framing(FramingError::ShortPacket { + offset: 0, + declared: 10, + remaining: 8, + }) + )); + } +} diff --git a/crates/xtce-cli/src/wireshark.rs b/crates/xtce-cli/src/wireshark.rs new file mode 100644 index 0000000..4867230 --- /dev/null +++ b/crates/xtce-cli/src/wireshark.rs @@ -0,0 +1,634 @@ +//! `xtce wireshark` — compile an XTCE definition into a Wireshark Lua dissector (`.lua`). +//! +//! During spacecraft bench integration (FlatSat / EGSE), engineers inspect live UDP telemetry +//! or recorded `.pcap` files in Wireshark. Hand-maintaining Lua dissectors whenever the +//! telemetry database changes is tedious and error-prone; this module compiles the XTCE +//! container hierarchy, restriction criteria, bit offsets, enumerations, and polynomial +//! calibrators directly into a standalone Wireshark Lua script. + +use std::collections::BTreeSet; +use std::fmt::Write as _; +use std::path::Path; + +use xtce_codegen::{ + Calibration, CodegenError, ContainerPlan, Criterion, Field, Guard, GuardTest, Node, Plan, Repr, +}; +use xtce_model::{CompareOp, IntegerCoding, XtceDb}; + +/// Configuration for `xtce wireshark`. +pub struct Options<'a> { + pub definition: &'a Path, + pub root: Option<&'a str>, + pub out: Option<&'a Path>, + pub udp_port: Option, +} + +/// Compiles `db` into a Wireshark Lua dissector script. +/// +/// # Errors +/// +/// Returns [`CodegenError`] if the root container cannot be resolved or if the definition uses +/// constructs outside the compilable subset. +pub fn generate_lua( + db: &XtceDb, + root: Option<&str>, + source_label: &str, + udp_port: Option, +) -> Result { + let plan = xtce_codegen::plan( + db, + &xtce_codegen::Options { + root: root.map(str::to_owned), + source_label: Some(source_label.to_owned()), + }, + )?; + + Ok(emit_lua(&plan, source_label, udp_port)) +} + +fn emit_lua(plan: &Plan, source_label: &str, udp_port: Option) -> String { + let mut out = String::with_capacity(8192); + let proto_name = sanitise_proto_name(&plan.root_name); + + emit_header(&mut out, source_label, &plan.root_name, &proto_name); + emit_proto_fields(&mut out, plan, &proto_name); + emit_bit_helpers(&mut out); + emit_container_dissectors(&mut out, &plan.containers); + emit_dispatcher(&mut out, &plan.root, &plan.containers); + emit_registration(&mut out, &proto_name, udp_port); + + out +} + +fn emit_header(out: &mut String, source_label: &str, root_name: &str, proto_name: &str) { + let _ = writeln!( + out, + "-- Generated by `xtce wireshark` from {source_label} (root: {root_name})." + ); + let _ = writeln!( + out, + "-- Do not edit by hand; regenerate from the XTCE definition." + ); + let _ = writeln!(out, "--"); + let _ = writeln!(out, "-- Quick start:"); + let _ = writeln!(out, "-- xtce pcap telemetry.bin -o telemetry.pcap"); + let _ = writeln!( + out, + "-- wireshark -X lua_script:{proto_name}.lua telemetry.pcap\n" + ); + let _ = write!(out, "local proto = Proto(\"{proto_name}\", "); + write_lua_quoted(out, root_name); + let _ = writeln!(out, ")\n"); +} + +fn emit_proto_fields(out: &mut String, plan: &Plan, proto_name: &str) { + let _ = writeln!( + out, + "local f__container = ProtoField.string(\"{proto_name}.container\", \"Container\")" + ); + + let mut seen: BTreeSet<&str> = BTreeSet::new(); + let mut field_vars: Vec<(&str, bool)> = Vec::new(); + + for container in &plan.containers { + for field in &container.fields { + if !seen.insert(field.ident.as_str()) { + continue; + } + let kind = lua_proto_field_kind(&field.repr); + let _ = write!( + out, + "local f_{} = ProtoField.{kind}(\"{proto_name}.{}\", ", + field.ident, field.ident + ); + write_lua_quoted(out, &field.xtce_name); + if matches!(field.repr, Repr::Unsigned | Repr::Signed(_)) { + let _ = writeln!(out, ", base.DEC)"); + } else { + let _ = writeln!(out, ")"); + } + + let has_eng = field.calibration.is_some(); + if has_eng { + let _ = write!( + out, + "local f_{}_eng = ProtoField.double(\"{proto_name}.{}.eng\", ", + field.ident, field.ident + ); + write_lua_quoted(out, &field.xtce_name); + let _ = writeln!(out, ")"); + } + field_vars.push((field.ident.as_str(), has_eng)); + } + } + + let _ = writeln!(out, "\nproto.fields = {{"); + let _ = writeln!(out, " f__container,"); + for (ident, has_eng) in &field_vars { + let _ = writeln!(out, " f_{ident},"); + if *has_eng { + let _ = writeln!(out, " f_{ident}_eng,"); + } + } + let _ = writeln!(out, "}}\n"); +} + +const fn lua_proto_field_kind(repr: &Repr) -> &'static str { + match repr { + Repr::Unsigned => "uint64", + Repr::Signed(_) => "int64", + Repr::Float16 | Repr::Float32 | Repr::Float64 | Repr::Mil1750a => "double", + Repr::Bool => "bool", + Repr::Enumerated(_) | Repr::Text { .. } => "string", + Repr::Binary => "bytes", + } +} + +fn emit_bit_helpers(out: &mut String) { + out.push_str( + r"local function has_bits(tvbuf, bit_offset, bit_width) + return (bit_offset + bit_width) <= (tvbuf:len() * 8) +end + +local function byte_range(tvbuf, bit_offset, bit_width) + if bit_width == 0 then + return tvbuf:range(0, 0) + end + local start_byte = math.floor(bit_offset / 8) + local end_byte = math.floor((bit_offset + bit_width - 1) / 8) + return tvbuf:range(start_byte, end_byte - start_byte + 1) +end + +local function read_bits_uint(tvbuf, bit_offset, bit_width, swap_bytes) + local acc = 0 + for i = 0, bit_width - 1 do + local pos = bit_offset + i + local byte_idx = math.floor(pos / 8) + local bit_idx = 7 - (pos % 8) + local b = tvbuf:range(byte_idx, 1):uint() + local bit_val = math.floor(b / (2 ^ bit_idx)) % 2 + acc = acc * 2 + bit_val + end + if swap_bytes and bit_width >= 16 and (bit_width % 8 == 0) then + local nbytes = bit_width / 8 + local swapped = 0 + for _ = 1, nbytes do + swapped = swapped * 256 + (acc % 256) + acc = math.floor(acc / 256) + end + return swapped + end + return acc +end + +local function read_bits_int(tvbuf, bit_offset, bit_width, swap_bytes) + local raw = read_bits_uint(tvbuf, bit_offset, bit_width, swap_bytes) + local sign_bit = 2 ^ (bit_width - 1) + if raw >= sign_bit then + return raw - (2 ^ bit_width) + end + return raw +end + +", + ); +} + +fn emit_container_dissectors(out: &mut String, containers: &[ContainerPlan]) { + for container in containers { + let _ = writeln!( + out, + "local function dissect_{}(tvbuf, pinfo, subtree)", + container.type_ident + ); + let _ = write!(out, " pinfo.cols.info:set("); + write_lua_quoted(out, &container.xtce_name); + let _ = writeln!(out, ")"); + let _ = write!( + out, + " subtree:add(f__container, tvbuf:range(0, tvbuf:len()), " + ); + write_lua_quoted(out, &container.xtce_name); + let _ = writeln!(out, ")"); + + for field in &container.fields { + emit_field_dissection(out, field); + } + + let _ = writeln!(out, "end\n"); + } +} + +fn emit_field_dissection(out: &mut String, field: &Field) { + let Some((bit_offset, bit_width)) = field.static_span() else { + return; + }; + if bit_width == 0 { + return; + } + + let swap = if field.swap_bytes { "true" } else { "false" }; + let ident = &field.ident; + let _ = writeln!( + out, + " if has_bits(tvbuf, {bit_offset}, {bit_width}) then" + ); + let _ = writeln!( + out, + " local rng = byte_range(tvbuf, {bit_offset}, {bit_width})" + ); + + match &field.repr { + Repr::Unsigned => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, UInt64.new(raw))"); + emit_calibration(out, field); + } + Repr::Signed(IntegerCoding::TwosComplement) => { + let _ = writeln!( + out, + " local raw = read_bits_int(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, Int64.new(raw))"); + emit_calibration(out, field); + } + Repr::Signed(_) => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, Int64.new(raw))"); + emit_calibration(out, field); + } + Repr::Bool => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw ~= 0)"); + } + Repr::Enumerated(entries) => { + let _ = writeln!( + out, + " local raw = read_bits_int(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " local label = tostring(raw)"); + for (low, high, label) in entries { + if low == high { + let _ = write!(out, " if raw == {low} then label = "); + } else { + let _ = write!( + out, + " if raw >= {low} and raw <= {high} then label = " + ); + } + write_lua_quoted(out, label); + let _ = writeln!(out, " .. \" (\" .. tostring(raw) .. \")\" end"); + } + let _ = writeln!(out, " subtree:add(f_{ident}, rng, label)"); + } + Repr::Float32 | Repr::Float64 if bit_offset % 8 == 0 && !field.swap_bytes => { + let _ = writeln!(out, " local raw = rng:float()"); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw)"); + emit_calibration(out, field); + } + Repr::Float16 | Repr::Float32 | Repr::Float64 | Repr::Mil1750a => { + let _ = writeln!( + out, + " local raw = read_bits_uint(tvbuf, {bit_offset}, {bit_width}, {swap})" + ); + let _ = writeln!(out, " subtree:add(f_{ident}, rng, raw)"); + emit_calibration(out, field); + } + Repr::Text { .. } => { + let _ = writeln!(out, " subtree:add(f_{ident}, rng, rng:string())"); + } + Repr::Binary => { + let _ = writeln!(out, " subtree:add(f_{ident}, rng)"); + } + } + + let _ = writeln!(out, " end"); +} + +fn emit_calibration(out: &mut String, field: &Field) { + let Some(Calibration::Polynomial(terms)) = &field.calibration else { + return; + }; + if terms.is_empty() { + return; + } + let _ = write!(out, " local eng = 0.0"); + for term in terms { + let c = term.coefficient; + let e = term.exponent; + let _ = write!(out, " + ({c:?} * (raw ^ {e}))"); + } + let _ = writeln!(out); + let _ = writeln!(out, " subtree:add(f_{}_eng, rng, eng)", field.ident); +} + +fn emit_dispatcher(out: &mut String, root: &Node, containers: &[ContainerPlan]) { + let _ = writeln!(out, "local function dispatch(tvbuf, pinfo, subtree)"); + emit_node_dispatch(out, root, containers, 1); + let _ = writeln!(out, " return false"); + let _ = writeln!(out, "end\n"); +} + +fn emit_node_dispatch(out: &mut String, node: &Node, containers: &[ContainerPlan], depth: usize) { + for (criterion, child) in &node.children { + write_indent(out, depth); + let _ = write!(out, "if "); + emit_criterion_expr(out, criterion); + let _ = writeln!(out, " then"); + emit_node_dispatch(out, child, containers, depth + 1); + write_indent(out, depth); + let _ = writeln!(out, "end"); + } + + if !node.is_abstract { + if let Some(idx) = node.plan { + if let Some(plan) = containers.get(idx) { + write_indent(out, depth); + let _ = writeln!(out, "dissect_{}(tvbuf, pinfo, subtree)", plan.type_ident); + write_indent(out, depth); + let _ = writeln!(out, "return true"); + } + } + } +} + +fn emit_criterion_expr(out: &mut String, criterion: &Criterion) { + match criterion { + Criterion::Test(guard) => emit_guard_expr(out, guard), + Criterion::All(children) => { + if children.is_empty() { + out.push_str("true"); + return; + } + out.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + out.push_str(" and "); + } + emit_criterion_expr(out, child); + } + out.push(')'); + } + Criterion::Any(children) => { + if children.is_empty() { + out.push_str("false"); + return; + } + out.push('('); + for (idx, child) in children.iter().enumerate() { + if idx > 0 { + out.push_str(" or "); + } + emit_criterion_expr(out, child); + } + out.push(')'); + } + } +} + +fn emit_guard_expr(out: &mut String, guard: &Guard) { + let offset = guard.bit_offset; + let width = guard.bit_width; + let swap = if guard.swap_bytes { "true" } else { "false" }; + let reader = if matches!(guard.repr, Repr::Signed(_)) { + "read_bits_int" + } else { + "read_bits_uint" + }; + + let _ = write!(out, "(has_bits(tvbuf, {offset}, {width}) and "); + match &guard.test { + GuardTest::Value { operator, value } => { + let op = lua_compare_op(*operator); + let _ = write!( + out, + "({reader}(tvbuf, {offset}, {width}, {swap}) {op} {value}))" + ); + } + GuardTest::Labels { ranges, .. } => { + if ranges.is_empty() { + out.push_str("false)"); + return; + } + out.push('('); + for (idx, (low, high)) in ranges.iter().enumerate() { + if idx > 0 { + out.push_str(" or "); + } + if low == high { + let _ = write!(out, "({reader}(tvbuf, {offset}, {width}, {swap}) == {low})"); + } else { + let _ = write!( + out, + "({reader}(tvbuf, {offset}, {width}, {swap}) >= {low} and \ + {reader}(tvbuf, {offset}, {width}, {swap}) <= {high})" + ); + } + } + out.push_str("))"); + } + } +} + +const fn lua_compare_op(op: CompareOp) -> &'static str { + match op { + CompareOp::Equal => "==", + CompareOp::NotEqual => "~=", + CompareOp::Less => "<", + CompareOp::LessOrEqual => "<=", + CompareOp::Greater => ">", + CompareOp::GreaterOrEqual => ">=", + } +} + +fn emit_registration(out: &mut String, proto_name: &str, udp_port: Option) { + let _ = writeln!( + out, + "function proto.dissector(tvbuf, pinfo, root)\n \ + pinfo.cols.protocol:set(\"{proto_name}\")\n \ + local subtree = root:add(proto, tvbuf:range(0, tvbuf:len()))\n \ + if not dispatch(tvbuf, pinfo, subtree) then\n \ + pinfo.cols.info:set(\"Unrecognised XTCE packet\")\n \ + end\n\ + end\n" + ); + + let _ = writeln!( + out, + "local wtap_table = DissectorTable.get(\"wtap_encap\")\n\ + if wtap_table and wtap_encaps and wtap_encaps.USER0 then\n \ + wtap_table:add(wtap_encaps.USER0, proto)\n\ + end" + ); + + if let Some(port) = udp_port { + let _ = writeln!( + out, + "\nlocal udp_table = DissectorTable.get(\"udp.port\")\n\ + if udp_table then\n \ + udp_table:add({port}, proto)\n\ + end" + ); + } +} + +fn write_indent(out: &mut String, depth: usize) { + for _ in 0..depth { + out.push_str(" "); + } +} + +fn sanitise_proto_name(name: &str) -> String { + let mut out = String::with_capacity(5 + name.len()); + out.push_str("xtce_"); + for ch in name.chars() { + if ch.is_ascii_alphanumeric() { + out.push(ch.to_ascii_lowercase()); + } else { + out.push('_'); + } + } + out +} + +fn write_lua_quoted(out: &mut String, text: &str) { + out.push('"'); + for ch in text.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + c if c.is_control() => { + let _ = write!(out, "\\{:03}", c as u32); + } + c => out.push(c), + } + } + out.push('"'); +} + +/// Executes `xtce wireshark` using a pre-loaded [`XtceDb`]. +/// +/// # Errors +/// +/// Returns an error if dissector compilation or file output fails. +pub fn run_with_db(db: &XtceDb, options: &Options<'_>) -> Result<(), Box> { + let label = if options.definition.as_os_str() == "-" { + "" + } else { + options.definition.to_str().unwrap_or("") + }; + let lua = generate_lua(db, options.root, label, options.udp_port)?; + + match options.out { + Some(path) if path.as_os_str() != "-" => { + std::fs::write(path, lua)?; + eprintln!("wrote Wireshark dissector to {}", path.display()); + } + _ => print!("{lua}"), + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use xtce_model::XtceDb; + + use super::{generate_lua, write_lua_quoted}; + + const SAMPLE_XTCE: &str = r#" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +"#; + + #[test] + fn generates_lua_dissector_with_proto_fields_and_containers() { + let db = XtceDb::from_xml(SAMPLE_XTCE).expect("valid xml"); + let lua = generate_lua(&db, None, "cubesat.xml", Some(5005)).expect("generates lua"); + + assert!(lua.contains("local proto = Proto(\"xtce_ccsdspacket\", \"CCSDSPacket\")")); + assert!(lua.contains("ProtoField.uint64(\"xtce_ccsdspacket.apid\", \"APID\", base.DEC)")); + assert!(lua.contains("ProtoField.string(\"xtce_ccsdspacket.mode\", \"MODE\")")); + assert!(lua.contains("ProtoField.int64(\"xtce_ccsdspacket.temp\", \"TEMP\", base.DEC)")); + assert!(lua.contains("ProtoField.double(\"xtce_ccsdspacket.temp.eng\", \"TEMP\")")); + assert!(lua.contains("local function dissect_Hkpacket(tvbuf, pinfo, subtree)")); + assert!(lua.contains("(read_bits_uint(tvbuf, 0, 11, false) == 42)")); + assert!(lua.contains("if raw == 0 then label = \"SAFE\"")); + assert!(lua.contains("if raw == 1 then label = \"NOMINAL\"")); + assert!(lua.contains("wtap_table:add(wtap_encaps.USER0, proto)")); + assert!(lua.contains("udp_table:add(5005, proto)")); + } + + #[test] + fn omits_udp_registration_when_port_is_none() { + let db = XtceDb::from_xml(SAMPLE_XTCE).expect("valid xml"); + let lua = generate_lua(&db, None, "cubesat.xml", None).expect("generates lua"); + + assert!(lua.contains("wtap_table:add(wtap_encaps.USER0, proto)")); + assert!(!lua.contains("udp_table:add(")); + } + + #[test] + fn escapes_lua_strings_safely() { + let mut buf = String::new(); + write_lua_quoted(&mut buf, "a\"b\\c\nd"); + assert_eq!(buf, "\"a\\\"b\\\\c\\nd\""); + } +}