Skip to main content

uas_cot/mavlink_m/
dialect.rs

1//! MAVLink XML dialect definitions: messages, enums and the MAVLink 2 wire
2//! layout (field order, offsets, `CRC_EXTRA`) computed from them.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::path::Path;
7
8/// A field's primitive type.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum FieldType {
11    /// `char`
12    Char,
13    /// `uint8_t` (and `uint8_t_mavlink_version`)
14    U8,
15    /// `int8_t`
16    I8,
17    /// `uint16_t`
18    U16,
19    /// `int16_t`
20    I16,
21    /// `uint32_t`
22    U32,
23    /// `int32_t`
24    I32,
25    /// `float`
26    F32,
27    /// `uint64_t`
28    U64,
29    /// `int64_t`
30    I64,
31    /// `double`
32    F64,
33}
34
35impl FieldType {
36    /// Parses a MAVLink XML primitive type name (without the array suffix).
37    pub fn parse(s: &str) -> Option<Self> {
38        Some(match s {
39            "char" => FieldType::Char,
40            "uint8_t" | "uint8_t_mavlink_version" => FieldType::U8,
41            "int8_t" => FieldType::I8,
42            "uint16_t" => FieldType::U16,
43            "int16_t" => FieldType::I16,
44            "uint32_t" => FieldType::U32,
45            "int32_t" => FieldType::I32,
46            "float" => FieldType::F32,
47            "uint64_t" => FieldType::U64,
48            "int64_t" => FieldType::I64,
49            "double" => FieldType::F64,
50            _ => return None,
51        })
52    }
53
54    /// Size of one element on the wire, in bytes.
55    pub fn size(self) -> usize {
56        match self {
57            FieldType::Char | FieldType::U8 | FieldType::I8 => 1,
58            FieldType::U16 | FieldType::I16 => 2,
59            FieldType::U32 | FieldType::I32 | FieldType::F32 => 4,
60            FieldType::U64 | FieldType::I64 | FieldType::F64 => 8,
61        }
62    }
63
64    /// The type name that goes into the `CRC_EXTRA` computation.
65    pub fn crc_name(self) -> &'static str {
66        match self {
67            FieldType::Char => "char",
68            FieldType::U8 => "uint8_t",
69            FieldType::I8 => "int8_t",
70            FieldType::U16 => "uint16_t",
71            FieldType::I16 => "int16_t",
72            FieldType::U32 => "uint32_t",
73            FieldType::I32 => "int32_t",
74            FieldType::F32 => "float",
75            FieldType::U64 => "uint64_t",
76            FieldType::I64 => "int64_t",
77            FieldType::F64 => "double",
78        }
79    }
80}
81
82/// A message field, with its position in the MAVLink 2 payload.
83#[derive(Clone, Debug, PartialEq)]
84pub struct Field {
85    /// Field name.
86    pub name: String,
87    /// Element type.
88    pub ty: FieldType,
89    /// Array length, or `None` for a scalar.
90    pub array_len: Option<usize>,
91    /// Enum that constrains the value, if any.
92    pub enum_name: Option<String>,
93    /// `units` attribute, if any.
94    pub units: Option<String>,
95    /// True for fields after `<extensions/>`.
96    pub extension: bool,
97    /// Byte offset in the payload.
98    pub offset: usize,
99    /// Field description text.
100    pub description: String,
101}
102
103impl Field {
104    /// Size on the wire, in bytes.
105    pub fn size(&self) -> usize {
106        self.ty.size() * self.array_len.unwrap_or(1)
107    }
108}
109
110/// A message definition.
111#[derive(Clone, Debug, PartialEq)]
112pub struct Message {
113    /// Message id.
114    pub id: u32,
115    /// Message name, for example `PARTICIPANT_POSITION`.
116    pub name: String,
117    /// Description text.
118    pub description: String,
119    /// Fields in wire order: base fields sorted by element size (largest
120    /// first, stable), then extension fields in XML order.
121    pub fields: Vec<Field>,
122    /// `CRC_EXTRA` seed byte.
123    pub crc_extra: u8,
124    /// Payload length without extensions (the MAVLink 1 length).
125    pub base_len: usize,
126    /// Payload length with extensions.
127    pub max_len: usize,
128}
129
130impl Message {
131    /// The field called `name`.
132    pub fn field(&self, name: &str) -> Option<&Field> {
133        self.fields.iter().find(|f| f.name == name)
134    }
135
136    /// True if this message is out of scope (target, track, handover,
137    /// fires, munition, arming, weapon, engagement or payload, see
138    /// [`super::scope`]). Its fields are never decoded or encoded.
139    pub fn is_blocked(&self) -> bool {
140        super::scope::is_blocked(self.id, &self.name)
141    }
142
143    /// Decodes field `name` from `payload`. MAVLink 2 trims trailing zero
144    /// bytes, so missing bytes read as zero. `None` for a blocked message
145    /// ([`Message::is_blocked`]).
146    pub fn get(&self, payload: &[u8], name: &str) -> Option<Value> {
147        if self.is_blocked() {
148            return None;
149        }
150        self.field(name).map(|f| decode_field(f, payload))
151    }
152
153    /// Decodes every field, in wire order. Empty for a blocked message
154    /// ([`Message::is_blocked`]).
155    pub fn decode(&self, payload: &[u8]) -> Vec<(&Field, Value)> {
156        if self.is_blocked() {
157            return Vec::new();
158        }
159        self.fields
160            .iter()
161            .map(|f| (f, decode_field(f, payload)))
162            .collect()
163    }
164
165    /// Encodes `values` (by field name) into a full-length payload; fields
166    /// not given are zero. Unknown names and wrong value kinds are errors,
167    /// and so is a blocked message ([`Message::is_blocked`]).
168    pub fn encode(&self, values: &[(&str, Value)]) -> Result<Vec<u8>, Error> {
169        if self.is_blocked() {
170            return Err(Error(format!(
171                "{} is out of scope (targeting or engagement) and is not encoded",
172                self.name
173            )));
174        }
175        let mut out = vec![0u8; self.max_len];
176        for (name, v) in values {
177            let f = self
178                .field(name)
179                .ok_or_else(|| Error(format!("{} has no field {name}", self.name)))?;
180            encode_field(f, v, &mut out[f.offset..f.offset + f.size()])
181                .map_err(|e| Error(format!("{}.{name}: {e}", self.name)))?;
182        }
183        Ok(out)
184    }
185}
186
187/// An enum entry.
188#[derive(Clone, Debug, PartialEq, Eq)]
189pub struct Entry {
190    /// Entry name.
191    pub name: String,
192    /// Entry value.
193    pub value: u64,
194}
195
196/// An enum definition.
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct Enum {
199    /// Enum name.
200    pub name: String,
201    /// True if `bitmask="true"`.
202    pub bitmask: bool,
203    /// Entries in XML order (entries from included files first).
204    pub entries: Vec<Entry>,
205    /// Description text.
206    pub description: String,
207}
208
209impl Enum {
210    /// The entry with `value`.
211    pub fn entry(&self, value: u64) -> Option<&Entry> {
212        self.entries.iter().find(|e| e.value == value)
213    }
214
215    /// OR of every entry value (for bitmask enums).
216    pub fn all_bits(&self) -> u64 {
217        self.entries.iter().fold(0, |a, e| a | e.value)
218    }
219
220    /// Smallest Hamming distance between two of the entries, if there are
221    /// at least two. The MAVLink-M safety-critical enums keep this at 4 or
222    /// more so that 1 to 3 flipped bits never produce another valid value.
223    pub fn min_hamming_distance(&self) -> Option<u32> {
224        let mut best = None::<u32>;
225        for (i, a) in self.entries.iter().enumerate() {
226            for b in &self.entries[i + 1..] {
227                let d = (a.value ^ b.value).count_ones();
228                best = Some(best.map_or(d, |x| x.min(d)));
229            }
230        }
231        best
232    }
233
234    /// A readable label for `value`: the entry name without the enum's
235    /// prefix, lower case with spaces (`MAVLINK_M_TARGET_FORCE_FOE` gives
236    /// `foe`). `None` if the value is not defined.
237    pub fn label(&self, value: u64) -> Option<String> {
238        let e = self.entry(value)?;
239        let own = format!("{}_", self.name);
240        let prefix = if self.entries.iter().all(|x| x.name.starts_with(&own)) {
241            own
242        } else {
243            self.common_prefix()
244        };
245        let short = e.name.strip_prefix(&prefix).unwrap_or(&e.name);
246        let short = if short.is_empty() { &e.name } else { short };
247        Some(short.to_ascii_lowercase().replace('_', " "))
248    }
249
250    /// Longest `_`-terminated prefix shared by every entry name (empty if
251    /// there are fewer than two entries).
252    fn common_prefix(&self) -> String {
253        if self.entries.len() < 2 {
254            return String::new();
255        }
256        let first = &self.entries[0].name;
257        let mut n = first.len();
258        for x in &self.entries[1..] {
259            n = n.min(
260                first
261                    .bytes()
262                    .zip(x.name.bytes())
263                    .take_while(|(a, b)| a == b)
264                    .count(),
265            );
266        }
267        match first[..n].rfind('_') {
268            Some(i) => first[..=i].to_string(),
269            None => String::new(),
270        }
271    }
272}
273
274/// A decoded field value.
275#[derive(Clone, Debug, PartialEq)]
276pub enum Value {
277    /// Unsigned integer.
278    Uint(u64),
279    /// Signed integer.
280    Int(i64),
281    /// Floating point.
282    Float(f64),
283    /// `char[N]`, cut at the first NUL. Invalid UTF-8 is replaced.
284    Text(String),
285    /// Numeric array.
286    Array(Vec<Value>),
287}
288
289impl Value {
290    /// The value as `u64` (integers only; negative values give `None`).
291    pub fn as_u64(&self) -> Option<u64> {
292        match *self {
293            Value::Uint(v) => Some(v),
294            Value::Int(v) => u64::try_from(v).ok(),
295            _ => None,
296        }
297    }
298
299    /// The value as `i64` (integers only).
300    pub fn as_i64(&self) -> Option<i64> {
301        match *self {
302            Value::Uint(v) => i64::try_from(v).ok(),
303            Value::Int(v) => Some(v),
304            _ => None,
305        }
306    }
307
308    /// The value as `f64` (any number).
309    pub fn as_f64(&self) -> Option<f64> {
310        match *self {
311            Value::Uint(v) => Some(v as f64),
312            Value::Int(v) => Some(v as f64),
313            Value::Float(v) => Some(v),
314            _ => None,
315        }
316    }
317
318    /// The text of a `char[N]` field.
319    pub fn as_str(&self) -> Option<&str> {
320        match self {
321            Value::Text(s) => Some(s),
322            _ => None,
323        }
324    }
325
326    /// A `uint8_t[N]` array as bytes.
327    pub fn as_bytes(&self) -> Option<Vec<u8>> {
328        match self {
329            Value::Array(v) => v
330                .iter()
331                .map(|x| x.as_u64().and_then(|b| u8::try_from(b).ok()))
332                .collect(),
333            _ => None,
334        }
335    }
336}
337
338fn read_scalar(ty: FieldType, b: &[u8]) -> Value {
339    let mut a = [0u8; 8];
340    a[..b.len()].copy_from_slice(b);
341    match ty {
342        FieldType::Char | FieldType::U8 => Value::Uint(a[0] as u64),
343        FieldType::I8 => Value::Int(a[0] as i8 as i64),
344        FieldType::U16 => Value::Uint(u16::from_le_bytes([a[0], a[1]]) as u64),
345        FieldType::I16 => Value::Int(i16::from_le_bytes([a[0], a[1]]) as i64),
346        FieldType::U32 => Value::Uint(u32::from_le_bytes([a[0], a[1], a[2], a[3]]) as u64),
347        FieldType::I32 => Value::Int(i32::from_le_bytes([a[0], a[1], a[2], a[3]]) as i64),
348        FieldType::F32 => Value::Float(f32::from_le_bytes([a[0], a[1], a[2], a[3]]) as f64),
349        FieldType::U64 => Value::Uint(u64::from_le_bytes(a)),
350        FieldType::I64 => Value::Int(i64::from_le_bytes(a)),
351        FieldType::F64 => Value::Float(f64::from_le_bytes(a)),
352    }
353}
354
355/// Decodes one field; bytes past the end of `payload` read as zero.
356pub fn decode_field(f: &Field, payload: &[u8]) -> Value {
357    let mut buf = vec![0u8; f.size()];
358    if f.offset < payload.len() {
359        let n = (payload.len() - f.offset).min(buf.len());
360        buf[..n].copy_from_slice(&payload[f.offset..f.offset + n]);
361    }
362    let es = f.ty.size();
363    match (f.ty, f.array_len) {
364        (FieldType::Char, Some(_)) => {
365            let end = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
366            Value::Text(String::from_utf8_lossy(&buf[..end]).into_owned())
367        }
368        (ty, Some(n)) => Value::Array(
369            (0..n)
370                .map(|i| read_scalar(ty, &buf[i * es..(i + 1) * es]))
371                .collect(),
372        ),
373        (ty, None) => read_scalar(ty, &buf),
374    }
375}
376
377fn encode_scalar(ty: FieldType, v: &Value, out: &mut [u8]) -> Result<(), String> {
378    let int = || {
379        v.as_i64()
380            .or_else(|| v.as_u64().map(|u| u as i64))
381            .ok_or_else(|| format!("expected an integer, got {v:?}"))
382    };
383    let float = || {
384        v.as_f64()
385            .ok_or_else(|| format!("expected a number, got {v:?}"))
386    };
387    match ty {
388        FieldType::Char | FieldType::U8 | FieldType::I8 => out[0] = int()? as u8,
389        FieldType::U16 | FieldType::I16 => out.copy_from_slice(&(int()? as u16).to_le_bytes()),
390        FieldType::U32 | FieldType::I32 => out.copy_from_slice(&(int()? as u32).to_le_bytes()),
391        FieldType::U64 => out.copy_from_slice(
392            &v.as_u64()
393                .ok_or_else(|| format!("expected an unsigned integer, got {v:?}"))?
394                .to_le_bytes(),
395        ),
396        FieldType::I64 => out.copy_from_slice(&int()?.to_le_bytes()),
397        FieldType::F32 => out.copy_from_slice(&(float()? as f32).to_le_bytes()),
398        FieldType::F64 => out.copy_from_slice(&float()?.to_le_bytes()),
399    }
400    Ok(())
401}
402
403fn encode_field(f: &Field, v: &Value, out: &mut [u8]) -> Result<(), String> {
404    let es = f.ty.size();
405    match (f.ty, f.array_len, v) {
406        (FieldType::Char, Some(n), Value::Text(s)) => {
407            if s.len() > n {
408                return Err(format!("text longer than {n} bytes"));
409            }
410            out[..s.len()].copy_from_slice(s.as_bytes());
411            Ok(())
412        }
413        (_, Some(n), Value::Array(items)) => {
414            if items.len() > n {
415                return Err(format!("more than {n} elements"));
416            }
417            for (i, it) in items.iter().enumerate() {
418                encode_scalar(f.ty, it, &mut out[i * es..(i + 1) * es])?;
419            }
420            Ok(())
421        }
422        (_, Some(_), _) => Err(format!("array field needs an array value, got {v:?}")),
423        (_, None, _) => encode_scalar(f.ty, v, out),
424    }
425}
426
427/// A dialect: its messages and enums, including those of the files it
428/// includes when it was loaded with [`Dialect::from_file`].
429#[derive(Clone, Debug, Default, PartialEq)]
430pub struct Dialect {
431    /// Dialect name (the file stem, or `"military"` for the embedded copy).
432    pub name: String,
433    /// Messages by id.
434    pub messages: BTreeMap<u32, Message>,
435    /// Enums by name.
436    pub enums: BTreeMap<String, Enum>,
437    /// `<include>` file names that were not loaded.
438    pub unresolved_includes: Vec<String>,
439}
440
441/// A dialect loading or encoding error.
442#[derive(Clone, Debug, PartialEq, Eq)]
443pub struct Error(pub String);
444
445impl fmt::Display for Error {
446    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
447        f.write_str(&self.0)
448    }
449}
450
451impl std::error::Error for Error {}
452
453/// Parses an enum entry value: decimal, `0x` hex, `0b` binary or `2**n`.
454fn parse_value(s: &str) -> Option<u64> {
455    let s = s.trim();
456    if let Some(h) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
457        u64::from_str_radix(h, 16).ok()
458    } else if let Some(b) = s.strip_prefix("0b").or_else(|| s.strip_prefix("0B")) {
459        u64::from_str_radix(b, 2).ok()
460    } else if let Some(p) = s.strip_prefix("2**") {
461        p.parse::<u32>().ok().and_then(|p| 1u64.checked_shl(p))
462    } else {
463        s.parse().ok()
464    }
465}
466
467fn text_of(n: roxmltree::Node<'_, '_>) -> String {
468    n.text()
469        .unwrap_or("")
470        .split_whitespace()
471        .collect::<Vec<_>>()
472        .join(" ")
473}
474
475fn child_text(n: roxmltree::Node<'_, '_>, tag: &str) -> String {
476    n.children()
477        .find(|c| c.has_tag_name(tag))
478        .map(text_of)
479        .unwrap_or_default()
480}
481
482/// MAVLink's CRC-16/MCRF4XX step.
483pub fn crc_accumulate(byte: u8, crc: u16) -> u16 {
484    let mut tmp = byte ^ (crc & 0xff) as u8;
485    tmp ^= tmp << 4;
486    let t = tmp as u16;
487    (crc >> 8) ^ (t << 8) ^ (t << 3) ^ (t >> 4)
488}
489
490fn crc_str(s: &str, mut crc: u16) -> u16 {
491    for b in s.bytes() {
492        crc = crc_accumulate(b, crc);
493    }
494    crc
495}
496
497/// Lays out a message: wire order, offsets, lengths and `CRC_EXTRA`.
498pub fn layout(id: u32, name: &str, description: &str, xml_fields: Vec<Field>) -> Message {
499    let (mut base, ext): (Vec<Field>, Vec<Field>) =
500        xml_fields.into_iter().partition(|f| !f.extension);
501    // stable sort, largest element first
502    base.sort_by_key(|f| std::cmp::Reverse(f.ty.size()));
503    let mut crc = crc_str(&format!("{name} "), 0xFFFF);
504    for f in &base {
505        crc = crc_str(&format!("{} ", f.ty.crc_name()), crc);
506        crc = crc_str(&format!("{} ", f.name), crc);
507        if let Some(n) = f.array_len {
508            crc = crc_accumulate(n as u8, crc);
509        }
510    }
511    let crc_extra = ((crc & 0xFF) ^ (crc >> 8)) as u8;
512    let mut fields = base;
513    fields.extend(ext);
514    let mut off = 0;
515    let mut base_len = 0;
516    for f in &mut fields {
517        f.offset = off;
518        off += f.size();
519        if !f.extension {
520            base_len = off;
521        }
522    }
523    Message {
524        id,
525        name: name.to_string(),
526        description: description.to_string(),
527        fields,
528        crc_extra,
529        base_len,
530        max_len: off,
531    }
532}
533
534impl Dialect {
535    /// Parses one dialect XML document. `<include>` elements are listed in
536    /// `unresolved_includes`, not loaded; use [`Dialect::from_file`] for that.
537    pub fn parse(name: &str, xml: &str) -> Result<Self, Error> {
538        let doc = roxmltree::Document::parse(xml).map_err(|e| Error(format!("{name}: {e}")))?;
539        let root = doc.root_element();
540        if !root.has_tag_name("mavlink") {
541            return Err(Error(format!("{name}: root element is not <mavlink>")));
542        }
543        let mut d = Dialect {
544            name: name.to_string(),
545            ..Default::default()
546        };
547        for n in root.children().filter(|n| n.is_element()) {
548            match n.tag_name().name() {
549                "include" => d.unresolved_includes.push(text_of(n)),
550                "enums" => {
551                    for e in n.children().filter(|c| c.has_tag_name("enum")) {
552                        d.add_enum(name, e)?;
553                    }
554                }
555                "messages" => {
556                    for m in n.children().filter(|c| c.has_tag_name("message")) {
557                        let msg = parse_message(name, m)?;
558                        d.messages.insert(msg.id, msg);
559                    }
560                }
561                _ => {}
562            }
563        }
564        Ok(d)
565    }
566
567    fn add_enum(&mut self, file: &str, e: roxmltree::Node<'_, '_>) -> Result<(), Error> {
568        let ename = e
569            .attribute("name")
570            .ok_or_else(|| Error(format!("{file}: enum without a name")))?;
571        let mut entries = Vec::new();
572        for en in e.children().filter(|c| c.has_tag_name("entry")) {
573            let n = en.attribute("name").unwrap_or("").to_string();
574            let v = en
575                .attribute("value")
576                .and_then(parse_value)
577                .ok_or_else(|| Error(format!("{file}: {ename}.{n}: missing or bad value")))?;
578            entries.push(Entry { name: n, value: v });
579        }
580        let slot = self.enums.entry(ename.to_string()).or_insert_with(|| Enum {
581            name: ename.to_string(),
582            bitmask: false,
583            entries: Vec::new(),
584            description: String::new(),
585        });
586        slot.bitmask |= e.attribute("bitmask") == Some("true");
587        if slot.description.is_empty() {
588            slot.description = child_text(e, "description");
589        }
590        for en in entries {
591            if !slot.entries.iter().any(|x| x.name == en.name) {
592                slot.entries.push(en);
593            }
594        }
595        Ok(())
596    }
597
598    /// Loads a dialect file and, recursively, the files it includes from the
599    /// same directory. An include that is missing is listed in
600    /// `unresolved_includes`.
601    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
602        let path = path.as_ref();
603        let mut seen = Vec::new();
604        load(path, &mut seen)
605    }
606
607    /// Adds the messages and enums of `other` (as an include does).
608    pub fn merge(&mut self, other: Dialect) {
609        for (id, m) in other.messages {
610            self.messages.entry(id).or_insert(m);
611        }
612        for (name, e) in other.enums {
613            match self.enums.get_mut(&name) {
614                None => {
615                    self.enums.insert(name, e);
616                }
617                Some(mine) => {
618                    // included entries come first
619                    let mut all = e.entries;
620                    for x in std::mem::take(&mut mine.entries) {
621                        if !all.iter().any(|y| y.name == x.name) {
622                            all.push(x);
623                        }
624                    }
625                    mine.entries = all;
626                    mine.bitmask |= e.bitmask;
627                }
628            }
629        }
630    }
631
632    /// The message with `id`.
633    pub fn message(&self, id: u32) -> Option<&Message> {
634        self.messages.get(&id)
635    }
636
637    /// The message called `name`.
638    pub fn message_by_name(&self, name: &str) -> Option<&Message> {
639        self.messages.values().find(|m| m.name == name)
640    }
641
642    /// `CRC_EXTRA` of message `id`.
643    pub fn crc_extra(&self, id: u32) -> Option<u8> {
644        self.message(id).map(|m| m.crc_extra)
645    }
646
647    /// Readable label of `value` in enum `enum_name` (see [`Enum::label`]).
648    pub fn label(&self, enum_name: &str, value: u64) -> Option<String> {
649        self.enums.get(enum_name)?.label(value)
650    }
651}
652
653fn load(path: &Path, seen: &mut Vec<std::path::PathBuf>) -> Result<Dialect, Error> {
654    let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
655    seen.push(canon);
656    let xml =
657        std::fs::read_to_string(path).map_err(|e| Error(format!("{}: {e}", path.display())))?;
658    let stem = path
659        .file_stem()
660        .map(|s| s.to_string_lossy().into_owned())
661        .unwrap_or_default();
662    let mut d = Dialect::parse(&stem, &xml)?;
663    let dir = path.parent().unwrap_or_else(|| Path::new("."));
664    let mut unresolved = Vec::new();
665    for inc in std::mem::take(&mut d.unresolved_includes) {
666        let p = dir.join(&inc);
667        let c = p.canonicalize().unwrap_or_else(|_| p.clone());
668        if seen.contains(&c) {
669            continue;
670        }
671        if !p.is_file() {
672            unresolved.push(inc);
673            continue;
674        }
675        let sub = load(&p, seen)?;
676        unresolved.extend(sub.unresolved_includes.iter().cloned());
677        d.merge(sub);
678    }
679    d.unresolved_includes = unresolved;
680    Ok(d)
681}
682
683fn parse_message(file: &str, m: roxmltree::Node<'_, '_>) -> Result<Message, Error> {
684    let name = m
685        .attribute("name")
686        .ok_or_else(|| Error(format!("{file}: message without a name")))?;
687    let id = m
688        .attribute("id")
689        .and_then(|v| v.trim().parse::<u32>().ok())
690        .ok_or_else(|| Error(format!("{file}: {name}: missing or bad id")))?;
691    let mut fields = Vec::new();
692    let mut extension = false;
693    for c in m.children().filter(|c| c.is_element()) {
694        match c.tag_name().name() {
695            "extensions" => extension = true,
696            "field" => {
697                let fname = c.attribute("name").unwrap_or("").to_string();
698                let t = c.attribute("type").unwrap_or("");
699                let (base, len) = match t.split_once('[') {
700                    Some((b, rest)) => {
701                        let n = rest
702                            .trim_end_matches(']')
703                            .parse::<usize>()
704                            .map_err(|_| Error(format!("{file}: {name}.{fname}: bad type {t}")))?;
705                        (b, Some(n))
706                    }
707                    None => (t, None),
708                };
709                let ty = FieldType::parse(base)
710                    .ok_or_else(|| Error(format!("{file}: {name}.{fname}: unknown type {t}")))?;
711                fields.push(Field {
712                    name: fname,
713                    ty,
714                    array_len: len,
715                    enum_name: c.attribute("enum").map(str::to_string),
716                    units: c.attribute("units").map(str::to_string),
717                    extension,
718                    offset: 0,
719                    description: text_of(c),
720                });
721            }
722            _ => {}
723        }
724    }
725    Ok(layout(id, name, &child_text(m, "description"), fields))
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731
732    #[test]
733    fn crc_extra_matches_known_common_values() {
734        // HEARTBEAT and GLOBAL_POSITION_INT from common.xml; their CRC_EXTRA
735        // values (50 and 104) are in every MAVLink implementation.
736        let xml = r#"<mavlink><messages>
737          <message id="0" name="HEARTBEAT">
738            <field type="uint8_t" name="type">t</field>
739            <field type="uint8_t" name="autopilot">a</field>
740            <field type="uint8_t" name="base_mode">b</field>
741            <field type="uint32_t" name="custom_mode">c</field>
742            <field type="uint8_t" name="system_status">s</field>
743            <field type="uint8_t_mavlink_version" name="mavlink_version">v</field>
744          </message>
745          <message id="33" name="GLOBAL_POSITION_INT">
746            <field type="uint32_t" name="time_boot_ms">t</field>
747            <field type="int32_t" name="lat">a</field>
748            <field type="int32_t" name="lon">a</field>
749            <field type="int32_t" name="alt">a</field>
750            <field type="int32_t" name="relative_alt">a</field>
751            <field type="int16_t" name="vx">a</field>
752            <field type="int16_t" name="vy">a</field>
753            <field type="int16_t" name="vz">a</field>
754            <field type="uint16_t" name="hdg">a</field>
755          </message></messages></mavlink>"#;
756        let d = Dialect::parse("t", xml).unwrap();
757        assert_eq!(d.crc_extra(0), Some(50));
758        assert_eq!(d.crc_extra(33), Some(104));
759        let hb = d.message(0).unwrap();
760        assert_eq!(hb.fields[0].name, "custom_mode");
761        assert_eq!(hb.base_len, 9);
762    }
763
764    #[test]
765    fn values() {
766        assert_eq!(parse_value("0x0303"), Some(0x0303));
767        assert_eq!(parse_value("2**3"), Some(8));
768        assert_eq!(parse_value("0b101"), Some(5));
769        assert_eq!(parse_value(" 42 "), Some(42));
770        assert_eq!(parse_value("x"), None);
771    }
772}