pipewire/registry/
rc.rs

1// Copyright The pipewire-rs Contributors.
2// SPDX-License-Identifier: MIT
3
4use std::{
5    ops::Deref,
6    ptr,
7    rc::{Rc, Weak},
8};
9
10use super::{Registry, RegistryBox};
11
12#[derive(Debug)]
13struct RegistryRcInner {
14    registry: RegistryBox<'static>,
15    // Store the core here, so that the registry is not dropped before the core,
16    // which may lead to undefined behaviour. Rusts drop order of struct fields
17    // (from top to bottom) ensures that this is always destroyed _after_ the registry.
18    _core: crate::core::CoreRc,
19}
20
21#[derive(Debug, Clone)]
22pub struct RegistryRc {
23    inner: Rc<RegistryRcInner>,
24}
25
26impl RegistryRc {
27    /// Create a `RegistryRc` by taking ownership of a raw `pw_registry`.
28    ///
29    /// # Safety
30    /// The provided pointer must point to a valid, well aligned [`pw_registry`](`pw_sys::pw_registry`).
31    ///
32    /// The raw registry must not be manually destroyed or moved, as the new [`RegistryRc`] takes
33    /// ownership of it.
34    pub unsafe fn from_raw(
35        ptr: ptr::NonNull<pw_sys::pw_registry>,
36        core: crate::core::CoreRc,
37    ) -> Self {
38        let registry = unsafe { RegistryBox::from_raw(ptr) };
39
40        Self {
41            inner: Rc::new(RegistryRcInner {
42                registry,
43                _core: core,
44            }),
45        }
46    }
47
48    pub fn downgrade(&self) -> RegistryWeak {
49        let weak = Rc::downgrade(&self.inner);
50        RegistryWeak { weak }
51    }
52}
53
54impl Deref for RegistryRc {
55    type Target = Registry;
56
57    fn deref(&self) -> &Self::Target {
58        self.inner.registry.deref()
59    }
60}
61
62impl AsRef<Registry> for RegistryRc {
63    fn as_ref(&self) -> &Registry {
64        self.deref()
65    }
66}
67
68pub struct RegistryWeak {
69    weak: Weak<RegistryRcInner>,
70}
71
72impl RegistryWeak {
73    pub fn upgrade(&self) -> Option<RegistryRc> {
74        self.weak.upgrade().map(|inner| RegistryRc { inner })
75    }
76}