clack-host 0.2.0

Low-level, safe Rust wrappers to create audio plugin hosts using the CLAP audio plugin API.
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use clack_common::extensions::{Extension, PluginExtensionSide, RawExtension};
use clack_common::plugin::PluginDescriptor;
use clap_sys::plugin::clap_plugin;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::ops::Deref;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, RwLock};

/// A main-thread handle to the plugin instance.
///
/// This can be used to make requests to the plugin that can only be made in the main thread, which
/// is required for e.g. some extensions.
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct PluginMainThreadHandle<'a> {
    raw: NonNull<clap_plugin>,
    lifetime: PhantomData<&'a clap_plugin>,
}

impl<'a> PluginMainThreadHandle<'a> {
    /// # Safety
    /// The user must ensure the provided plugin pointer is valid.
    /// This can only be called on the main thread.
    pub(crate) const unsafe fn new(raw: NonNull<clap_plugin>) -> Self {
        Self {
            raw,
            lifetime: PhantomData,
        }
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.raw.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.raw.as_ptr()
    }

    /// Produces a [`PluginSharedHandle`] from this main-thread handle.
    #[inline]
    pub const fn shared(&self) -> PluginSharedHandle<'a> {
        // SAFETY: This type ensures the provided pointer is valid for 'a
        unsafe { PluginSharedHandle::new(self.raw) }
    }

    /// Turns this handle reference to a [`PluginSharedHandle`] reference.
    #[inline]
    pub const fn as_shared(&self) -> &PluginSharedHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const PluginSharedHandle<'a>) }
    }
}

impl Debug for PluginMainThreadHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "PluginMainThreadHandle ({:p})", self.raw)
    }
}

impl<'a> Deref for PluginMainThreadHandle<'a> {
    type Target = PluginSharedHandle<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_shared()
    }
}

/// A main-thread handle to the plugin, that can only exist while the plugin is in the 'inactive' state.
///
/// This is used by some extensions that e.g. require a function to be called on the main thread only
/// if the plugin is inactive, and on the audio thread if it is active.
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct InactivePluginMainThreadHandle<'a> {
    raw: NonNull<clap_plugin>,
    lifetime: PhantomData<&'a clap_plugin>,
}

impl<'a> InactivePluginMainThreadHandle<'a> {
    /// # Safety
    /// The user must ensure the provided plugin pointer is valid.
    /// This can only be called on the main thread, and the plugin instance must be inactive for `'a`.
    pub(crate) const unsafe fn new(raw: NonNull<clap_plugin>) -> Self {
        Self {
            raw,
            lifetime: PhantomData,
        }
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.raw.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.raw.as_ptr()
    }

    /// Produces a [`PluginSharedHandle`] from this main-thread handle.
    #[inline]
    pub const fn shared(&self) -> PluginSharedHandle<'a> {
        // SAFETY: This type ensures the provided pointer is valid for 'a
        unsafe { PluginSharedHandle::new(self.raw) }
    }

    /// Turns this handle reference to a [`PluginSharedHandle`] reference.
    #[inline]
    pub const fn as_shared(&self) -> &PluginSharedHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const PluginSharedHandle<'a>) }
    }

    // Note: this function is pretty useless, but is needed for the Deref impl (required by DerefMut)
    #[inline]
    const fn as_main_thread_ref(&self) -> &PluginMainThreadHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const PluginMainThreadHandle<'a>) }
    }

    /// Turns this handle reference to an exclusive [`PluginMainThreadHandle`] reference.
    ///
    /// This may be useful if you receive a [`InactivePluginMainThreadHandle`] but need to use
    /// some methods or extensions that do not care whether the plugin instance is currently active or not.
    ///
    /// Only one of the [`InactivePluginMainThreadHandle`] and [`PluginMainThreadHandle`] may be
    /// used at the same time.
    #[inline]
    pub const fn as_main_thread(&mut self) -> &PluginMainThreadHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &mut *(self as *mut Self as *mut PluginMainThreadHandle<'a>) }
    }
}

impl Debug for InactivePluginMainThreadHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "InactivePluginMainThreadHandle ({:p})", self.raw)
    }
}

impl<'a> Deref for InactivePluginMainThreadHandle<'a> {
    type Target = PluginMainThreadHandle<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_main_thread_ref()
    }
}

/// A thread-safe handle to the plugin instance.
///
/// This can be used to make requests to the plugin that support being made from any threads.
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct PluginSharedHandle<'a> {
    raw: NonNull<clap_plugin>,
    lifetime: PhantomData<&'a clap_plugin>,
}

// SAFETY: The Shared handle only exposes thread-safe methods
unsafe impl Send for PluginSharedHandle<'_> {}
// SAFETY: The Shared handle only exposes thread-safe methods
unsafe impl Sync for PluginSharedHandle<'_> {}

impl<'a> PluginSharedHandle<'a> {
    /// # Safety
    ///
    /// Users must ensure the provided instance pointer is valid.
    pub(crate) const unsafe fn new(raw: NonNull<clap_plugin>) -> Self {
        Self {
            raw,
            lifetime: PhantomData,
        }
    }

    /// Returns the [`PluginDescriptor`] this instance corresponds to.
    ///
    /// This may return `None` if the underlying plugin implementation didn't properly populate
    /// the descriptor pointer.
    pub const fn descriptor(&self) -> Option<&'a PluginDescriptor> {
        // SAFETY: the desc pointer is guaranteed to be valid (if present) by the CLAP spec.
        let Some(descriptor) = (unsafe { self.as_raw().desc.as_ref() }) else {
            return None;
        };

        // SAFETY: the desc pointer is guaranteed to be valid (if present) by the CLAP spec.
        Some(unsafe { PluginDescriptor::from_raw(descriptor) })
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.raw.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.raw.as_ptr()
    }

    /// Retrieves the plugin's pointer to the given [extension type](Extension) `E`.
    ///
    /// This returns `None` if the plugin does not support the given extension.
    ///
    /// # Example
    ///
    /// ```
    /// use clack_extensions::params::{PluginParams};
    /// use clack_host::plugin::PluginSharedHandle;
    ///
    /// # fn foo(info: PluginSharedHandle) {
    /// let info: PluginSharedHandle = /* ... */
    /// # info;
    /// if let Some(params) = info.get_extension::<PluginParams>() {
    ///     // The params extension is supported by this plugin
    /// } else {
    ///     // The params extension is not supported by this plugin
    /// }
    /// # }
    /// ```
    pub fn get_extension<E: Extension<ExtensionSide = PluginExtensionSide>>(&self) -> Option<E> {
        let identifier = const { E::IDENTIFIERS.first().unwrap() };
        // SAFETY: This type ensures the function pointers are valid
        let ext = unsafe { self.as_raw().get_extension?(self.raw.as_ptr(), identifier.as_ptr()) };

        let ext = NonNull::new(ext as *mut _)?;
        // SAFETY: The CLAP spec guarantees that the extension lives as long as the instance.
        let raw = unsafe { RawExtension::from_raw_plugin_extension(ext, self.raw) };

        // SAFETY: pointer comes from the associated E::IDENTIFIER.
        unsafe { Some(E::from_raw(raw)) }
    }

    /// Safely dereferences a [`RawExtension`] pointer produced by this plugin instance.
    ///
    /// See the documentation of the [`RawExtension`] type for more information about how this works
    /// internally.
    ///
    /// # Panics
    ///
    /// This method will panic if the given extension pointer does not match the plugin instance of
    /// this handle.
    #[inline]
    pub fn use_extension<E: Sized>(
        &self,
        extension: &RawExtension<PluginExtensionSide, E>,
    ) -> &'a E {
        if self.raw != extension.plugin_ptr() {
            mismatched_instance();
        }

        // SAFETY: the RawExtension type enforces the pointee is valid for as long as the matching
        // instance is still alive.
        unsafe { extension.as_ptr().as_ref() }
    }
}

impl Debug for PluginSharedHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "PluginSharedHandle ({:p})", self.raw)
    }
}

/// An audio-thread handle to an activated plugin instance.
///
/// This can be used to make requests to the plugin that can only be made from the audio thread.
#[derive(Eq, PartialEq)]
#[repr(transparent)]
pub struct PluginAudioProcessorHandle<'a> {
    raw: NonNull<clap_plugin>,
    lifetime: PhantomData<&'a clap_plugin>,
}

// SAFETY: This type only exposes audio-thread methods
unsafe impl Send for PluginAudioProcessorHandle<'_> {}

impl<'a> PluginAudioProcessorHandle<'a> {
    pub(crate) const fn new(raw: NonNull<clap_plugin>) -> Self {
        Self {
            raw,
            lifetime: PhantomData,
        }
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.raw.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.raw.as_ptr()
    }

    /// Turns this handle reference to a [`PluginSharedHandle`] reference.
    #[inline]
    pub const fn shared(&self) -> PluginSharedHandle<'a> {
        PluginSharedHandle {
            raw: self.raw,
            lifetime: PhantomData,
        }
    }

    /// Turns this handle reference to a [`PluginSharedHandle`] reference.
    #[inline]
    pub const fn as_shared(&self) -> &PluginSharedHandle<'a> {
        // SAFETY: this cast is valid since both types are just a NonNull<clap_host> and repr(transparent)
        unsafe { &*(self as *const Self as *const PluginSharedHandle<'a>) }
    }
}

impl<'a> Deref for PluginAudioProcessorHandle<'a> {
    type Target = PluginSharedHandle<'a>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_shared()
    }
}

impl Debug for PluginAudioProcessorHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "PluginAudioProcessorHandle ({:p})", self.raw)
    }
}

/// A handle to a plugin instance that may be in the process of initializing.
///
/// In this state, only [querying plugin extensions](Self::get_extension) is allowed.
#[derive(Clone, Eq, PartialEq)]
pub struct InitializingPluginHandle<'a> {
    inner: RemoteHandleInner,
    lifetime: PhantomData<&'a clap_plugin>,
}

impl<'a> InitializingPluginHandle<'a> {
    /// # Safety
    ///
    /// Users must ensure the provided instance pointer is valid until the given lock is marked as destroying.
    pub(crate) const unsafe fn new(lock: Arc<DestroyLock>, instance: NonNull<clap_plugin>) -> Self {
        Self {
            lifetime: PhantomData,
            inner: RemoteHandleInner { instance, lock },
        }
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.inner.instance.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.inner.instance.as_ptr()
    }

    /// Retrieves the plugin's pointer to the given [extension type](Extension) `E`.
    ///
    /// This returns `None` if the plugin does not support the given extension.
    pub fn get_extension<E: Extension<ExtensionSide = PluginExtensionSide>>(&self) -> Option<E> {
        self.inner.get_extension()
    }
}

impl Debug for InitializingPluginHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "InitializingPluginHandle ({:p})", self.inner.instance)
    }
}

/// A handle to a plugin instance that has finished initializing.
///
/// This handle can be used to obtain a [`PluginSharedHandle`] to then call the plugin's thread-safe
/// method.
///
/// However, this handle can outlive the plugin instance, as host callbacks may be called during
/// the plugin's destruction.
///
/// Therefore, the [`PluginSharedHandle`] can only be accessed through the [`access`](Self::access)
/// method, ensuring no access can be made during or after destruction.
#[derive(Clone, Eq, PartialEq)]
pub struct InitializedPluginHandle<'a> {
    inner: RemoteHandleInner,
    lifetime: PhantomData<&'a clap_plugin>,
}

impl<'a> InitializedPluginHandle<'a> {
    /// # Safety
    ///
    /// Users must ensure the provided instance pointer is valid until the given lock is marked as destroying.
    pub(crate) const unsafe fn new(lock: Arc<DestroyLock>, instance: NonNull<clap_plugin>) -> Self {
        Self {
            lifetime: PhantomData,
            inner: RemoteHandleInner { instance, lock },
        }
    }

    /// Returns a shared reference to the raw, C-FFI compatible plugin instance struct.
    ///
    /// This type enforces that the reference is valid for the lifetime of the instance (`'a`).
    ///
    /// If you need to access the raw pointer without dereferencing it first, use
    /// [`as_raw_ptr`](Self::as_raw_ptr) instead.
    #[inline]
    pub const fn as_raw(&self) -> &'a clap_plugin {
        // SAFETY: this type enforces that the clap_plugin instance is valid for 'a.
        unsafe { self.inner.instance.as_ref() }
    }

    /// Returns a raw pointer to the raw, C-FFI compatible plugin instance struct, without dereferencing it.
    ///
    /// If you need to safely access the plugin instance struct through a shared reference,
    /// use [`as_raw`](Self::as_raw) instead.
    #[inline]
    pub const fn as_raw_ptr(&self) -> *const clap_plugin {
        self.inner.instance.as_ptr()
    }

    /// Attempts to access and perform the given operation on the plugin's handle, returning its
    /// result.
    ///
    /// This method will return `None` if the plugin instance is being or has been destroyed, and
    /// `f` will not be called.
    ///
    /// However, this method guarantees that the plugin instance will block starting its destruction
    /// while the given operation `f` is still ongoing.
    ///
    /// This ensures the plugin instance is always valid if and when `f` runs.
    ///
    /// # Realtime safety
    ///
    /// This method *may* block the current thread if it is called concurrently while the plugin's
    /// instance is being destroyed (i.e. [`PluginInstance::drop`] is running).
    ///
    /// [`PluginInstance::drop`]: crate::plugin::PluginInstance::drop
    #[inline]
    pub fn access<T>(&self, f: impl FnOnce(PluginSharedHandle) -> T) -> Option<T> {
        self.inner.access(f)
    }

    /// Retrieves the plugin's pointer to the given [extension type](Extension) `E`.
    ///
    /// This returns `None` if the plugin does not support the given extension.
    pub fn get_extension<E: Extension<ExtensionSide = PluginExtensionSide>>(&self) -> Option<E> {
        self.inner.get_extension()
    }
}

impl Debug for InitializedPluginHandle<'_> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "InitializingPluginHandle ({:p})", self.inner.instance)
    }
}

#[derive(Clone)]
struct RemoteHandleInner {
    lock: Arc<DestroyLock>,
    instance: NonNull<clap_plugin>,
}

impl RemoteHandleInner {
    fn access<T>(&self, f: impl FnOnce(PluginSharedHandle) -> T) -> Option<T> {
        self.lock.hold_off_destruction(|| {
            // SAFETY: this type ensures the plugin is not being destroyed yet.
            let handle = unsafe { PluginSharedHandle::new(self.instance) };
            f(handle)
        })
    }

    #[inline]
    fn get_extension<E: Extension<ExtensionSide = PluginExtensionSide>>(&self) -> Option<E> {
        self.access(|handle| handle.get_extension())?
    }
}

impl PartialEq for RemoteHandleInner {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.instance == other.instance
    }
}

impl Eq for RemoteHandleInner {}

// SAFETY: The Shared handles only exposes thread-safe methods
unsafe impl Send for RemoteHandleInner {}
// SAFETY: The Shared handles only exposes thread-safe methods
unsafe impl Sync for RemoteHandleInner {}

pub(crate) struct DestroyLock {
    is_destroying: AtomicBool,
    lock: RwLock<bool>,
}

impl DestroyLock {
    pub(crate) fn new() -> Self {
        Self {
            is_destroying: AtomicBool::new(false),
            lock: RwLock::new(false),
        }
    }

    pub(crate) fn start_destroying(&self) {
        // Notify threads that may use the lock in the future that we are about to start destroying.
        self.is_destroying.store(true, Ordering::SeqCst);

        let mut guard = self.lock.write().unwrap_or_else(|err| err.into_inner());
        // This additional check may not be very useful, it's there just in case.
        *guard = true;
    }

    fn hold_off_destruction<T>(&self, handler: impl FnOnce() -> T) -> Option<T> {
        if self.is_destroying.load(Ordering::SeqCst) {
            return None;
        }

        // Poisoning doesn't matter, we are only reading a bool
        let guard = self.lock.read().unwrap_or_else(|err| err.into_inner());
        if *guard {
            return None;
        }

        let result = handler();

        drop(guard);

        Some(result)
    }
}

#[cold]
const fn mismatched_instance() -> ! {
    panic!("Given plugin instance handle doesn't match the extension pointer it was used on.")
}