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.
45use core::fmt;
6use core::marker::PhantomData;
7use core::mem::forget;
8use core::ops::Deref;
9use core::ptr::NonNull;
1011/// 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}
1920// 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> {}
2324// 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> {}
2627impl<T: ?Sized> Drop for Owned<'_, T> {
28fn drop(&mut self) {
29unsafe {
30self.ptr.as_ptr().drop_in_place();
31 }
32 }
33}
3435impl<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.
42pub unsafe fn new_unchecked(ptr: *mut T) -> Self {
43Self { ptr: unsafe { NonNull::new_unchecked(ptr) }, _phantom: PhantomData }
44 }
4546/// Consumes the `Owned`, returning its pointer to the owned value.
47pub fn into_raw(self) -> *mut T {
48let result = self.ptr.as_ptr();
49 forget(self);
50 result
51 }
52}
5354impl<T: ?Sized> Deref for Owned<'_, T> {
55type Target = T;
5657fn deref(&self) -> &Self::Target {
58unsafe { self.ptr.as_ref() }
59 }
60}
6162impl<T: fmt::Debug + ?Sized> fmt::Debug for Owned<'_, T> {
63fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64self.deref().fmt(f)
65 }
66}