intercom 0.4.0

Utilities for writing COM visible Rust components.
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
use crate::prelude::*;
use crate::ComItf;

#[derive(Debug, Clone, Copy, Hash, PartialOrd, PartialEq, Eq)]
#[repr(C)]
pub enum TypeSystemName
{
    Automation = 0,
    Raw = 1,
}

impl TypeSystemName
{
    pub fn get_ptr<I: ?Sized>(self, itf: &ComItf<I>) -> crate::raw::RawComPtr
    {
        let opt = match self {
            TypeSystemName::Automation => AutomationTypeSystem::get_ptr(itf).map(|p| p.ptr),
            TypeSystemName::Raw => RawTypeSystem::get_ptr(itf).map(|p| p.ptr),
        };

        match opt {
            Some(ptr) => ptr.as_ptr(),
            None => std::ptr::null_mut(),
        }
    }
}

/// Common trait for type systems.
pub trait TypeSystem: Clone + Copy
{
    const AUTOMATION: TypeSystemName = TypeSystemName::Automation;
    const RAW: TypeSystemName = TypeSystemName::Raw;

    fn key() -> TypeSystemName;

    /// Gets the type system pointer from a ComItf.
    fn get_ptr<I: ?Sized>(itf: &ComItf<I>) -> Option<crate::raw::InterfacePtr<Self, I>>;

    /// Constructs a ComItf from a pointer.
    fn wrap_ptr<I: ?Sized>(ptr: crate::raw::InterfacePtr<Self, I>) -> ComItf<I>;
}

/// Automation type system.
#[derive(Clone, Copy)]
pub struct AutomationTypeSystem;
impl TypeSystem for AutomationTypeSystem
{
    fn key() -> TypeSystemName
    {
        TypeSystemName::Automation
    }

    /// Gets the type system pointer from a ComItf.
    fn get_ptr<I: ?Sized>(itf: &ComItf<I>) -> Option<crate::raw::InterfacePtr<Self, I>>
    {
        itf.automation_ptr
    }

    /// Constructs a ComItf from a pointer.
    fn wrap_ptr<I: ?Sized>(ptr: crate::raw::InterfacePtr<Self, I>) -> ComItf<I>
    {
        ComItf {
            automation_ptr: Some(ptr),
            raw_ptr: None,
            phantom: std::marker::PhantomData,
        }
    }
}

/// Raw type system.
#[derive(Clone, Copy)]
pub struct RawTypeSystem;
impl TypeSystem for RawTypeSystem
{
    fn key() -> TypeSystemName
    {
        TypeSystemName::Raw
    }

    /// Gets the type system pointer from a ComItf.
    fn get_ptr<I: ?Sized>(itf: &ComItf<I>) -> Option<crate::raw::InterfacePtr<Self, I>>
    {
        itf.raw_ptr
    }

    /// Constructs a ComItf from a pointer.
    fn wrap_ptr<I: ?Sized>(ptr: crate::raw::InterfacePtr<Self, I>) -> ComItf<I>
    {
        ComItf {
            automation_ptr: None,
            raw_ptr: Some(ptr),
            phantom: std::marker::PhantomData,
        }
    }
}

/// Defines a type that has identical representation for both input and output directions.
pub trait ForeignType
{
    /// The name of the type.
    fn type_name() -> &'static str;
    fn indirection_level() -> u32
    {
        0
    }
}

/// Specifies the raw COM type to use for the specific Rust type.
pub trait ExternType<TS: TypeSystem>
{
    type ForeignType: ForeignType;
}

/// Defines a type that may be used as a parameter type in Intercom interfaces.
///
/// # Safety
///
/// Implementing this trait allows Intercom to use the type as an input type.
/// This trait will be used within the code generated in the procedural macros.
/// It is important to ensure this trait is implemented in such a way that its
/// use in the macros is sound.
pub unsafe trait ExternInput<TS: TypeSystem>: ExternType<TS> + Sized
{
    type Lease;

    /// # Safety
    ///
    /// The returned `ForeignType` value is valid only as long as the `Lease`
    /// is held.
    unsafe fn into_foreign_parameter(self) -> ComResult<(Self::ForeignType, Self::Lease)>;

    type Owned;

    /// # Safety
    ///
    /// The validity of the returned `Owned` value depends on the source type.
    /// In general it shouldn't be used past the lifetime of the `source`
    /// reference.
    unsafe fn from_foreign_parameter(source: Self::ForeignType) -> ComResult<Self::Owned>;
}

/// Defines a type that may be used as an output type in Intercom interfaces.
///
/// # Safety
///
/// Implementing this trait allows Intercom to use the type as an output type.
/// This trait will be used within the code generated in the procedural macros.
/// It is important to ensure this trait is implemented in such a way that its
/// use in the macros is sound.
pub unsafe trait ExternOutput<TS: TypeSystem>: ExternType<TS> + Sized
{
    fn into_foreign_output(self) -> ComResult<Self::ForeignType>;

    /// # Safety
    ///
    /// The source ownership is transferred to the function invoker. In case of
    /// pointers, the function (or the `Self` type) is given the ownership of
    /// the memory. The caller must ensure that it owns the source parameter
    /// and is allowed to pass the ownership in this way.
    unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self>;

    /// # Safety
    ///
    /// The source ownership is transferred to the function invoker. In case of
    /// pointers, the function (or the `Self` type) is given the ownership of
    /// the memory. The caller must ensure that it owns the source parameter
    /// and is allowed to pass the ownership in this way.
    unsafe fn drop_foreign_output(source: Self::ForeignType)
    {
        // Default implementation just converts this back to the original.
        //
        // The `from_foreign_output` is supposed to ensure unused memory isn't leaked and dropping
        // the return value will clean up the remaining memory.
        //
        // Type-specific implementation can clean up the source memory without going through the
        // trouble of creating  new `Self` value.
        let _ = Self::from_foreign_output(source);
    }
}

/// Defines a type that may be used as a parameter type in Intercom interfaces.
///
/// # Safety
///
/// Implementing this trait allows Intercom to use the type as an input type.
/// This trait will be used within the code generated in the procedural macros.
/// It is important to ensure this trait is implemented in such a way that its
/// use in the macros is sound.
pub unsafe trait InfallibleExternInput<TS: TypeSystem>: ExternType<TS> + Sized
{
    type Lease;

    /// # Safety
    ///
    /// The returned `ForeignType` value is valid only as long as the `Lease`
    /// is held.
    unsafe fn into_foreign_parameter(self) -> (Self::ForeignType, Self::Lease);

    type Owned;

    /// # Safety
    ///
    /// The validity of the returned `Owned` value depends on the source type.
    /// In general it shouldn't be used past the lifetime of the `source`
    /// reference.
    unsafe fn from_foreign_parameter(source: Self::ForeignType) -> Self::Owned;
}

/// Defines a type that may be used as an output type in Intercom interfaces.
///
/// # Safety
///
/// Implementing this trait allows Intercom to use the type as an output type.
/// This trait will be used within the code generated in the procedural macros.
/// It is important to ensure this trait is implemented in such a way that its
/// use in the macros is sound.
pub unsafe trait InfallibleExternOutput<TS: TypeSystem>: ExternType<TS> + Sized
{
    fn into_foreign_output(self) -> Self::ForeignType;

    /// # Safety
    ///
    /// The source ownership is transferred to the function invoker. In case of
    /// pointers, the function (or the `Self` type) is given the ownership of
    /// the memory. The caller must ensure that it owns the source parameter
    /// and is allowed to pass the ownership in this way.
    unsafe fn from_foreign_output(source: Self::ForeignType) -> Self;
}

/// Holds a conversion result foreign value and cleans it up unless consumed
pub struct OutputGuard<TS, TType>
where
    TS: TypeSystem,
    TType: ExternOutput<TS>,
{
    value: std::mem::ManuallyDrop<TType::ForeignType>,
}

impl<TS, TType> OutputGuard<TS, TType>
where
    TS: TypeSystem,
    TType: ExternOutput<TS>,
{
    /// Wrap a foreign value in the guard.
    pub fn wrap(value: TType::ForeignType) -> OutputGuard<TS, TType>
    {
        OutputGuard {
            value: std::mem::ManuallyDrop::new(value),
        }
    }

    /// Consume the guard to acquire the final value and giving up on having to clean it later.
    pub fn consume(self) -> TType::ForeignType
    {
        unsafe {
            // Read the value out of the guard and forget the guard to avoid
            // dropping it, which would clean the value.
            let value = std::ptr::read(&self.value);
            std::mem::forget(self);
            std::mem::ManuallyDrop::into_inner(value)
        }
    }
}

impl<TS, TType> Drop for OutputGuard<TS, TType>
where
    TS: TypeSystem,
    TType: ExternOutput<TS>,
{
    fn drop(&mut self)
    {
        unsafe {
            // Clean the value on drop..
            let v = std::mem::ManuallyDrop::take(&mut self.value);
            TType::drop_foreign_output(v);
        }
    }
}

/// A quick macro for implementing ExternInput/etc. for various basic types
/// that should represent themselves.
macro_rules! self_extern {
    ( $t:ty ) => {
        impl ForeignType for $t
        {
            /// The default name is the name of the type.
            fn type_name() -> &'static str
            {
                stringify!($t)
            }
        }

        impl<TS: TypeSystem> ExternType<TS> for $t
        {
            type ForeignType = $t;
        }

        unsafe impl<TS: TypeSystem> ExternInput<TS> for $t
        {
            type Lease = ();
            unsafe fn into_foreign_parameter(self) -> ComResult<(Self::ForeignType, ())>
            {
                Ok((self, ()))
            }

            type Owned = Self;
            unsafe fn from_foreign_parameter(source: Self::ForeignType) -> ComResult<Self::Owned>
            {
                Ok(source)
            }
        }

        unsafe impl<TS: TypeSystem> ExternOutput<TS> for $t
        {
            fn into_foreign_output(self) -> ComResult<Self::ForeignType>
            {
                Ok(self)
            }

            unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self>
            {
                Ok(source)
            }
        }

        unsafe impl<TS: TypeSystem> InfallibleExternInput<TS> for $t
        {
            type Lease = ();
            unsafe fn into_foreign_parameter(self) -> (Self::ForeignType, ())
            {
                (self, ())
            }

            type Owned = Self;
            unsafe fn from_foreign_parameter(source: Self::ForeignType) -> Self::Owned
            {
                source
            }
        }

        unsafe impl<TS: TypeSystem> InfallibleExternOutput<TS> for $t
        {
            fn into_foreign_output(self) -> Self::ForeignType
            {
                self
            }

            unsafe fn from_foreign_output(source: Self::ForeignType) -> Self
            {
                source
            }
        }
    };
}

// Define all types that should have built-in Self extern type.
self_extern!(());
self_extern!(i8);
self_extern!(i16);
self_extern!(i32);
self_extern!(i64);
self_extern!(isize);
self_extern!(u8);
self_extern!(u16);
self_extern!(u32);
self_extern!(u64);
self_extern!(usize);
self_extern!(f32);
self_extern!(f64);
self_extern!(bool);

use crate::raw::HRESULT;
self_extern!(HRESULT);

use crate::GUID;
self_extern!(GUID);

self_extern!(TypeSystemName);

self_extern!(std::ffi::c_void);

macro_rules! extern_ptr {
    ( $mut:tt ) => {
        impl<TS: TypeSystem, TPtr: ForeignType + ?Sized> ExternType<TS> for *$mut TPtr
        {
            type ForeignType = Self;
        }

        unsafe impl<TS: TypeSystem, TPtr: ForeignType + ?Sized> ExternOutput<TS> for *$mut TPtr
        {
            fn into_foreign_output(self) -> ComResult<Self::ForeignType>
            {
                Ok(self)
            }

            unsafe fn from_foreign_output(source: Self::ForeignType) -> ComResult<Self>
            {
                Ok(source)
            }
        }

        unsafe impl<TS: TypeSystem, TPtr: ForeignType + ?Sized> ExternInput<TS> for *$mut TPtr
        {
            type Lease = ();
            unsafe fn into_foreign_parameter(self) -> ComResult<(Self::ForeignType, ())>
            {
                Ok((self, ()))
            }

            type Owned = Self;
            unsafe fn from_foreign_parameter(source: Self::ForeignType) -> ComResult<Self::Owned>
            {
                Ok(source)
            }
        }

        unsafe impl<TS: TypeSystem, TPtr: ForeignType + ?Sized> InfallibleExternOutput<TS> for *$mut TPtr
        {
            fn into_foreign_output(self) -> Self::ForeignType
            {
                self
            }

            unsafe fn from_foreign_output(source: Self::ForeignType) -> Self
            {
                source
            }
        }

        unsafe impl<TS: TypeSystem, TPtr: ForeignType + ?Sized> InfallibleExternInput<TS> for *$mut TPtr
        {
            type Lease = ();
            unsafe fn into_foreign_parameter(self) -> (Self::ForeignType, ())
            {
                (self, ())
            }

            type Owned = Self;
            unsafe fn from_foreign_parameter(source: Self::ForeignType) -> Self::Owned
            {
                source
            }
        }

        impl<TPtr: ForeignType + ?Sized> ForeignType for *$mut TPtr
        {
            fn type_name() -> &'static str
            {
                <TPtr as ForeignType>::type_name()
            }

            fn indirection_level() -> u32
            {
                <TPtr as ForeignType>::indirection_level() + 1
            }
        }
    }
}

extern_ptr!(mut);
extern_ptr!(const);

/// Defines the uninitialized values for out parameters when calling into
/// Intercom interfaces.
pub trait ExternDefault
{
    /// # Safety
    ///
    /// This results in zeroed values. This should only be used for types that
    /// are okay being zeroed (mainly `#[repr(C)]` types).
    unsafe fn extern_default() -> Self;
}

impl<T> ExternDefault for T
{
    unsafe fn extern_default() -> Self
    {
        std::mem::zeroed()
    }
}