pipewire/core/
box_.rs

1// Copyright The pipewire-rs Contributors.
2// SPDX-License-Identifier: MIT
3
4use std::{marker::PhantomData, ops::Deref};
5
6use crate::context::Context;
7
8use super::Core;
9
10/// Smart pointer providing unique ownership of a PipeWire [core](super).
11///
12/// For shared ownership, see [`CoreRc`](super::CoreRc).
13///
14/// For an explanation of these, see [Smart pointers to PipeWire objects](crate#smart-pointers-to-pipewire-objects).
15#[derive(Debug)]
16pub struct CoreBox<'c> {
17    ptr: std::ptr::NonNull<pw_sys::pw_core>,
18    context: PhantomData<&'c Context>,
19}
20
21impl<'c> CoreBox<'c> {
22    /// Create a `CoreBox` by taking ownership of a raw `pw_core`.
23    ///
24    /// # Safety
25    /// The provided pointer must point to a valid, well aligned [`pw_core`](`pw_sys::pw_core`).
26    ///
27    /// The raw core must not be manually destroyed or moved, as the new [`CoreBox`] takes
28    /// ownership of it.
29    ///
30    /// The lifetime of the returned box is unbounded. The caller is responsible to make sure
31    /// that the context used with this core outlives the core.
32    pub unsafe fn from_raw(raw: std::ptr::NonNull<pw_sys::pw_core>) -> CoreBox<'c> {
33        Self {
34            ptr: raw,
35            context: PhantomData,
36        }
37    }
38
39    pub fn into_raw(self) -> std::ptr::NonNull<pw_sys::pw_core> {
40        std::mem::ManuallyDrop::new(self).ptr
41    }
42}
43
44impl<'c> std::ops::Deref for CoreBox<'c> {
45    type Target = Core;
46
47    fn deref(&self) -> &Self::Target {
48        unsafe { self.ptr.cast::<Core>().as_ref() }
49    }
50}
51
52impl<'c> AsRef<Core> for CoreBox<'c> {
53    fn as_ref(&self) -> &Core {
54        self.deref()
55    }
56}
57
58impl<'c> std::ops::Drop for CoreBox<'c> {
59    fn drop(&mut self) {
60        unsafe {
61            pw_sys::pw_core_disconnect(self.as_raw_ptr());
62        }
63    }
64}