fdomain_client/handle/
unowned.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::{AsHandleRef, Handle, HandleBased, HandleRef};
6
7/// Represents a copy of a handle that is owned elsewhere. I.e. dropping this
8/// value won't result in the handle being closed.
9pub struct Unowned<T: HandleBased>(T);
10
11impl<T: HandleBased> Unowned<T> {
12    /// Convert an `Unowned<Handle>` into an `Unowned<T>`
13    pub fn from_unowned_handle(src: Unowned<Handle>) -> Unowned<T> {
14        Unowned(T::from_handle(Handle { id: src.0.id, client: src.0.client.clone() }))
15    }
16
17    /// Get an `Unowned` copy of a given handle.
18    pub fn from_handle(src: &Handle) -> Unowned<T> {
19        Unowned::<T>::from_unowned_handle(Unowned::<Handle>::from(src))
20    }
21}
22
23impl<T: HandleBased> Drop for Unowned<T> {
24    fn drop(&mut self) {
25        self.0.invalidate()
26    }
27}
28
29impl<T: AsHandleRef + HandleBased> AsHandleRef for Unowned<T> {
30    fn as_handle_ref(&self) -> HandleRef<'_> {
31        self.0.as_handle_ref()
32    }
33
34    fn object_type() -> fidl::ObjectType {
35        T::object_type()
36    }
37}
38
39impl<T: HandleBased> std::ops::Deref for Unowned<T> {
40    type Target = T;
41
42    fn deref(&self) -> &Self::Target {
43        &self.0
44    }
45}
46
47impl<T: HandleBased> From<&T> for Unowned<T> {
48    fn from(src: &T) -> Unowned<T> {
49        let handle = src.as_handle_ref();
50        let handle = Handle { id: handle.id, client: handle.client.clone() };
51        let inner = T::from_handle(handle);
52        Unowned(inner)
53    }
54}