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