astrodynamics 0.14.0

Numerical astrodynamics engine for orbit propagation, force models, and flight-dynamics primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! CCSDS Conjunction Data Message (CDM) KVN and XML format reader and writer.
//!
//! CDM (CCSDS 508.0-B-1) describes a predicted close approach between two space
//! objects: the time of closest approach, miss geometry, collision probability,
//! and per-object state vectors with RTN position covariance. This module owns
//! the language-independent grammar for both serializations:
//!
//! - KVN (Keyword=Value Notation): line tokenization, the `KEY = VALUE [unit]`
//!   split, trailing-unit stripping, the `COMMENT HBR =` convention,
//!   object-block segmentation, the leading-float value parser, the
//!   state/covariance extraction, and the KVN line layout used on encode.
//! - XML: a real DOM parse via the `roxmltree` crate (which correctly handles
//!   the `<?xml?>` declaration, comments, namespaces, entity escaping, and
//!   encoding), then name-based leaf-element lookup over the document and the
//!   two `<segment>` subtrees for the same state/covariance extraction. Encoding
//!   emits the CCSDS document layout through a controlled serializer (see
//!   [`encode_xml`]).
//!
//! Both run identically regardless of the calling language, so they live in the
//! core.
//!
//! Date/time fields cross this boundary as raw strings: resolving `TCA` /
//! `CREATION_DATE` to a concrete instant (and formatting one back) is the host's
//! job using its native date/time type, exactly as the TLE epoch is handled. This
//! module deliberately does not depend on the time-scale machinery, and applies
//! no calendar validation; it only carries the textual value through.

use roxmltree::{Document, Node};
use std::fmt;

/// Keys of the six-component state vector, in CCSDS order (position then
/// velocity). Used to pull the state out of a parsed object block.
const STATE_KEYS: [&str; 6] = ["X", "Y", "Z", "X_DOT", "Y_DOT", "Z_DOT"];
/// Keys of the RTN position covariance lower triangle, in CCSDS order.
const COVARIANCE_KEYS: [&str; 6] = ["CR_R", "CT_R", "CT_T", "CN_R", "CN_T", "CN_N"];
/// Marker keyword whose value (`OBJECT1` / `OBJECT2`) opens an object block.
const OBJECT_MARKER: &str = "OBJECT";
/// Comment prefix: lines beginning with this are dropped before key/value
/// parsing (the embedded `COMMENT HBR =` value is recovered separately).
const COMMENT_PREFIX: &str = "COMMENT";
/// Missing covariance components default to zero variance.
const COVARIANCE_DEFAULT: f64 = 0.0;
/// Element name wrapping one object's metadata/data block in the CDM XML schema.
const SEGMENT_TAG: &str = "segment";

/// A two-object conjunction parsed from a CDM message (KVN or XML). Date/time
/// fields are the raw textual values; the host resolves them to its own instant
/// type.
#[derive(Debug, Clone, PartialEq)]
pub struct CdmKvn {
    pub creation_date: Option<String>,
    pub originator: Option<String>,
    pub message_id: Option<String>,
    pub tca: Option<String>,
    pub miss_distance_m: Option<f64>,
    pub relative_speed_m_s: Option<f64>,
    pub collision_probability: Option<f64>,
    pub collision_probability_method: Option<String>,
    pub hard_body_radius_m: Option<f64>,
    pub object1: CdmObject,
    pub object2: CdmObject,
}

/// One object's metadata, state vector, and RTN position covariance.
#[derive(Debug, Clone, PartialEq)]
pub struct CdmObject {
    pub object_designator: Option<String>,
    pub catalog_name: Option<String>,
    pub object_name: Option<String>,
    pub international_designator: Option<String>,
    pub object_type: Option<String>,
    pub ref_frame: Option<String>,
    /// Position `(x, y, z)` then velocity `(x_dot, y_dot, z_dot)`.
    pub state: ((f64, f64, f64), (f64, f64, f64)),
    /// RTN position covariance lower triangle: CR_R, CT_R, CT_T, CN_R, CN_T, CN_N.
    pub covariance_rtn: [f64; 6],
}

/// Failure modes of [`parse_kvn`]. The message strings are the historical public
/// contract surfaced by the Elixir binding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CdmError {
    /// An object block was missing one or more state-vector components.
    IncompleteStateVector,
    /// The XML reader was handed text that is not a well-formed XML document.
    MalformedXml(String),
}

impl fmt::Display for CdmError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CdmError::IncompleteStateVector => write!(f, "incomplete state vector"),
            CdmError::MalformedXml(detail) => write!(f, "malformed XML: {detail}"),
        }
    }
}

impl std::error::Error for CdmError {}

/// Parse a CDM in KVN format.
///
/// Tokenizes the message, recovers the header/relative-metadata fields, the
/// `COMMENT HBR =` hard-body radius, and the two object blocks. Date/time fields
/// are returned verbatim for the host to resolve; presence/format checks on them
/// (and on `MESSAGE_ID`) are the host's concern. An object block missing any
/// state component is rejected with [`CdmError::IncompleteStateVector`].
pub fn parse_kvn(text: &str) -> Result<CdmKvn, CdmError> {
    let lines = significant_lines(text);
    let kv = parse_kv_lines(&lines);

    let (object1_kv, object2_kv) = split_object_blocks(&lines);
    let object1 = parse_object(&object1_kv)?;
    let object2 = parse_object(&object2_kv)?;

    Ok(CdmKvn {
        creation_date: kv_get(&kv, "CREATION_DATE"),
        originator: kv_get(&kv, "ORIGINATOR"),
        message_id: kv_get(&kv, "MESSAGE_ID"),
        tca: kv_get(&kv, "TCA"),
        miss_distance_m: kv_num(&kv, "MISS_DISTANCE"),
        relative_speed_m_s: kv_num(&kv, "RELATIVE_SPEED"),
        collision_probability: kv_num(&kv, "COLLISION_PROBABILITY"),
        collision_probability_method: kv_get(&kv, "COLLISION_PROBABILITY_METHOD"),
        hard_body_radius_m: parse_hbr(text),
        object1,
        object2,
    })
}

/// Encode a [`CdmKvn`] back to KVN text.
///
/// The date/time fields are taken as already-formatted strings (the host owns
/// the instant-to-string conversion). Numeric values are written with their
/// shortest round-tripping decimal form, so a re-parse recovers the exact same
/// bits; the output is therefore round-trip faithful rather than byte-identical
/// to any one producer.
pub fn encode_kvn(cdm: &CdmKvn) -> String {
    let mut lines: Vec<String> = vec![
        "CCSDS_CDM_VERS = 1.0".to_string(),
        format!("CREATION_DATE = {}", opt_str(&cdm.creation_date)),
        format!("ORIGINATOR = {}", opt_str(&cdm.originator)),
        format!("MESSAGE_ID = {}", opt_str(&cdm.message_id)),
        format!("TCA = {}", opt_str(&cdm.tca)),
        format!("MISS_DISTANCE = {} [m]", opt_num(cdm.miss_distance_m)),
        format!("RELATIVE_SPEED = {} [m/s]", opt_num(cdm.relative_speed_m_s)),
        format!(
            "COLLISION_PROBABILITY = {}",
            opt_num(cdm.collision_probability)
        ),
        format!(
            "COLLISION_PROBABILITY_METHOD = {}",
            opt_str(&cdm.collision_probability_method)
        ),
    ];

    if let Some(hbr) = cdm.hard_body_radius_m {
        lines.push(format!("COMMENT HBR = {}", fmt_num(hbr)));
    }

    lines.extend(encode_object(&cdm.object1, "OBJECT1"));
    lines.extend(encode_object(&cdm.object2, "OBJECT2"));

    lines.join("\n")
}

/// Parse a CDM in XML format.
///
/// Parses the document with `roxmltree` (a real XML DOM reader: the `<?xml?>`
/// declaration, comments, namespaces, entity escaping, and encoding are handled
/// by the library, not by string scanning), then reads the header and
/// relative-metadata leaf elements by name from the document and the per-object
/// state/covariance from the two `<segment>` subtrees. The CCSDS CDM XML schema
/// is flat, so a name match uniquely identifies each value (extra sibling
/// elements such as `CRDOT_R` in a covariance block are ignored). Date/time
/// fields are returned verbatim for the host to resolve, matching [`parse_kvn`];
/// text that is not well-formed XML is rejected with [`CdmError::MalformedXml`]
/// and an object block missing any state component with
/// [`CdmError::IncompleteStateVector`].
pub fn parse_xml(text: &str) -> Result<CdmKvn, CdmError> {
    let doc = Document::parse(text).map_err(|e| CdmError::MalformedXml(e.to_string()))?;
    let root = doc.root();

    let mut segments = root
        .descendants()
        .filter(|n| n.is_element() && n.tag_name().name() == SEGMENT_TAG);
    let object1 = parse_xml_object(segments.next())?;
    let object2 = parse_xml_object(segments.next())?;

    Ok(CdmKvn {
        creation_date: node_text(root, "CREATION_DATE"),
        originator: node_text(root, "ORIGINATOR"),
        message_id: node_text(root, "MESSAGE_ID"),
        tca: node_text(root, "TCA"),
        miss_distance_m: node_num(root, "MISS_DISTANCE"),
        relative_speed_m_s: node_num(root, "RELATIVE_SPEED"),
        collision_probability: node_num(root, "COLLISION_PROBABILITY"),
        collision_probability_method: node_text(root, "COLLISION_PROBABILITY_METHOD"),
        hard_body_radius_m: node_num(root, "HBR"),
        object1,
        object2,
    })
}

/// Encode a [`CdmKvn`] to a CCSDS 508.0-B-1 CDM XML document.
///
/// The date/time fields are taken as already-formatted strings (the host owns
/// the instant-to-string conversion), and numeric values use the shortest
/// round-tripping decimal form, so the output is round-trip faithful rather than
/// byte-identical to any one producer. String values are XML-escaped.
///
/// This is a controlled straight-line serializer (no parsing, no tag scanning)
/// rather than a generic streaming-writer dependency: the output is a fixed,
/// documented CCSDS layout (`cdm > header/body > segment > metadata/data`) whose
/// element nesting and `units` attributes are the inter-system exchange contract,
/// and every interpolated value is escaped via [`xml_escape`]. The matching
/// reader is the vetted `roxmltree` DOM parser in [`parse_xml`].
pub fn encode_xml(cdm: &CdmKvn) -> String {
    let mut lines: Vec<String> = vec![
        r#"<?xml version="1.0" encoding="UTF-8"?>"#.to_string(),
        r#"<cdm id="CCSDS_CDM_VERS" version="1.0">"#.to_string(),
        "  <header>".to_string(),
        "    <CCSDS_CDM_VERS>1.0</CCSDS_CDM_VERS>".to_string(),
        format!(
            "    <CREATION_DATE>{}</CREATION_DATE>",
            opt_str(&cdm.creation_date)
        ),
        format!(
            "    <ORIGINATOR>{}</ORIGINATOR>",
            xml_escape_opt(&cdm.originator)
        ),
        format!(
            "    <MESSAGE_ID>{}</MESSAGE_ID>",
            xml_escape_opt(&cdm.message_id)
        ),
        "  </header>".to_string(),
        "  <body>".to_string(),
        "    <relativeMetadataData>".to_string(),
        format!("      <TCA>{}</TCA>", opt_str(&cdm.tca)),
        format!(
            r#"      <MISS_DISTANCE units="m">{}</MISS_DISTANCE>"#,
            opt_num(cdm.miss_distance_m)
        ),
        format!(
            r#"      <RELATIVE_SPEED units="m/s">{}</RELATIVE_SPEED>"#,
            opt_num(cdm.relative_speed_m_s)
        ),
        format!(
            "      <COLLISION_PROBABILITY>{}</COLLISION_PROBABILITY>",
            opt_num(cdm.collision_probability)
        ),
        format!(
            "      <COLLISION_PROBABILITY_METHOD>{}</COLLISION_PROBABILITY_METHOD>",
            xml_escape_opt(&cdm.collision_probability_method)
        ),
        "    </relativeMetadataData>".to_string(),
    ];

    lines.extend(encode_xml_segment(&cdm.object1, "OBJECT1"));
    lines.extend(encode_xml_segment(&cdm.object2, "OBJECT2"));
    lines.push("  </body>".to_string());
    lines.push("</cdm>".to_string());

    lines.join("\n")
}

// -- KVN tokenization --

/// Trim every line, then drop blanks and comment lines. Comment values that the
/// grammar needs (the HBR) are recovered from the raw text separately.
fn significant_lines(text: &str) -> Vec<String> {
    text.split('\n')
        .map(|line| line.trim().to_string())
        .filter(|line| !line.is_empty() && !line.starts_with(COMMENT_PREFIX))
        .collect()
}

/// Build the key/value map from `KEY = VALUE` lines. Later duplicates win, which
/// only matters for header keys repeated across object blocks (those are read per
/// block instead). The value has any trailing `[unit]` removed.
fn parse_kv_lines(lines: &[String]) -> Vec<(String, String)> {
    lines
        .iter()
        .filter_map(|line| {
            line.split_once('=').map(|(key, value)| {
                (
                    key.trim().to_string(),
                    strip_units(value.trim()).to_string(),
                )
            })
        })
        .collect()
}

/// Look up the last value for a key (matching the map-overwrite semantics).
fn kv_lookup<'a>(kv: &'a [(String, String)], key: &str) -> Option<&'a str> {
    kv.iter()
        .rev()
        .find(|(k, _)| k == key)
        .map(|(_, v)| v.as_str())
}

fn kv_get(kv: &[(String, String)], key: &str) -> Option<String> {
    kv_lookup(kv, key).map(str::to_string)
}

fn kv_num(kv: &[(String, String)], key: &str) -> Option<f64> {
    kv_lookup(kv, key).and_then(parse_num)
}

/// Remove a trailing bracketed unit (` [m]`, `[m**2/kg]`, ...) and surrounding
/// whitespace, leaving the bare value.
fn strip_units(value: &str) -> &str {
    let trimmed = value.trim_end();
    if let Some(open) = trimmed.rfind('[') {
        if trimmed.ends_with(']') {
            return trimmed[..open].trim_end();
        }
    }
    trimmed
}

/// Split the line stream into the two object blocks at the `OBJECT =` markers.
/// CDM always carries exactly two; if fewer are present the blocks are empty and
/// the state-vector check rejects the message.
fn split_object_blocks(lines: &[String]) -> (Vec<String>, Vec<String>) {
    let markers: Vec<usize> = lines
        .iter()
        .enumerate()
        .filter(|(_, line)| {
            line.split_once('=')
                .is_some_and(|(key, _)| key.trim() == OBJECT_MARKER)
        })
        .map(|(idx, _)| idx)
        .collect();

    match markers.as_slice() {
        [i1, i2, ..] => (lines[*i1..*i2].to_vec(), lines[*i2..].to_vec()),
        _ => (Vec::new(), Vec::new()),
    }
}

fn parse_object(lines: &[String]) -> Result<CdmObject, CdmError> {
    let kv = parse_kv_lines(lines);

    let mut state = [0.0_f64; 6];
    for (slot, key) in state.iter_mut().zip(STATE_KEYS) {
        match kv_num(&kv, key) {
            Some(value) => *slot = value,
            None => return Err(CdmError::IncompleteStateVector),
        }
    }

    let mut covariance_rtn = [COVARIANCE_DEFAULT; 6];
    for (slot, key) in covariance_rtn.iter_mut().zip(COVARIANCE_KEYS) {
        if let Some(value) = kv_num(&kv, key) {
            *slot = value;
        }
    }

    Ok(CdmObject {
        object_designator: kv_get(&kv, "OBJECT_DESIGNATOR"),
        catalog_name: kv_get(&kv, "CATALOG_NAME"),
        object_name: kv_get(&kv, "OBJECT_NAME"),
        international_designator: kv_get(&kv, "INTERNATIONAL_DESIGNATOR"),
        object_type: kv_get(&kv, "OBJECT_TYPE"),
        ref_frame: kv_get(&kv, "REF_FRAME"),
        state: (
            (state[0], state[1], state[2]),
            (state[3], state[4], state[5]),
        ),
        covariance_rtn,
    })
}

/// Recover the hard-body radius from a `COMMENT HBR = <value>` line (NASA CARA
/// convention). Scans the raw text case-insensitively, taking the leading
/// digits-and-dot run as the value.
fn parse_hbr(text: &str) -> Option<f64> {
    for line in text.split('\n') {
        let trimmed = line.trim();
        let mut rest = match strip_prefix_ci(trimmed, COMMENT_PREFIX) {
            Some(rest) if starts_with_ascii_ws(rest) => rest.trim_start(),
            _ => continue,
        };
        rest = match strip_prefix_ci(rest, "HBR") {
            Some(rest) => rest.trim_start(),
            None => continue,
        };
        let rest = match rest.strip_prefix('=') {
            Some(rest) => rest.trim_start(),
            None => continue,
        };
        let digits: String = rest
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '.')
            .collect();
        if let Some(value) = parse_num(&digits) {
            return Some(value);
        }
    }
    None
}

// -- KVN encoding --

fn encode_object(object: &CdmObject, name: &str) -> Vec<String> {
    let ((x, y, z), (xd, yd, zd)) = object.state;
    let [cr_r, ct_r, ct_t, cn_r, cn_t, cn_n] = object.covariance_rtn;

    vec![
        format!("OBJECT = {name}"),
        format!("OBJECT_DESIGNATOR = {}", opt_str(&object.object_designator)),
        format!("OBJECT_NAME = {}", opt_str(&object.object_name)),
        format!("REF_FRAME = {}", opt_str(&object.ref_frame)),
        format!("X = {} [km]", fmt_num(x)),
        format!("Y = {} [km]", fmt_num(y)),
        format!("Z = {} [km]", fmt_num(z)),
        format!("X_DOT = {} [km/s]", fmt_num(xd)),
        format!("Y_DOT = {} [km/s]", fmt_num(yd)),
        format!("Z_DOT = {} [km/s]", fmt_num(zd)),
        format!("CR_R = {} [m**2]", fmt_num(cr_r)),
        format!("CT_R = {} [m**2]", fmt_num(ct_r)),
        format!("CT_T = {} [m**2]", fmt_num(ct_t)),
        format!("CN_R = {} [m**2]", fmt_num(cn_r)),
        format!("CN_T = {} [m**2]", fmt_num(cn_t)),
        format!("CN_N = {} [m**2]", fmt_num(cn_n)),
    ]
}

// -- Value helpers --

/// Parse the leading float from a value string, returning `None` when no number
/// is present. Mirrors the binding's lenient numeric read.
fn parse_num(value: &str) -> Option<f64> {
    value.trim().parse::<f64>().ok()
}

/// Shortest round-tripping decimal for a finite value.
fn fmt_num(value: f64) -> String {
    format!("{value}")
}

fn opt_str(value: &Option<String>) -> String {
    value.clone().unwrap_or_default()
}

fn opt_num(value: Option<f64>) -> String {
    value.map(fmt_num).unwrap_or_default()
}

/// Case-insensitive ASCII prefix strip.
fn strip_prefix_ci<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
    if text.len() >= prefix.len() && text[..prefix.len()].eq_ignore_ascii_case(prefix) {
        Some(&text[prefix.len()..])
    } else {
        None
    }
}

fn starts_with_ascii_ws(text: &str) -> bool {
    text.chars().next().is_some_and(|c| c.is_ascii_whitespace())
}

// -- XML parsing --

/// First descendant element of `node` (document order) whose local tag name is
/// `tag`, returning its trimmed text. `None` if the element is absent, empty, or
/// self-closing. roxmltree decodes entities and ignores attributes, so the value
/// is the element's resolved text content.
fn node_text(node: Node, tag: &str) -> Option<String> {
    let element = node
        .descendants()
        .find(|n| n.is_element() && n.tag_name().name() == tag)?;
    let text = element.text()?.trim();
    if text.is_empty() {
        None
    } else {
        Some(text.to_string())
    }
}

/// Leaf-element value parsed as a leading float, or `None`.
fn node_num(node: Node, tag: &str) -> Option<f64> {
    node_text(node, tag).as_deref().and_then(parse_num)
}

/// Build one [`CdmObject`] from its `<segment>` subtree. A missing segment (fewer
/// than two present) or any missing state component is rejected with
/// [`CdmError::IncompleteStateVector`]; missing covariance components default to
/// zero variance.
fn parse_xml_object(segment: Option<Node>) -> Result<CdmObject, CdmError> {
    let segment = segment.ok_or(CdmError::IncompleteStateVector)?;

    let mut state = [0.0_f64; 6];
    for (slot, key) in state.iter_mut().zip(STATE_KEYS) {
        match node_num(segment, key) {
            Some(value) => *slot = value,
            None => return Err(CdmError::IncompleteStateVector),
        }
    }

    let mut covariance_rtn = [COVARIANCE_DEFAULT; 6];
    for (slot, key) in covariance_rtn.iter_mut().zip(COVARIANCE_KEYS) {
        if let Some(value) = node_num(segment, key) {
            *slot = value;
        }
    }

    Ok(CdmObject {
        object_designator: node_text(segment, "OBJECT_DESIGNATOR"),
        catalog_name: node_text(segment, "CATALOG_NAME"),
        object_name: node_text(segment, "OBJECT_NAME"),
        international_designator: node_text(segment, "INTERNATIONAL_DESIGNATOR"),
        object_type: node_text(segment, "OBJECT_TYPE"),
        ref_frame: node_text(segment, "REF_FRAME"),
        state: (
            (state[0], state[1], state[2]),
            (state[3], state[4], state[5]),
        ),
        covariance_rtn,
    })
}

// -- XML encoding --

fn encode_xml_segment(object: &CdmObject, name: &str) -> Vec<String> {
    let ((x, y, z), (xd, yd, zd)) = object.state;
    let [cr_r, ct_r, ct_t, cn_r, cn_t, cn_n] = object.covariance_rtn;

    vec![
        "    <segment>".to_string(),
        "      <metadata>".to_string(),
        format!("        <OBJECT>{name}</OBJECT>"),
        format!(
            "        <OBJECT_DESIGNATOR>{}</OBJECT_DESIGNATOR>",
            xml_escape_opt(&object.object_designator)
        ),
        format!(
            "        <OBJECT_NAME>{}</OBJECT_NAME>",
            xml_escape_opt(&object.object_name)
        ),
        format!(
            "        <REF_FRAME>{}</REF_FRAME>",
            xml_escape_opt(&object.ref_frame)
        ),
        "      </metadata>".to_string(),
        "      <data>".to_string(),
        "        <stateVector>".to_string(),
        format!(r#"          <X units="km">{}</X>"#, fmt_num(x)),
        format!(r#"          <Y units="km">{}</Y>"#, fmt_num(y)),
        format!(r#"          <Z units="km">{}</Z>"#, fmt_num(z)),
        format!(r#"          <X_DOT units="km/s">{}</X_DOT>"#, fmt_num(xd)),
        format!(r#"          <Y_DOT units="km/s">{}</Y_DOT>"#, fmt_num(yd)),
        format!(r#"          <Z_DOT units="km/s">{}</Z_DOT>"#, fmt_num(zd)),
        "        </stateVector>".to_string(),
        "        <covarianceMatrix>".to_string(),
        format!(r#"          <CR_R units="m**2">{}</CR_R>"#, fmt_num(cr_r)),
        format!(r#"          <CT_R units="m**2">{}</CT_R>"#, fmt_num(ct_r)),
        format!(r#"          <CT_T units="m**2">{}</CT_T>"#, fmt_num(ct_t)),
        format!(r#"          <CN_R units="m**2">{}</CN_R>"#, fmt_num(cn_r)),
        format!(r#"          <CN_T units="m**2">{}</CN_T>"#, fmt_num(cn_t)),
        format!(r#"          <CN_N units="m**2">{}</CN_N>"#, fmt_num(cn_n)),
        "        </covarianceMatrix>".to_string(),
        "      </data>".to_string(),
        "    </segment>".to_string(),
    ]
}

/// Escape the five XML predefined entities, in the historical replacement order.
fn xml_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

fn xml_escape_opt(value: &Option<String>) -> String {
    value.as_deref().map(xml_escape).unwrap_or_default()
}

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

    #[test]
    fn strip_units_removes_trailing_bracket() {
        assert_eq!(strip_units("7000.0 [km]"), "7000.0");
        assert_eq!(strip_units("4.835E-05"), "4.835E-05");
        assert_eq!(strip_units("0.045663 [m**2/kg]"), "0.045663");
        assert_eq!(strip_units("97.8 [%]"), "97.8");
    }

    #[test]
    fn parse_num_handles_integers_signs_and_exponents() {
        assert_eq!(parse_num("715"), Some(715.0));
        assert_eq!(parse_num("-8.579E+00"), Some(-8.579));
        assert_eq!(parse_num("4.835E-05"), Some(4.835e-5));
        assert_eq!(parse_num("not a number"), None);
    }

    #[test]
    fn incomplete_state_vector_is_rejected() {
        let kvn = "OBJECT = OBJECT1\nX = 7000.0 [km]\nOBJECT = OBJECT2\nX = 1.0 [km]\n";
        assert_eq!(parse_kvn(kvn), Err(CdmError::IncompleteStateVector));
    }

    #[test]
    fn hbr_is_recovered_from_comment_only() {
        let with_hbr = "COMMENT HBR = 15.5\n";
        assert_eq!(parse_hbr(with_hbr), Some(15.5));
        assert_eq!(parse_hbr("COMMENT Relative Metadata/Data\n"), None);
    }

    #[test]
    fn node_text_reads_leaf_value_ignoring_attrs() {
        let doc = Document::parse(
            r#"<r><MESSAGE_ID>abc123</MESSAGE_ID><X units="km">2570.097065</X><ORIGINATOR></ORIGINATOR></r>"#,
        )
        .unwrap();
        let root = doc.root();
        assert_eq!(node_text(root, "MESSAGE_ID").as_deref(), Some("abc123"));
        // The `units` attribute is ignored; the element text is returned.
        assert_eq!(node_text(root, "X").as_deref(), Some("2570.097065"));
        // An empty leaf element yields None.
        assert_eq!(node_text(root, "ORIGINATOR"), None);

        // A distinct element name sharing a prefix must not match.
        let only_xdot = Document::parse(r#"<r><X_DOT units="km/s">4.4</X_DOT></r>"#).unwrap();
        assert_eq!(node_text(only_xdot.root(), "X"), None);
    }

    #[test]
    fn xml_parse_decodes_entities_and_ignores_extra_covariance_element() {
        let xml = r#"<cdm><body>
<segment><metadata><OBJECT_NAME>SAT A &amp; B</OBJECT_NAME></metadata>
<data><stateVector>
<X units="km">1.0</X><Y units="km">2.0</Y><Z units="km">3.0</Z>
<X_DOT units="km/s">0.1</X_DOT><Y_DOT units="km/s">0.2</Y_DOT><Z_DOT units="km/s">0.3</Z_DOT>
</stateVector><covarianceMatrix>
<CR_R units="m**2">41.42</CR_R><CT_R units="m**2">-8.579</CT_R><CT_T units="m**2">2533.0</CT_T>
<CN_R units="m**2">-23.13</CN_R><CN_T units="m**2">13.36</CN_T><CN_N units="m**2">70.98</CN_N>
<CRDOT_R units="m**2/s">2.52e-3</CRDOT_R>
</covarianceMatrix></data></segment>
<segment><data><stateVector>
<X units="km">4.0</X><Y units="km">5.0</Y><Z units="km">6.0</Z>
<X_DOT units="km/s">0.4</X_DOT><Y_DOT units="km/s">0.5</Y_DOT><Z_DOT units="km/s">0.6</Z_DOT>
</stateVector></data></segment>
</body></cdm>"#;
        let cdm = parse_xml(xml).unwrap();
        // The DOM reader decodes the `&amp;` entity.
        assert_eq!(cdm.object1.object_name.as_deref(), Some("SAT A & B"));
        // The trailing CRDOT_R element is not one of the six RTN keys, so the
        // covariance is exactly the six lower-triangle components.
        assert_eq!(
            cdm.object1.covariance_rtn,
            [41.42, -8.579, 2533.0, -23.13, 13.36, 70.98]
        );
    }

    #[test]
    fn xml_incomplete_state_vector_is_rejected() {
        let xml = "<cdm><body>\
<segment><data><stateVector><X units=\"km\">1.0</X></stateVector></data></segment>\
<segment><data><stateVector></stateVector></data></segment>\
</body></cdm>";
        assert_eq!(parse_xml(xml), Err(CdmError::IncompleteStateVector));
    }

    #[test]
    fn xml_malformed_document_is_rejected() {
        // Two root elements is not well-formed XML; the DOM reader rejects it
        // rather than silently scanning past the structure.
        assert!(matches!(
            parse_xml("<segment></segment><segment></segment>"),
            Err(CdmError::MalformedXml(_))
        ));
    }

    #[test]
    fn xml_round_trips_through_encode_and_parse() {
        let object = CdmObject {
            object_designator: Some("12345".to_string()),
            catalog_name: None,
            object_name: Some("SAT A & B".to_string()),
            international_designator: None,
            object_type: None,
            ref_frame: Some("EME2000".to_string()),
            state: ((1.5, 2.5, 3.5), (0.1, 0.2, 0.3)),
            covariance_rtn: [41.42, -8.579, 2533.0, -23.13, 13.36, 70.98],
        };
        let original = CdmKvn {
            creation_date: Some("2024-01-01T00:00:00.000".to_string()),
            originator: Some("TEST".to_string()),
            message_id: Some("ID-1".to_string()),
            tca: Some("2024-01-01T12:00:00.000".to_string()),
            miss_distance_m: Some(715.0),
            relative_speed_m_s: Some(14762.0),
            collision_probability: Some(4.835e-5),
            collision_probability_method: Some("FOSTER-1992".to_string()),
            hard_body_radius_m: None,
            object1: object.clone(),
            object2: object,
        };

        let encoded = encode_xml(&original);
        assert!(encoded.starts_with("<?xml"));
        // The ampersand in the object name must be escaped on encode.
        assert!(encoded.contains("SAT A &amp; B"));

        let reparsed = parse_xml(&encoded).unwrap();
        assert_eq!(reparsed.object1.state, original.object1.state);
        assert_eq!(
            reparsed.object2.covariance_rtn,
            original.object2.covariance_rtn
        );
        assert_eq!(reparsed.miss_distance_m, original.miss_distance_m);
        assert_eq!(
            reparsed.collision_probability,
            original.collision_probability
        );
        assert_eq!(reparsed.message_id, original.message_id);
        assert_eq!(reparsed.tca, original.tca);
    }
}