nsi-ffi-wrap 0.9.0

FFI wrapper and macro for NSI-compliant renderers – ɴsɪ.
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
//! C API function generation for [`Nsi`] trait implementations.
//!
//! This module provides the infrastructure for generating C-compatible
//! `extern "C"` functions from an [`Nsi`] implementation.
//!
//! # Usage
//!
//! A renderer implementing the [`Nsi`] trait can use this module to expose
//! a C API. The typical pattern is:
//!
//! 1. Implement [`Nsi`] for your renderer type
//! 2. Create a [`FfiApiAdapter`] wrapping your renderer
//! 3. Store the adapter in a `static` or use the provided macros
//! 4. Implement the `extern "C"` functions delegating to the adapter
//!
//! # Example
//!
//! ```ignore
//! use nsi_ffi_wrap::{FfiApiAdapter, Nsi, Action};
//! use std::sync::OnceLock;
//!
//! // Your renderer implementation
//! struct MyRenderer { /* ... */ }
//! impl Nsi for MyRenderer { /* ... */ }
//!
//! // Global adapter instance
//! static ADAPTER: OnceLock<FfiApiAdapter<MyRenderer>> = OnceLock::new();
//!
//! fn init_adapter() -> &'static FfiApiAdapter<MyRenderer> {
//!     ADAPTER.get_or_init(|| FfiApiAdapter::new(MyRenderer::new()))
//! }
//!
//! // C API functions
//! #[unsafe(no_mangle)]
//! pub extern "C" fn NSIBegin(
//!     nparams: std::ffi::c_int,
//!     params: *const nsi_sys::NSIParam,
//! ) -> std::ffi::c_int {
//!     let args = unsafe { marshal_params(nparams, params) };
//!     init_adapter().begin(args.as_deref())
//! }
//! ```

use crate::{
    Action, Arg, ArgData, F32, F64, I32, I64, NodeType, String as NsiString,
};
use nsi_sys::NSIParam;
use std::ffi::{CStr, c_char, c_int};

/// Convert C API parameters to Rust [`Arg`] slice.
///
/// # Safety
///
/// The caller must ensure:
/// - `params` is valid for `nparams` elements (or null if nparams is 0)
/// - The parameter data pointers are valid for the duration of the call
/// - String data is valid UTF-8 or at least valid C strings
pub unsafe fn marshal_params_to_args<'a>(
    nparams: c_int,
    params: *const NSIParam,
) -> Option<Vec<Arg<'a, 'a>>> {
    if nparams <= 0 || params.is_null() {
        return None;
    }

    // SAFETY: Caller guarantees params is valid for nparams elements
    let params_slice =
        unsafe { std::slice::from_raw_parts(params, nparams as usize) };
    let mut args = Vec::with_capacity(nparams as usize);

    for param in params_slice {
        // SAFETY: Each param in the slice is valid per caller's guarantee
        if let Some(arg) = unsafe { marshal_single_param(param) } {
            args.push(arg);
        }
    }

    if args.is_empty() { None } else { Some(args) }
}

/// Convert a single C API parameter to a Rust [`Arg`].
///
/// # Safety
///
/// Same requirements as [`marshal_params_to_args`].
unsafe fn marshal_single_param<'a>(param: &NSIParam) -> Option<Arg<'a, 'a>> {
    if param.name.is_null() || param.data.is_null() {
        return None;
    }

    // SAFETY: Caller guarantees param.name is a valid C string
    let name = unsafe { CStr::from_ptr(param.name) }.to_str().ok()?;

    // Convert based on type
    // This is a simplified version - full implementation would handle all types
    let arg_data = match param.type_ {
        t if t == nsi_sys::NSIType::F32 as i32 => {
            // SAFETY: Caller guarantees param.data points to valid f32
            let value = unsafe { *(param.data as *const f32) };
            ArgData::from(F32::new(value))
        }
        t if t == nsi_sys::NSIType::F64 as i32 => {
            // SAFETY: Caller guarantees param.data points to valid f64
            let value = unsafe { *(param.data as *const f64) };
            ArgData::from(F64::new(value))
        }
        t if t == nsi_sys::NSIType::I32 as i32 => {
            // SAFETY: Caller guarantees param.data points to valid i32
            let value = unsafe { *(param.data as *const i32) };
            ArgData::from(I32::new(value))
        }
        t if t == nsi_sys::NSIType::I64 as i32 => {
            // SAFETY: Caller guarantees param.data points to valid i64
            let value = unsafe { *(param.data as *const i64) };
            ArgData::from(I64::new(value))
        }
        t if t == nsi_sys::NSIType::String as i32 => {
            // SAFETY: Caller guarantees param.data points to valid string pointer
            let ptr = unsafe { *(param.data as *const *const c_char) };
            if ptr.is_null() {
                return None;
            }
            // SAFETY: Caller guarantees the string pointer is valid
            let s = unsafe { CStr::from_ptr(ptr) }.to_str().ok()?;
            ArgData::from(NsiString::new(s))
        }
        // Add other types as needed...
        _ => return None,
    };

    Some(Arg::new(name, arg_data))
}

/// Parse a node type string to [`NodeType`].
///
/// # Safety
///
/// `type_str` must be a valid, null-terminated C string.
pub unsafe fn parse_node_type(type_str: *const c_char) -> Option<NodeType> {
    if type_str.is_null() {
        return None;
    }
    // SAFETY: Caller guarantees type_str is a valid C string
    let s = unsafe { CStr::from_ptr(type_str) }.to_str().ok()?;
    NodeType::from_name(s)
}

/// Parse an action string to [`Action`].
///
/// # Safety
///
/// `action_str` must be a valid, null-terminated C string.
pub unsafe fn parse_action(action_str: *const c_char) -> Option<Action> {
    if action_str.is_null() {
        return None;
    }
    // SAFETY: Caller guarantees action_str is a valid C string
    let s = unsafe { CStr::from_ptr(action_str) }.to_str().ok()?;
    Action::from_name(s)
}

/// Extract the "action" parameter from a parameter list.
///
/// This is used by `NSIRenderControl` which takes the action as a parameter.
///
/// # Safety
///
/// Same requirements as [`marshal_params_to_args`].
pub unsafe fn extract_action_from_params(
    nparams: c_int,
    params: *const NSIParam,
) -> Option<Action> {
    if nparams <= 0 || params.is_null() {
        return None;
    }

    // SAFETY: Caller guarantees params is valid for nparams elements
    let params_slice =
        unsafe { std::slice::from_raw_parts(params, nparams as usize) };

    for param in params_slice {
        if param.name.is_null() {
            continue;
        }

        // SAFETY: We checked param.name is not null
        let name = match unsafe { CStr::from_ptr(param.name) }.to_str() {
            Ok(s) => s,
            Err(_) => continue,
        };

        if name == "action" && param.type_ == nsi_sys::NSIType::String as i32 {
            // SAFETY: Caller guarantees param.data is valid for String type
            let ptr = unsafe { *(param.data as *const *const c_char) };
            if !ptr.is_null() {
                // SAFETY: We checked ptr is not null
                if let Ok(s) = unsafe { CStr::from_ptr(ptr) }.to_str() {
                    return Action::from_name(s);
                }
            }
        }
    }

    None
}

/// Convert a C string handle to a Rust string slice.
///
/// # Safety
///
/// `handle` must be a valid, null-terminated C string.
pub unsafe fn handle_to_str<'a>(handle: *const c_char) -> Option<&'a str> {
    if handle.is_null() {
        return None;
    }
    // SAFETY: Caller guarantees handle is a valid C string
    unsafe { CStr::from_ptr(handle) }.to_str().ok()
}

/// Macro for defining the complete C API for an [`Nsi`] implementation.
///
/// This macro generates all the `extern "C"` functions required for a
/// complete NSI C API implementation.
///
/// # Usage
///
/// ```ignore
/// use nsi_ffi_wrap::{define_nsi_c_api, FfiApiAdapter, Nsi};
///
/// struct MyRenderer { /* ... */ }
/// impl Nsi for MyRenderer { /* ... */ }
///
/// define_nsi_c_api!(MyRenderer, || MyRenderer::new());
/// ```
#[macro_export]
macro_rules! define_nsi_c_api {
    ($renderer_type:ty, $init:expr) => {
        use std::sync::OnceLock;

        static __NSI_ADAPTER: OnceLock<$crate::FfiApiAdapter<$renderer_type>> =
            OnceLock::new();

        fn __nsi_adapter() -> &'static $crate::FfiApiAdapter<$renderer_type> {
            __NSI_ADAPTER.get_or_init(|| $crate::FfiApiAdapter::new($init))
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIBegin(
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) -> ::std::ffi::c_int {
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };
            __nsi_adapter().begin(args.as_deref())
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIEnd(ctx: ::std::ffi::c_int) {
            __nsi_adapter().end(ctx);
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSICreate(
            ctx: ::std::ffi::c_int,
            handle: *const ::std::ffi::c_char,
            type_: *const ::std::ffi::c_char,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let handle_str = unsafe { $crate::c_api::handle_to_str(handle) };
            let node_type = unsafe { $crate::c_api::parse_node_type(type_) };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let (Some(h), Some(t)) = (handle_str, node_type) {
                __nsi_adapter().create(ctx, h, t, args.as_deref());
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIDelete(
            ctx: ::std::ffi::c_int,
            handle: *const ::std::ffi::c_char,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let handle_str = unsafe { $crate::c_api::handle_to_str(handle) };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let Some(h) = handle_str {
                __nsi_adapter().delete(ctx, h, args.as_deref());
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSISetAttribute(
            ctx: ::std::ffi::c_int,
            object: *const ::std::ffi::c_char,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let handle_str = unsafe { $crate::c_api::handle_to_str(object) };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let (Some(h), Some(a)) = (handle_str, args.as_deref()) {
                __nsi_adapter().set_attribute(ctx, h, a);
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSISetAttributeAtTime(
            ctx: ::std::ffi::c_int,
            object: *const ::std::ffi::c_char,
            time: f64,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let handle_str = unsafe { $crate::c_api::handle_to_str(object) };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let (Some(h), Some(a)) = (handle_str, args.as_deref()) {
                __nsi_adapter().set_attribute_at_time(ctx, h, time, a);
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIDeleteAttribute(
            ctx: ::std::ffi::c_int,
            object: *const ::std::ffi::c_char,
            name: *const ::std::ffi::c_char,
        ) {
            let handle_str = unsafe { $crate::c_api::handle_to_str(object) };
            let name_str = unsafe { $crate::c_api::handle_to_str(name) };

            if let (Some(h), Some(n)) = (handle_str, name_str) {
                __nsi_adapter().delete_attribute(ctx, h, n);
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIConnect(
            ctx: ::std::ffi::c_int,
            from: *const ::std::ffi::c_char,
            from_attr: *const ::std::ffi::c_char,
            to: *const ::std::ffi::c_char,
            to_attr: *const ::std::ffi::c_char,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let from_str = unsafe { $crate::c_api::handle_to_str(from) };
            let from_attr_str =
                unsafe { $crate::c_api::handle_to_str(from_attr) };
            let to_str = unsafe { $crate::c_api::handle_to_str(to) };
            let to_attr_str = unsafe { $crate::c_api::handle_to_str(to_attr) };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let (Some(f), Some(t), Some(ta)) =
                (from_str, to_str, to_attr_str)
            {
                __nsi_adapter().connect(
                    ctx,
                    f,
                    from_attr_str,
                    t,
                    ta,
                    args.as_deref(),
                );
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIDisconnect(
            ctx: ::std::ffi::c_int,
            from: *const ::std::ffi::c_char,
            from_attr: *const ::std::ffi::c_char,
            to: *const ::std::ffi::c_char,
            to_attr: *const ::std::ffi::c_char,
        ) {
            let from_str = unsafe { $crate::c_api::handle_to_str(from) };
            let from_attr_str =
                unsafe { $crate::c_api::handle_to_str(from_attr) };
            let to_str = unsafe { $crate::c_api::handle_to_str(to) };
            let to_attr_str = unsafe { $crate::c_api::handle_to_str(to_attr) };

            if let (Some(f), Some(t), Some(ta)) =
                (from_str, to_str, to_attr_str)
            {
                __nsi_adapter().disconnect(ctx, f, from_attr_str, t, ta);
            }
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIEvaluate(
            ctx: ::std::ffi::c_int,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };
            __nsi_adapter().evaluate(ctx, args.as_deref());
        }

        #[unsafe(no_mangle)]
        pub extern "C" fn NSIRenderControl(
            ctx: ::std::ffi::c_int,
            nparams: ::std::ffi::c_int,
            params: *const ::nsi_sys::NSIParam,
        ) {
            let action = unsafe {
                $crate::c_api::extract_action_from_params(nparams, params)
            };
            let args = unsafe {
                $crate::c_api::marshal_params_to_args(nparams, params)
            };

            if let Some(a) = action {
                __nsi_adapter().render_control(ctx, a, args.as_deref());
            }
        }
    };
}