openrr_plugin/
proxy.rs

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
//! This module defines FFI-safe equivalents of the various types and traits
//! used in arci and openrr-plugin. The types defined by this module will never
//! appear in the public API, and the conversion is done internally.

#![allow(clippy::let_unit_value)] // this lint is triggered for code generated by #[sabi_trait]
#![allow(clippy::unnecessary_cast)] // this lint is triggered for code generated by #[sabi_trait]

#[rustfmt::skip]
#[path = "gen/proxy.rs"]
mod impls;

use std::{sync::Arc, time::SystemTime};

use abi_stable::{
    declare_root_module_statics,
    library::RootModule,
    package_version_strings,
    prefix_type::PrefixTypeTrait,
    rtry, sabi_trait,
    sabi_types::VersionStrings,
    std_types::{RBoxError, RDuration, ROk, ROption, RString, RVec},
    StableAbi,
};
use anyhow::format_err;
use arci::nalgebra;
use async_ffi::{FfiFuture, FutureExt as _};

pub(crate) use self::impls::*;
use crate::PluginProxy;

type RResult<T, E = RError> = abi_stable::std_types::RResult<T, E>;

// =============================================================================
// std::time::SystemTime

/// FFI-safe equivalent of [`std::time::SystemTime`].
///
/// `SystemTime` does not implement `StableAbi`, so convert it to duration since unix epoch,
/// and recover it on conversion to `SystemTime`.
/// This is inspired by the way `serde` implements `Serialize`/`Deserialize` on `SystemTime`.
///
/// Refs:
/// - <https://github.com/serde-rs/serde/blob/v1.0.126/serde/src/ser/impls.rs#L610-L625>
/// - <https://github.com/serde-rs/serde/blob/v1.0.126/serde/src/de/impls.rs#L1993-L2138>
#[repr(C)]
#[derive(StableAbi)]
pub(crate) struct RSystemTime {
    duration_since_epoch: RDuration,
}

impl TryFrom<SystemTime> for RSystemTime {
    type Error = RError;

    fn try_from(val: SystemTime) -> Result<Self, Self::Error> {
        let duration_since_epoch = val
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|_| format_err!("SystemTime must be later than UNIX_EPOCH"))?;
        Ok(Self {
            duration_since_epoch: duration_since_epoch.into(),
        })
    }
}

impl TryFrom<RSystemTime> for SystemTime {
    type Error = RError;

    fn try_from(val: RSystemTime) -> Result<Self, Self::Error> {
        let duration_since_epoch = val.duration_since_epoch.into();
        SystemTime::UNIX_EPOCH
            .checked_add(duration_since_epoch)
            .ok_or_else(|| format_err!("overflow deserializing SystemTime").into())
    }
}

// =============================================================================
// nalgebra::Isometry2<f64>

/// FFI-safe equivalent of [`nalgebra::Isometry2<f64>`](nalgebra::Isometry2).
#[repr(C)]
#[derive(StableAbi)]
pub(crate) struct RIsometry2F64 {
    rotation: RUnitComplexF64,
    translation: RTranslation2F64,
}

impl From<nalgebra::Isometry2<f64>> for RIsometry2F64 {
    fn from(val: nalgebra::Isometry2<f64>) -> Self {
        Self {
            rotation: val.rotation.into(),
            translation: val.translation.into(),
        }
    }
}

impl From<RIsometry2F64> for nalgebra::Isometry2<f64> {
    fn from(val: RIsometry2F64) -> Self {
        Self::from_parts(val.translation.into(), val.rotation.into())
    }
}

/// FFI-safe equivalent of [`nalgebra::UnitComplex<f64>`](nalgebra::UnitComplex).
#[repr(C)]
#[derive(StableAbi)]
struct RUnitComplexF64 {
    re: f64,
    im: f64,
}

impl From<nalgebra::UnitComplex<f64>> for RUnitComplexF64 {
    fn from(val: nalgebra::UnitComplex<f64>) -> Self {
        let val = val.into_inner();
        Self {
            re: val.re,
            im: val.im,
        }
    }
}

impl From<RUnitComplexF64> for nalgebra::UnitComplex<f64> {
    fn from(val: RUnitComplexF64) -> Self {
        Self::from_complex(nalgebra::Complex {
            re: val.re,
            im: val.im,
        })
    }
}

/// FFI-safe equivalent of [`nalgebra::Translation2<f64>`](nalgebra::Translation2).
#[repr(C)]
#[derive(StableAbi)]
struct RTranslation2F64 {
    x: f64,
    y: f64,
}

impl From<nalgebra::Translation2<f64>> for RTranslation2F64 {
    fn from(val: nalgebra::Translation2<f64>) -> Self {
        Self {
            x: val.vector.x,
            y: val.vector.y,
        }
    }
}

impl From<RTranslation2F64> for nalgebra::Translation2<f64> {
    fn from(val: RTranslation2F64) -> Self {
        Self::new(val.x, val.y)
    }
}

// =============================================================================
// nalgebra::Isometry3<f64>

/// FFI-safe equivalent of [`nalgebra::Isometry3<f64>`](nalgebra::Isometry3).
#[repr(C)]
#[derive(StableAbi)]
pub(crate) struct RIsometry3F64 {
    rotation: RUnitQuaternionF64,
    translation: RTranslation3F64,
}

impl From<nalgebra::Isometry3<f64>> for RIsometry3F64 {
    fn from(val: nalgebra::Isometry3<f64>) -> Self {
        Self {
            rotation: val.rotation.into(),
            translation: val.translation.into(),
        }
    }
}

impl From<RIsometry3F64> for nalgebra::Isometry3<f64> {
    fn from(val: RIsometry3F64) -> Self {
        Self::from_parts(val.translation.into(), val.rotation.into())
    }
}

/// FFI-safe equivalent of [`nalgebra::UnitQuaternion<f64>`](nalgebra::UnitQuaternion).
#[repr(C)]
#[derive(StableAbi)]
struct RUnitQuaternionF64 {
    x: f64,
    y: f64,
    z: f64,
    w: f64,
}

impl From<nalgebra::UnitQuaternion<f64>> for RUnitQuaternionF64 {
    fn from(val: nalgebra::UnitQuaternion<f64>) -> Self {
        let val = val.into_inner();
        Self {
            x: val.coords.x,
            y: val.coords.y,
            z: val.coords.z,
            w: val.coords.w,
        }
    }
}

impl From<RUnitQuaternionF64> for nalgebra::UnitQuaternion<f64> {
    fn from(val: RUnitQuaternionF64) -> Self {
        Self::from_quaternion(nalgebra::Quaternion::new(val.w, val.x, val.y, val.z))
    }
}

/// FFI-safe equivalent of [`nalgebra::Translation3<f64>`](nalgebra::Translation3).
#[repr(C)]
#[derive(StableAbi)]
struct RTranslation3F64 {
    x: f64,
    y: f64,
    z: f64,
}

impl From<nalgebra::Translation3<f64>> for RTranslation3F64 {
    fn from(val: nalgebra::Translation3<f64>) -> Self {
        Self {
            x: val.vector.x,
            y: val.vector.y,
            z: val.vector.z,
        }
    }
}

impl From<RTranslation3F64> for nalgebra::Translation3<f64> {
    fn from(val: RTranslation3F64) -> Self {
        Self::new(val.x, val.y, val.z)
    }
}

// =============================================================================
// arci::Error

/// FFI-safe equivalent of [`arci::Error`].
#[repr(C)]
#[derive(StableAbi)]
pub(crate) struct RError {
    repr: RBoxError,
}

impl From<arci::Error> for RError {
    fn from(e: arci::Error) -> Self {
        Self {
            // TODO: propagate error kind.
            repr: RBoxError::from_box(e.into()),
        }
    }
}

impl From<anyhow::Error> for RError {
    fn from(e: anyhow::Error) -> Self {
        Self {
            // TODO: propagate error kind.
            repr: RBoxError::from_box(e.into()),
        }
    }
}

impl From<RError> for arci::Error {
    fn from(e: RError) -> Self {
        // TODO: propagate error kind.
        Self::Other(format_err!("{}", e.repr))
    }
}

// =============================================================================
// arci::WaitFuture

#[repr(C)]
#[derive(StableAbi)]
#[must_use]
pub(crate) struct RWaitFuture(FfiFuture<RResult<()>>);

impl From<arci::WaitFuture> for RWaitFuture {
    #[allow(clippy::unit_arg)] // false positive that triggered for external macro
    fn from(wait: arci::WaitFuture) -> Self {
        Self(async move { ROk(rtry!(wait.await)) }.into_ffi())
    }
}

impl From<RWaitFuture> for arci::WaitFuture {
    fn from(wait: RWaitFuture) -> Self {
        arci::WaitFuture::new(async move { Ok(wait.0.await.into_result()?) })
    }
}

// =============================================================================
// PluginMod

// Not public API.
#[doc(hidden)]
#[allow(missing_debug_implementations)]
#[repr(C)]
#[derive(StableAbi)]
#[sabi(kind(Prefix))]
#[sabi(missing_field(panic))]
pub struct PluginMod {
    #[sabi(last_prefix_field)]
    pub(crate) plugin_constructor: extern "C" fn() -> PluginProxy,
}

impl RootModule for PluginMod_Ref {
    const BASE_NAME: &'static str = "plugin";
    const NAME: &'static str = "plugin";
    const VERSION_STRINGS: VersionStrings = package_version_strings!();

    declare_root_module_statics!(PluginMod_Ref);
}

impl PluginMod_Ref {
    #[doc(hidden)]
    pub fn new(plugin_constructor: extern "C" fn() -> PluginProxy) -> Self {
        PluginMod { plugin_constructor }.leak_into_prefix()
    }
}