Skip to main content

il2cpp_bridge_rs/structs/
ptr.rs

1//! Safe wrapper for valid mutable pointers
2//!
3//! This module provides the `MutPtr` wrapper which guarantees non-null pointer access
4//! with safe ergonomic wrappers while maintaining the raw pointer representation.
5
6use std::ops::{Deref, DerefMut};
7
8/// A transparent wrapper around a mutable pointer that ensures safety checks on access
9#[repr(transparent)]
10#[derive(Debug, Clone, Copy)]
11pub struct MutPtr<T>(pub *mut T);
12
13impl<T> MutPtr<T> {
14    /// Creates a new `MutPtr` from a raw pointer
15    #[inline(always)]
16    pub fn new(ptr: *mut T) -> Self {
17        Self(ptr)
18    }
19
20    /// Checks if the underlying pointer is null
21    #[inline(always)]
22    pub fn is_null(&self) -> bool {
23        self.0.is_null()
24    }
25
26    /// Returns the underlying raw pointer
27    #[inline(always)]
28    pub fn as_ptr(&self) -> *mut T {
29        self.0
30    }
31}
32
33impl<T> Deref for MutPtr<T> {
34    type Target = T;
35
36    /// Dereferences the pointer. Panics if the pointer is null.
37    #[inline(always)]
38    fn deref(&self) -> &Self::Target {
39        if self.0.is_null() {
40            panic!("Null pointer dereference: {}", std::any::type_name::<T>());
41        }
42        unsafe { &*self.0 }
43    }
44}
45
46impl<T> DerefMut for MutPtr<T> {
47    /// Mutably dereferences the pointer. Panics if the pointer is null.
48    #[inline(always)]
49    fn deref_mut(&mut self) -> &mut Self::Target {
50        if self.0.is_null() {
51            panic!("Null pointer dereference: {}", std::any::type_name::<T>());
52        }
53        unsafe { &mut *self.0 }
54    }
55}