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
//! API of a native module.
use crate::ffi::collections::NonNullConst;
use crate::ffi::module::native_module::{
    NativeModule as NativeModuleFFI, NativeModuleBinding,
    NativeModuleInterface as NativeModuleInterfaceFFI,
};
use crate::ffi::CBaseBinding;
use crate::module::{Error, Interface, InterfaceDescriptor, Module, ModuleInfo};
use crate::ownership::{
    AccessIdentifier, BorrowImmutable, BorrowMutable, ImmutableAccessIdentifier,
    MutableAccessIdentifier, Owned,
};
use crate::CBaseInterfaceInfo;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;

/// An instance from a native module.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct NativeModuleInstance<'a, O> {
    _handle: Option<NonNull<NativeModuleFFI>>,
    _phantom: PhantomData<&'a ()>,
    _ownership: PhantomData<*const O>,
}

unsafe impl<O> Send for NativeModuleInstance<'_, O> {}
unsafe impl<O> Sync for NativeModuleInstance<'_, O> {}

impl<O> NativeModuleInstance<'_, O>
where
    O: AccessIdentifier,
{
    /// Construct a new instance from a handle.
    ///
    /// # Safety
    ///
    /// This function allows the creation of invalid handles
    /// by bypassing lifetimes.
    #[inline]
    pub const unsafe fn new(handle: Option<NonNull<NativeModuleFFI>>) -> Self {
        Self {
            _handle: handle,
            _phantom: PhantomData,
            _ownership: PhantomData,
        }
    }

    /// Fetches the internal handle.
    #[inline]
    pub const fn as_handle(&self) -> Option<NonNull<NativeModuleFFI>> {
        self._handle
    }
}

impl NativeModuleInstance<'_, Owned> {
    /// Borrows the instance.
    #[inline]
    pub const fn as_borrowed(&self) -> NativeModuleInstance<'_, BorrowImmutable<'_>> {
        unsafe { NativeModuleInstance::<BorrowImmutable<'_>>::new(self._handle) }
    }

    /// Borrows the instance mutably.
    #[inline]
    pub fn as_borrowed_mut(&mut self) -> NativeModuleInstance<'_, BorrowMutable<'_>> {
        unsafe { NativeModuleInstance::<BorrowMutable<'_>>::new(self._handle) }
    }
}

/// A native module.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct NativeModule<'a, O> {
    _interface: NonNullConst<NativeModuleInterfaceFFI>,
    _phantom: PhantomData<&'a ()>,
    _ownership: PhantomData<*const O>,
}

unsafe impl<O> Send for NativeModule<'_, O> {}
unsafe impl<O> Sync for NativeModule<'_, O> {}

impl<O> Deref for NativeModule<'_, O> {
    type Target = NonNullConst<NativeModuleInterfaceFFI>;

    fn deref(&self) -> &Self::Target {
        &self._interface
    }
}

impl<O> DerefMut for NativeModule<'_, O> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self._interface
    }
}

impl<O> NativeModule<'_, O>
where
    O: AccessIdentifier,
{
    /// Construct a new instance from an interface.
    ///
    /// # Safety
    ///
    /// This function allows the creation of invalid modules
    /// by bypassing lifetimes.
    #[inline]
    pub const unsafe fn new(interface: NonNullConst<NativeModuleInterfaceFFI>) -> Self {
        Self {
            _interface: interface,
            _phantom: PhantomData,
            _ownership: PhantomData,
        }
    }
}

impl NativeModule<'_, Owned> {
    /// Borrows the module interface.
    #[inline]
    pub const fn as_borrowed(&self) -> NativeModule<'_, BorrowImmutable<'_>> {
        unsafe { NativeModule::<'_, BorrowImmutable<'_>>::new(self._interface) }
    }

    /// Borrows the module interface mutably.
    #[inline]
    pub fn as_borrowed_mut(&mut self) -> NativeModule<'_, BorrowMutable<'_>> {
        unsafe { NativeModule::<'_, BorrowMutable<'_>>::new(self._interface) }
    }
}

impl<'a, O> NativeModule<'a, O>
where
    O: MutableAccessIdentifier,
{
    /// Loads the module.
    ///
    /// # Failure
    ///
    /// The function can fail if some module invariant is not met.
    ///
    /// # Return
    ///
    /// Handle on success, error otherwise.
    ///
    /// # Safety
    ///
    /// The function crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn load<MO>(
        &mut self,
        module: &Module<'_, MO>,
        interface: &impl CBaseInterfaceInfo,
    ) -> Result<NativeModuleInstance<'a, Owned>, Error>
    where
        MO: AccessIdentifier,
    {
        let internal = interface.internal_interface();
        let interface_handle = internal.base_module();
        let has_fn_fn = internal.fetch_has_function_fn();
        let get_fn_fn = internal.fetch_get_function_fn();

        self._interface
            .into_mut()
            .as_mut()
            .load(module.as_handle(), interface_handle, has_fn_fn, get_fn_fn)
            .map_or_else(
                |e| Err(Error::FFIError(e)),
                |v| Ok(NativeModuleInstance::new(v)),
            )
    }

    /// Unloads the module.
    ///
    /// # Failure
    ///
    /// The function can fail if some module invariant is not met or `instance` is invalid.
    ///
    /// # Return
    ///
    /// Error on failure.
    ///
    /// # Safety
    ///
    /// The function crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn unload(
        &mut self,
        instance: NativeModuleInstance<'_, Owned>,
    ) -> Result<(), Error> {
        self._interface
            .into_mut()
            .as_mut()
            .unload(instance.as_handle())
            .to_result()
            .map_or_else(|e| Err(Error::FFIError(e)), |_v| Ok(()))
    }

    /// Initializes the module.
    ///
    /// # Failure
    ///
    /// The function can fail if some module invariant is not met or `instance` is invalid.
    ///
    /// # Return
    ///
    /// Error on failure.
    ///
    /// # Safety
    ///
    /// The function crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn initialize(
        &mut self,
        instance: &mut NativeModuleInstance<'_, Owned>,
    ) -> Result<(), Error> {
        self._interface
            .into_mut()
            .as_mut()
            .initialize(instance.as_handle())
            .to_result()
            .map_or_else(|e| Err(Error::FFIError(e)), |_v| Ok(()))
    }

    /// Terminates the module.
    ///
    /// # Failure
    ///
    /// The function can fail if some module invariant is not met or `instance` is invalid.
    ///
    /// # Return
    ///
    /// Error on failure.
    ///
    /// # Safety
    ///
    /// The function crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn terminate(
        &mut self,
        instance: &mut NativeModuleInstance<'_, Owned>,
    ) -> Result<(), Error> {
        self._interface
            .into_mut()
            .as_mut()
            .terminate(instance.as_handle())
            .to_result()
            .map_or_else(|e| Err(Error::FFIError(e)), |_v| Ok(()))
    }
}

impl<'a, O> NativeModule<'a, O>
where
    O: ImmutableAccessIdentifier,
{
    /// Fetches an interface from the module.
    ///
    /// # Failure
    ///
    /// The function fails if `instance` is invalid.
    ///
    /// # Return
    ///
    /// Interface on success, error otherwise.
    ///
    /// # Safety
    ///
    /// The function is not thread-safe and crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn get_interface<'instance, IO, T>(
        &self,
        instance: &'instance NativeModuleInstance<'instance, IO>,
        interface: &InterfaceDescriptor,
        caster: impl FnOnce(crate::ffi::module::Interface) -> T,
    ) -> Result<Interface<'instance, T>, Error>
    where
        IO: ImmutableAccessIdentifier,
    {
        self._interface
            .as_ref()
            .get_interface(instance.as_handle(), NonNullConst::from(interface))
            .to_result()
            .map_or_else(
                |e| Err(Error::FFIError(e)),
                |v| Ok(Interface::new(caster(v))),
            )
    }

    /// Fetches the module info of the module.
    ///
    /// # Failure
    ///
    /// The function fails if `instance` is invalid.
    ///
    /// # Return
    ///
    /// Module info on success, error otherwise.
    ///
    /// # Safety
    ///
    /// The function is not thread-safe and crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn get_module_info<'instance, IO>(
        &self,
        instance: &'instance NativeModuleInstance<'instance, IO>,
    ) -> Result<&'instance ModuleInfo, Error>
    where
        IO: ImmutableAccessIdentifier,
    {
        self._interface
            .as_ref()
            .get_module_info(instance.as_handle())
            .to_result()
            .map_or_else(|e| Err(Error::FFIError(e)), |v| Ok(&*v.as_ptr()))
    }

    /// Fetches the load dependencies of the module.
    ///
    /// # Return
    ///
    /// Load dependencies.
    ///
    /// # Safety
    ///
    /// The function crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn get_load_dependencies(&self) -> &'a [InterfaceDescriptor] {
        let span = self._interface.as_ref().get_load_dependencies();
        if span.is_empty() {
            <&[_]>::default()
        } else {
            std::slice::from_raw_parts(span.as_ptr(), span.len())
        }
    }

    /// Fetches the runtime dependencies of the module.
    ///
    /// # Failure
    ///
    /// The function fails if `instance` is invalid.
    ///
    /// # Return
    ///
    /// Runtime dependencies on success, error otherwise.
    ///
    /// # Safety
    ///
    /// The function is not thread-safe and crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn get_runtime_dependencies<'instance, IO>(
        &self,
        instance: &'instance NativeModuleInstance<'instance, IO>,
    ) -> Result<&'instance [InterfaceDescriptor], Error>
    where
        IO: ImmutableAccessIdentifier,
    {
        self._interface
            .as_ref()
            .get_runtime_dependencies(instance.as_handle())
            .to_result()
            .map_or_else(
                |e| Err(Error::FFIError(e)),
                |v| {
                    if v.is_empty() {
                        Ok(<&[_]>::default())
                    } else {
                        Ok(std::slice::from_raw_parts(v.as_ptr(), v.len()))
                    }
                },
            )
    }

    /// Fetches the exportable interfaces of the module.
    ///
    /// # Failure
    ///
    /// The function fails if `instance` is invalid.
    ///
    /// # Return
    ///
    /// Exportable interfaces on success, error otherwise.
    ///
    /// # Safety
    ///
    /// The function is not thread-safe and crosses the ffi boundary.
    /// Direct usage of a [NativeModule] may break some invariants
    /// of the module api, if not handled with care.
    #[inline]
    pub unsafe fn get_exportable_interfaces<'instance, IO>(
        &self,
        instance: &'instance NativeModuleInstance<'instance, IO>,
    ) -> Result<&'instance [InterfaceDescriptor], Error>
    where
        IO: ImmutableAccessIdentifier,
    {
        self._interface
            .as_ref()
            .get_exportable_interfaces(instance.as_handle())
            .to_result()
            .map_or_else(
                |e| Err(Error::FFIError(e)),
                |v| {
                    if v.is_empty() {
                        Ok(<&[_]>::default())
                    } else {
                        Ok(std::slice::from_raw_parts(v.as_ptr(), v.len()))
                    }
                },
            )
    }
}