summary refs log tree commit diff stats
path: root/src/lib.rs
blob: ad2905d4aab7ece7c72d75fca21bd23b2eef4cfc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Copyright (C) 2022 Soni L.
// SPDX-License-Identifier: 0BSD

#![cfg_attr(not(feature="std"),no_std)]
#![deny(unsafe_op_in_unsafe_fn)]

//! This crate provides "checked" raw pointers.
//!
//! We found ourselves to be experiencing a lot of cognitive overhead when
//! doing FFI interactions. A non-insignificant portion of them came from raw
//! pointers, `as_ptr`, `as_mut_ptr`, and the like. This removes that cognitive
//! overhead.
//!
//! And as [Amos once said], "Until we demand better of our tools, we are
//! doomed to be woken up in the middle of the night, over and over again,
//! because some nil value slipped in where it never should have.". That is, we
//! are doomed to repeat the same mistakes over and over again. So we must
//! demand better of our tools!
//!
//! [Amos once said]: https://fasterthanli.me/articles/lies-we-tell-ourselves-to-keep-using-golang

use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ops::Range;

/// The actual impls.
mod impls;

/// `*const T` with a lifetime.
///
/// # Examples
///
/// Rust doesn't catch incorrect `as_ptr` usage (tho there is a lint for it):
///
/// ```no_run
/// use std::ffi::{CString, CStr};
/// use std::os::raw::c_char;
///
/// extern "C" {
///     fn my_ffi_function(data: *const c_char);
/// }
/// let str = CString::new("world!").unwrap().as_ptr();
/// //                    oops! CString dropped here! ^
/// unsafe { my_ffi_function(str) } // crashes at runtime
/// ```
///
/// but we can use a `ConstLtPtr` to make it do so:
///
/// ```compile_fail
/// use std::ffi::{CString, CStr};
/// use std::os::raw::c_char;
/// use ltptr::*;
///
/// extern "C" {
///     fn my_ffi_function(data: ConstLtPtr<'_, c_char>);
/// }
/// let str = CString::new("world!").unwrap().as_lt_ptr();
/// unsafe { my_ffi_function(str) }
/// // error[E0716]: temporary value dropped while borrowed
/// ```
///
/// which we can then fix:
///
/// ```no_run
/// use std::ffi::{CString, CStr};
/// use std::os::raw::c_char;
/// use ltptr::*;
///
/// extern "C" {
///     fn my_ffi_function(data: ConstLtPtr<'_, c_char>);
/// }
/// let str = CString::new("world!").unwrap();
/// unsafe { my_ffi_function(str.as_lt_ptr()) }
/// ```
///
///
/// and if we call the wrong thing, it fails to compile:
///
/// ```compile_fail
/// use std::ffi::{CString, CStr};
/// use std::os::raw::c_char;
/// use ltptr::*;
///
/// extern "C" {
///     fn my_ffi_function(data: ConstLtPtr<'_, c_char>);
/// }
/// let str = CString::new("world!").unwrap();
/// unsafe { my_ffi_function(str.as_ptr()) } // should be as_lt_ptr!
/// ```
#[repr(transparent)]
pub struct ConstLtPtr<'a, T: ?Sized> {
  raw: *const T,
  _lt: PhantomData<&'a T>,
}

/// `*mut T` with a lifetime.
#[repr(transparent)]
pub struct MutLtPtr<'a, T: ?Sized> {
  raw: *mut T,
  _lt: PhantomData<&'a UnsafeCell<T>>,
}

/// Trait for conversion into a [`ConstLtPtr`].
pub trait AsLtPtr {
    type Target: ?Sized;
    /// Returns a pointer as if by `as_ptr` on a type that implements this, but
    /// with a bound lifetime.
    fn as_lt_ptr<'a>(&'a self) -> ConstLtPtr<'a, Self::Target>;
}

/// Trait for conversion from a [`ConstLtPtr`] of the given `Source` type.
pub trait FromLtPtr<Source> {
    /// Returns a value as if by `from_ptr` on a type that implements this, but
    /// with a bound lifetime.
    unsafe fn from_lt_ptr<'a>(ptr: ConstLtPtr<'a, Source>) -> &'a Self;
}

/// Trait for conversion into a [`MutLtPtr`].
pub trait AsMutLtPtr: AsLtPtr {
    /// Returns a pointer as if by `as_ptr` on a type that implements this, but
    /// with a bound lifetime.
    fn as_mut_lt_ptr<'a>(&'a mut self) -> MutLtPtr<'a, Self::Target>;
}

/// Additional slice methods.
pub trait SliceExt<T>: impls::slice::Sealed {
    /// Returns the two raw pointers spanning the slice.
    ///
    /// See [`slice::as_ptr_range`] for extended documentation.
    ///
    /// The pointers returned by this function have bound lifetimes.
    fn as_lt_ptr_range<'a>(&'a self) -> Range<ConstLtPtr<'a, T>>;

    /// Returns the two unsafe mutable pointers spanning the slice.
    ///
    /// See [`slice::as_mut_ptr_range`] for extended documentation.
    ///
    /// The pointers returned by this function have bound lifetimes.
    fn as_mut_lt_ptr_range<'a>(&'a mut self) -> Range<MutLtPtr<'a, T>>;
}

impl<'a, T: ?Sized> ConstLtPtr<'a, T> {
    /// Creates a new `ConstLtPtr` from the given raw pointer.
    ///
    /// # Safety
    ///
    /// This function is unsafe as an advisory: the returned `ConstLtPtr` has
    /// an arbitrary lifetime `'a`, so using this function directly doesn't
    /// help reduce cognitive overhead.
    #[inline]
    pub const unsafe fn from_raw(raw: *const T) -> Self {
        Self {
            raw: raw,
            _lt: PhantomData,
        }
    }

    /// Returns this `ConstLtPtr` as a raw pointer.
    ///
    /// # Safety
    ///
    /// This function is unsafe as an advisory: the returned raw pointer loses
    /// the lifetime.
    #[inline]
    pub const unsafe fn as_raw(&self) -> *const T {
        self.raw
    }

    /// Checks if this pointer is null.
    ///
    /// # Examples
    ///
    /// A null pointer is null:
    ///
    /// ```rust
    /// use ltptr::ConstLtPtr;
    ///
    /// let raw_ptr = core::ptr::null::<()>();
    /// let lt_ptr = unsafe { ConstLtPtr::from_raw(raw_ptr) };
    /// assert!(lt_ptr.is_null());
    /// ```
    #[inline]
    pub fn is_null(self) -> bool {
        self.raw.is_null()
    }
}

impl<'a, T: ?Sized> MutLtPtr<'a, T> {
    /// Creates a new `MutLtPtr` from the given raw pointer.
    ///
    /// # Safety
    ///
    /// This function is unsafe as an advisory: the returned `MutLtPtr` has
    /// an arbitrary lifetime `'a`, so using this function directly doesn't
    /// help reduce cognitive overhead.
    #[inline]
    pub const unsafe fn from_raw(raw: *mut T) -> Self {
        Self {
            raw: raw,
            _lt: PhantomData,
        }
    }

    /// Returns this `MutLtPtr` as a raw pointer.
    ///
    /// # Safety
    ///
    /// This function is unsafe as an advisory: the returned raw pointer loses
    /// the lifetime.
    #[inline]
    pub const unsafe fn as_raw(&self) -> *mut T {
        self.raw
    }

    /// Checks if this pointer is null.
    /// # Examples
    ///
    /// A null pointer is null:
    ///
    /// ```rust
    /// use ltptr::MutLtPtr;
    ///
    /// let raw_ptr = core::ptr::null_mut::<()>();
    /// let lt_ptr = unsafe { MutLtPtr::from_raw(raw_ptr) };
    /// assert!(lt_ptr.is_null());
    /// ```
    #[inline]
    pub fn is_null(self) -> bool {
        self.raw.is_null()
    }
}