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