fidl_next_codec/
owned.rs

1// Copyright 2024 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 core::fmt;
6use core::marker::PhantomData;
7use core::mem::forget;
8use core::ops::Deref;
9use core::ptr::NonNull;
10
11/// An owned value in borrowed backing memory.
12///
13/// While the owned value may be dropped, it does not provide a mutable reference to the contained
14/// value.
15pub struct Owned<'buf, T: ?Sized> {
16    ptr: NonNull<T>,
17    _phantom: PhantomData<&'buf mut [u8]>,
18}
19
20// SAFETY: `Owned` doesn't add any restrictions on sending across thread boundaries, and so is
21// `Send` if `T` is `Send`.
22unsafe impl<T: Send + ?Sized> Send for Owned<'_, T> {}
23
24// SAFETY: `Owned` doesn't add any interior mutability, so it is `Sync` if `T` is `Sync`.
25unsafe impl<T: Sync + ?Sized> Sync for Owned<'_, T> {}
26
27impl<T: ?Sized> Drop for Owned<'_, T> {
28    fn drop(&mut self) {
29        unsafe {
30            self.ptr.as_ptr().drop_in_place();
31        }
32    }
33}
34
35impl<T: ?Sized> Owned<'_, T> {
36    /// Returns an `Owned` of the given pointer.
37    ///
38    /// # Safety
39    ///
40    /// `new_unchecked` takes ownership of the pointed-to value. It must point
41    /// to a valid value that is not aliased.
42    pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
43        Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _phantom: PhantomData }
44    }
45
46    /// Consumes the `Owned`, returning its pointer to the owned value.
47    pub fn into_raw(self) -> *mut T {
48        let result = self.ptr.as_ptr();
49        forget(self);
50        result
51    }
52}
53
54impl<T: ?Sized> Deref for Owned<'_, T> {
55    type Target = T;
56
57    fn deref(&self) -> &Self::Target {
58        unsafe { self.ptr.as_ref() }
59    }
60}
61
62impl<T: fmt::Debug + ?Sized> fmt::Debug for Owned<'_, T> {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        self.deref().fmt(f)
65    }
66}