Skip to main content

mavwire_ffi/
lib.rs

1//! C FFI bindings for the `mavwire` `MAVLink` v1/v2 decoder.
2//!
3//! Exposes a decode-only subset of `mavwire`'s API: decode a single v2 (or
4//! v1) frame from a raw byte buffer into an opaque message handle, then
5//! read its fields via a `mavwire_message_as_<type>` function that fills a
6//! plain C struct - one call per message, rather than one accessor call
7//! per field, since `MAVLink` has many small messages with several fields
8//! each. See `include/mavwire.h` for the generated C declarations.
9//!
10//! This crate is a plain (non-`no_std`) library: it targets host
11//! environments linking a shared or static C library, not the embedded
12//! `no_alloc` use case `mavwire` itself supports. Embedded consumers
13//! should use the `mavwire` Rust crate directly.
14
15use std::ffi::c_char;
16use std::ptr;
17
18use mavwire::MavMessage;
19use mavwire::message::{
20    Attitude, CommandAck, CommandLong, GlobalPositionInt, GpsRawInt, Heartbeat, ParamValue,
21    RcChannels, StatusText, SysStatus, VfrHud,
22};
23
24/// Opaque handle to a decoded `MAVLink` message, owned by the caller until
25/// freed with [`mavwire_message_free`].
26pub struct MavwireMessage {
27    system_id: u8,
28    component_id: u8,
29    sequence: u8,
30    message: MavMessage,
31}
32
33/// Error codes returned by [`mavwire_decode`].
34#[repr(u8)]
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum MavwireError {
37    /// No error.
38    Ok = 0,
39    /// The `buf` pointer was NULL.
40    NullInput = 1,
41    /// The frame itself was malformed (bad magic byte, wrong length,
42    /// unsupported v2 signing).
43    Frame = 2,
44    /// The message id is unknown/undecoded, or the checksum didn't match.
45    Message = 3,
46}
47
48impl From<mavwire::MavError> for MavwireError {
49    fn from(e: mavwire::MavError) -> Self {
50        match e {
51            mavwire::MavError::Frame(_) => Self::Frame,
52            // covers Message(_) and any future non_exhaustive variant
53            _ => Self::Message,
54        }
55    }
56}
57
58/// Decodes a single `MAVLink` v1 or v2 frame from the start of `buf`
59/// (`len` bytes long). `buf` may contain trailing bytes after the frame
60/// (e.g. the start of the next frame in a stream); only the leading frame
61/// is parsed.
62///
63/// On success, returns a non-NULL handle (free it with
64/// [`mavwire_message_free`] when done) and, if `out_error` is non-NULL,
65/// writes [`MavwireError::Ok`] through it. On failure, returns NULL and,
66/// if `out_error` is non-NULL, writes the reason through it.
67///
68/// # Safety
69/// `buf` must be NULL or valid for reads of `len` bytes. `out_error` must
70/// be NULL or a pointer valid for a single `u8`-sized write.
71#[unsafe(no_mangle)]
72pub unsafe extern "C" fn mavwire_decode(
73    buf: *const u8,
74    len: usize,
75    out_error: *mut MavwireError,
76) -> *mut MavwireMessage {
77    let set_error = |code: MavwireError| {
78        if !out_error.is_null() {
79            // SAFETY: caller guarantees `out_error` is a valid write target or NULL.
80            unsafe {
81                out_error.write(code);
82            }
83        }
84    };
85
86    if buf.is_null() {
87        set_error(MavwireError::NullInput);
88        return ptr::null_mut();
89    }
90
91    // SAFETY: caller guarantees `buf` is valid for reads of `len` bytes.
92    let bytes = unsafe { core::slice::from_raw_parts(buf, len) };
93
94    let frame = match mavwire::Frame::parse(bytes) {
95        Ok(frame) => frame,
96        Err(e) => {
97            set_error(MavwireError::from(mavwire::MavError::from(e)));
98            return ptr::null_mut();
99        }
100    };
101
102    match MavMessage::decode(&frame) {
103        Ok(message) => {
104            set_error(MavwireError::Ok);
105            Box::into_raw(Box::new(MavwireMessage {
106                system_id: frame.system_id(),
107                component_id: frame.component_id(),
108                sequence: frame.sequence(),
109                message,
110            }))
111        }
112        Err(e) => {
113            set_error(MavwireError::from(mavwire::MavError::from(e)));
114            ptr::null_mut()
115        }
116    }
117}
118
119/// Frees a message handle returned by [`mavwire_decode`]. Passing NULL is
120/// a no-op.
121///
122/// # Safety
123/// `msg` must be NULL or a pointer previously returned by [`mavwire_decode`]
124/// that has not already been freed.
125#[unsafe(no_mangle)]
126pub unsafe extern "C" fn mavwire_message_free(msg: *mut MavwireMessage) {
127    if !msg.is_null() {
128        // SAFETY: caller guarantees `msg` is a live handle from `mavwire_decode`.
129        drop(unsafe { Box::from_raw(msg) });
130    }
131}
132
133/// The message's `MAVLink` message id (e.g. `0` for HEARTBEAT), or
134/// `0xFFFFFFFF` for a NULL handle.
135///
136/// # Safety
137/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
138#[unsafe(no_mangle)]
139pub unsafe extern "C" fn mavwire_message_id(msg: *const MavwireMessage) -> u32 {
140    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
141    match unsafe { msg.as_ref() } {
142        Some(m) => match m.message {
143            MavMessage::Heartbeat(_) => 0,
144            MavMessage::SysStatus(_) => 1,
145            MavMessage::ParamValue(_) => 22,
146            MavMessage::GpsRawInt(_) => 24,
147            MavMessage::Attitude(_) => 30,
148            MavMessage::GlobalPositionInt(_) => 33,
149            MavMessage::RcChannels(_) => 65,
150            MavMessage::VfrHud(_) => 74,
151            MavMessage::CommandLong(_) => 76,
152            MavMessage::CommandAck(_) => 77,
153            MavMessage::StatusText(_) => 253,
154            _ => u32::MAX,
155        },
156        None => u32::MAX,
157    }
158}
159
160/// The sending system's ID, or `0` for a NULL handle.
161///
162/// # Safety
163/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
164#[unsafe(no_mangle)]
165pub unsafe extern "C" fn mavwire_message_system_id(msg: *const MavwireMessage) -> u8 {
166    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
167    unsafe { msg.as_ref() }.map_or(0, |m| m.system_id)
168}
169
170/// The sending component's ID, or `0` for a NULL handle.
171///
172/// # Safety
173/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
174#[unsafe(no_mangle)]
175pub unsafe extern "C" fn mavwire_message_component_id(msg: *const MavwireMessage) -> u8 {
176    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
177    unsafe { msg.as_ref() }.map_or(0, |m| m.component_id)
178}
179
180/// The frame's sequence number, or `0` for a NULL handle.
181///
182/// # Safety
183/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
184#[unsafe(no_mangle)]
185pub unsafe extern "C" fn mavwire_message_sequence(msg: *const MavwireMessage) -> u8 {
186    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
187    unsafe { msg.as_ref() }.map_or(0, |m| m.sequence)
188}
189
190/// Copies a Rust `&str` into a fixed-size C buffer, truncating to fit and
191/// always NUL-terminating (so `cap` must be at least 1).
192fn copy_str_into(s: &str, buf: &mut [c_char]) {
193    let bytes = s.as_bytes();
194    let n = bytes.len().min(buf.len() - 1);
195    for (dst, &b) in buf.iter_mut().zip(bytes.iter().take(n)) {
196        #[allow(
197            clippy::cast_possible_wrap,
198            reason = "reinterpreting a UTF-8 byte (always < 0x80 for callsign/status text) as c_char"
199        )]
200        {
201            *dst = b as c_char;
202        }
203    }
204    buf[n] = 0;
205}
206
207/// HEARTBEAT (id 0): system presence/type/mode.
208#[repr(C)]
209#[derive(Debug, Clone, Copy)]
210pub struct MavwireHeartbeat {
211    /// Vehicle/component type (`MAV_TYPE`).
212    pub mav_type: u8,
213    /// Autopilot type/class (`MAV_AUTOPILOT`).
214    pub autopilot: u8,
215    /// System mode bitmask (`MAV_MODE_FLAG`).
216    pub base_mode: u8,
217    /// Autopilot-specific navigation mode.
218    pub custom_mode: u32,
219    /// System status (`MAV_STATE`).
220    pub system_status: u8,
221    /// `MAVLink` version this node speaks.
222    pub mavlink_version: u8,
223}
224
225impl From<Heartbeat> for MavwireHeartbeat {
226    fn from(m: Heartbeat) -> Self {
227        Self {
228            mav_type: m.mav_type,
229            autopilot: m.autopilot,
230            base_mode: m.base_mode,
231            custom_mode: m.custom_mode,
232            system_status: m.system_status,
233            mavlink_version: m.mavlink_version,
234        }
235    }
236}
237
238/// `SYS_STATUS` (id 1): onboard sensor and battery health.
239#[repr(C)]
240#[derive(Debug, Clone, Copy)]
241pub struct MavwireSysStatus {
242    /// Battery voltage, millivolts.
243    pub voltage_battery: u16,
244    /// Battery current, centiamps (`-1` if not measured).
245    pub current_battery: i16,
246    /// Remaining battery, percent (`-1` if not measured).
247    pub battery_remaining: i8,
248    /// Autopilot main loop load, permille.
249    pub load: u16,
250}
251
252impl From<SysStatus> for MavwireSysStatus {
253    fn from(m: SysStatus) -> Self {
254        Self {
255            voltage_battery: m.voltage_battery,
256            current_battery: m.current_battery,
257            battery_remaining: m.battery_remaining,
258            load: m.load,
259        }
260    }
261}
262
263/// `GPS_RAW_INT` (id 24): raw GPS fix.
264#[repr(C)]
265#[derive(Debug, Clone, Copy)]
266pub struct MavwireGpsRawInt {
267    /// GPS fix type.
268    pub fix_type: u8,
269    /// Latitude in `WGS84`, degrees * 1e7.
270    pub lat: i32,
271    /// Longitude in `WGS84`, degrees * 1e7.
272    pub lon: i32,
273    /// Altitude (MSL), millimeters.
274    pub alt: i32,
275    /// Number of visible satellites (`0xFF` if unknown).
276    pub satellites_visible: u8,
277}
278
279impl From<GpsRawInt> for MavwireGpsRawInt {
280    fn from(m: GpsRawInt) -> Self {
281        Self {
282            fix_type: m.fix_type,
283            lat: m.lat,
284            lon: m.lon,
285            alt: m.alt,
286            satellites_visible: m.satellites_visible,
287        }
288    }
289}
290
291/// ATTITUDE (id 30): roll/pitch/yaw and their rates.
292#[repr(C)]
293#[derive(Debug, Clone, Copy)]
294pub struct MavwireAttitude {
295    /// Roll angle, radians.
296    pub roll: f32,
297    /// Pitch angle, radians.
298    pub pitch: f32,
299    /// Yaw angle, radians.
300    pub yaw: f32,
301    /// Roll angular speed, rad/s.
302    pub rollspeed: f32,
303    /// Pitch angular speed, rad/s.
304    pub pitchspeed: f32,
305    /// Yaw angular speed, rad/s.
306    pub yawspeed: f32,
307}
308
309impl From<Attitude> for MavwireAttitude {
310    fn from(m: Attitude) -> Self {
311        Self {
312            roll: m.roll,
313            pitch: m.pitch,
314            yaw: m.yaw,
315            rollspeed: m.rollspeed,
316            pitchspeed: m.pitchspeed,
317            yawspeed: m.yawspeed,
318        }
319    }
320}
321
322/// `GLOBAL_POSITION_INT` (id 33): fused global position.
323#[repr(C)]
324#[derive(Debug, Clone, Copy)]
325pub struct MavwireGlobalPositionInt {
326    /// Latitude in `WGS84`, degrees * 1e7.
327    pub lat: i32,
328    /// Longitude in `WGS84`, degrees * 1e7.
329    pub lon: i32,
330    /// Altitude (MSL), millimeters.
331    pub alt: i32,
332    /// Altitude above ground/home, millimeters.
333    pub relative_alt: i32,
334    /// Vehicle heading, centidegrees.
335    pub hdg: u16,
336}
337
338impl From<GlobalPositionInt> for MavwireGlobalPositionInt {
339    fn from(m: GlobalPositionInt) -> Self {
340        Self {
341            lat: m.lat,
342            lon: m.lon,
343            alt: m.alt,
344            relative_alt: m.relative_alt,
345            hdg: m.hdg,
346        }
347    }
348}
349
350/// `RC_CHANNELS` (id 65): raw RC receiver channel values.
351#[repr(C)]
352#[derive(Debug, Clone, Copy)]
353pub struct MavwireRcChannels {
354    /// Raw channel values, microseconds (18 channels).
355    pub channels: [u16; 18],
356    /// Total number of RC channels received.
357    pub chancount: u8,
358    /// Receive signal strength (`0`-`254`, `255` if unknown).
359    pub rssi: u8,
360}
361
362impl From<RcChannels> for MavwireRcChannels {
363    fn from(m: RcChannels) -> Self {
364        Self {
365            channels: m.channels,
366            chancount: m.chancount,
367            rssi: m.rssi,
368        }
369    }
370}
371
372/// `VFR_HUD` (id 74): airspeed/altitude/heading HUD data.
373#[repr(C)]
374#[derive(Debug, Clone, Copy)]
375pub struct MavwireVfrHud {
376    /// Indicated airspeed, m/s.
377    pub airspeed: f32,
378    /// Ground speed, m/s.
379    pub groundspeed: f32,
380    /// Altitude (MSL), meters.
381    pub alt: f32,
382    /// Climb rate, m/s.
383    pub climb: f32,
384    /// Heading, degrees.
385    pub heading: i16,
386    /// Throttle, percent.
387    pub throttle: u16,
388}
389
390impl From<VfrHud> for MavwireVfrHud {
391    fn from(m: VfrHud) -> Self {
392        Self {
393            airspeed: m.airspeed,
394            groundspeed: m.groundspeed,
395            alt: m.alt,
396            climb: m.climb,
397            heading: m.heading,
398            throttle: m.throttle,
399        }
400    }
401}
402
403/// `PARAM_VALUE` (id 22): a single parameter's current value.
404#[repr(C)]
405#[derive(Debug, Clone, Copy)]
406pub struct MavwireParamValue {
407    /// Parameter name, NUL-terminated.
408    pub param_id: [c_char; 17],
409    /// Parameter value (always `MAVLink`'s generic `f32` encoding).
410    pub param_value: f32,
411    /// Onboard parameter type (`MAV_PARAM_TYPE`).
412    pub param_type: u8,
413    /// Total number of onboard parameters.
414    pub param_count: u16,
415    /// Index of this parameter among all onboard parameters.
416    pub param_index: u16,
417}
418
419impl From<ParamValue> for MavwireParamValue {
420    fn from(m: ParamValue) -> Self {
421        let mut param_id = [0 as c_char; 17];
422        copy_str_into(m.param_id.as_str(), &mut param_id);
423        Self {
424            param_id,
425            param_value: m.param_value,
426            param_type: m.param_type,
427            param_count: m.param_count,
428            param_index: m.param_index,
429        }
430    }
431}
432
433/// `COMMAND_LONG` (id 76): sends a command with up to seven parameters.
434#[repr(C)]
435#[derive(Debug, Clone, Copy)]
436pub struct MavwireCommandLong {
437    /// System id of the target.
438    pub target_system: u8,
439    /// Component id of the target.
440    pub target_component: u8,
441    /// Command to execute (`MAV_CMD`).
442    pub command: u16,
443    /// `0`: first transmission, `1+`: confirmation/retransmission count.
444    pub confirmation: u8,
445    /// Command-specific parameters 1-7.
446    pub params: [f32; 7],
447}
448
449impl From<CommandLong> for MavwireCommandLong {
450    fn from(m: CommandLong) -> Self {
451        Self {
452            target_system: m.target_system,
453            target_component: m.target_component,
454            command: m.command,
455            confirmation: m.confirmation,
456            params: m.params,
457        }
458    }
459}
460
461/// `COMMAND_ACK` (id 77): the result of executing a `COMMAND_LONG`.
462#[repr(C)]
463#[derive(Debug, Clone, Copy)]
464pub struct MavwireCommandAck {
465    /// The command being acknowledged (`MAV_CMD`).
466    pub command: u16,
467    /// The command's result (`MAV_RESULT`).
468    pub result: u8,
469    /// Completion progress, `0`-`100`.
470    pub progress: u8,
471}
472
473impl From<CommandAck> for MavwireCommandAck {
474    fn from(m: CommandAck) -> Self {
475        Self {
476            command: m.command,
477            result: m.result,
478            progress: m.progress,
479        }
480    }
481}
482
483/// `STATUSTEXT` (id 253): a human-readable status/log message.
484#[repr(C)]
485#[derive(Debug, Clone, Copy)]
486pub struct MavwireStatusText {
487    /// Severity (`MAV_SEVERITY`, syslog levels: `0` = emergency, `7` = debug).
488    pub severity: u8,
489    /// The status text, NUL-terminated.
490    pub text: [c_char; 51],
491}
492
493impl From<StatusText> for MavwireStatusText {
494    fn from(m: StatusText) -> Self {
495        let mut text = [0 as c_char; 51];
496        copy_str_into(m.text.as_str(), &mut text);
497        Self {
498            severity: m.severity,
499            text,
500        }
501    }
502}
503
504// Each `mavwire_message_as_<type>` accessor below has the same shape
505// (return false and leave `*out` untouched unless `msg` holds that exact
506// variant, otherwise fill `*out` and return true), written out by hand
507// rather than generated by a macro: `cbindgen` does static analysis of
508// the source, not macro expansion, so a `macro_rules!`-generated function
509// (and the struct types it references) is invisible to it and silently
510// missing from the generated header - confirmed by generating the header
511// once with a macro version of these and finding every one of them, and
512// every Mavwire* struct, absent from the output.
513
514/// Reads this message's fields into `*out` if it is a HEARTBEAT message.
515///
516/// Returns `true` and fills `*out` on a match; returns `false` (leaving
517/// `*out` untouched) otherwise.
518///
519/// # Safety
520/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
521/// `out` must be a valid pointer to writable memory of the matching type.
522#[unsafe(no_mangle)]
523pub unsafe extern "C" fn mavwire_message_as_heartbeat(
524    msg: *const MavwireMessage,
525    out: *mut MavwireHeartbeat,
526) -> bool {
527    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
528    let Some(m) = (unsafe { msg.as_ref() }) else {
529        return false;
530    };
531    let MavMessage::Heartbeat(inner) = m.message else {
532        return false;
533    };
534    // SAFETY: caller guarantees `out` is a valid write target.
535    unsafe {
536        out.write(inner.into());
537    }
538    true
539}
540
541/// Reads this message's fields into `*out` if it is a `SYS_STATUS` message.
542///
543/// Returns `true` and fills `*out` on a match; returns `false` (leaving
544/// `*out` untouched) otherwise.
545///
546/// # Safety
547/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
548/// `out` must be a valid pointer to writable memory of the matching type.
549#[unsafe(no_mangle)]
550pub unsafe extern "C" fn mavwire_message_as_sys_status(
551    msg: *const MavwireMessage,
552    out: *mut MavwireSysStatus,
553) -> bool {
554    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
555    let Some(m) = (unsafe { msg.as_ref() }) else {
556        return false;
557    };
558    let MavMessage::SysStatus(inner) = m.message else {
559        return false;
560    };
561    // SAFETY: caller guarantees `out` is a valid write target.
562    unsafe {
563        out.write(inner.into());
564    }
565    true
566}
567
568/// Reads this message's fields into `*out` if it is a `GPS_RAW_INT` message.
569///
570/// Returns `true` and fills `*out` on a match; returns `false` (leaving
571/// `*out` untouched) otherwise.
572///
573/// # Safety
574/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
575/// `out` must be a valid pointer to writable memory of the matching type.
576#[unsafe(no_mangle)]
577pub unsafe extern "C" fn mavwire_message_as_gps_raw_int(
578    msg: *const MavwireMessage,
579    out: *mut MavwireGpsRawInt,
580) -> bool {
581    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
582    let Some(m) = (unsafe { msg.as_ref() }) else {
583        return false;
584    };
585    let MavMessage::GpsRawInt(inner) = m.message else {
586        return false;
587    };
588    // SAFETY: caller guarantees `out` is a valid write target.
589    unsafe {
590        out.write(inner.into());
591    }
592    true
593}
594
595/// Reads this message's fields into `*out` if it is an ATTITUDE message.
596///
597/// Returns `true` and fills `*out` on a match; returns `false` (leaving
598/// `*out` untouched) otherwise.
599///
600/// # Safety
601/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
602/// `out` must be a valid pointer to writable memory of the matching type.
603#[unsafe(no_mangle)]
604pub unsafe extern "C" fn mavwire_message_as_attitude(
605    msg: *const MavwireMessage,
606    out: *mut MavwireAttitude,
607) -> bool {
608    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
609    let Some(m) = (unsafe { msg.as_ref() }) else {
610        return false;
611    };
612    let MavMessage::Attitude(inner) = m.message else {
613        return false;
614    };
615    // SAFETY: caller guarantees `out` is a valid write target.
616    unsafe {
617        out.write(inner.into());
618    }
619    true
620}
621
622/// Reads this message's fields into `*out` if it is a
623/// `GLOBAL_POSITION_INT` message.
624///
625/// Returns `true` and fills `*out` on a match; returns `false` (leaving
626/// `*out` untouched) otherwise.
627///
628/// # Safety
629/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
630/// `out` must be a valid pointer to writable memory of the matching type.
631#[unsafe(no_mangle)]
632pub unsafe extern "C" fn mavwire_message_as_global_position_int(
633    msg: *const MavwireMessage,
634    out: *mut MavwireGlobalPositionInt,
635) -> bool {
636    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
637    let Some(m) = (unsafe { msg.as_ref() }) else {
638        return false;
639    };
640    let MavMessage::GlobalPositionInt(inner) = m.message else {
641        return false;
642    };
643    // SAFETY: caller guarantees `out` is a valid write target.
644    unsafe {
645        out.write(inner.into());
646    }
647    true
648}
649
650/// Reads this message's fields into `*out` if it is an `RC_CHANNELS`
651/// message.
652///
653/// Returns `true` and fills `*out` on a match; returns `false` (leaving
654/// `*out` untouched) otherwise.
655///
656/// # Safety
657/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
658/// `out` must be a valid pointer to writable memory of the matching type.
659#[unsafe(no_mangle)]
660pub unsafe extern "C" fn mavwire_message_as_rc_channels(
661    msg: *const MavwireMessage,
662    out: *mut MavwireRcChannels,
663) -> bool {
664    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
665    let Some(m) = (unsafe { msg.as_ref() }) else {
666        return false;
667    };
668    let MavMessage::RcChannels(inner) = m.message else {
669        return false;
670    };
671    // SAFETY: caller guarantees `out` is a valid write target.
672    unsafe {
673        out.write(inner.into());
674    }
675    true
676}
677
678/// Reads this message's fields into `*out` if it is a `VFR_HUD` message.
679///
680/// Returns `true` and fills `*out` on a match; returns `false` (leaving
681/// `*out` untouched) otherwise.
682///
683/// # Safety
684/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
685/// `out` must be a valid pointer to writable memory of the matching type.
686#[unsafe(no_mangle)]
687pub unsafe extern "C" fn mavwire_message_as_vfr_hud(
688    msg: *const MavwireMessage,
689    out: *mut MavwireVfrHud,
690) -> bool {
691    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
692    let Some(m) = (unsafe { msg.as_ref() }) else {
693        return false;
694    };
695    let MavMessage::VfrHud(inner) = m.message else {
696        return false;
697    };
698    // SAFETY: caller guarantees `out` is a valid write target.
699    unsafe {
700        out.write(inner.into());
701    }
702    true
703}
704
705/// Reads this message's fields into `*out` if it is a `PARAM_VALUE`
706/// message.
707///
708/// Returns `true` and fills `*out` on a match; returns `false` (leaving
709/// `*out` untouched) otherwise.
710///
711/// # Safety
712/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
713/// `out` must be a valid pointer to writable memory of the matching type.
714#[unsafe(no_mangle)]
715pub unsafe extern "C" fn mavwire_message_as_param_value(
716    msg: *const MavwireMessage,
717    out: *mut MavwireParamValue,
718) -> bool {
719    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
720    let Some(m) = (unsafe { msg.as_ref() }) else {
721        return false;
722    };
723    let MavMessage::ParamValue(inner) = m.message else {
724        return false;
725    };
726    // SAFETY: caller guarantees `out` is a valid write target.
727    unsafe {
728        out.write(inner.into());
729    }
730    true
731}
732
733/// Reads this message's fields into `*out` if it is a `COMMAND_LONG`
734/// message.
735///
736/// Returns `true` and fills `*out` on a match; returns `false` (leaving
737/// `*out` untouched) otherwise.
738///
739/// # Safety
740/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
741/// `out` must be a valid pointer to writable memory of the matching type.
742#[unsafe(no_mangle)]
743pub unsafe extern "C" fn mavwire_message_as_command_long(
744    msg: *const MavwireMessage,
745    out: *mut MavwireCommandLong,
746) -> bool {
747    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
748    let Some(m) = (unsafe { msg.as_ref() }) else {
749        return false;
750    };
751    let MavMessage::CommandLong(inner) = m.message else {
752        return false;
753    };
754    // SAFETY: caller guarantees `out` is a valid write target.
755    unsafe {
756        out.write(inner.into());
757    }
758    true
759}
760
761/// Reads this message's fields into `*out` if it is a `COMMAND_ACK`
762/// message.
763///
764/// Returns `true` and fills `*out` on a match; returns `false` (leaving
765/// `*out` untouched) otherwise.
766///
767/// # Safety
768/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
769/// `out` must be a valid pointer to writable memory of the matching type.
770#[unsafe(no_mangle)]
771pub unsafe extern "C" fn mavwire_message_as_command_ack(
772    msg: *const MavwireMessage,
773    out: *mut MavwireCommandAck,
774) -> bool {
775    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
776    let Some(m) = (unsafe { msg.as_ref() }) else {
777        return false;
778    };
779    let MavMessage::CommandAck(inner) = m.message else {
780        return false;
781    };
782    // SAFETY: caller guarantees `out` is a valid write target.
783    unsafe {
784        out.write(inner.into());
785    }
786    true
787}
788
789/// Reads this message's fields into `*out` if it is a `STATUSTEXT` message.
790///
791/// Returns `true` and fills `*out` on a match; returns `false` (leaving
792/// `*out` untouched) otherwise.
793///
794/// # Safety
795/// `msg` must be NULL or a valid, non-freed handle from [`mavwire_decode`].
796/// `out` must be a valid pointer to writable memory of the matching type.
797#[unsafe(no_mangle)]
798pub unsafe extern "C" fn mavwire_message_as_statustext(
799    msg: *const MavwireMessage,
800    out: *mut MavwireStatusText,
801) -> bool {
802    // SAFETY: caller guarantees `msg` is a valid handle or NULL.
803    let Some(m) = (unsafe { msg.as_ref() }) else {
804        return false;
805    };
806    let MavMessage::StatusText(inner) = m.message else {
807        return false;
808    };
809    // SAFETY: caller guarantees `out` is a valid write target.
810    unsafe {
811        out.write(inner.into());
812    }
813    true
814}
815
816/// The `mavwire` crate version, as a NUL-terminated, statically allocated
817/// string (e.g. `"0.1.0"`). Do not free.
818#[unsafe(no_mangle)]
819pub extern "C" fn mavwire_version() -> *const c_char {
820    const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "\0");
821    VERSION.as_ptr().cast::<c_char>()
822}