1#![no_std]
7
8#![feature(const_destruct)]
10#![feature(const_option_ops)]
11#![feature(const_trait_impl)]
12#![feature(const_closures)]
13#![feature(const_try)]
14#![feature(const_default)]
15#![feature(const_convert)]
16#![feature(ptr_mask)]
17
18mod comparisons;
20mod conversions;
21#[cfg(test)]
22mod tests;
23
24use core::{
26 ptr::{
27 NonNull,
28 null,
29 null_mut
30 },
31 fmt::{
32 Debug,
33 Formatter,
34 Result as Format
35 },
36 any::type_name,
37 marker::Destruct
38};
39
40
41pub struct Pointer<Type> {
47 to: Option<NonNull<Type>>
48}
49
50impl<Type> Pointer<Type> {
52 pub const fn is_null(self) -> bool {return self.to.is_none()}
53 pub fn address(self) -> usize {return self.to.map(|pointer| pointer.addr().into()).unwrap_or_default()}
54 pub const fn add(self, count: usize) -> Pointer<Type> {return Self {
55 to: self.to.map(const |pointer| unsafe {pointer.add(count)})
56 }}
57 pub const fn sub(self, count: usize) -> Pointer<Type> {return Self {
58 to: self.to.map(const |pointer| unsafe {pointer.sub(count)})
59 }}
60 pub const unsafe fn read(self) -> Option<Type> {return Some(unsafe {self.to?.read()})}
61 pub const fn as_ptr(self) -> *const Type {return match self.to {
62 None => null(),
63 Some(pointer) => pointer.as_ptr()
64 }}
65 pub const fn as_ptr_mut(self) -> *mut Type {return match self.to {
66 None => null_mut(),
67 Some(pointer) => pointer.as_ptr()
68 }}
69 pub const fn get<'lifetime>(self) -> Option<&'lifetime Type> {return self.to.map(const |pointer| unsafe {pointer.as_ref()})}
70 pub const fn get_mut<'lifetime>(self) -> Option<&'lifetime mut Type> {return self.to.map(const |mut pointer| unsafe {pointer.as_mut()})}
71 pub const fn take(self) -> Option<NonNull<Type>> {return self.to}
72 pub fn is_aligned(self) -> bool {return self.address() % align_of::<Type>() == 0}
73 pub const fn cast<Other>(self) -> Pointer<Other> {return Pointer {
74 to: self.to.map(const |pointer| pointer.cast())
75 }}
76 pub fn mask(self, mask: usize) -> Pointer<Type> {Pointer::from(self.to.map(|pointer| pointer.as_ptr()).unwrap_or(null_mut()).mask(mask))}
77}
78
79const impl<Type: [const] Destruct> Pointer<Type> {
81 pub unsafe fn write(self, value: Type) -> () {if let Some(pointer) = self.to {unsafe {pointer.write(value)}}}
82 pub unsafe fn replace(self, with: Type) -> Option<Type> {return Some(unsafe {self.to?.replace(with)})}
83}
84
85impl<Type> Clone for Pointer<Type> {
87 fn clone(&self) -> Self {return Self {
88 to: self.to.clone()
89 }}
90}
91
92impl<Type> Copy for Pointer<Type> {}
94
95impl<Type: Debug> Debug for Pointer<Type> {
97 fn fmt(&self, formatter: &mut Formatter<'_>) -> Format {write!(formatter, "*{}", type_name::<Type>())}
98}
99
100const impl<Type> Default for Pointer<Type> {
102 fn default() -> Self {return Self {
103 to: None
104 }}
105}
106
107unsafe impl<Type> Send for Pointer<Type> {}
109
110unsafe impl<Type> Sync for Pointer<Type> {}