rust

The Rust target, rust, generates a crate binding the API, in the manner of a -sys crate, into <output>/rust:

Cargo.toml and build.rs

The crate. The build script links the library, named in the IR’s meta without the lib prefix, searching the directory in <PREFIX>_LIB_DIR when set. With <PREFIX>_NO_LINK set it links nothing, for what uses only the types.

lib.rs and bindings.rs

bindings.rs holds the bindings and uses nothing outside the standard library. lib.rs is the root of the crate: it sets the attributes of the crate and includes bindings.rs. Another crate can include bindings.rs with include!(), for example from a build script. That crate must allow non_camel_case_types, non_snake_case, non_upper_case_globals and clippy::all, as lib.rs does. The crate takes its name from the prefix, or from crate in the IR’s meta, such as foo-sys.

check.rs

The check, an example of the crate rather than part of it: it asserts at compile time that every record has the size, alignment and field offsets recorded in the IR, then prints a zeroed instance of every record, as YAML or JSON.

The check is built with $CARGO, by default cargo, offline, and run; yace then parses what it printed, as YAML and as JSON. It calls no function of the library, so needs it neither built nor linked. As for the C API, the layout is asserted only on the platform it was recorded on. The crate needs Rust 1.81 or later, where a panic unwinding out of a callback aborts.

The bindings

Names are those of the C API, so its documentation applies. Only types are renamed, to CamelCase, as Rust names types: struct foo_point is FooPoint, and typedef struct foo_point foo_point; is that type. Where two C names would get the same Rust name, both keep their C names. A name that is a Rust keyword is a raw identifier, r#type, or, for those that cannot be, gets a trailing underscore, self_. So does a parameter named ret, the local of the result, Some, None, Ok or Err, as a type of the crate, or ending in _ or _trampoline, so no two parameters share a name.

Constants

#define constants, as pub const: strings as &CStr, integers as i32, or i64 or u64 when that does not hold them.

Enumerations

Each enum is a #[repr(transparent)] integer newtype, with its members as associated constants, also given as constants of the crate. C does not restrict an enum to its members, and a Rust enum holding another value is undefined behaviour, so the enum is an integer. name() is the name of a value, None when it has none.

Records

Each struct and union is #[repr(C)], Clone and Copy, and has a Default of all zeros. Each has the pretty-printers: fpr(w, obj, flags) and pr(obj, flags), printing obj, or null for None, as the C API’s <name>_fpr() and <name>_pr() do, and Display, printing YAML. Debug shows a struct by its C fields; a union, or a record of bit-fields kept as bytes, shows none, FooValue { .. }, as which member of a union is meant is not known. An opaque record is a zero-sized type that cannot be constructed, used through pointers. Each part of a field of bits, see The C Subset, has a getter and a setter, code_type() and set_code_type(value), of the field’s type; the setter panics on a value that does not fit the part’s bits. The field itself is there as before; a getter of a union’s field is safe, as every value of an integer is one. Reading a member of a union is unsafe in Rust, as its bytes may not be a value of the member’s type. Where every member of a union is as large as the union and has no padding, every byte of the union is initialised however it was written, by C or by Rust, and each member of a type for which every bit pattern is a value has a safe getter of its name, value.u(): integers, floats, raw pointers, enums, and arrays and records of those. A bool or a function pointer is not such a type, and keeps the unsafe read. The crate asserts the sizes this relies on when it is compiled. A packed record is #[repr(C, packed)]: a reference to one of its fields may not be aligned, which Rust does not allow, so Debug, the printers and the getters read each field by a copy.

Callbacks

A function pointer type is an Option of an unsafe extern "C" fn, the nullable function pointer of Rust.

Functions

Declared in an extern "C" block, by their C names and parameters, and so unsafe to call, as calling C is. A pointer to const is *const, any other *mut.

The idiomatic layer

Over the raw functions, the module safe is the idiomatic layer, from what the header says beyond C, see The C Subset. Its names lose the prefix of the API:

Handles

An opaque record is a type owning a pointer to it, named without the prefix: struct foo_handle is safe::Handle, with Handle appended where the name is a raw type’s or one the module uses from std, as Option. Its constructor is an associated function, Handle::open(), returning an Option where it has no @errno; its destructor is called when it is dropped, or by close(); the functions taking it first are its methods, taking &self where the pointer is to const and it keeps no closure, &mut self otherwise. as_ptr() is the raw pointer, for the raw functions; a method named as_ptr is as_ptr_(). It is neither Send nor Sync: the header does not say it may be, and the closures it keeps run on the thread that calls it, so they need not be Send.

Buffers

A buffer that <stem>_alloc allocates, see the buffer pattern in The C Subset, is returned as a safe::Buffer, an Option where @nullable: dev.buf_alloc(4096). as_ptr() and len() are its address and size in bytes, and realloc(nbytes) resizes it with <stem>_realloc. Dropping it frees it with <stem>_free, which is given the arguments it was allocated with; neither has a name of its own in the layer. The Buffer borrows the handles it was allocated with, so they outlive it; the method that allocates takes &self, so that the handle allocates several buffers. The memory may be a device’s, such as GPU memory, which the CPU cannot read, and nothing in the API says which; so as_slice() and as_mut_slice() are unsafe, requiring the memory to be the host’s. The type is Buffer_ where the API names a type or a handle Buffer.

Registrations

Memory that <stem>_register registers, see the registration pattern in The C Subset, is given as a &mut [u8], whose length is the size: dev.buf_register(&mut memory). The function returns a safe::Registration, which borrows the slice and the handles it was registered with, and dereferences to the slice. Dropping it, or calling unregister(), which returns the error, unregisters the memory with <stem>_unregister, which has no name of its own in the layer. The method that registers takes &self, as the one that allocates does. The type is Registration_ where the API names a type or a handle Registration.

Errors

A function documented @errno returns io::Result, its error made by io::Error::from_raw_os_error(). One returning int returns () otherwise; one returning another integer, such as a count, a usize.

Results

What a function writes through an [out] pointer is returned rather than passed. An [out] array is written to a slice the caller gives, whose length is the capacity, and the part written is returned, as a slice of as many elements as the function says it wrote; nothing is allocated, as with std::io::Read::read(). A returned string is a &CStr borrowed from the handle, from the one reference given, or 'static when none is; with more than one, the function is unsafe. A buffer given for an [out] array is not counted as a reference. A returned pointer to a record is a copy of it, an Option where @nullable.

Arguments

A string is a &CStr; a string with a length, which C reads as bytes rather than to a NUL, is a &str, and the length is that of its bytes. An array read through a pointer is a slice; slices sharing one length must be as long, or the call panics; a @nullable one is an Option, None passing NULL. A void * @arrparam is a slice of u8. The size of a @recparam record is not given; the layer passes size_of of the record’s type. A handle given is a reference to its type. A callback is a &mut dyn FnMut closure, called through a generated trampoline with the void * context; the pointers to records it receives are references. One of @lifetime once (see Callback lifetimes) is a Box<dyn FnOnce>, freed once called, or when the call fails, and Send where the function is not a method, as any later call, from any thread, may run it; one of @lifetime handle a Box<dyn FnMut>, which the handle keeps, unless the call fails, until it is dropped, and for good where destroying it fails or nothing destroys it, as C may still hold it. A @nullable pointer is an Option.

A function is safe where everything a caller gives is checked by the types: a function taking a raw pointer, or a record holding one, is unsafe, as safe Rust can make those point anywhere. A panic in a closure aborts, as unwinding cannot cross C.

A record with bit-fields, which Rust has none of, keeps only its size and alignment, as an array of integers as wide as its alignment, and is not printed. Its alignment is that of the integers, not repr(align), which a packed record may not hold. Types declared outside the header, such as FILE, are opaque types, usable through pointers. These are outside the C subset; the diagnostics of the header say so.

Example

yace output/foo.yaml --emit rust --output output
output/rust
├── Cargo.lock
├── Cargo.toml
├── bindings.rs
├── build.rs
├── cargo.log
├── check.json
├── check.rs
├── check.yaml
├── lib.rs
└── rustfmt.toml

1 directory, 10 files

The fixture library is called through the raw layer by examples/libfoo/checks/rust/check.rs, and through the idiomatic layer by:

../../../../examples/libfoo/checks/rust/idiomatic.rs
//! The check of the idiomatic Rust layer of libfoo, the module 'safe': as
//! check.rs, through an owned handle, io::Result and returned values rather
//! than raw calls. An error is printed as the negative errno the C function
//! returned, so the documents printed are those of 'expected.yaml'.
//!
//! What safe Rust cannot express, a NULL where none is allowed, is called raw.

use std::ffi::{c_int, c_void};
use std::io;
use std::ptr;

use foo::safe::{self, Handle};
use foo::*;

mod common;

use common::*;

unsafe extern "C" fn add_x(arg: *mut c_void, point: *const FooPoint) -> c_int {
    *(arg as *mut i64) += (*point).x as i64;
    0
}

/// The value, 0 for (), or the negative errno of the error
fn errno<T: Into<i64>>(result: io::Result<T>) -> i64 {
    match result {
        Ok(value) => value.into(),
        Err(err) => -(err.raw_os_error().unwrap_or(0) as i64),
    }
}

/// Compiles only while T is not Send: were it Send, both impls would apply
/// and the call in main() would be ambiguous. A handle keeps the callbacks
/// given to it, which need not be Send, and they run on the thread that
/// polls it, so a handle must not leave its thread.
trait NotSend<A> {
    fn not_send() {}
}
impl<T: ?Sized> NotSend<()> for T {}
impl<T: ?Sized + Send> NotSend<u8> for T {}

/// As NotSend, for Sync: a handle shared between threads would let two of
/// them call it, and run its callbacks, at once
trait NotSync<A> {
    fn not_sync() {}
}
impl<T: ?Sized> NotSync<()> for T {}
impl<T: ?Sized + Sync> NotSync<u8> for T {}

fn status(result: io::Result<()>) -> i64 {
    errno(result.map(|()| 0i64))
}

fn count(result: io::Result<usize>) -> i64 {
    errno(result.map(|n| n as i64))
}

fn main() -> io::Result<()> {
    let as_json = std::env::args().nth(1).as_deref() == Some("json");
    <Handle as NotSend<_>>::not_send();
    <Handle as NotSync<_>>::not_sync();
    let flags = if as_json { FOO_PR_JSON } else { FOO_PR_YAML };

    document(
        "defines",
        &[
            ("FOO_NAME", Value::Str(FOO_NAME.to_string_lossy().into_owned())),
            ("FOO_MAGIC", Value::Int(FOO_MAGIC.into())),
            ("FOO_VERSION_MAJOR", Value::Int(FOO_VERSION_MAJOR.into())),
            ("FOO_VERSION_MINOR", Value::Int(FOO_VERSION_MINOR.into())),
            ("FOO_VERSION_PATCH", Value::Int(FOO_VERSION_PATCH.into())),
            ("FOO_POINTS_MAX", Value::Int(FOO_POINTS_MAX.into())),
            ("FOO_DEFAULT_SHAPE_SIDES", Value::Int(FOO_DEFAULT_SHAPE_SIDES.into())),
        ],
        as_json,
    );
    let names = |values: &[c_int], name: fn(c_int) -> Option<&'static str>| {
        Value::Names(values.iter().map(|&v| name(v).unwrap_or("UNKNOWN")).collect())
    };
    document(
        "enums",
        &[
            ("foo_shape", names(&[-1, 0, 1, 2, 3], |v| FooShape(v as _).name())),
            ("foo_option", names(&[1, 2, 3], |v| FooOption(v as _).name())),
        ],
        as_json,
    );

    let points = [FooPoint { x: 1, y: 2 }, FooPoint { x: 3, y: 4 }, FooPoint { x: 5, y: 6 }];
    let mut handle = Handle::open(c"points")?;
    let open_without_name = unsafe { foo_open(ptr::null(), &mut ptr::null_mut()) };
    let name = handle.name().to_string_lossy().into_owned();
    let watched = std::rc::Rc::new(std::cell::Cell::new((0usize, 0i64)));
    let (watcher, busy) = (watched.clone(), watched.clone());
    let watch = status(handle.point_watch(Box::new(move |p: &FooPoint| {
        let (n, x) = watcher.get();
        watcher.set((n + 1, x + p.x as i64));
    })));
    let watch_busy = status(handle.point_watch(Box::new(move |_: &FooPoint| busy.set((0, 0)))));
    let added = points.iter().filter(|p| handle.point_add(p).is_ok()).count();
    let count_before = handle.point_count();

    let (mut sum_x, mut sum_y) = (0i64, 0i64);
    let visit = count(handle.point_visit(&mut |p: &FooPoint| {
        sum_x += p.x as i64;
        sum_y += p.y as i64;
        0
    }));
    let mut seen = 0;
    let stopped = count(handle.point_visit(&mut |_: &FooPoint| {
        seen += 1;
        (seen == 2) as c_int
    }));
    let without = unsafe { foo_point_visit(handle.as_ptr(), None, ptr::null_mut()) };
    let mut with_x = 0i64;
    let visitor = FooVisitor {
        visit: Some(add_x),
        arg: &mut with_x as *mut i64 as *mut c_void,
    };
    // A record holding a callback and its context: unsafe, as nothing checks them
    let visit_with = count(unsafe { handle.point_visit_with(&visitor) });
    let unknown = status(safe::figure_fill(3).map(|_| ()));
    let add_many = count(handle.point_add_many(&points));
    let mut buffer = [FooPoint::default(); 4];
    let copied = handle.point_copy(&mut buffer)?;
    let counted = std::rc::Rc::new(std::cell::Cell::new(0));
    let (once, again) = (counted.clone(), counted.clone());
    let submit = status(handle.count_submit(Box::new(move |n| once.set(n))));
    let submit_busy = status(handle.count_submit(Box::new(move |n| again.set(n))));
    let complete = handle.count_complete();
    let complete_again = handle.count_complete();

    document(
        "calls",
        &[
            ("version", Value::Str(safe::version().to_string_lossy().into_owned())),
            ("open", Value::Int(0)),
            ("open_without_name", Value::Int(open_without_name.into())),
            ("name", Value::Str(name)),
            ("watch", Value::Int(watch)),
            ("watch_busy", Value::Int(watch_busy)),
            ("added", Value::Int(added as i64)),
            ("count", Value::Int(count_before as i64)),
            ("visit", Value::Int(visit)),
            ("visit_sum_x", Value::Int(sum_x)),
            ("visit_sum_y", Value::Int(sum_y)),
            ("visit_stopped", Value::Int(stopped)),
            ("visit_without_callback", Value::Int(without as i64)),
            ("visit_with", Value::Int(visit_with)),
            ("visit_with_sum_x", Value::Int(with_x)),
            ("figure_of_unknown_shape", Value::Int(unknown)),
            ("add_many", Value::Int(add_many)),
            ("count_after_add_many", Value::Int(handle.point_count() as i64)),
            ("watched", Value::Int(watched.get().0 as i64)),
            ("watched_sum_x", Value::Int(watched.get().1)),
            ("points_copied", Value::Int(copied.len() as i64)),
            ("points_sum_x", Value::Int(copied.iter().map(|p| p.x as i64).sum())),
            ("submit", Value::Int(submit)),
            ("submit_busy", Value::Int(submit_busy)),
            ("complete", Value::Int(complete as i64)),
            ("done_count", Value::Int(counted.get() as i64)),
            ("complete_again", Value::Int(complete_again as i64)),
        ],
        as_json,
    );

    record("foo_point", FooPoint::fpr, handle.point_get(1).as_ref(), flags)?;
    record("foo_point", FooPoint::fpr, handle.point_get(6).as_ref(), flags)?;

    while handle.point_add(&points[0]).is_ok() {}
    document(
        "full",
        &[
            ("count", Value::Int(handle.point_count() as i64)),
            ("add", Value::Int(status(handle.point_add(&points[0])))),
            ("add_many", Value::Int(count(handle.point_add_many(&points[..1])))),
            ("watched", Value::Int(watched.get().0 as i64)),
        ],
        as_json,
    );
    statuses(&handle.status_get(), flags, as_json)?;
    handle.close();

    record("foo_scalars", FooScalars::fpr, Some(&safe::scalars_fill()), flags)?;
    for shape in [FOO_SHAPE_POINT, FOO_SHAPE_LINE, FOO_SHAPE_POLYGON] {
        let figure = safe::figure_fill(shape.0 as u32)?;
        record("foo_figure", FooFigure::fpr, Some(&figure), flags)?;
    }
    record("foo_value", FooValue::fpr, Some(&safe::value_set(-1)), flags)?;
    record("foo_wire", FooWire::fpr, Some(&safe::wire_fill()), flags)?;

    Ok(())
}

Bindings

../../../../output/rust/bindings.rs
// yace generated these bindings of libfoo from foo.h; do not
// edit them. lib.rs includes this file. Another crate can include it with
// include!() if that crate allows non_camel_case_types, non_snake_case,
// non_upper_case_globals and clippy::all, because the bindings use the C names.

#[allow(unused_imports)]
use std::ffi::{
    c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint,
    c_ulong, c_ulonglong, c_ushort, c_void, CStr,
};
#[allow(unused_imports)]
use std::fmt;
#[allow(unused_imports)]
use std::io::{self, Write};

/// Output formats of the pretty-printers
pub const FOO_PR_DEF: c_int = 0x0;
/// YAML
pub const FOO_PR_YAML: c_int = 0x1;
/// Terse; the generated printers print YAML
pub const FOO_PR_TERSE: c_int = 0x2;
/// JSON, on one line
pub const FOO_PR_JSON: c_int = 0x4;

#[allow(dead_code)]
mod yace_pp {
    use std::ffi::{c_char, CStr};
    use std::io::{self, Write};

    pub fn strn(w: &mut dyn Write, chars: &[c_char]) -> io::Result<()> {
        w.write_all(b"\"")?;
        for &chr in chars.iter().take_while(|&&c| c != 0) {
            let chr = chr as u8;
            match chr {
                b'"' | b'\\' => w.write_all(&[b'\\', chr])?,
                0..=0x1f | 0x7f => write!(w, "\\u{:04x}", chr)?,
                _ => w.write_all(&[chr])?,
            }
        }
        w.write_all(b"\"")
    }

    pub fn str(w: &mut dyn Write, ptr: *const c_char) -> io::Result<()> {
        if ptr.is_null() {
            return w.write_all(b"null");
        }
        let bytes = unsafe { CStr::from_ptr(ptr) }.to_bytes();
        let chars: Vec<c_char> = bytes.iter().map(|&b| b as c_char).collect();
        strn(w, &chars)
    }

    pub fn ptr(w: &mut dyn Write, addr: usize) -> io::Result<()> {
        if addr == 0 {
            return w.write_all(b"null");
        }
        write!(w, "\"{:#x}\"", addr)
    }

    /// 'value' as C's printf() prints it with "%g"
    pub fn g(value: f64) -> String {
        if value.is_nan() {
            return if value.is_sign_negative() {
                "-nan"
            } else {
                "nan"
            }
            .into();
        }
        if value.is_infinite() {
            return if value < 0.0 { "-inf" } else { "inf" }.into();
        }
        if value == 0.0 {
            return if value.is_sign_negative() { "-0" } else { "0" }.into();
        }
        let sci = format!("{:.5e}", value);
        let (mantissa, exp) = sci.split_once('e').unwrap();
        let exp: i32 = exp.parse().unwrap();
        let trim = |text: &str| -> String {
            if text.contains('.') {
                text.trim_end_matches('0').trim_end_matches('.').into()
            } else {
                text.into()
            }
        };
        if exp < -4 || exp >= 6 {
            let sign = if exp < 0 { '-' } else { '+' };
            format!("{}e{}{:02}", trim(mantissa), sign, exp.abs())
        } else {
            trim(&format!("{:.*}", (5 - exp) as usize, value))
        }
    }
}

/// Name of the library
pub const FOO_NAME: &CStr = c"foo";

/// A hexadecimal constant
pub const FOO_MAGIC: i32 = 0xacdc;

/// Major version
pub const FOO_VERSION_MAJOR: i32 = 1;

/// Minor version
pub const FOO_VERSION_MINOR: i32 = 2;

/// Patch version
pub const FOO_VERSION_PATCH: i32 = 3;

/// Points a handle holds at most
pub const FOO_POINTS_MAX: i32 = 8;

/// A constant, by name
pub const FOO_DEFAULT_SHAPE_SIDES: i32 = 8;

/// A count is submitted and not yet completed; bit 0 of 'code'
pub const FOO_STATUS_CODE_PENDING: i32 = 0x1;

/// Points held; bits 11:4 of 'code'
pub const FOO_STATUS_CODE_POINTS: i32 = 0xff0;

/// The handle holds FOO_POINTS_MAX points; bit 15 of 'code'
pub const FOO_STATUS_CODE_FULL: i32 = 0x8000;

/// Kinds of figure
///
/// An integer, not a Rust enum: C gives no guarantee that a value is one of
/// those named.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FooShape(pub c_int);

impl FooShape {
    /// No figure
    pub const FOO_SHAPE_NONE: Self = Self(-1);
    /// A single point
    pub const FOO_SHAPE_POINT: Self = Self(0);
    /// Two points
    pub const FOO_SHAPE_LINE: Self = Self(1);
    /// Three points or more
    pub const FOO_SHAPE_POLYGON: Self = Self(2);

    /// The name of the value, None when it is none of those named
    pub fn name(self) -> Option<&'static str> {
        match self.0 {
            -1 => Some("FOO_SHAPE_NONE"),
            0 => Some("FOO_SHAPE_POINT"),
            1 => Some("FOO_SHAPE_LINE"),
            2 => Some("FOO_SHAPE_POLYGON"),
            _ => None,
        }
    }
}

pub const FOO_SHAPE_NONE: FooShape = FooShape::FOO_SHAPE_NONE;
pub const FOO_SHAPE_POINT: FooShape = FooShape::FOO_SHAPE_POINT;
pub const FOO_SHAPE_LINE: FooShape = FooShape::FOO_SHAPE_LINE;
pub const FOO_SHAPE_POLYGON: FooShape = FooShape::FOO_SHAPE_POLYGON;

/// Options of a figure, combined as bits
///
/// An integer, not a Rust enum: C gives no guarantee that a value is one of
/// those named.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct FooOption(pub c_uint);

impl FooOption {
    /// The last corner connects to the first
    pub const FOO_OPTION_CLOSED: Self = Self(1);
    /// The inside is filled
    pub const FOO_OPTION_FILLED: Self = Self(2);

    /// The name of the value, None when it is none of those named
    pub fn name(self) -> Option<&'static str> {
        match self.0 {
            1 => Some("FOO_OPTION_CLOSED"),
            2 => Some("FOO_OPTION_FILLED"),
            _ => None,
        }
    }
}

pub const FOO_OPTION_CLOSED: FooOption = FooOption::FOO_OPTION_CLOSED;
pub const FOO_OPTION_FILLED: FooOption = FooOption::FOO_OPTION_FILLED;

/// A collection of points, opened with foo_open() and closed with foo_close()
#[repr(C)]
pub struct FooHandle {
    _private: [u8; 0],
    _marker: std::marker::PhantomData<(*mut u8, std::marker::PhantomPinned)>,
}

/// A point on the plane
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FooPoint {
    /// Horizontal position
    pub x: i32,
    /// Vertical position
    pub y: i32,
}

impl Default for FooPoint {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// A callback and its argument
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FooVisitor {
    /// Called for each point
    pub visit: FooVisitCb,
    /// Given to 'visit'
    pub arg: *mut c_void,
}

impl Default for FooVisitor {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// A value of every kind of scalar
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FooScalars {
    /// bool
    pub flag: bool,
    /// char
    pub letter: c_char,
    /// signed char
    pub schar: c_schar,
    /// unsigned char
    pub uchar: c_uchar,
    /// short
    pub s: c_short,
    /// unsigned short
    pub us: c_ushort,
    /// int
    pub i: c_int,
    /// unsigned int
    pub ui: c_uint,
    /// long
    pub l: c_long,
    /// unsigned long
    pub ul: c_ulong,
    /// long long
    pub ll: c_longlong,
    /// unsigned long long
    pub ull: c_ulonglong,
    /// float
    pub f: c_float,
    /// double
    pub d: c_double,
    /// int8_t
    pub i8: i8,
    /// int16_t
    pub i16: i16,
    /// int32_t
    pub i32: i32,
    /// int64_t
    pub i64: i64,
    /// uint8_t
    pub u8: u8,
    /// uint16_t
    pub u16: u16,
    /// uint32_t
    pub u32: u32,
    /// uint64_t
    pub u64: u64,
    /// intptr_t
    pub iptr: isize,
    /// uintptr_t
    pub uptr: usize,
    /// size_t
    pub size: usize,
    /// ssize_t
    pub ssize: isize,
    /// ptrdiff_t
    pub diff: isize,
}

impl Default for FooScalars {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// A figure: its kind, where it is, and its corners
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FooFigure {
    /// One of enum foo_shape
    pub shape: u32,
    /// Bits of enum foo_option
    pub options: u32,
    /// Where the figure is
    pub origin: FooPoint,
    /// The corners, relative to 'origin'
    pub corners: [FooPoint; 4],
    /// How many of 'corners' are used
    pub ncorners: u8,
    /// Name of the figure
    pub name: [c_char; 16],
    /// A two-dimensional array
    pub grid: [[i16; 3]; 2],
    /// A string, NULL when there is none
    pub label: *const c_char,
    /// Scale of the figure
    pub scale: c_float,
    /// Area of the figure
    pub area: c_double,
}

impl Default for FooFigure {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// A 32-bit value, read as signed, as unsigned, or as the 'x' of a point
#[repr(C)]
#[derive(Clone, Copy)]
pub union FooValue {
    /// Signed
    pub i: i32,
    /// Unsigned
    pub u: u32,
    /// A point, its 'x' sharing the bits of 'i'
    pub point: FooPoint,
}

impl fmt::Debug for FooValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FooValue").finish_non_exhaustive()
    }
}

impl Default for FooValue {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// A record laid out without padding, as a wire format is: no field after the first is aligned
#[repr(C, packed)]
#[derive(Clone, Copy, Debug)]
pub struct FooWire {
    /// One of enum foo_shape
    pub kind: u8,
    /// At offset 1
    pub length: u32,
    /// A point, at offset 5
    pub at: FooPoint,
    /// An array, at offset 13
    pub pair: [u16; 2],
}

impl Default for FooWire {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// The status of a handle, its code a field of bits
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct FooStatus {
    /// Status code, see FOO_STATUS_CODE_*
    pub code: u16,
    /// Points the handle holds at most
    pub max: u16,
}

impl Default for FooStatus {
    /// All zero: no field has a type for which zero is not a value
    fn default() -> Self {
        unsafe { std::mem::zeroed() }
    }
}

/// The parts of its fields of bits, by name
impl FooStatus {
    /// A count is submitted and not yet completed; bit 0 of 'code'
    pub fn code_pending(&self) -> u16 {
        (self.code & 0x1) >> 0
    }

    /// Set the part of 'code' that code_pending() reads
    ///
    /// # Panics
    ///
    /// When 'value' does not fit in 1 bit
    pub fn set_code_pending(&mut self, value: u16) {
        assert!(value <= 0x1, "code_pending is 1 bit");
        self.code = (self.code & !0x1) | (value << 0);
    }

    /// Points held; bits 11:4 of 'code'
    pub fn code_points(&self) -> u16 {
        (self.code & 0xff0) >> 4
    }

    /// Set the part of 'code' that code_points() reads
    ///
    /// # Panics
    ///
    /// When 'value' does not fit in 8 bits
    pub fn set_code_points(&mut self, value: u16) {
        assert!(value <= 0xff, "code_points is 8 bits");
        self.code = (self.code & !0xff0) | (value << 4);
    }

    /// The handle holds FOO_POINTS_MAX points; bit 15 of 'code'
    pub fn code_full(&self) -> u16 {
        (self.code & 0x8000) >> 15
    }

    /// Set the part of 'code' that code_full() reads
    ///
    /// # Panics
    ///
    /// When 'value' does not fit in 1 bit
    pub fn set_code_full(&mut self, value: u16) {
        assert!(value <= 0x1, "code_full is 1 bit");
        self.code = (self.code & !0x8000) | (value << 15);
    }
}

/// Called back with each point visited
///
/// # Parameters
///
/// * `arg`: The argument given along with the callback
/// * `point`: The point visited
///
/// # Returns
///
/// 0 to go on, anything else to stop
pub type FooVisitCb = Option<unsafe extern "C" fn(*mut c_void, *const FooPoint) -> c_int>;

/// Called back when a count submitted completes
///
/// # Parameters
///
/// * `arg`: The argument given along with the callback
/// * `count`: The number of points when it completed
pub type FooDoneCb = Option<unsafe extern "C" fn(*mut c_void, usize)>;

/// Called back with each point added to a handle watched
///
/// # Parameters
///
/// * `arg`: The argument given along with the callback
/// * `point`: The point added
pub type FooAddedCb = Option<unsafe extern "C" fn(*mut c_void, *const FooPoint)>;

impl FooPoint {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"x\": ")?;
            write!(w, "{}", self.x)?;
            w.write_all(b", \"y\": ")?;
            write!(w, "{}", self.y)?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}x: ", "")?;
            write!(w, "{}", self.x)?;
            writeln!(w)?;
            write!(w, "{:indent$}y: ", "")?;
            write!(w, "{}", self.y)?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_point:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_point: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooPoint {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooVisitor {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"visit\": ")?;
            yace_pp::ptr(w, self.visit.map_or(0, |f| f as usize))?;
            w.write_all(b", \"arg\": ")?;
            yace_pp::ptr(w, self.arg as usize)?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}visit: ", "")?;
            yace_pp::ptr(w, self.visit.map_or(0, |f| f as usize))?;
            writeln!(w)?;
            write!(w, "{:indent$}arg: ", "")?;
            yace_pp::ptr(w, self.arg as usize)?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_visitor:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_visitor: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooVisitor {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooScalars {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"flag\": ")?;
            write!(w, "{}", self.flag)?;
            w.write_all(b", \"letter\": ")?;
            write!(w, "{}", self.letter)?;
            w.write_all(b", \"schar\": ")?;
            write!(w, "{}", self.schar)?;
            w.write_all(b", \"uchar\": ")?;
            write!(w, "{}", self.uchar)?;
            w.write_all(b", \"s\": ")?;
            write!(w, "{}", self.s)?;
            w.write_all(b", \"us\": ")?;
            write!(w, "{}", self.us)?;
            w.write_all(b", \"i\": ")?;
            write!(w, "{}", self.i)?;
            w.write_all(b", \"ui\": ")?;
            write!(w, "{}", self.ui)?;
            w.write_all(b", \"l\": ")?;
            write!(w, "{}", self.l)?;
            w.write_all(b", \"ul\": ")?;
            write!(w, "{}", self.ul)?;
            w.write_all(b", \"ll\": ")?;
            write!(w, "{}", self.ll)?;
            w.write_all(b", \"ull\": ")?;
            write!(w, "{}", self.ull)?;
            w.write_all(b", \"f\": ")?;
            w.write_all(yace_pp::g(self.f as f64).as_bytes())?;
            w.write_all(b", \"d\": ")?;
            w.write_all(yace_pp::g(self.d as f64).as_bytes())?;
            w.write_all(b", \"i8\": ")?;
            write!(w, "{}", self.i8)?;
            w.write_all(b", \"i16\": ")?;
            write!(w, "{}", self.i16)?;
            w.write_all(b", \"i32\": ")?;
            write!(w, "{}", self.i32)?;
            w.write_all(b", \"i64\": ")?;
            write!(w, "{}", self.i64)?;
            w.write_all(b", \"u8\": ")?;
            write!(w, "{}", self.u8)?;
            w.write_all(b", \"u16\": ")?;
            write!(w, "{}", self.u16)?;
            w.write_all(b", \"u32\": ")?;
            write!(w, "{}", self.u32)?;
            w.write_all(b", \"u64\": ")?;
            write!(w, "{}", self.u64)?;
            w.write_all(b", \"iptr\": ")?;
            write!(w, "{}", self.iptr)?;
            w.write_all(b", \"uptr\": ")?;
            write!(w, "{}", self.uptr)?;
            w.write_all(b", \"size\": ")?;
            write!(w, "{}", self.size)?;
            w.write_all(b", \"ssize\": ")?;
            write!(w, "{}", self.ssize)?;
            w.write_all(b", \"diff\": ")?;
            write!(w, "{}", self.diff)?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}flag: ", "")?;
            write!(w, "{}", self.flag)?;
            writeln!(w)?;
            write!(w, "{:indent$}letter: ", "")?;
            write!(w, "{}", self.letter)?;
            writeln!(w)?;
            write!(w, "{:indent$}schar: ", "")?;
            write!(w, "{}", self.schar)?;
            writeln!(w)?;
            write!(w, "{:indent$}uchar: ", "")?;
            write!(w, "{}", self.uchar)?;
            writeln!(w)?;
            write!(w, "{:indent$}s: ", "")?;
            write!(w, "{}", self.s)?;
            writeln!(w)?;
            write!(w, "{:indent$}us: ", "")?;
            write!(w, "{}", self.us)?;
            writeln!(w)?;
            write!(w, "{:indent$}i: ", "")?;
            write!(w, "{}", self.i)?;
            writeln!(w)?;
            write!(w, "{:indent$}ui: ", "")?;
            write!(w, "{}", self.ui)?;
            writeln!(w)?;
            write!(w, "{:indent$}l: ", "")?;
            write!(w, "{}", self.l)?;
            writeln!(w)?;
            write!(w, "{:indent$}ul: ", "")?;
            write!(w, "{}", self.ul)?;
            writeln!(w)?;
            write!(w, "{:indent$}ll: ", "")?;
            write!(w, "{}", self.ll)?;
            writeln!(w)?;
            write!(w, "{:indent$}ull: ", "")?;
            write!(w, "{}", self.ull)?;
            writeln!(w)?;
            write!(w, "{:indent$}f: ", "")?;
            w.write_all(yace_pp::g(self.f as f64).as_bytes())?;
            writeln!(w)?;
            write!(w, "{:indent$}d: ", "")?;
            w.write_all(yace_pp::g(self.d as f64).as_bytes())?;
            writeln!(w)?;
            write!(w, "{:indent$}i8: ", "")?;
            write!(w, "{}", self.i8)?;
            writeln!(w)?;
            write!(w, "{:indent$}i16: ", "")?;
            write!(w, "{}", self.i16)?;
            writeln!(w)?;
            write!(w, "{:indent$}i32: ", "")?;
            write!(w, "{}", self.i32)?;
            writeln!(w)?;
            write!(w, "{:indent$}i64: ", "")?;
            write!(w, "{}", self.i64)?;
            writeln!(w)?;
            write!(w, "{:indent$}u8: ", "")?;
            write!(w, "{}", self.u8)?;
            writeln!(w)?;
            write!(w, "{:indent$}u16: ", "")?;
            write!(w, "{}", self.u16)?;
            writeln!(w)?;
            write!(w, "{:indent$}u32: ", "")?;
            write!(w, "{}", self.u32)?;
            writeln!(w)?;
            write!(w, "{:indent$}u64: ", "")?;
            write!(w, "{}", self.u64)?;
            writeln!(w)?;
            write!(w, "{:indent$}iptr: ", "")?;
            write!(w, "{}", self.iptr)?;
            writeln!(w)?;
            write!(w, "{:indent$}uptr: ", "")?;
            write!(w, "{}", self.uptr)?;
            writeln!(w)?;
            write!(w, "{:indent$}size: ", "")?;
            write!(w, "{}", self.size)?;
            writeln!(w)?;
            write!(w, "{:indent$}ssize: ", "")?;
            write!(w, "{}", self.ssize)?;
            writeln!(w)?;
            write!(w, "{:indent$}diff: ", "")?;
            write!(w, "{}", self.diff)?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_scalars:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_scalars: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooScalars {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooFigure {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"shape\": ")?;
            write!(w, "{}", self.shape)?;
            w.write_all(b", \"options\": ")?;
            write!(w, "{}", self.options)?;
            w.write_all(b", \"origin\": ")?;
            self.origin.yace_json(w)?;
            w.write_all(b", \"corners\": ")?;
            w.write_all(b"[")?;
            for (i0, v0) in self.corners.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                v0.yace_json(w)?;
            }
            w.write_all(b"]")?;
            w.write_all(b", \"ncorners\": ")?;
            write!(w, "{}", self.ncorners)?;
            w.write_all(b", \"name\": ")?;
            yace_pp::strn(w, &self.name)?;
            w.write_all(b", \"grid\": ")?;
            w.write_all(b"[")?;
            for (i0, v0) in self.grid.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                w.write_all(b"[")?;
                for (i1, v1) in v0.iter().copied().enumerate() {
                    if i1 > 0 {
                        w.write_all(b", ")?;
                    }
                    write!(w, "{}", v1)?;
                }
                w.write_all(b"]")?;
            }
            w.write_all(b"]")?;
            w.write_all(b", \"label\": ")?;
            yace_pp::str(w, self.label)?;
            w.write_all(b", \"scale\": ")?;
            w.write_all(yace_pp::g(self.scale as f64).as_bytes())?;
            w.write_all(b", \"area\": ")?;
            w.write_all(yace_pp::g(self.area as f64).as_bytes())?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}shape: ", "")?;
            write!(w, "{}", self.shape)?;
            writeln!(w)?;
            write!(w, "{:indent$}options: ", "")?;
            write!(w, "{}", self.options)?;
            writeln!(w)?;
            writeln!(w, "{:indent$}origin:", "")?;
            self.origin.yace_yaml(w, indent + 2)?;
            write!(w, "{:indent$}corners: ", "")?;
            w.write_all(b"[")?;
            for (i0, v0) in self.corners.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                v0.yace_json(w)?;
            }
            w.write_all(b"]")?;
            writeln!(w)?;
            write!(w, "{:indent$}ncorners: ", "")?;
            write!(w, "{}", self.ncorners)?;
            writeln!(w)?;
            write!(w, "{:indent$}name: ", "")?;
            yace_pp::strn(w, &self.name)?;
            writeln!(w)?;
            write!(w, "{:indent$}grid: ", "")?;
            w.write_all(b"[")?;
            for (i0, v0) in self.grid.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                w.write_all(b"[")?;
                for (i1, v1) in v0.iter().copied().enumerate() {
                    if i1 > 0 {
                        w.write_all(b", ")?;
                    }
                    write!(w, "{}", v1)?;
                }
                w.write_all(b"]")?;
            }
            w.write_all(b"]")?;
            writeln!(w)?;
            write!(w, "{:indent$}label: ", "")?;
            yace_pp::str(w, self.label)?;
            writeln!(w)?;
            write!(w, "{:indent$}scale: ", "")?;
            w.write_all(yace_pp::g(self.scale as f64).as_bytes())?;
            writeln!(w)?;
            write!(w, "{:indent$}area: ", "")?;
            w.write_all(yace_pp::g(self.area as f64).as_bytes())?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_figure:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_figure: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooFigure {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooValue {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"i\": ")?;
            write!(w, "{}", self.i)?;
            w.write_all(b", \"u\": ")?;
            write!(w, "{}", self.u)?;
            w.write_all(b", \"point\": ")?;
            self.point.yace_json(w)?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}i: ", "")?;
            write!(w, "{}", self.i)?;
            writeln!(w)?;
            write!(w, "{:indent$}u: ", "")?;
            write!(w, "{}", self.u)?;
            writeln!(w)?;
            writeln!(w, "{:indent$}point:", "")?;
            self.point.yace_yaml(w, indent + 2)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_value:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_value: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooValue {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooWire {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"kind\": ")?;
            write!(w, "{}", { self.kind })?;
            w.write_all(b", \"length\": ")?;
            write!(w, "{}", { self.length })?;
            w.write_all(b", \"at\": ")?;
            ({ self.at }).yace_json(w)?;
            w.write_all(b", \"pair\": ")?;
            w.write_all(b"[")?;
            for (i0, v0) in { self.pair }.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                write!(w, "{}", v0)?;
            }
            w.write_all(b"]")?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}kind: ", "")?;
            write!(w, "{}", { self.kind })?;
            writeln!(w)?;
            write!(w, "{:indent$}length: ", "")?;
            write!(w, "{}", { self.length })?;
            writeln!(w)?;
            writeln!(w, "{:indent$}at:", "")?;
            ({ self.at }).yace_yaml(w, indent + 2)?;
            write!(w, "{:indent$}pair: ", "")?;
            w.write_all(b"[")?;
            for (i0, v0) in { self.pair }.iter().copied().enumerate() {
                if i0 > 0 {
                    w.write_all(b", ")?;
                }
                write!(w, "{}", v0)?;
            }
            w.write_all(b"]")?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_wire:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_wire: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooWire {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

impl FooStatus {
    #[allow(unused_unsafe)]
    fn yace_json(&self, w: &mut dyn Write) -> io::Result<()> {
        unsafe {
            w.write_all(b"{")?;
            w.write_all(b"\"code\": ")?;
            write!(w, "{{\"val\": {}", self.code)?;
            write!(w, ", \"pending\": {}", (self.code & 0x1) >> 0)?;
            write!(w, ", \"points\": {}", (self.code & 0xff0) >> 4)?;
            write!(w, ", \"full\": {}", (self.code & 0x8000) >> 15)?;
            w.write_all(b"}")?;
            w.write_all(b", \"max\": ")?;
            write!(w, "{}", self.max)?;
            w.write_all(b"}")?;
        }
        Ok(())
    }

    #[allow(unused_unsafe)]
    fn yace_yaml(&self, w: &mut dyn Write, indent: usize) -> io::Result<()> {
        unsafe {
            write!(w, "{:indent$}code: ", "")?;
            write!(w, "{{val: {:#x}", self.code)?;
            write!(w, ", pending: {:#x}", (self.code & 0x1) >> 0)?;
            write!(w, ", points: {:#x}", (self.code & 0xff0) >> 4)?;
            write!(w, ", full: {:#x}", (self.code & 0x8000) >> 15)?;
            w.write_all(b"}")?;
            writeln!(w)?;
            write!(w, "{:indent$}max: ", "")?;
            write!(w, "{}", self.max)?;
            writeln!(w)?;
        }
        Ok(())
    }

    /// Print 'obj', or null when None, to 'w', as YAML or as JSON on one line
    ///
    /// # Parameters
    ///
    /// * `flags`: one of FOO_PR_DEF, FOO_PR_YAML,
    ///   FOO_PR_TERSE and FOO_PR_JSON
    pub fn fpr(w: &mut dyn Write, obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        if flags & FOO_PR_JSON != 0 {
            match obj {
                Some(obj) => obj.yace_json(w)?,
                None => w.write_all(b"null")?,
            }
            return w.write_all(b"\n");
        }
        match obj {
            Some(obj) => {
                w.write_all(b"foo_status:\n")?;
                obj.yace_yaml(w, 2)
            }
            None => w.write_all(b"foo_status: ~\n"),
        }
    }

    /// Print 'obj' to stdout, as fpr()
    pub fn pr(obj: Option<&Self>, flags: c_int) -> io::Result<()> {
        Self::fpr(&mut io::stdout().lock(), obj, flags)
    }
}

impl fmt::Display for FooStatus {
    /// The YAML of the pretty-printers
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut out = Vec::new();
        Self::fpr(&mut out, Some(self), FOO_PR_YAML).map_err(|_| fmt::Error)?;
        f.write_str(&String::from_utf8_lossy(&out))
    }
}

extern "C" {
    /// The version of the library
    ///
    /// # Returns
    ///
    /// The version, as "MAJOR.MINOR.PATCH"
    pub fn foo_version() -> *const c_char;
    /// Why the call that failed last on the calling thread failed
    ///
    /// A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
    ///
    /// # Returns
    ///
    /// The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
    pub fn foo_errmsg() -> *const c_char;
    /// Open a handle holding no points
    ///
    /// # Parameters
    ///
    /// * `name`: Name of the handle, copied
    /// * `handle`: Set to the handle opened
    ///
    /// # Returns
    ///
    /// 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
    pub fn foo_open(name: *const c_char, handle: *mut *mut FooHandle) -> c_int;
    /// Close a handle
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle to close, NULL is ignored
    pub fn foo_close(handle: *mut FooHandle);
    /// The name the handle was opened with
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    ///
    /// # Returns
    ///
    /// The name, owned by the handle
    pub fn foo_name(handle: *const FooHandle) -> *const c_char;
    /// Add a point to the handle
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `point`: The point to add, copied
    ///
    /// # Returns
    ///
    /// 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
    pub fn foo_point_add(handle: *mut FooHandle, point: *const FooPoint) -> c_int;
    /// Add points to the handle, as many as it has room for
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `points`: The points to add, copied
    /// * `points_len`: The number of points
    ///
    /// # Returns
    ///
    /// The number of points added, -ENOSPC when there was room for none
    pub fn foo_point_add_many(
        handle: *mut FooHandle,
        points: *const FooPoint,
        points_len: usize,
    ) -> isize;
    /// The number of points held
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    ///
    /// # Returns
    ///
    /// The number of points
    pub fn foo_point_count(handle: *const FooHandle) -> usize;
    /// A point held by the handle
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `idx`: Index of the point
    ///
    /// # Returns
    ///
    /// The point, NULL when 'idx' is past the last one
    pub fn foo_point_get(handle: *const FooHandle, idx: usize) -> *const FooPoint;
    /// Copy the points held, as many as fit
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `points`: Where to copy the points to
    /// * `points_len`: The number of points that fit
    ///
    /// # Returns
    ///
    /// The number of points copied
    pub fn foo_point_copy(
        handle: *const FooHandle,
        points: *mut FooPoint,
        points_len: usize,
    ) -> isize;
    /// Watch the points added to the handle, from now until it is closed
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `added`: Called with each point added, until the handle is closed
    /// * `arg`: Given to 'added'
    ///
    /// # Returns
    ///
    /// 0 on success, -EBUSY when the handle is watched already
    pub fn foo_point_watch(handle: *mut FooHandle, added: FooAddedCb, arg: *mut c_void) -> c_int;
    /// Visit the points in the order they were added
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `visit`: Called for each point, until it returns non-zero
    /// * `arg`: Given to 'visit'
    ///
    /// # Returns
    ///
    /// The number of points visited, -EINVAL when 'visit' is NULL
    pub fn foo_point_visit(handle: *mut FooHandle, visit: FooVisitCb, arg: *mut c_void) -> isize;
    /// Visit the points with a visitor; as foo_point_visit()
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `visitor`: The callback and its argument
    ///
    /// # Returns
    ///
    /// The number of points visited, -EINVAL when the callback is NULL
    pub fn foo_point_visit_with(handle: *mut FooHandle, visitor: *const FooVisitor) -> isize;
    /// Submit a count of the points, completed by foo_count_complete()
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `done`: Called once, by foo_count_complete(), with the number of points
    /// * `arg`: Given to 'done'
    ///
    /// # Returns
    ///
    /// 0, -EBUSY when a count is submitted and not yet completed
    pub fn foo_count_submit(handle: *mut FooHandle, done: FooDoneCb, arg: *mut c_void) -> c_int;
    /// Complete the count submitted, if any, calling its callback
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    ///
    /// # Returns
    ///
    /// The number of counts completed, 0 or 1
    pub fn foo_count_complete(handle: *mut FooHandle) -> usize;
    /// The status of the handle
    ///
    /// # Parameters
    ///
    /// * `handle`: The handle
    /// * `status`: The status to fill in
    pub fn foo_status_get(handle: *const FooHandle, status: *mut FooStatus);
    /// Fill in a value of every kind of scalar, the limits of the fixed-width ones
    ///
    /// # Parameters
    ///
    /// * `scalars`: The values to fill in
    pub fn foo_scalars_fill(scalars: *mut FooScalars);
    /// Fill in a figure of the given shape
    ///
    /// # Parameters
    ///
    /// * `figure`: The figure to fill in
    /// * `shape`: One of enum foo_shape
    ///
    /// # Returns
    ///
    /// 0 on success, -EINVAL when 'shape' is none of enum foo_shape
    pub fn foo_figure_fill(figure: *mut FooFigure, shape: u32) -> c_int;
    /// Set a value, clearing the bits it does not use
    ///
    /// # Parameters
    ///
    /// * `value`: The value to set
    /// * `i`: What to set it to
    pub fn foo_value_set(value: *mut FooValue, i: i32);
    /// Fill in a packed record
    ///
    /// # Parameters
    ///
    /// * `wire`: The record to fill in
    pub fn foo_wire_fill(wire: *mut FooWire);
}

/// The idiomatic layer, over the raw functions of the crate
pub mod safe {
    #![allow(unused_imports, unused_mut, clippy::all)]
    use super::{
        FooAddedCb, FooDoneCb, FooFigure, FooHandle, FooOption, FooPoint, FooScalars, FooShape,
        FooStatus, FooValue, FooVisitCb, FooVisitor, FooWire,
    };
    use std::ffi::*;
    use std::io;
    use std::ptr::NonNull;

    /// The closures given as FooAddedCb
    pub type FooAddedCbFn<'a> = dyn FnMut(&FooPoint) + 'a;

    unsafe extern "C" fn foo_added_cb_handle_trampoline(a0: *mut c_void, a1: *const FooPoint) {
        let f = &mut **(a0 as *mut Box<FooAddedCbFn<'static>>);
        f(&*a1)
    }

    /// The closures given as FooDoneCb
    pub type FooDoneCbFn<'a> = dyn FnMut(usize) + 'a;

    /// The closures given as FooDoneCb, called once
    pub type FooDoneCbOnce = dyn FnOnce(usize) + 'static;

    unsafe extern "C" fn foo_done_cb_once_trampoline(a0: *mut c_void, a1: usize) {
        let f = Box::from_raw(a0 as *mut Box<FooDoneCbOnce>);
        f(a1)
    }

    /// The closures given as FooVisitCb
    pub type FooVisitCbFn<'a> = dyn FnMut(&FooPoint) -> c_int + 'a;

    unsafe extern "C" fn foo_visit_cb_trampoline(a0: *mut c_void, a1: *const FooPoint) -> c_int {
        let f = &mut **(a0 as *mut &mut FooVisitCbFn);
        f(&*a1)
    }

    /// A collection of points, opened with foo_open() and closed with foo_close()
    ///
    /// Owns a [`super::FooHandle`], released when dropped, by [`super::foo_close`].
    pub struct Handle {
        ptr: NonNull<super::FooHandle>,
        keep: Vec<Box<dyn std::any::Any>>,
    }

    impl Handle {
        /// The raw pointer, still owned by the Handle
        pub fn as_ptr(&self) -> *mut super::FooHandle {
            self.ptr.as_ptr()
        }

        /// Open a handle holding no points
        ///
        /// Calls [`super::foo_open`].
        ///
        /// # Parameters
        ///
        /// * `name`: Name of the handle, copied
        ///
        /// # Errors
        ///
        /// foo_open() returns: 0 on success, -EINVAL when 'name' or 'handle' is NULL, -ENOMEM when memory ran out
        pub fn open(name: &CStr) -> io::Result<Handle> {
            let mut handle = std::ptr::null_mut();
            let ret = unsafe { super::foo_open(name.as_ptr(), &mut handle) };
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            let handle = Handle {
                ptr: NonNull::new(handle)
                    .ok_or_else(|| io::Error::other("foo_open() gave no handle"))?,
                keep: Vec::new(),
            };
            Ok(handle)
        }

        /// The name the handle was opened with
        ///
        /// Calls [`super::foo_name`].
        ///
        /// # Returns
        ///
        /// The name, owned by the handle
        pub fn name(&self) -> &CStr {
            let ret = unsafe { super::foo_name(self.ptr.as_ptr()) };
            unsafe { CStr::from_ptr(ret) }
        }

        /// Add a point to the handle
        ///
        /// Calls [`super::foo_point_add`].
        ///
        /// # Parameters
        ///
        /// * `point`: The point to add, copied
        ///
        /// # Errors
        ///
        /// foo_point_add() returns: 0 on success, -ENOSPC when the handle holds FOO_POINTS_MAX points
        pub fn point_add(&mut self, point: &FooPoint) -> io::Result<()> {
            let ret = unsafe { super::foo_point_add(self.ptr.as_ptr(), point) };
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(())
        }

        /// Add points to the handle, as many as it has room for
        ///
        /// Calls [`super::foo_point_add_many`].
        ///
        /// # Parameters
        ///
        /// * `points`: The points to add, copied
        ///
        /// # Errors
        ///
        /// foo_point_add_many() returns: The number of points added, -ENOSPC when there was room for none
        pub fn point_add_many(&mut self, points: &[FooPoint]) -> io::Result<usize> {
            let ret = unsafe {
                super::foo_point_add_many(self.ptr.as_ptr(), points.as_ptr(), points.len() as usize)
            };
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(ret as usize)
        }

        /// The number of points held
        ///
        /// Calls [`super::foo_point_count`].
        ///
        /// # Returns
        ///
        /// The number of points
        pub fn point_count(&self) -> usize {
            let ret = unsafe { super::foo_point_count(self.ptr.as_ptr()) };
            ret
        }

        /// A point held by the handle
        ///
        /// Calls [`super::foo_point_get`].
        ///
        /// # Parameters
        ///
        /// * `idx`: Index of the point
        ///
        /// # Returns
        ///
        /// The point, NULL when 'idx' is past the last one
        pub fn point_get(&self, idx: usize) -> Option<FooPoint> {
            let ret = unsafe { super::foo_point_get(self.ptr.as_ptr(), idx) };
            unsafe { ret.as_ref() }.copied()
        }

        /// Copy the points held, as many as fit
        ///
        /// Calls [`super::foo_point_copy`].
        ///
        /// # Parameters
        ///
        /// * `points`: Where to copy the points to
        ///
        /// # Errors
        ///
        /// foo_point_copy() returns: The number of points copied
        pub fn point_copy<'buf>(
            &self,
            points: &'buf mut [FooPoint],
        ) -> io::Result<&'buf mut [FooPoint]> {
            let ret = unsafe {
                super::foo_point_copy(
                    self.ptr.as_ptr(),
                    points.as_mut_ptr(),
                    points.len() as usize,
                )
            };
            let points_len_ = (ret as usize).min(points.len());
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(&mut points[..points_len_])
        }

        /// Watch the points added to the handle, from now until it is closed
        ///
        /// Calls [`super::foo_point_watch`].
        ///
        /// # Parameters
        ///
        /// * `added`: Called with each point added, until the handle is closed
        ///
        /// # Errors
        ///
        /// foo_point_watch() returns: 0 on success, -EBUSY when the handle is watched already
        pub fn point_watch(&mut self, added: Box<FooAddedCbFn<'static>>) -> io::Result<()> {
            let added_kept = self.keep.len();
            let added_cb = Some(foo_added_cb_handle_trampoline as _);
            let added_ctx = {
                let f = added;
                {
                    self.keep.push(Box::new(f));
                    &mut **self.keep.last_mut().unwrap() as *mut dyn std::any::Any as *mut c_void
                }
            };
            let ret = unsafe { super::foo_point_watch(self.ptr.as_ptr(), added_cb, added_ctx) };
            if ret < 0 {
                self.keep.truncate(added_kept);
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(())
        }

        /// Visit the points in the order they were added
        ///
        /// Calls [`super::foo_point_visit`].
        ///
        /// # Parameters
        ///
        /// * `visit`: Called for each point, until it returns non-zero
        ///
        /// # Errors
        ///
        /// foo_point_visit() returns: The number of points visited, -EINVAL when 'visit' is NULL
        pub fn point_visit(&mut self, visit: &mut FooVisitCbFn) -> io::Result<usize> {
            let mut visit = visit;
            let visit_cb = Some(foo_visit_cb_trampoline as _);
            let visit_ctx = &mut visit as *mut _ as *mut c_void;
            let ret = unsafe { super::foo_point_visit(self.ptr.as_ptr(), visit_cb, visit_ctx) };
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(ret as usize)
        }

        /// Visit the points with a visitor; as foo_point_visit()
        ///
        /// Calls [`super::foo_point_visit_with`].
        ///
        /// # Parameters
        ///
        /// * `visitor`: The callback and its argument
        ///
        /// # Errors
        ///
        /// foo_point_visit_with() returns: The number of points visited, -EINVAL when the callback is NULL
        ///
        /// # Safety
        ///
        /// Pointers given, also those in records, must be valid for
        /// foo_point_visit_with(); nothing here can check them.
        pub unsafe fn point_visit_with(&mut self, visitor: &FooVisitor) -> io::Result<usize> {
            let ret = unsafe { super::foo_point_visit_with(self.ptr.as_ptr(), visitor) };
            if ret < 0 {
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(ret as usize)
        }

        /// Submit a count of the points, completed by foo_count_complete()
        ///
        /// Calls [`super::foo_count_submit`].
        ///
        /// # Parameters
        ///
        /// * `done`: Called once, by foo_count_complete(), with the number of points
        ///
        /// # Errors
        ///
        /// foo_count_submit() returns: 0, -EBUSY when a count is submitted and not yet completed
        pub fn count_submit(&mut self, done: Box<FooDoneCbOnce>) -> io::Result<()> {
            let done_cb = Some(foo_done_cb_once_trampoline as _);
            let done_ctx = {
                let f = done;
                Box::into_raw(Box::new(f)) as *mut c_void
            };
            let ret = unsafe { super::foo_count_submit(self.ptr.as_ptr(), done_cb, done_ctx) };
            if ret < 0 {
                if !done_ctx.is_null() {
                    let f = done_ctx as *mut Box<FooDoneCbOnce>;
                    std::mem::drop(unsafe { Box::from_raw(f) });
                }
                return Err(io::Error::from_raw_os_error(-(ret as i32)));
            }
            Ok(())
        }

        /// Complete the count submitted, if any, calling its callback
        ///
        /// Calls [`super::foo_count_complete`].
        ///
        /// # Returns
        ///
        /// The number of counts completed, 0 or 1
        pub fn count_complete(&mut self) -> usize {
            let ret = unsafe { super::foo_count_complete(self.ptr.as_ptr()) };
            ret
        }

        /// The status of the handle
        ///
        /// Calls [`super::foo_status_get`].
        pub fn status_get(&self) -> FooStatus {
            let mut status = FooStatus::default();
            unsafe { super::foo_status_get(self.ptr.as_ptr(), &mut status) };
            status
        }

        /// Close a handle
        ///
        /// Calls [`super::foo_close`].
        pub fn close(self) {
            let mut this = std::mem::ManuallyDrop::new(self);
            unsafe { super::foo_close(this.ptr.as_ptr()) };
            std::mem::drop(unsafe { std::ptr::read(&this.keep) });
        }
    }

    impl Drop for Handle {
        fn drop(&mut self) {
            unsafe { super::foo_close(self.ptr.as_ptr()) };
        }
    }

    /// The version of the library
    ///
    /// Calls [`super::foo_version`].
    ///
    /// # Returns
    ///
    /// The version, as "MAJOR.MINOR.PATCH"
    pub fn version() -> &'static CStr {
        let ret = unsafe { super::foo_version() };
        unsafe { CStr::from_ptr(ret) }
    }

    /// Why the call that failed last on the calling thread failed
    ///
    /// A function that returns a negative errno keeps a message saying what the errno does not, such as the name of the handle that is full. The meta names this function as 'errmsg', so that the error of a binding holds the message.
    ///
    /// Calls [`super::foo_errmsg`].
    ///
    /// # Returns
    ///
    /// The message, owned by the library and valid until the next call fails on the calling thread; "" when no call has failed
    pub fn errmsg() -> &'static CStr {
        let ret = unsafe { super::foo_errmsg() };
        unsafe { CStr::from_ptr(ret) }
    }

    /// Fill in a value of every kind of scalar, the limits of the fixed-width ones
    ///
    /// Calls [`super::foo_scalars_fill`].
    pub fn scalars_fill() -> FooScalars {
        let mut scalars = FooScalars::default();
        unsafe { super::foo_scalars_fill(&mut scalars) };
        scalars
    }

    /// Fill in a figure of the given shape
    ///
    /// Calls [`super::foo_figure_fill`].
    ///
    /// # Parameters
    ///
    /// * `shape`: One of enum foo_shape
    ///
    /// # Errors
    ///
    /// foo_figure_fill() returns: 0 on success, -EINVAL when 'shape' is none of enum foo_shape
    pub fn figure_fill(shape: u32) -> io::Result<FooFigure> {
        let mut figure = FooFigure::default();
        let ret = unsafe { super::foo_figure_fill(&mut figure, shape) };
        if ret < 0 {
            return Err(io::Error::from_raw_os_error(-(ret as i32)));
        }
        Ok(figure)
    }

    /// Set a value, clearing the bits it does not use
    ///
    /// Calls [`super::foo_value_set`].
    ///
    /// # Parameters
    ///
    /// * `i`: What to set it to
    pub fn value_set(i: i32) -> FooValue {
        let mut value = FooValue::default();
        unsafe { super::foo_value_set(&mut value, i) };
        value
    }

    /// Fill in a packed record
    ///
    /// Calls [`super::foo_wire_fill`].
    pub fn wire_fill() -> FooWire {
        let mut wire = FooWire::default();
        unsafe { super::foo_wire_fill(&mut wire) };
        wire
    }
}

Implementation

The Rust target: a crate binding the API, in the manner of a -sys crate, with pretty-printers for every struct and union, and a check of what it generated

Emits, into <output>/rust:

  • Cargo.toml and build.rs, the crate, linking the library

  • lib.rs, the crate of the bindings, which includes bindings.rs

  • bindings.rs, the bindings, which another crate may include!()

  • check.rs, the check program, an example of the crate

Functions, constants and enum members keep their C names, so the documentation of the C API applies; types become CamelCase, as Rust names types: struct foo_point is FooPoint.

class yace.targets.rust.target.Rust(output: Path, include: List[Path] | None = None, options: Dict[str, str] | None = None)
check(model: Model) → list

Build and run the check program; returns what failed, if anything

emit(model: Model) → list

Emit the code for ‘model’; returns the paths written

yace.targets.rust.target.rustdoc(doc) → str

‘doc’ as a Rust doc comment, on lines of its own, or nothing

Rust code for the IR: names, the Rust type of each IR type, and the statements of the pretty-printers. The Rust target’s templates lay out the crate; rgen produces what goes in it that depends on the types.

class yace.targets.rust.rgen.Namer(model: Model)

The Rust names of the IR’s types: CamelCase of the C name, or the C name itself where two would get the same one

function(typ: FunctionType) → str

A nullable pointer to a function of type ‘typ’, as Rust has them

rtype(typ, param: bool = False) → str

The Rust type of ‘typ’; a parameter’s arrays are pointers, as in C

class yace.targets.rust.rgen.Printer(model: Model, namer: Namer)

The Rust statements printing a value of a type as JSON

parts(field, expr: str, fmt: str, quote: str) → List[str]

The value of a field of bits and of each of its parts, as a mapping on one line, with the keys quoted by ‘quote’, the values by ‘fmt’

value(typ, expr: str, depth: int = 0) → List[str]

Statements printing the place ‘expr’ to ‘w’

class yace.targets.rust.rgen.Unions(model: Model, namer: Namer, blobs)

Which members of a union safe code may read. Reading a union’s member is unsafe in Rust because the bytes may not be a value of the member’s type. Where every member of a union is as large as the union and has no padding, a value of the union written through any member, by C or by Rust, has every byte initialised; a member of a type for which every bit pattern is a value then reads soundly. The sizes are the host’s, and the crate asserts them when compiled, so a target where they differ fails to build.

any_bits(typ) → bool

Whether every bit pattern of the size of ‘typ’ is a value of it in Rust: not of a bool, nor of a function pointer, which may not be null once Some

asserts(record) → List[str]

The assertions, at compile time, of the sizes ‘readable(record)’ relies on: each member as large as the union, and each record within as large as its fields

covered(union) → bool

Whether every member of ‘union’ spans all of it, without padding

dense(typ) → bool

Whether every byte of a value of ‘typ’ belongs to a field

getters(record) → List[str]

The methods reading the members of ‘readable(record)’

readable(record) → List[Field]

The members of ‘record’ that safe code may read, if it is a union

size(typ) → int | None

The size in bytes of a value of ‘typ’, None where not known

yace.targets.rust.rgen.accessors(record, namer: Namer) → List[str]

The methods reading and writing the parts of the fields of bits of ‘record’; reading a field of a union is unsafe, writing one is not

yace.targets.rust.rgen.debug(record, namer: Namer, blob: bool) → List[str]

A hand-written Debug of ‘record’, or none where derive(Debug) names its fields as C does. Of a union, or of a blob, no field is shown: which member of a union is meant is not known, and reading the wrong one may be unsound; a blob has no field to read.

yace.targets.rust.rgen.define_type(value) → str

The type of the Rust constant for a #define

yace.targets.rust.rgen.doc_lines(doc, errors: str = '', lead: Sequence[str] = ()) → List[str]

‘doc’ as the lines of a Rust doc comment, without the ‘///’; ‘lead’ is a paragraph before its sections, and ‘errors’ says when the function documented returns an error

yace.targets.rust.rgen.ident(name: str) → str

‘name’, usable as a Rust identifier

yace.targets.rust.rgen.place(record, field) → str

The expression of ‘field’ of ‘self’; of a packed record, a copy, as a reference to the field may not be aligned

yace.targets.rust.rgen.receiver(expr: str) → str

‘expr’ as the receiver of a method called as a statement, which a block would end

The idiomatic Rust layer of the crate, the module safe, over the raw functions: handles that release themselves when dropped, io::Result for errors, what is written through [out] pointers returned, slices for arrays, &CStr for strings, Option where NULL is allowed, and closures for callbacks. See yace.targets.idiom for what is derived from where.

A function of the layer is safe where its types check everything the caller gives: a valid handle, a pointer that is not NULL, a buffer as long as its count, by the semantics the header documents. One taking a raw pointer, or a record holding one, is unsafe, as is one returning a string borrowed from one of several arguments.