Skip to content

Commit fe176e2

Browse files
committed
Refactor for small clean up and delete deprecated functions
1 parent 8b9066a commit fe176e2

File tree

7 files changed

+37
-92
lines changed

7 files changed

+37
-92
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Opaque Pointer for seamless Rust FFI
22

3-
Harnessing generics with opaque pointers for seamless Rust FFI interoperability with C and C++
3+
Harnessing generics with opaque pointers for seamless Rust FFI interoperability with C and C++.
44

55
[![Crates.io](https://img.shields.io/crates/v/opaque-pointer)](https://crates.io/crates/opaque-pointer)
66
[![Crates.io](https://img.shields.io/crates/l/opaque-pointer)](https://unlicense.org/)

src/c.rs

Lines changed: 0 additions & 32 deletions
This file was deleted.

src/error.rs

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ use std::collections::TryReserveError;
99
/// Errors that can be detected by the functions of this crate.
1010
///
1111
/// Of course, invalid address can not be detected, then it's unsafe yet.
12-
#[allow(clippy::module_name_repetitions)] // Like std::error::Error, it is for pointer errors
1312
#[derive(Debug, PartialEq, Eq)]
1413
pub enum PointerError {
15-
#[allow(missing_docs)] // Obviously, the name is the ref doc.
14+
// Obviously, the name is the ref doc.
1615
Null,
1716
/// A pointer that was not previously lent to the FFI user.
17+
#[cfg(all(feature = "std", feature = "lender"))]
1818
Invalid,
1919
/// Trying to convert to `&str` a C string which content is not valid UTF-8.
2020
Utf8Error(Utf8Error),
@@ -26,18 +26,12 @@ pub enum PointerError {
2626
impl core::fmt::Display for PointerError {
2727
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
2828
match self {
29-
Self::Null => {
30-
write!(f, "dereference a null pointer will produce a crash")
31-
}
32-
Self::Invalid => {
33-
write!(f, "dereference a unknown pointer could produce a crash")
34-
}
35-
Self::Utf8Error(error) => {
36-
write!(
37-
f,
38-
"the provided C string is not a valid UTF-8 string: {error}"
39-
)
40-
}
29+
Self::Null => write!(f, "dereference a null pointer will produce a crash"),
30+
Self::Invalid => write!(f, "dereference a unknown pointer could produce a crash"),
31+
Self::Utf8Error(error) => write!(
32+
f,
33+
"the provided C string is not a valid UTF-8 string: {error}"
34+
),
4135
#[cfg(any(feature = "alloc", feature = "std"))]
4236
Self::TryReserveError(error) => {
4337
write!(f, "can not alloc memory of internal usage: {error}")

src/lender.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,5 @@
11
#![cfg(all(feature = "std", feature = "lender"))]
22

3-
//! # Lender of Rust's memory by FFI
4-
//!
5-
//! To control that pointers at least were returned by [`crate::raw`]. But
6-
//! it can not ensure if type is correct, yet.
7-
83
use lazy_static::lazy_static;
94
use std::collections::HashSet;
105
use std::sync::{RwLock, RwLockWriteGuard};
@@ -25,7 +20,7 @@ lazy_static! {
2520
pub(super) fn is_lent<T>(pointer: *const T) -> bool {
2621
let Ok(lent_pointers) = LENT_POINTERS.read() else {
2722
log::error!("RwLock poisoned, it is not possible to check pointers");
28-
unreachable!("RwLock poisoned when there is not panics in code that can hold it");
23+
unreachable!();
2924
};
3025
return lent_pointers.contains(&(pointer as usize));
3126
}
@@ -39,6 +34,7 @@ pub(super) fn is_lent<T>(pointer: *const T) -> bool {
3934
/// avoid panics while holding it.
4035
pub(super) fn lend<T>(pointer: *const T) -> Result<(), PointerError> {
4136
let mut lent_pointers = writable_lent_pointers();
37+
4238
if let Err(error) = lent_pointers.try_reserve(1) {
4339
log::error!("Can not alloc memory to lent a pointer: {error}");
4440
return Err(PointerError::from(error));
@@ -61,7 +57,8 @@ pub(super) fn retrieve<T>(pointer: *const T) {
6157
fn writable_lent_pointers() -> RwLockWriteGuard<'static, HashSet<usize>> {
6258
let Ok(lent_pointers) = LENT_POINTERS.write() else {
6359
log::error!("RwLock poisoned, it is not possible to add or remove pointers");
64-
unreachable!("RwLock poisoned when there is not panics in code that can hold it");
60+
unreachable!();
6561
};
66-
return lent_pointers;
62+
63+
lent_pointers
6764
}

src/lib.rs

Lines changed: 12 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
#![doc = include_str!("../README.md")] // This also allow to run examples in that file.
22
#![allow(unsafe_code)]
3-
#![warn(missing_docs)]
4-
#![warn(clippy::pedantic)]
53
#![deny(clippy::complexity)]
64
#![deny(clippy::cognitive_complexity)]
7-
#![allow(clippy::needless_return)] // To avoid surprise in devs more familiar with languages where return is always explicit
85
#![doc(html_no_source)]
96
#![no_std]
107

@@ -18,9 +15,6 @@ extern crate std;
1815
#[cfg(feature = "std")]
1916
use std::boxed::Box;
2017

21-
#[cfg(all(feature = "std", feature = "c-types"))]
22-
pub mod c;
23-
2418
pub mod error;
2519
use error::PointerError;
2620

@@ -40,56 +34,42 @@ mod validation;
4034
#[inline]
4135
pub fn raw<T>(data: T) -> Result<*mut T, PointerError> {
4236
let pointer = Box::into_raw(Box::new(data));
37+
4338
#[cfg(all(feature = "std", feature = "lender"))]
4439
lender::lend(pointer)?;
45-
return Ok(pointer);
40+
41+
Ok(pointer)
4642
}
4743

48-
/// Call to [`own_back<T>()`] ignoring the result.
49-
///
50-
/// This is deprecated and will be removed in the version 0.9.0 then you can do this:
44+
/// Opposite of [`raw<T>()`], to use Rust's ownership as usually.
5145
///
52-
/// ```no_run
46+
/// ```
5347
/// # let value = 0;
5448
/// # let pointer = opaque_pointer::raw(value).unwrap();
55-
/// std::mem::drop(unsafe { opaque_pointer::own_back(pointer) });
49+
/// drop(unsafe { opaque_pointer::own_back(pointer) });
5650
/// ```
5751
///
58-
/// # Safety
59-
///
60-
/// See [`own_back<T>()`] reference doc.
61-
#[deprecated(
62-
since = "0.7.2",
63-
note = "Use own_back<T>() instead, it'll be removed at version 0.9.0"
64-
)]
65-
#[cfg(any(feature = "alloc", feature = "std"))]
66-
#[inline]
67-
pub unsafe fn free<T>(pointer: *mut T) {
68-
core::mem::drop(own_back(pointer));
69-
}
70-
71-
/// Opposite of [`raw<T>()`], to use Rust's ownership as usually.
72-
///
7352
/// # Errors
7453
///
7554
/// The pointer must be not null as it is an obvious invalid pointer.
7655
///
7756
/// # Safety
7857
///
7958
/// Invalid pointer or call it twice could cause an undefined behavior or heap error and a crash.
80-
#[doc(alias = "free")]
8159
#[cfg(any(feature = "alloc", feature = "std"))]
8260
#[inline]
8361
#[allow(clippy::not_unsafe_ptr_arg_deref)]
8462
pub unsafe fn own_back<T>(pointer: *mut T) -> Result<T, PointerError> {
8563
validation::lent_pointer(pointer)?;
8664
let boxed = { Box::from_raw(pointer) };
65+
8766
#[cfg(all(feature = "std", feature = "lender"))]
8867
lender::retrieve(pointer);
89-
return Ok(*boxed);
68+
69+
Ok(*boxed)
9070
}
9171

92-
/// Reference to a object but without to own it.
72+
/// Reference to an object but without to own it.
9373
///
9474
/// # Errors
9575
///
@@ -101,7 +81,7 @@ pub unsafe fn own_back<T>(pointer: *mut T) -> Result<T, PointerError> {
10181
#[inline]
10282
pub unsafe fn object<'a, T>(pointer: *const T) -> Result<&'a T, PointerError> {
10383
validation::not_null_pointer(pointer)?;
104-
return Ok(&*pointer);
84+
Ok(&*pointer)
10585
}
10686

10787
/// Mutable reference to a object but without back to own it.
@@ -116,5 +96,5 @@ pub unsafe fn object<'a, T>(pointer: *const T) -> Result<&'a T, PointerError> {
11696
#[inline]
11797
pub unsafe fn mut_object<'a, T>(pointer: *mut T) -> Result<&'a mut T, PointerError> {
11898
validation::not_null_pointer(pointer)?;
119-
return Ok(&mut *pointer);
99+
Ok(&mut *pointer)
120100
}

src/validation.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,19 @@ pub fn not_null_pointer<T>(pointer: *const T) -> Result<(), PointerError> {
88
log::error!("Using a NULL pointer as an opaque pointer to Rust's data");
99
return Err(PointerError::Null);
1010
}
11-
return Ok(());
11+
12+
Ok(())
1213
}
1314

1415
#[inline]
1516
pub fn lent_pointer<T>(pointer: *const T) -> Result<(), PointerError> {
1617
not_null_pointer(pointer)?;
18+
1719
#[cfg(all(feature = "std", feature = "lender"))]
1820
if !lender::is_lent(pointer) {
1921
log::error!("Using an invalid pointer as an opaque pointer to Rust's data");
2022
return Err(PointerError::Invalid);
2123
}
22-
return Ok(());
24+
25+
Ok(())
2326
}

tests/pointer.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use opaque_pointer;
2+
use opaque_pointer::error::PointerError;
23

34
#[derive(Debug)]
45
struct TestIt {
@@ -28,10 +29,10 @@ fn own_back() {
2829
#[test]
2930
fn own_back_invalid_pointer() {
3031
let pointer = Box::into_raw(Box::new(TestIt::new(2)));
31-
let invalid_pointer_error = unsafe { opaque_pointer::own_back(pointer).unwrap_err() };
32+
let error = unsafe { opaque_pointer::own_back(pointer).unwrap_err() };
3233
assert_eq!(
33-
invalid_pointer_error,
34-
opaque_pointer::error::PointerError::Invalid
34+
error,
35+
PointerError::Invalid
3536
);
3637
}
3738

@@ -40,6 +41,7 @@ fn immutable_reference() {
4041
let pointer = opaque_pointer::raw(TestIt::new(2)).unwrap();
4142
let object = unsafe { opaque_pointer::object(pointer).unwrap() };
4243
assert_eq!(object.get(), 2);
44+
4345
unsafe { opaque_pointer::own_back(pointer).unwrap() };
4446
}
4547

@@ -49,5 +51,6 @@ fn mutable_reference() {
4951
let object = unsafe { opaque_pointer::mut_object(pointer).unwrap() };
5052
object.add(3);
5153
assert_eq!(object.get(), 5);
54+
5255
unsafe { opaque_pointer::own_back(pointer).unwrap() };
5356
}

0 commit comments

Comments
 (0)