fromsoftware_shared/
owned_pointer.rs

1use std::{
2    fmt,
3    ops::{Deref, DerefMut},
4    ptr::NonNull,
5};
6
7/// Pointer to a structure that the containing structure owns. You will generally use this to model
8/// structures in foreign memory when extending the game libraries. Do not use this in your own
9/// code as you're risking all rusts safety reasoning.
10///
11/// # Safety
12///
13/// User must ensure that it's safe for this pointer to be turned into a (potentially mutable)
14/// reference if a reference to its embedding structure is obtained.
15#[repr(transparent)]
16pub struct OwnedPtr<T>(NonNull<T>);
17
18impl<T> OwnedPtr<T> {
19    pub fn as_ptr(&self) -> *mut T {
20        self.0.as_ptr()
21    }
22}
23
24impl<T> Deref for OwnedPtr<T> {
25    type Target = T;
26
27    fn deref(&self) -> &Self::Target {
28        unsafe { self.0.as_ref() }
29    }
30}
31
32impl<T> AsRef<T> for OwnedPtr<T> {
33    fn as_ref(&self) -> &T {
34        self.deref()
35    }
36}
37
38impl<T> DerefMut for OwnedPtr<T> {
39    fn deref_mut(&mut self) -> &mut Self::Target {
40        unsafe { self.0.as_mut() }
41    }
42}
43
44impl<T> AsMut<T> for OwnedPtr<T> {
45    fn as_mut(&mut self) -> &mut T {
46        self.deref_mut()
47    }
48}
49
50impl<T> fmt::Debug for OwnedPtr<T> {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
52        self.0.fmt(f)
53    }
54}
55
56unsafe impl<T> Send for OwnedPtr<T> {}
57unsafe impl<T> Sync for OwnedPtr<T> where T: Sync {}