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#[derive(Debug)]
11pub struct CoreBox<'c> {
12    ptr: std::ptr::NonNull<pw_sys::pw_core>,
13    context: PhantomData<&'c Context>,
14}
15
16impl<'c> CoreBox<'c> {
17    /// Create a `CoreBox` by taking ownership of a raw `pw_core`.
18    ///
19    /// # Safety
20    /// The provided pointer must point to a valid, well aligned [`pw_core`](`pw_sys::pw_core`).
21    ///
22    /// The raw core must not be manually destroyed or moved, as the new [`CoreBox`] takes
23    /// ownership of it.
24    ///
25    /// The lifetime of the returned box is unbounded. The caller is responsible to make sure
26    /// that the context used with this core outlives the core.
27    pub unsafe fn from_raw(raw: std::ptr::NonNull<pw_sys::pw_core>) -> CoreBox<'c> {
28        Self {
29            ptr: raw,
30            context: PhantomData,
31        }
32    }
33
34    pub fn into_raw(self) -> std::ptr::NonNull<pw_sys::pw_core> {
35        std::mem::ManuallyDrop::new(self).ptr
36    }
37}
38
39impl<'c> std::ops::Deref for CoreBox<'c> {
40    type Target = Core;
41
42    fn deref(&self) -> &Self::Target {
43        unsafe { self.ptr.cast::<Core>().as_ref() }
44    }
45}
46
47impl<'c> AsRef<Core> for CoreBox<'c> {
48    fn as_ref(&self) -> &Core {
49        self.deref()
50    }
51}
52
53impl<'c> std::ops::Drop for CoreBox<'c> {
54    fn drop(&mut self) {
55        unsafe {
56            pw_sys::pw_core_disconnect(self.as_raw_ptr());
57        }
58    }
59}