kernel_api/ptr/
mod.rs

1#![unstable(feature = "kernel_ptr", issue = "none")]
2
3use core::fmt;
4use core::marker::PhantomData;
5use core::ptr::NonNull;
6
7#[cfg(feature = "full")]
8mod user_ptr;
9#[cfg(feature = "full")]
10pub use user_ptr::*;
11
12pub struct Unique<T: ?Sized> {
13	pointer: NonNull<T>,
14	_marker: PhantomData<T>,
15}
16
17/// `Unique` pointers are `Send` if `T` is `Send` because the data they
18/// reference is unaliased. Note that this aliasing invariant is
19/// unenforced by the type system; the abstraction using the
20/// `Unique` must enforce it.
21unsafe impl<T: Send + ?Sized> Send for Unique<T> { }
22
23/// `Unique` pointers are `Sync` if `T` is `Sync` because the data they
24/// reference is unaliased. Note that this aliasing invariant is
25/// unenforced by the type system; the abstraction using the
26/// `Unique` must enforce it.
27unsafe impl<T: Sync + ?Sized> Sync for Unique<T> { }
28
29impl<T: Sized> Unique<T> {
30	/// Creates a new `Unique` that is dangling, but well-aligned.
31	///
32	/// This is useful for initializing types which lazily allocate, like
33	/// `Vec::new` does.
34	pub fn empty() -> Self {
35		unsafe {
36			Unique::new(NonNull::dangling().as_ptr())
37		}
38	}
39}
40
41impl<T: ?Sized> Unique<T> {
42	/// Creates a new `Unique`.
43	///
44	/// # Safety
45	///
46	/// `ptr` must be non-null.
47	pub const unsafe fn new(ptr: *mut T) -> Unique<T> {
48		Unique { pointer: NonNull::new_unchecked(ptr), _marker: PhantomData }
49	}
50
51	/// Acquires the underlying `*mut` pointer.
52	pub fn as_ptr(self) -> *mut T {
53		self.pointer.as_ptr()
54	}
55
56	/// Dereferences the content.
57	///
58	/// The resulting lifetime is bound to self so this behaves "as if"
59	/// it were actually an instance of T that is getting borrowed. If a longer
60	/// (unbound) lifetime is needed, use `&*my_ptr.ptr()`.
61	pub unsafe fn as_ref(&self) -> &T {
62		&*self.as_ptr()
63	}
64
65	/// Mutably dereferences the content.
66	///
67	/// The resulting lifetime is bound to self so this behaves "as if"
68	/// it were actually an instance of T that is getting borrowed. If a longer
69	/// (unbound) lifetime is needed, use `&mut *my_ptr.ptr()`.
70	pub unsafe fn as_mut(&mut self) -> &mut T {
71		&mut *self.as_ptr()
72	}
73}
74
75impl<T: ?Sized> Clone for Unique<T> {
76	fn clone(&self) -> Self {
77		*self
78	}
79}
80
81impl<T: ?Sized> Copy for Unique<T> {}
82
83impl<T: ?Sized> fmt::Pointer for Unique<T> {
84	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85		fmt::Pointer::fmt(&self.as_ptr(), f)
86	}
87}
88
89#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
90#[path = "x86_64.rs"]
91#[cfg(feature = "full")]
92#[unstable(feature = "kernel_internals", issue = "none")]
93pub mod impls;