Skip to main content

grafton_ndi/sys/
table.rs

1//! Typed tables of native entry points and the trait their providers implement.
2
3use std::{
4    ffi::{c_void, CStr},
5    ptr::NonNull,
6};
7
8use crate::LoadRefusal;
9
10/// The native SDK entry point that produced a result.
11///
12/// Values originate in the resolved native tables, so a reported operation
13/// retains the exact name of the function that was called.
14#[derive(Clone, Copy, PartialEq, Eq, Hash)]
15pub struct NativeFunction(&'static CStr);
16
17impl NativeFunction {
18    pub(in crate::sys) const fn new(name: &'static CStr) -> Self {
19        Self(name)
20    }
21
22    /// The SDK entry point name, including its C-string terminator.
23    pub const fn name(self) -> &'static CStr {
24        self.0
25    }
26}
27
28impl std::fmt::Display for NativeFunction {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        self.0.to_string_lossy().fmt(f)
31    }
32}
33
34impl std::fmt::Debug for NativeFunction {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_tuple("NativeFunction").field(&self.0).finish()
37    }
38}
39
40impl std::error::Error for NativeFunction {}
41
42impl PartialEq<&CStr> for NativeFunction {
43    fn eq(&self, other: &&CStr) -> bool {
44        self.0 == *other
45    }
46}
47
48/// A table view whose calls retain their entry-point identity.
49pub(crate) struct Named<'a, T>(pub(in crate::sys) &'a T);
50
51/// One native result together with the entry point that produced it.
52#[derive(Clone, Copy)]
53pub(crate) struct Called<R> {
54    pub(in crate::sys) value: R,
55    pub(in crate::sys) function: NativeFunction,
56}
57
58#[allow(dead_code)]
59impl<R> Called<R> {
60    pub(crate) fn function(&self) -> NativeFunction {
61        self.function
62    }
63
64    pub(crate) fn value(&self) -> &R {
65        &self.value
66    }
67
68    pub(crate) fn into_value(self) -> R {
69        self.value
70    }
71
72    pub(crate) fn into_parts(self) -> (R, NativeFunction) {
73        (self.value, self.function)
74    }
75
76    pub(crate) fn map<T>(self, map: impl FnOnce(R) -> T) -> Called<T> {
77        Called {
78            value: map(self.value),
79            function: self.function,
80        }
81    }
82
83    pub(crate) fn failed(&self) -> crate::Error {
84        crate::Error::NativeOperationFailed {
85            operation: self.function,
86        }
87    }
88}
89
90#[allow(dead_code)]
91impl Called<bool> {
92    pub(crate) fn performed(self) -> crate::Result<()> {
93        if self.value {
94            Ok(())
95        } else {
96            Err(self.failed())
97        }
98    }
99}
100
101impl Called<i32> {
102    pub(crate) fn count(self) -> crate::Result<u32> {
103        u32::try_from(self.value).map_err(|_| {
104            crate::Error::UnexpectedSdkResult(crate::SdkResultDefect::NegativeCount {
105                operation: self.function,
106                value: self.value.into(),
107            })
108        })
109    }
110}
111
112impl Called<i64> {
113    pub(crate) fn count(self) -> crate::Result<u64> {
114        u64::try_from(self.value).map_err(|_| {
115            crate::Error::UnexpectedSdkResult(crate::SdkResultDefect::NegativeCount {
116                operation: self.function,
117                value: self.value.into(),
118            })
119        })
120    }
121}
122
123#[allow(dead_code)]
124impl<T> Called<*mut T> {
125    pub(crate) fn created(self) -> crate::Result<NonNull<T>> {
126        NonNull::new(self.value).ok_or_else(|| self.failed())
127    }
128}
129
130#[allow(dead_code)]
131impl<T> Called<*const T> {
132    pub(crate) fn created(self) -> crate::Result<NonNull<T>> {
133        NonNull::new(self.value.cast_mut()).ok_or_else(|| self.failed())
134    }
135}
136
137/// A source of native entry points: a pinned shared module or the statically
138/// linked SDK.
139pub(crate) trait Resolver {
140    /// The address of `name`, or `None` when the implementation does not export it.
141    /// Names come from static entry-point declarations, so refusals retain the
142    /// exact C string without allocating a copy.
143    ///
144    /// # Errors
145    ///
146    /// Fails when the name resolves to code outside the selected implementation.
147    fn resolve(
148        &self,
149        name: &'static CStr,
150    ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal>;
151}
152
153/// A table's exported symbol name, always validated at compile time.
154macro_rules! native_name {
155    ($name:ident) => {
156        const {
157            match ::std::ffi::CStr::from_bytes_with_nul(concat!(stringify!($name), "\0").as_bytes())
158            {
159                Ok(name) => name,
160                Err(_) => panic!("a native symbol name must end with its only NUL"),
161            }
162        }
163    };
164}
165pub(crate) use native_name;
166
167/// Define a table of native functions that is resolved as one unit.
168///
169/// Every signature is checked at compile time against the declaration bindgen
170/// produced from the SDK header in the `from` module, so a table cannot drift
171/// from the ABI. That check is the only use of the declarations on dynamically
172/// loaded targets, where nothing links them. Call an entry through the method of the same name; the field
173/// holds the raw pointer for the rare caller that passes it on.
174macro_rules! native_table {
175    (@return) => { () };
176    (@return $return:ty) => { $return };
177    (
178        $(#[$meta:meta])*
179        $vis:vis struct $Table:ident from $($declarations:ident)::+ {
180            $(
181                $(#[$function_meta:meta])*
182                fn $name:ident($($argument:ident: $type:ty),* $(,)?) $(-> $return:ty)?;
183            )+
184        }
185    ) => {
186        $(#[$meta])*
187        #[allow(non_snake_case)]
188        $vis struct $Table {
189            $(pub(crate) $name: unsafe extern "C" fn($($type),*) $(-> $return)?,)+
190        }
191
192        const_assert!({
193            use $($declarations)::+ as declarations;
194            $(const _: unsafe extern "C" fn($($type),*) $(-> $return)? = declarations::$name;)+
195        });
196
197        #[allow(non_snake_case, clippy::too_many_arguments)]
198        impl $Table {
199            /// Call entries while retaining their native function identity.
200            #[allow(dead_code)]
201            pub(crate) fn named(&self) -> $crate::sys::table::Named<'_, Self> {
202                $crate::sys::table::Named(self)
203            }
204
205            /// Exported names, in declaration order.
206            #[cfg(test)]
207            pub(crate) const SYMBOLS: &'static [&'static ::std::ffi::CStr] = &[
208                $($crate::sys::table::native_name!($name),)+
209            ];
210
211            /// Resolve every entry point, or name the first one `resolver` lacks.
212            pub(crate) fn load(
213                resolver: &dyn $crate::sys::table::Resolver,
214            ) -> ::std::result::Result<::std::result::Result<Self, &'static ::std::ffi::CStr>, $crate::LoadRefusal> {
215                Ok(Ok(Self {
216                    $($name: {
217                        const NAME: &::std::ffi::CStr =
218                            $crate::sys::table::native_name!($name);
219                        match resolver.resolve(NAME)? {
220                            // SAFETY: the resolver returned the address the selected SDK
221                            // implementation exports under this name, and the target type
222                            // is the signature its header declares (asserted above).
223                            Some(address) => unsafe {
224                                ::std::mem::transmute::<
225                                    *mut ::std::ffi::c_void,
226                                    unsafe extern "C" fn($($type),*) $(-> $return)?,
227                                >(address.as_ptr())
228                            },
229                            None => return Ok(Err(NAME)),
230                        }
231                    },)+
232                }))
233            }
234
235            $(
236                $(#[$function_meta])*
237                ///
238                /// # Safety
239                ///
240                /// The caller upholds the SDK's contract for this function.
241                #[inline]
242                #[allow(dead_code)]
243                pub(crate) unsafe fn $name(&self, $($argument: $type),*) $(-> $return)? {
244                    // SAFETY: forwarded to the caller's obligations above.
245                    unsafe { (self.$name)($($argument),*) }
246                }
247            )+
248        }
249
250        #[allow(non_snake_case, clippy::too_many_arguments, dead_code)]
251        impl $crate::sys::table::Named<'_, $Table> {
252            $(
253                /// Call this SDK entry point and retain its name.
254                ///
255                /// # Safety
256                ///
257                /// The caller upholds the SDK's contract for this function.
258                #[inline]
259                pub(crate) unsafe fn $name(&self, $($argument: $type),*)
260                    -> $crate::sys::table::Called<$crate::sys::table::native_table!(@return $($return)?)>
261                {
262                    $crate::sys::table::Called {
263                        // SAFETY: forwarded to the caller's obligations above.
264                        value: unsafe { (self.0.$name)($($argument),*) },
265                        function: $crate::sys::table::NativeFunction::new(
266                            $crate::sys::table::native_name!($name),
267                        ),
268                    }
269                }
270            )+
271        }
272    };
273}
274
275pub(crate) use native_table;
276
277/// Construct a synthetic native result for tests of SDK-output policies.
278#[cfg(test)]
279pub(crate) fn for_test<R>(value: R, name: &'static CStr) -> Called<R> {
280    Called {
281        value,
282        function: NativeFunction::new(name),
283    }
284}
285
286/// A provider for unit tests that exports the names a predicate accepts. The
287/// addresses it returns are placeholders and must never be called.
288#[cfg(test)]
289pub(crate) struct ExportsWhere<F: Fn(&str) -> bool>(pub(crate) F);
290
291#[cfg(test)]
292impl<F: Fn(&str) -> bool> Resolver for ExportsWhere<F> {
293    fn resolve(
294        &self,
295        name: &'static CStr,
296    ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal> {
297        let exported = (self.0)(name.to_str().expect("symbol names are ASCII"));
298        Ok(exported.then(NonNull::dangling))
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::sys::bindings::*;
306
307    native_table! {
308        /// Two entry points, to exercise the generated loader.
309        struct Pair from crate::sys::declarations {
310            fn NDIlib_initialize() -> bool;
311            fn NDIlib_recv_destroy(p_instance: NDIlib_recv_instance_t);
312        }
313    }
314
315    #[test]
316    fn counts_preserve_signed_evidence_without_allocating() {
317        fn negative(result: crate::Result<impl std::fmt::Debug>, value: i64) {
318            assert!(matches!(result,
319                Err(crate::Error::UnexpectedSdkResult(crate::SdkResultDefect::NegativeCount {
320                    operation, value: evidence,
321                })) if operation == c"native count" && evidence.get() == value));
322        }
323        for value in [0, i32::MAX, -1, i32::MIN] {
324            let (result, allocations) =
325                crate::test_alloc::allocation_count(|| for_test(value, c"native count").count());
326            assert_eq!(allocations, 0);
327            if value < 0 {
328                negative(result, i64::from(value));
329            } else {
330                assert_eq!(result.unwrap(), u32::try_from(value).unwrap());
331            }
332        }
333        for value in [0, i64::MAX, -1, i64::MIN] {
334            let (result, allocations) =
335                crate::test_alloc::allocation_count(|| for_test(value, c"native count").count());
336            assert_eq!(allocations, 0);
337            if value < 0 {
338                negative(result, value);
339            } else {
340                assert_eq!(result.unwrap(), u64::try_from(value).unwrap());
341            }
342        }
343    }
344
345    #[test]
346    fn a_table_lists_its_symbols_in_declaration_order() {
347        assert_eq!(
348            Pair::SYMBOLS,
349            [c"NDIlib_initialize", c"NDIlib_recv_destroy"]
350        );
351    }
352
353    #[test]
354    fn a_table_loads_only_when_every_symbol_resolves() {
355        assert!(Pair::load(&ExportsWhere(|_| true)).unwrap().is_ok());
356        let missing = Pair::load(&ExportsWhere(|name| name != "NDIlib_recv_destroy"))
357            .unwrap()
358            .err();
359        assert_eq!(missing, Some(c"NDIlib_recv_destroy"));
360    }
361
362    #[test]
363    fn a_loaded_table_forwards_arguments_and_return_values() {
364        unsafe extern "C" fn initialize() -> bool {
365            true
366        }
367        unsafe extern "C" fn destroy(instance: NDIlib_recv_instance_t) {
368            // SAFETY: this stub receives the uniquely borrowed flag below,
369            // passed through the opaque native handle without dereferencing it.
370            unsafe { instance.cast::<bool>().write(true) };
371        }
372
373        struct Stubs;
374        impl Resolver for Stubs {
375            fn resolve(
376                &self,
377                name: &'static CStr,
378            ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal> {
379                Ok(NonNull::new(match name.to_bytes() {
380                    b"NDIlib_initialize" => initialize as *mut c_void,
381                    b"NDIlib_recv_destroy" => destroy as *mut c_void,
382                    _ => return Ok(None),
383                }))
384            }
385        }
386
387        let table = Pair::load(&Stubs).unwrap().ok().unwrap();
388        let mut destroyed = false;
389        // SAFETY: this table resolved the callable stubs above. Initialization
390        // has no preconditions, and destruction receives the flag it expects.
391        unsafe {
392            assert!(table.NDIlib_initialize());
393            let called = table.named().NDIlib_initialize();
394            assert_eq!(called.function(), c"NDIlib_initialize");
395            assert!(called.into_value());
396            let called = table
397                .named()
398                .NDIlib_recv_destroy(std::ptr::from_mut(&mut destroyed).cast());
399            assert_eq!(called.function().name(), c"NDIlib_recv_destroy");
400            called.into_value();
401            table.NDIlib_recv_destroy(std::ptr::from_mut(&mut destroyed).cast());
402        }
403        assert!(destroyed);
404    }
405
406    #[test]
407    fn refused_results_retain_the_entry_point_without_allocating() {
408        unsafe extern "C" fn refuse() -> bool {
409            false
410        }
411        unsafe extern "C" fn destroy(_: NDIlib_recv_instance_t) {}
412        let table = Pair {
413            NDIlib_initialize: refuse,
414            NDIlib_recv_destroy: destroy,
415        };
416        let (result, allocations) = crate::test_alloc::allocation_count(|| {
417            // SAFETY: the table contains the no-argument stub above.
418            unsafe { table.named().NDIlib_initialize() }.performed()
419        });
420        assert!(
421            matches!(result, Err(crate::Error::NativeOperationFailed { operation })
422            if operation == c"NDIlib_initialize")
423        );
424        assert_eq!(allocations, 0);
425        let called = for_test(std::ptr::null_mut::<u8>(), c"NDIlib_send_create");
426        assert!(
427            matches!(called.created(), Err(crate::Error::NativeOperationFailed { operation })
428            if operation == c"NDIlib_send_create")
429        );
430        let mut live = 7u8;
431        let pointer = std::ptr::from_mut(&mut live);
432        assert_eq!(
433            for_test(pointer, c"NDIlib_send_create")
434                .created()
435                .unwrap()
436                .as_ptr(),
437            pointer
438        );
439    }
440
441    #[test]
442    fn a_provenance_failure_is_an_error_not_a_missing_symbol() {
443        struct Foreign;
444        impl Resolver for Foreign {
445            fn resolve(
446                &self,
447                _name: &'static CStr,
448            ) -> std::result::Result<Option<NonNull<c_void>>, LoadRefusal> {
449                Err(LoadRefusal::EntryPointOutsideModule {
450                    symbol: c"NDIlib_initialize",
451                    module: "selected module".into(),
452                })
453            }
454        }
455        assert!(Pair::load(&Foreign).is_err());
456    }
457}