nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
//! Safe, DRY Rust application trait (`NvApp`) and `export_nv_app!` macro.
//!
//! Apps implement `NvApp` once with zero `unsafe`. Rust-native hosts (Web WASM, Headless tests,
//! static release builds) invoke `NvApp` directly with zero FFI overhead (monomorphized/inlined),
//! while `export_nv_app!(MyApp)` generates the modular `nv_get_interface(uint32_t)` C ABI for
//! C++ Fabric, iOS/macOS, Android/JNI, Flutter `dart:ffi`, SwiftUI, and Tier-2 `cdylib` hot-swap.

use std::any::Any;
use std::cell::RefCell;

use nativeview_abi::{
    FrameId, HostServiceId, NvDirectHostEnv, NvGestureDisposition, NvHostCallbacks,
    NvIntrinsicSize, NvPropsRef, NvSizeConstraints, SurfaceId, ValidatedEvents,
};

thread_local! {
    static LAST_FFI_PANIC: RefCell<Option<String>> = const { RefCell::new(None) };
}

/// Formats a caught panic payload into a human-readable message.
#[cold]
#[inline(never)]
#[expect(
    clippy::disallowed_methods,
    reason = "FFI catch_unwind panic payload boundary requires std::any::Any downcast"
)]
pub fn format_panic_payload(payload: &(dyn Any + Send)) -> String {
    if let Some(s) = payload.downcast_ref::<&str>() {
        (*s).to_owned()
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s.clone()
    } else {
        "non-string panic payload".to_owned()
    }
}

/// Records a panic captured at an `extern "C"` FFI boundary for the current thread.
#[cold]
#[inline(never)]
#[doc(hidden)]
pub fn record_ffi_panic(fn_name: &'static str, payload: Box<dyn Any + Send>) {
    let detail = format_panic_payload(&*payload);
    let msg = format!("{fn_name}: {detail}");
    LAST_FFI_PANIC.with(|slot| {
        *slot.borrow_mut() = Some(msg);
    });
}

/// Returns a copy of the last panic message captured at an `extern "C"` FFI boundary on the
/// current thread, if any, without clearing it.
pub fn last_ffi_panic() -> Option<String> {
    LAST_FFI_PANIC.with(|slot| slot.borrow().clone())
}

/// Takes and clears the last panic message captured at an `extern "C"` FFI boundary on the
/// current thread, if any.
pub fn take_last_ffi_panic() -> Option<String> {
    LAST_FFI_PANIC.with(|slot| slot.borrow_mut().take())
}

/// Clears any recorded FFI panic on the current thread.
pub fn clear_last_ffi_panic() {
    LAST_FFI_PANIC.with(|slot| {
        let _ = slot.borrow_mut().take();
    });
}

/// Executes `f` inside a zero-cost `catch_unwind` boundary.
///
/// On normal non-panicking execution, this returns `f()` directly without touching thread-local
/// storage. On panic, it prevents unwinding across `extern "C"`, records the formatted message in
/// the current thread's FFI panic slot, and returns `fallback`.
#[inline(always)]
#[doc(hidden)]
pub fn ffi_catch_unwind<T, F>(fn_name: &'static str, fallback: T, f: F) -> T
where
    F: FnOnce() -> T,
{
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(val) => val,
        Err(payload) => {
            record_ffi_panic(fn_name, payload);
            fallback
        }
    }
}

/// Default intrinsic size calculation shared by [`NvApp::measure`] and framework adapters.
#[inline]
pub fn default_measure_constraints(constraints: NvSizeConstraints) -> NvIntrinsicSize {
    let w = if constraints.max_w.is_finite() {
        constraints.max_w.max(constraints.min_w)
    } else {
        constraints.min_w
    };
    let h = if constraints.max_h.is_finite() {
        constraints.max_h.max(constraints.min_h)
    } else {
        constraints.min_h
    };
    NvIntrinsicSize {
        width: w,
        height: h,
    }
}

pub trait NvApp: Sized + 'static {
    fn create(surface_id: SurfaceId) -> Self;

    /// Renders pending mutations into a binary `nativeview_abi::CommandBuffer` slice valid until the next call.
    fn render(&mut self, frame_id: FrameId) -> &[u8];

    /// Processes an ingress-validated event batch (`ValidatedEvents`); returns `true` if re-render is needed.
    fn dispatch_events(&mut self, events: ValidatedEvents<'_>) -> bool;

    /// Takes the close request of the last [`Self::dispatch_events`]: an `Escape` / `GoBack` key
    /// down no listener consumed, which the runtime routes to the topmost escapable overlay
    /// ([INV:close-request-single-path]).
    fn take_close_request(&mut self) -> bool {
        false
    }

    /// Takes whether the last `KeyDown` of [`Self::dispatch_events`] went unconsumed by app
    /// listeners (eligible for post-dispatch runtime `DefaultAction`s).
    fn take_unconsumed_key(&mut self) -> bool {
        false
    }

    /// Drains the W3C pointer capture requests listeners made during the last
    /// [`Self::dispatch_events`] (see `crate::RuntimeApp::drain_pointer_capture_requests`;
    /// `export_nv_app!` carries them over `NvPointerApi`).
    fn drain_pointer_capture_requests(
        &mut self,
        _sink: &mut dyn FnMut(crate::tracker::PointerCaptureRequest),
    ) {
    }

    /// Polls the app's async tasks (timers, fetches) against `waker`, which a task woken later
    /// fires to request a frame. Returns `true` when work became ready and a render must follow.
    fn poll_work(&mut self, _waker: &core::task::Waker) -> bool {
        false
    }

    /// Intrinsic size measurement for embedded hosts (RN Yoga, Flutter RenderBox, SwiftUI, Compose).
    fn measure(&mut self, constraints: NvSizeConstraints) -> NvIntrinsicSize {
        default_measure_constraints(constraints)
    }

    /// Synchronous hit-test / gesture disposition query across framework boundaries.
    fn hit_test(&mut self, _x: f32, _y: f32, _pointer_phase: u8) -> NvGestureDisposition {
        NvGestureDisposition::PassThrough
    }

    /// Applies host-supplied direct typed props (`NvPropsRef`); returns `true` if re-render is needed.
    fn set_props(&mut self, _props: NvPropsRef<'_>) -> bool {
        false
    }

    /// Drains component-emitted outbound events as an ingress-validated zero-copy batch.
    fn drain_emitted_events(&mut self) -> ValidatedEvents<'_> {
        ValidatedEvents::EMPTY
    }

    /// Applies a Tier-1 hot-reload patch, decoded from the `NV_HOT_PATCH` bytes the host passed to
    /// `NvDevApi::apply_hot_patch`.
    fn apply_hot_patch(&mut self, _patch: &crate::HotPatchMsg) -> bool {
        false
    }

    /// Serializes state for preservation across a Tier-2 `cdylib` hot-swap.
    fn snapshot_state(&mut self) -> &[u8] {
        &[]
    }

    /// Restores previously snapshotted state after a Tier-2 `cdylib` hot-swap.
    fn restore_state(&mut self, _state: &[u8]) {}

    /// Binds host-provided binary capability callbacks (`NV_IFACE_HOST = 5`).
    /// Passing `None` unbinds any previously attached host callbacks.
    fn bind_host(&mut self, _callbacks: Option<NvHostCallbacks>) {}

    /// Dispatches a host-event payload buffer across `NV_IFACE_HOST = 5`.
    /// Returns `true` if the surface should re-render.
    fn dispatch_host_events(&mut self, _batch: &[u8]) -> bool {
        false
    }

    /// Binds or unbinds the non-reloaded `NV_IFACE_DIRECT_HOST = 6` direct host environment.
    fn bind_direct_host(&mut self, _env: Option<NvDirectHostEnv>) {}

    /// Dispatches one completed direct-FFI async reply on the owner thread.
    fn dispatch_direct_completion(
        &mut self,
        _local_req_id: u64,
        _status: i32,
        _payload: &[u8],
    ) -> bool {
        false
    }

    /// Dispatches one direct-FFI push event on the owner thread.
    fn dispatch_direct_event(
        &mut self,
        _service_id: HostServiceId,
        _event_id: u32,
        _flags: u32,
        _payload: &[u8],
    ) -> bool {
        false
    }
}

/// Generates the modular `nv_get_interface` C ABI (and optional custom symbol alias) from any
/// safe `NvApp` implementation with zero boilerplate `unsafe` in app code.
#[macro_export]
macro_rules! export_nv_app {
    ($app_ty:ty) => {
        $crate::export_nv_app!($app_ty, symbol = nv_get_interface);
    };
    ($app_ty:ty, symbol = $symbol:ident) => {
        #[allow(unsafe_code)]
        const _: () = {
            use ::std::ffi::c_void;
            use $crate::abi::{
                DispatchResult, FrameId, HostServiceId, InterfaceId, NvAppHandle, NvBufferSlice,
                NvComponentApi,
                NvDevApi, NvDirectHostApi, NvDirectHostEnv, NvEventBatch,
                NvGestureDisposition, NvHostApi, NvHostCallbacks, NvIntrinsicSize,
                NvLayoutApi, NvMapEntry, NvPointerApi, NvPointerCaptureRequest, NvPropsRef,
                NvSizeConstraints, NvSurfaceApi, SurfaceId, ValidatedEvents, NV_IFACE_COMPONENT,
                NV_IFACE_DEV, NV_IFACE_DIRECT_HOST, NV_IFACE_HOST, NV_IFACE_LAYOUT,
                NV_IFACE_POINTER, NV_IFACE_SURFACE,
            };
            use $crate::NvApp;

            unsafe extern "C" fn __nv_create(surface_id: SurfaceId) -> NvAppHandle {
                $crate::app::ffi_catch_unwind(
                    "NvSurfaceApi::create",
                    ::std::ptr::null_mut(),
                    || {
                        let canonical = SurfaceId::from_raw_or_null(surface_id.raw());
                        let boxed = Box::new(<$app_ty as NvApp>::create(canonical));
                        Box::into_raw(boxed) as NvAppHandle
                    },
                )
            }

            unsafe extern "C" fn __nv_destroy(handle: NvAppHandle) {
                if handle.is_null() {
                    return;
                }
                $crate::app::ffi_catch_unwind("NvSurfaceApi::destroy", (), || {
                    // SAFETY: `handle` was allocated by `__nv_create` via `Box::into_raw` and is destroyed at most once.
                    unsafe { drop(Box::from_raw(handle as *mut $app_ty)) };
                });
            }

            unsafe extern "C" fn __nv_render(
                handle: NvAppHandle,
                frame_id: FrameId,
            ) -> NvBufferSlice {
                if handle.is_null() {
                    return NvBufferSlice::EMPTY;
                }
                $crate::app::ffi_catch_unwind(
                    "NvSurfaceApi::render",
                    NvBufferSlice::EMPTY,
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        NvBufferSlice::from_slice(app.render(frame_id))
                    },
                )
            }

            unsafe extern "C" fn __nv_dispatch_events(
                handle: NvAppHandle,
                batch: NvEventBatch,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvSurfaceApi::dispatch_events", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `batch` points to readable `NvEvent` and byte arena slices for this call.
                    let Ok(events) = (unsafe { ValidatedEvents::try_from_raw(batch) }) else {
                        return 0;
                    };
                    let dirty = app.dispatch_events(events);
                    DispatchResult::from_parts(
                        dirty,
                        app.take_close_request(),
                        app.take_unconsumed_key(),
                    )
                    .bits()
                })
            }

            unsafe extern "C" fn __nv_measure(
                handle: NvAppHandle,
                constraints: NvSizeConstraints,
            ) -> NvIntrinsicSize {
                if handle.is_null() {
                    return NvIntrinsicSize {
                        width: 0.0,
                        height: 0.0,
                    };
                }
                $crate::app::ffi_catch_unwind(
                    "NvLayoutApi::measure",
                    NvIntrinsicSize {
                        width: 0.0,
                        height: 0.0,
                    },
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        app.measure(constraints)
                    },
                )
            }

            unsafe extern "C" fn __nv_hit_test(
                handle: NvAppHandle,
                x: f32,
                y: f32,
                pointer_phase: u8,
            ) -> u8 {
                if handle.is_null() {
                    return NvGestureDisposition::PassThrough as u8;
                }
                $crate::app::ffi_catch_unwind(
                    "NvLayoutApi::hit_test",
                    NvGestureDisposition::PassThrough as u8,
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        app.hit_test(x, y, pointer_phase) as u8
                    },
                )
            }

            unsafe extern "C" fn __nv_set_props(
                handle: NvAppHandle,
                entries: *const NvMapEntry,
                count: u32,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvComponentApi::set_props", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `entries..entries+count` is readable for this call.
                    let props = unsafe { NvPropsRef::from_raw_parts(entries, count) };
                    u32::from(app.set_props(props))
                })
            }

            unsafe extern "C" fn __nv_drain_emitted_events(
                handle: NvAppHandle,
            ) -> NvEventBatch {
                if handle.is_null() {
                    return NvEventBatch::EMPTY;
                }
                $crate::app::ffi_catch_unwind(
                    "NvComponentApi::drain_emitted_events",
                    NvEventBatch::EMPTY,
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        app.drain_emitted_events().as_raw_batch()
                    },
                )
            }

            unsafe extern "C" fn __nv_apply_hot_patch(
                handle: NvAppHandle,
                patch: NvBufferSlice,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvDevApi::apply_hot_patch", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `patch` is readable for the duration of this call.
                    let raw = unsafe { patch.as_slice() };
                    let Ok(msg) = $crate::HotPatchMsg::from_bytes(raw)
                    else {
                        return 0;
                    };
                    u32::from(app.apply_hot_patch(&msg))
                })
            }

            unsafe extern "C" fn __nv_snapshot_state(handle: NvAppHandle) -> NvBufferSlice {
                if handle.is_null() {
                    return NvBufferSlice::EMPTY;
                }
                $crate::app::ffi_catch_unwind(
                    "NvDevApi::snapshot_state",
                    NvBufferSlice::EMPTY,
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        NvBufferSlice::from_slice(app.snapshot_state())
                    },
                )
            }

            unsafe extern "C" fn __nv_restore_state(
                handle: NvAppHandle,
                state: NvBufferSlice,
            ) {
                if handle.is_null() {
                    return;
                }
                $crate::app::ffi_catch_unwind("NvDevApi::restore_state", (), || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `state` is readable for the duration of this call.
                    let bytes = unsafe { state.as_slice() };
                    app.restore_state(bytes);
                });
            }

            unsafe extern "C" fn __nv_bind_host(
                handle: NvAppHandle,
                callbacks: *const NvHostCallbacks,
            ) {
                if handle.is_null() {
                    return;
                }
                $crate::app::ffi_catch_unwind("NvHostApi::bind_host", (), || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    let bound = if callbacks.is_null() {
                        None
                    } else {
                        // SAFETY: Non-null `callbacks` points to a valid `NvHostCallbacks` struct.
                        Some(unsafe { *callbacks })
                    };
                    app.bind_host(bound);
                });
            }

            unsafe extern "C" fn __nv_dispatch_host_events(
                handle: NvAppHandle,
                batch: NvBufferSlice,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvHostApi::dispatch_host_events", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `batch` is readable for the duration of this call.
                    let bytes = unsafe { batch.as_slice() };
                    u32::from(app.dispatch_host_events(bytes))
                })
            }

            unsafe extern "C" fn __nv_bind_direct_host(
                handle: NvAppHandle,
                env: *const NvDirectHostEnv,
            ) {
                if handle.is_null() {
                    return;
                }
                $crate::app::ffi_catch_unwind("NvDirectHostApi::bind_direct_host", (), || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: `from_raw_checked` validates non-null, alignment, `abi_version`, and
                    // `struct_size >= size_of::<NvDirectHostEnv>()` before reading the full struct.
                    let bound = unsafe { NvDirectHostEnv::from_raw_checked(env) };
                    app.bind_direct_host(bound);
                });
            }

            unsafe extern "C" fn __nv_dispatch_direct_completion(
                handle: NvAppHandle,
                local_req_id: u64,
                status: i32,
                ptr: *const u8,
                len: usize,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind(
                    "NvDirectHostApi::dispatch_direct_completion",
                    0,
                    || {
                        // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                        let app = unsafe { &mut *(handle as *mut $app_ty) };
                        // SAFETY: Host guarantees `(ptr, len)` is readable for this synchronous call.
                        let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
                            return u32::from(app.dispatch_direct_completion(
                                local_req_id,
                                $crate::abi::NvModStatus::Codec.as_i32(),
                                &[],
                            ));
                        };
                        u32::from(app.dispatch_direct_completion(local_req_id, status, bytes))
                    },
                )
            }

            unsafe extern "C" fn __nv_dispatch_direct_event(
                handle: NvAppHandle,
                service_id: HostServiceId,
                event_id: u32,
                flags: u32,
                ptr: *const u8,
                len: usize,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvDirectHostApi::dispatch_direct_event", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: Host guarantees `(ptr, len)` is readable for this synchronous call.
                    let Some(bytes) = (unsafe { $crate::abi::sink_bytes(ptr, len) }) else {
                        return 0;
                    };
                    u32::from(app.dispatch_direct_event(service_id, event_id, flags, bytes))
                })
            }

            unsafe extern "C" fn __nv_drain_capture_requests(
                handle: NvAppHandle,
                out: *mut NvPointerCaptureRequest,
                cap: u32,
            ) -> u32 {
                if handle.is_null() {
                    return 0;
                }
                $crate::app::ffi_catch_unwind("NvPointerApi::drain_capture_requests", 0, || {
                    // SAFETY: Non-null `handle` is an exclusive live `$app_ty` created by `__nv_create`.
                    let app = unsafe { &mut *(handle as *mut $app_ty) };
                    // SAFETY: The caller guarantees `out` is NULL or writable for `cap` records.
                    unsafe { $crate::app::pointer::write_capture_requests(app, out, cap) }
                })
            }

            static __NV_POINTER_API: NvPointerApi = NvPointerApi {
                drain_capture_requests: __nv_drain_capture_requests,
            };

            static __NV_SURFACE_API: NvSurfaceApi = NvSurfaceApi {
                create: __nv_create,
                destroy: __nv_destroy,
                render: __nv_render,
                dispatch_events: __nv_dispatch_events,
            };

            static __NV_LAYOUT_API: NvLayoutApi = NvLayoutApi {
                measure: __nv_measure,
                hit_test: __nv_hit_test,
            };

            static __NV_COMPONENT_API: NvComponentApi = NvComponentApi {
                set_props: __nv_set_props,
                drain_emitted_events: __nv_drain_emitted_events,
            };

            static __NV_DEV_API: NvDevApi = NvDevApi {
                apply_hot_patch: __nv_apply_hot_patch,
                snapshot_state: __nv_snapshot_state,
                restore_state: __nv_restore_state,
            };

            static __NV_HOST_API: NvHostApi = NvHostApi {
                bind_host: __nv_bind_host,
                dispatch_host_events: __nv_dispatch_host_events,
            };

            static __NV_DIRECT_HOST_API: NvDirectHostApi = NvDirectHostApi {
                bind_direct_host: __nv_bind_direct_host,
                dispatch_direct_completion: __nv_dispatch_direct_completion,
                dispatch_direct_event: __nv_dispatch_direct_event,
            };

            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn $symbol(interface_id: InterfaceId) -> *const c_void {
                match interface_id {
                    NV_IFACE_SURFACE => &__NV_SURFACE_API as *const NvSurfaceApi as *const c_void,
                    NV_IFACE_LAYOUT => &__NV_LAYOUT_API as *const NvLayoutApi as *const c_void,
                    NV_IFACE_COMPONENT => {
                        &__NV_COMPONENT_API as *const NvComponentApi as *const c_void
                    }
                    NV_IFACE_DEV => &__NV_DEV_API as *const NvDevApi as *const c_void,
                    NV_IFACE_HOST => &__NV_HOST_API as *const NvHostApi as *const c_void,
                    NV_IFACE_DIRECT_HOST => {
                        &__NV_DIRECT_HOST_API as *const NvDirectHostApi as *const c_void
                    }
                    NV_IFACE_POINTER => &__NV_POINTER_API as *const NvPointerApi as *const c_void,
                    _ => ::std::ptr::null(),
                }
            }
        };
    };
}

pub mod module;
pub mod pointer;

#[cfg(test)]
mod tests;