#raw-pointers #convert #traits

no-std ptrplus

Additional funtionality for pointer types

6 releases (stable)

2.1.0 Nov 22, 2022
2.0.0 Apr 29, 2022
1.1.0 Jan 13, 2021
1.0.0 Jan 7, 2017
0.1.0 Dec 10, 2016

#787 in Rust patterns

Download history 116/week @ 2024-06-30 145/week @ 2024-07-07 186/week @ 2024-07-14 254/week @ 2024-07-21 337/week @ 2024-07-28 225/week @ 2024-08-04 252/week @ 2024-08-11 129/week @ 2024-08-18 169/week @ 2024-08-25 191/week @ 2024-09-01 422/week @ 2024-09-08 192/week @ 2024-09-15 321/week @ 2024-09-22 239/week @ 2024-09-29 227/week @ 2024-10-06 209/week @ 2024-10-13

1,019 downloads per month
Used in 12 crates (4 directly)

MIT license

21KB
428 lines

Build status Crates.io Crates.io

ptrplus

Ptrplus is a library that adds additional functionality around raw pointers.

Conversions

Ptrplus provides traits to convert between raw pointers and safer Rust pointer types. AsPtr, IntoRaw, and FromRaw provide common traits for types that implement as_ptr, into_raw, and from_raw respectively. Of note, these traits also have implementations for Option to handle nullable raw pointers.

Examples

use ptrplus::AsPtr;

let x: &u32 = &5;
let y: *const u32 = x.as_ptr();
unsafe {
    assert_eq!(*y, 5);
}
use ptrplus::AsPtr;

let x = 5;
let o1: Option<&u32> = None;
let o2: Option<&u32> = Some(&x);

assert!(o1.as_ptr().is_null());
assert!(!o2.as_ptr().is_null());
unsafe {
    assert_eq!(*o2.as_ptr(), 5);
}
use ptrplus::IntoRaw;

let x: Box<u32> = Box::new(5);
let y: *mut u32 = IntoRaw::into_raw(x);
unsafe {
  assert_eq!(*y, 5);
  *y = 6;
  Box::from_raw(y);
}

use ptrplus::{FromRaw, IntoRaw};

let o1: Option<Box<u32>> = None;
let o2: Option<Box<u32>> = Some(Box::new(5));

let p1: *mut u32 = o1.into_raw();
let p2: *mut u32 = o2.into_raw();

assert!(p1.is_null());
assert!(!p2.is_null());
unsafe {
    assert_eq!(*p2, 5);
    let o1: Option<Box<u32>> = Option::from_raw(p1);
    let o2: Option<Box<u32>> = Option::from_raw(p2);
    assert!(o1.is_none());
    assert!(!o2.is_none());
}

No runtime deps

Features