Skip to main content

edgefirst_tensor_abi/
lib.rs

1// SPDX-FileCopyrightText: Copyright 2026 Au-Zone Technologies
2// SPDX-License-Identifier: Apache-2.0
3
4//! Layout-only C ABI contract for the EdgeFirst tensor surface.
5//!
6//! Plain `#[repr(C)]` values and the integer vocabularies, declared exactly
7//! once. Every `-capi` crate imports these instead of carrying an "identical
8//! copy" — r2's duplication was safe but unverified-by-construction; a single
9//! declaration makes divergence impossible instead of merely absent.
10//!
11//! This crate has **no dependencies** and must never gain one. The vocabulary
12//! values are asserted against `edgefirst-tensor`'s authority from the crates
13//! that depend on both (see `edgefirst-tensor-capi/src/codes.rs`) — this
14//! crate is emitted surface, never a second authority.
15
16/// One plane's location, mirroring `TensorPlane` on the wire.
17///
18/// The route by which one library consumes a tensor another minted: the Rust
19/// types are not shared across `.so` boundaries, so the planes are the
20/// interface. Emitted into `edgefirst/tensor.h` as `ef_tensor_plane` by
21/// cbindgen.
22#[repr(C)]
23#[derive(Debug, Clone, Copy, Default)]
24pub struct EfTensorPlane {
25    /// dma-buf fd, IOSurface id, or -1 when host memory.
26    pub handle: i64,
27    /// Byte offset of this plane within the handle.
28    pub offset: u64,
29    /// Bytes per line.
30    pub stride: u64,
31    /// Plane extent in bytes.
32    pub size: u64,
33    /// Valid payload bytes.
34    pub used: u64,
35    /// DRM format modifier; 0 = linear.
36    pub modifier: u64,
37}
38
39/// Element type of a tensor's addressing grid.
40#[repr(u32)]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum EfDtype {
43    U8 = 0,
44    I8 = 1,
45    U16 = 2,
46    I16 = 3,
47    U32 = 4,
48    I32 = 5,
49    U64 = 6,
50    I64 = 7,
51    F16 = 8,
52    F32 = 9,
53    F64 = 10,
54}
55
56/// Backing store for a tensor.
57///
58/// Every kind is declared on every platform. Whether one can be *materialised*
59/// here is a runtime question — an IOSurface is a meaningful thing to name on
60/// Linux even though nothing will allocate one — and platform-gating the
61/// vocabulary would make the same integer mean different things per target.
62#[repr(u32)]
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum EfStorageKind {
65    Mem = 0,
66    Shm = 1,
67    DmaBuf = 2,
68    IoSurface = 3,
69    Pbo = 4,
70    Cuda = 5,
71}
72
73/// CPU access direction for a map window.
74///
75/// Mirrors `edgefirst_tensor::CpuAccess`'s semantics; the values are the wire
76/// codes. `None` names the no-CPU-access declaration and is never a valid map
77/// direction.
78#[repr(u32)]
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum EfCpuAccess {
81    None = 0,
82    Read = 1,
83    Write = 2,
84    ReadWrite = 3,
85}
86
87/// Vendor tile-compression scheme actually in force for a tensor's
88/// allocation.
89///
90/// A *result*, not a request: [`EfImageDescView::compression`] carries what
91/// an allocation asked for ("any scheme" / "a specific one"), whereas this
92/// names the scheme the allocator actually resolved to. `None` is a real
93/// enumerator rather than a presence flag because "linear" is the answer for
94/// almost every allocation on almost every platform -- there is no absent
95/// case to distinguish from it, unlike `EfViewOrigin`/`EfQuantizationInfo`
96/// where every field value is legitimate.
97///
98/// Mirrors `edgefirst_tensor::CompressionScheme`'s variants, plus the
99/// `None` the Rust side spells as `Option::None`.
100#[repr(u32)]
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub enum EfCompression {
103    /// Linear layout -- no vendor tile compression.
104    #[default]
105    None = 0,
106    /// Qualcomm Adreno Universal Bandwidth Compression.
107    Ubwc = 1,
108    /// Arm Mali/Immortalis Framebuffer Compression.
109    Afbc = 2,
110    /// Imagination PowerVR Image Compression.
111    Pvric = 3,
112    /// Samsung Xclipse (AMD RDNA) Delta Color Compression.
113    Dcc = 4,
114}
115
116/// Whether a tensor's memory is known to be physically contiguous
117/// (`ef_tensor_contiguity`).
118///
119/// Mirrors `edgefirst_tensor::Contiguity`.
120#[repr(u32)]
121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
122pub enum EfContiguity {
123    /// Not known: an imported fd, or memory not allocated from a DMA heap.
124    #[default]
125    Unknown = 0,
126    /// Allocated from the CMA heap.
127    Contiguous = 1,
128    /// Allocated from the system heap.
129    NonContiguous = 2,
130}
131
132/// Which *kind* of failure the calling thread's last failing
133/// `ef_tensor_*` call was.
134///
135/// The companion to `ef_tensor_last_error_message`, and the reason it
136/// exists: an entry point that reports failure by returning `NULL` has no
137/// errno to carry a class, so a Rust consumer rebuilding a typed
138/// `edgefirst_tensor::Error` from it had nothing to go on but the advisory
139/// message -- which the message's own contract says must never be parsed.
140/// `ef_tensor_batch` really did match on a fragment of a `Display` string
141/// for exactly this reason.
142///
143/// A **class**, not a one-to-one mirror of `edgefirst_tensor::Error`. Its
144/// variants are the distinctions a caller acts on differently; several Rust
145/// variants deliberately collapse into one here, and adding a Rust variant
146/// does not oblige adding one here. `Unspecified` is the honest answer when
147/// a failure path recorded only a message, and is what every such path
148/// resets this to -- a stale class from an earlier failure would be read as
149/// this call's, which is the confident-falsehood shape this whole mechanism
150/// exists to remove.
151#[repr(u32)]
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
153pub enum EfErrorClass {
154    /// No class recorded for this failure; the message is all there is.
155    #[default]
156    Unspecified = 0,
157    /// A caller argument was malformed, out of range, or not recognized.
158    InvalidArgument = 1,
159    /// A shape was rejected: wrong rank, wrong element count, or not a
160    /// shape the format admits.
161    InvalidShape = 2,
162    /// A shape or window did not fit the allocation behind it.
163    InsufficientCapacity = 3,
164    /// An index was outside the leading (batch) dimension.
165    BatchIndexOutOfBounds = 4,
166    /// A spatial region did not fit inside its parent frame.
167    RegionOutOfBounds = 5,
168    /// The operation is not available for this tensor's backing, on this
169    /// platform, or in this build.
170    NotSupported = 6,
171    /// The operation is legal but not permitted right now -- a live map, a
172    /// shared handle, a lock another holder owns.
173    InvalidOperation = 7,
174    /// An allocation failed, or a syscall backing one did.
175    AllocationFailed = 8,
176    /// A quantization payload was rejected.
177    QuantizationInvalid = 9,
178}
179
180/// Flattened, `#[repr(C)]` view of an image-request descriptor's fields.
181///
182/// `ef_tensor_image_desc` is opaque (handles are opaque both ways: a
183/// receiving library never dereferences, sizes, or copies one). This is the
184/// scalar block `ef_tensor_image_desc_get` fills instead -- the same shape as
185/// `ef_tensor_plane`, which lets one library read a tensor it did not mint
186/// without touching the other's private layout.
187///
188/// `memory` and `compression` are each a value plus an explicit presence
189/// flag rather than a sentinel: every code in `ef_storage_kind` (0..=5) is a
190/// real value, so there is no unused number to repurpose as "no request"
191/// without colliding with `ef_storage_kind`'s `MEM == 0`. `compression` is 1
192/// for "any scheme" and 2 for "a specific vendor scheme", the latter not
193/// further decodable through this view -- no `ef_tensor_image_desc_set_*`
194/// entry point can request one, so this view has never needed to carry more
195/// detail than "present, and it's a specific one."
196#[repr(C)]
197#[derive(Debug, Clone, Copy, Default)]
198pub struct EfImageDescView {
199    /// Requested width in pixels.
200    pub width: u64,
201    /// Requested height in pixels.
202    pub height: u64,
203    /// The requested pixel format's wire code (`PixelFormat::code()`).
204    pub format: u32,
205    /// `ef_dtype`.
206    pub dtype: u32,
207    /// `ef_cpu_access`.
208    pub access: u32,
209    /// `ef_storage_kind`, meaningful only when `has_memory != 0`.
210    pub memory: u32,
211    /// Non-zero when a specific memory backing was requested (`None` on the
212    /// Rust side auto-selects).
213    pub has_memory: u32,
214    /// 1 = any scheme the platform offers; 2 = a specific vendor scheme.
215    /// Meaningful only when `has_compression != 0`.
216    pub compression: u32,
217    /// Non-zero when a compression request was made.
218    pub has_compression: u32,
219}
220
221/// Parent-region snapshot for a tensor that is a `view`/`batch` sub-region.
222///
223/// The scalar block `ef_tensor_view_origin` fills, the same shape as
224/// `ef_tensor_plane` and `ef_tensor_image_desc_view` -- one library reading a
225/// tensor it did not mint. `has_origin` is a presence flag rather than a
226/// sentinel value because every field is a legitimate 0 for a view pinned at
227/// the parent's top-left corner; the other fields are meaningful only when
228/// it is non-zero. Mirrors `edgefirst_tensor::ViewOrigin`.
229#[repr(C)]
230#[derive(Debug, Clone, Copy, Default)]
231pub struct EfViewOrigin {
232    /// Logical width of the root parent image, in pixels.
233    pub parent_width: u64,
234    /// Logical height of the root parent image, in pixels.
235    pub parent_height: u64,
236    /// The parent's row stride in bytes.
237    pub parent_row_stride: u64,
238    /// This view's top-left x origin within the root parent, in pixels.
239    pub x: u64,
240    /// This view's top-left y origin within the root parent, in pixels.
241    pub y: u64,
242    /// Non-zero when this tensor is a view/batch sub-region; 0 for a whole
243    /// tensor, in which case the other fields are all zero and unused.
244    pub has_origin: u32,
245}
246
247/// The D3D11 texture behind a Windows texture tensor.
248///
249/// The scalar block `ef_tensor_d3d11_layout` fills, the same shape as
250/// `ef_tensor_plane` and `ef_tensor_view_origin` -- one library reading a
251/// tensor it did not mint. Mirrors `edgefirst_tensor::d3d11_layout::
252/// D3d11ImageLayout`.
253///
254/// The dimensions are the texture's, in texels and rows, not the image's in
255/// pixels: a semi-planar image is one texture whose row count covers both
256/// planes, and a YUYV image is one texel per two pixels, so
257/// `texture_width`/`texture_height` do not match `ef_tensor_shape` for
258/// either. Read the image's own dimensions from the shape.
259///
260/// For a semi-planar format (`nv12`, `nv16`, `nv24`) `texture_width` is the
261/// driver's row pitch -- at least `even(width)`, and on a discrete adapter
262/// commonly more (128 bytes on NVIDIA, so a 64-wide NV12 image is a 128-wide
263/// texture). It is the pitch the combined plane's rows are spaced by and the
264/// width a sampler must address the texture at. Never derive it from the
265/// image width: read this field, or `ef_tensor_row_stride`, which carries the
266/// same number.
267///
268/// By-value and frozen forever: a consumer bakes this size and these offsets
269/// into its call sites, so the struct evolves by a suffixed successor, never
270/// by an in-place edit. `d3d11_layout_is_pinned` and the C golden in
271/// `tensor-capi/tests/c/test_layout_goldens.c` hold both sides to it.
272#[repr(C)]
273#[derive(Debug, Clone, Copy, Default)]
274pub struct EfD3d11Layout {
275    /// `DXGI_FORMAT` the texture was created with.
276    pub dxgi_format: u32,
277    /// Texture width in texels.
278    pub texture_width: u32,
279    /// Texture height in rows.
280    pub texture_height: u32,
281    /// Bytes per texel of `dxgi_format`.
282    pub bytes_per_texel: u32,
283    /// The GL internal format an importer binds this texture as; 0 when the
284    /// format has no GL equivalent.
285    pub gl_internal_format: u32,
286}
287
288/// Presence/shape summary of a tensor's quantization metadata.
289///
290/// The first half of the two-call idiom `ef_tensor_quantization_info` /
291/// `ef_tensor_quantization_get` use: this scalar block tells the caller
292/// *whether* quantization is attached and *how big* a buffer the second call
293/// needs, without allocating on either side of the boundary --
294/// `Quantization` itself is variable-length (an axis plus per-axis `scales`
295/// and `zero_points`), so unlike `ef_tensor_plane`/`ef_tensor_view_origin`
296/// this view cannot carry the payload itself.
297///
298/// `has_quantization` is a presence flag, not a sentinel, for the same
299/// reason `EfViewOrigin::has_origin` is: axis `0` and a scale of `0.0` are
300/// both legitimate values, so there is no unused bit pattern to repurpose as
301/// "absent" without colliding with a real one.
302#[repr(C)]
303#[derive(Debug, Clone, Copy, Default)]
304pub struct EfQuantizationInfo {
305    /// Channel axis for per-channel quantization; `-1` for per-tensor (no
306    /// axis). Meaningful only when `has_quantization != 0`.
307    pub axis: i32,
308    /// Number of entries in the `scale`/`zero_point` arrays (1 for
309    /// per-tensor). Meaningful only when `has_quantization != 0`.
310    pub count: u32,
311    /// Non-zero when this tensor carries quantization metadata; 0 when it
312    /// does not, in which case `axis` and `count` are both zeroed and
313    /// unused.
314    pub has_quantization: u32,
315}
316
317/// A mapped CPU window over a tensor's bytes.
318///
319/// By-value with no version field and no reserved tail, so its size
320/// is baked into consumer call sites, so it evolves by a suffixed successor
321/// (`ef_tensor_view2` + new entry points), never in place. The pointer is
322/// valid from `ef_tensor_map` until the matching `ef_tensor_unmap`; writing
323/// through it is allowed only when the map was taken with a writable access.
324#[repr(C)]
325#[derive(Debug, Clone, Copy)]
326pub struct EfTensorView {
327    pub ptr: *mut u8,
328    pub len: usize,
329}
330
331/// A retain or release call on a client-owned callback context.
332///
333/// Must be safe to call from any thread and must not unwind.
334pub type EfClientRefFn = unsafe extern "C" fn(ctx: *const core::ffi::c_void);
335
336/// Client-owned state a library entry point calls back into — **frozen by
337/// value, forever**, and reused verbatim by every domain that needs one
338/// (PBO today; CUDA-GL next).
339///
340/// # What `retain`/`release` govern — and what they do not
341///
342/// They extend the life of the **callback channel only**. They never
343/// transfer ownership of the GL buffer, the CUDA resource, or anything else
344/// the context happens to address. Getting this backwards double-frees a GL
345/// buffer:
346///
347/// * The producing side's own destructor stays the sole caller of the real
348///   `delete_buffer`.
349/// * A library that reconstructed operations from this struct treats
350///   `delete_buffer` as a no-op — it borrows the resource, it does not own
351///   it.
352///
353/// # Ownership at an entry point
354///
355/// An entry point that stores this struct calls `retain(ctx)` itself and
356/// calls `release(ctx)` exactly once when the object holding it is
357/// destroyed. The caller keeps its own count and may drop it at any time
358/// after the call returns.
359///
360/// # Freezing
361///
362/// This vocabulary declines the `struct_size` handshake (see the root
363/// `ARCHITECTURE.md`, "Why there is no `struct_size` handshake"), so a
364/// by-value struct grows only by a major bump or a suffixed successor.
365/// Freezing **one** tiny universal struct — rather than one per domain, or
366/// one that grows per domain — is what keeps that cost paid once. Its size
367/// and offsets are pinned by `tests/c/test_layout_goldens.c` in
368/// `edgefirst-tensor-capi` and by `client_state_layout_is_pinned` below.
369///
370/// `ctx` is opaque to the library: only the producing copy of the code ever
371/// dereferences it.
372#[repr(C)]
373#[derive(Clone, Copy)]
374pub struct EfClientState {
375    /// Opaque to every caller except this struct's own function pointers.
376    pub ctx: *const core::ffi::c_void,
377    // Spelled out rather than as `Option<EfClientRefFn>` -- the identical
378    // type -- because cbindgen resolves `Option<T>` to a plain C function
379    // pointer only when `T` is syntactically a bare `fn`. Given the alias it
380    // emits an opaque wrapper struct and uses it *by value*, an incomplete
381    // type in C: the header would not even compile, let alone match this
382    // struct's 24 bytes. (A third form also works and is what the PBO ops
383    // use -- an alias whose right-hand side is itself `Option<bare fn>`;
384    // see `EfPboMapFnNullable`. It is not used here because these fields
385    // want no name of their own in the header.)
386    //
387    // This comment is `//`, not `///`, on purpose: it would otherwise be
388    // copied into the C header, where it would describe Rust machinery to a
389    // C reader and name a struct that does not exist in the emitted output.
390    /// Add one reference to the callback channel. Never NULL in a valid
391    /// state; an entry point receiving NULL must fail with `EINVAL`.
392    pub retain: Option<unsafe extern "C" fn(ctx: *const core::ffi::c_void)>,
393    /// Drop one reference to the callback channel. Never NULL in a valid
394    /// state; an entry point receiving NULL must fail with `EINVAL`.
395    pub release: Option<unsafe extern "C" fn(ctx: *const core::ffi::c_void)>,
396}
397
398/// Map a PBO for CPU access. `0` on success; `-1` when the GL context is
399/// gone; any other non-zero value a generic failure.
400pub type EfPboMapFn = unsafe extern "C" fn(
401    ctx: *const core::ffi::c_void,
402    buffer_id: u32,
403    size: usize,
404    out_ptr: *mut *mut u8,
405    out_len: *mut usize,
406) -> core::ffi::c_int;
407
408/// Unmap a PBO previously mapped by an [`EfPboMapFn`]. Same return codes.
409pub type EfPboUnmapFn =
410    unsafe extern "C" fn(ctx: *const core::ffi::c_void, buffer_id: u32) -> core::ffi::c_int;
411
412// This doc is what a C reader sees for `ef_pbo_map_fn`, so it says what the
413// callback does and nothing about Rust. The mechanics, for Rust readers:
414//
415// Two Rust aliases, one C type. In C there is only ever a function pointer
416// that may or may not be NULL, so this one carries the `ef_pbo_map_fn` name
417// in the header and the bare `EfPboMapFn` is not emitted at all. The bare
418// alias is the Rust-side vocabulary for a pointer already checked -- what
419// `PboOpsVtable` stores and what `client_state_pbo_ops` takes -- and it must
420// stay bare, or every holder would carry an `Option` it has already proved
421// is `Some`.
422//
423// This one is spelled as `Option<` over a *bare* `fn`, not over
424// `EfPboMapFn`: cbindgen resolves `Option<T>` to a nullable C function
425// pointer only when `T` is syntactically a bare `fn`. Given the alias it
426// emits an opaque `struct Option_EfPboMapFn` and passes it by value -- an
427// incomplete type no C caller can name. Given this, it emits
428// `typedef int (*ef_pbo_map_fn)(...)` and uses that name at the call site,
429// which is why `ef_tensor_wrap_pbo`'s header signature does not move.
430/// Map a PBO for CPU access. `0` on success; `-1` when the GL context is
431/// gone; any other non-zero value a generic failure.
432///
433/// May be NULL where an entry point takes one; such an entry point refuses
434/// a NULL rather than calling through it.
435pub type EfPboMapFnNullable = Option<
436    unsafe extern "C" fn(
437        ctx: *const core::ffi::c_void,
438        buffer_id: u32,
439        size: usize,
440        out_ptr: *mut *mut u8,
441        out_len: *mut usize,
442    ) -> core::ffi::c_int,
443>;
444
445// See `EfPboMapFnNullable` for why there are two aliases and why this one
446// spells the `fn` out rather than naming `EfPboUnmapFn`.
447/// Unmap a PBO previously mapped by an `ef_pbo_map_fn`. Same return codes.
448///
449/// May be NULL where an entry point takes one; such an entry point refuses
450/// a NULL rather than calling through it.
451pub type EfPboUnmapFnNullable =
452    Option<unsafe extern "C" fn(ctx: *const core::ffi::c_void, buffer_id: u32) -> core::ffi::c_int>;
453
454/// Map a CUDA graphics resource to a device pointer. `0` on success.
455pub type EfCudaMapFn = unsafe extern "C" fn(
456    ctx: *const core::ffi::c_void,
457    resource: *mut core::ffi::c_void,
458    out_ptr: *mut *mut core::ffi::c_void,
459    out_len: *mut usize,
460) -> core::ffi::c_int;
461
462/// Unmap a resource previously mapped by an [`EfCudaMapFn`].
463pub type EfCudaUnmapFn =
464    unsafe extern "C" fn(ctx: *const core::ffi::c_void, resource: *mut core::ffi::c_void);
465
466/// Unregister a CUDA graphics resource.
467pub type EfCudaUnregisterFn =
468    unsafe extern "C" fn(ctx: *const core::ffi::c_void, resource: *mut core::ffi::c_void);
469
470/// Map a CUDA graphics resource to a device pointer. `0` on success.
471///
472/// May be NULL where an entry point takes one; such an entry point refuses
473/// a NULL rather than calling through it.
474pub type EfCudaMapFnNullable = Option<
475    unsafe extern "C" fn(
476        ctx: *const core::ffi::c_void,
477        resource: *mut core::ffi::c_void,
478        out_ptr: *mut *mut core::ffi::c_void,
479        out_len: *mut usize,
480    ) -> core::ffi::c_int,
481>;
482
483/// Unmap a resource previously mapped by an `ef_cuda_map_fn`.
484///
485/// May be NULL where an entry point takes one; such an entry point refuses
486/// a NULL rather than calling through it.
487pub type EfCudaUnmapFnNullable =
488    Option<unsafe extern "C" fn(ctx: *const core::ffi::c_void, resource: *mut core::ffi::c_void)>;
489
490/// Unregister a CUDA graphics resource.
491///
492/// May be NULL where an entry point takes one; such an entry point refuses
493/// a NULL rather than calling through it.
494pub type EfCudaUnregisterFnNullable =
495    Option<unsafe extern "C" fn(ctx: *const core::ffi::c_void, resource: *mut core::ffi::c_void)>;
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    #[test]
502    fn plane_layout_is_the_48_byte_scalar_block_the_blob_assumes() {
503        // The blob's 56-byte plane record is this 48-byte scalar block plus
504        // two 4-byte sequence counts (spec: Blob format, [r2] As built).
505        assert_eq!(std::mem::size_of::<EfTensorPlane>(), 48);
506        assert_eq!(std::mem::align_of::<EfTensorPlane>(), 8);
507    }
508
509    #[test]
510    fn vocabulary_enums_are_u32() {
511        assert_eq!(std::mem::size_of::<EfDtype>(), 4);
512        assert_eq!(std::mem::size_of::<EfStorageKind>(), 4);
513    }
514
515    #[test]
516    fn tensor_view_is_two_pointers_wide_and_frozen() {
517        assert_eq!(std::mem::size_of::<EfTensorView>(), 16);
518        assert_eq!(std::mem::align_of::<EfTensorView>(), 8);
519    }
520
521    #[test]
522    fn image_desc_view_layout_is_pinned() {
523        // Two `u64`s force 8-byte alignment, so the seven trailing `u32`s
524        // (28 bytes) pad out to a 48-byte struct. Pinned so a field reorder
525        // or an added field is a deliberate, visible change here.
526        assert_eq!(std::mem::size_of::<EfImageDescView>(), 48);
527        assert_eq!(std::mem::align_of::<EfImageDescView>(), 8);
528    }
529
530    #[test]
531    fn view_origin_layout_is_pinned() {
532        // Five `u64`s plus a trailing `u32` pad out to 48 at align 8. Same
533        // freeze as the C golden: a field reorder is a new suffixed struct.
534        assert_eq!(std::mem::size_of::<EfViewOrigin>(), 48);
535        assert_eq!(std::mem::align_of::<EfViewOrigin>(), 8);
536    }
537
538    #[test]
539    fn error_class_is_u32_and_unspecified_is_zero() {
540        assert_eq!(std::mem::size_of::<EfErrorClass>(), 4);
541        // 0 must be the "nothing recorded" answer: a zeroed or never-set
542        // slot has to read as "no class", never as a real classification a
543        // consumer would then act on.
544        assert_eq!(EfErrorClass::Unspecified as u32, 0);
545        assert_eq!(EfErrorClass::default(), EfErrorClass::Unspecified);
546    }
547
548    #[test]
549    fn compression_is_u32_and_none_is_zero() {
550        assert_eq!(std::mem::size_of::<EfCompression>(), 4);
551        assert_eq!(std::mem::size_of::<EfContiguity>(), 4);
552        // `ef_tensor_compression` returns this by value, and a zeroed/failed
553        // read must read as "linear", never as a scheme.
554        assert_eq!(EfCompression::None as u32, 0);
555        assert_eq!(EfCompression::default(), EfCompression::None);
556    }
557
558    #[test]
559    fn cpu_access_is_u32() {
560        assert_eq!(std::mem::size_of::<EfCpuAccess>(), 4);
561    }
562
563    #[test]
564    fn d3d11_layout_is_pinned() {
565        // Five 4-byte fields, no `u64` to force wider alignment -- 20 bytes,
566        // 4-byte aligned, and the field order the C golden asserts offsets
567        // for. A widened field or a reorder is a new suffixed struct.
568        assert_eq!(std::mem::size_of::<EfD3d11Layout>(), 20);
569        assert_eq!(std::mem::align_of::<EfD3d11Layout>(), 4);
570    }
571
572    #[test]
573    fn quantization_info_layout_is_pinned() {
574        // Three 4-byte fields, no `u64` to force wider alignment -- 12 bytes,
575        // 4-byte aligned. Pinned so a field reorder or an added field is a
576        // deliberate, visible change here.
577        assert_eq!(std::mem::size_of::<EfQuantizationInfo>(), 12);
578        assert_eq!(std::mem::align_of::<EfQuantizationInfo>(), 4);
579    }
580
581    #[test]
582    fn a_nullable_pbo_op_is_one_pointer_and_matches_its_bare_alias() {
583        // The nullable aliases are what `ef_tensor_wrap_pbo` receives and
584        // what the header's `ef_pbo_map_fn` typedef describes. If the
585        // null-pointer optimization did not apply they would not be plain C
586        // function pointers, and the header would describe an argument the
587        // ABI does not pass.
588        assert_eq!(
589            core::mem::size_of::<EfPboMapFnNullable>(),
590            core::mem::size_of::<EfPboMapFn>()
591        );
592        assert_eq!(
593            core::mem::size_of::<EfPboUnmapFnNullable>(),
594            core::mem::size_of::<EfPboUnmapFn>()
595        );
596        assert_eq!(
597            core::mem::size_of::<EfPboMapFnNullable>(),
598            core::mem::size_of::<*const core::ffi::c_void>()
599        );
600        // And `Some(f)` really is `f`: the two aliases describe one C type,
601        // so these assignments must compile.
602        unsafe extern "C" fn m(
603            _: *const core::ffi::c_void,
604            _: u32,
605            _: usize,
606            _: *mut *mut u8,
607            _: *mut usize,
608        ) -> core::ffi::c_int {
609            0
610        }
611        unsafe extern "C" fn u(_: *const core::ffi::c_void, _: u32) -> core::ffi::c_int {
612            0
613        }
614        let f: EfPboMapFn = m;
615        let _: EfPboMapFnNullable = Some(f);
616        let g: EfPboUnmapFn = u;
617        let _: EfPboUnmapFnNullable = Some(g);
618    }
619
620    #[test]
621    fn client_state_layout_is_pinned() {
622        // Three pointer-sized members at align 8. Frozen forever: this
623        // vocabulary declines a `struct_size` handshake, so a field added
624        // here is a new suffixed struct, not an edit. Mirrored by
625        // `_Static_assert`s in edgefirst-tensor-capi's C layout goldens.
626        assert_eq!(std::mem::size_of::<EfClientState>(), 24);
627        assert_eq!(std::mem::align_of::<EfClientState>(), 8);
628        assert_eq!(std::mem::offset_of!(EfClientState, ctx), 0);
629        assert_eq!(std::mem::offset_of!(EfClientState, retain), 8);
630        assert_eq!(std::mem::offset_of!(EfClientState, release), 16);
631    }
632
633    #[test]
634    fn a_nullable_client_ref_fn_is_pointer_sized() {
635        // `Option<extern "C" fn(..)>` must use the null-pointer
636        // optimization, or `retain`/`release` would not be a plain C
637        // function pointer and the struct above would not be 24 bytes.
638        // `EfClientRefFn` is the same type the two fields spell out (they
639        // spell it out only so cbindgen emits a C function pointer rather
640        // than an opaque `Option_` struct), so this covers both.
641        assert_eq!(
642            std::mem::size_of::<Option<EfClientRefFn>>(),
643            std::mem::size_of::<*const core::ffi::c_void>()
644        );
645        // And they really are the same type, not merely the same size: this
646        // assignment would not compile otherwise.
647        let _: Option<EfClientRefFn> = EfClientState {
648            ctx: core::ptr::null(),
649            retain: None,
650            release: None,
651        }
652        .retain;
653    }
654
655    #[test]
656    fn this_crate_has_no_dependencies_and_never_may() {
657        // Load-bearing for the whole design: tensor-ffi -> tensor-abi must never
658        // drag an implementation into the dynamic backend (spec r3). The
659        // [dependencies] table is empty and this test keeps it that way.
660        let manifest = include_str!("../Cargo.toml");
661        assert!(
662            !manifest.contains("[dependencies."),
663            "dependency sub-tables are dependencies too"
664        );
665        let deps = manifest
666            .split("[dependencies]")
667            .nth(1)
668            .expect("manifest has a [dependencies] table");
669        let table_body = deps.split("\n[").next().unwrap_or(deps);
670        let non_comment_lines: Vec<&str> = table_body
671            .lines()
672            .map(str::trim)
673            .filter(|l| !l.is_empty() && !l.starts_with('#'))
674            .collect();
675        assert!(
676            non_comment_lines.is_empty(),
677            "edgefirst-tensor-abi grew dependencies: {non_comment_lines:?}"
678        );
679    }
680}