Skip to content

safer_ffi::Vec seems to be unsafe #267

@QuarticCat

Description

@QuarticCat

safer_ffi/src/vec.rs

Lines 41 to 70 in 310a2c9

/// Convert a [`std::vec::Vec`] to a [`safer_ffi::Vec`].
impl<T> From<rust::Vec<T>> for Vec<T> {
#[inline]
fn from(vec: rust::Vec<T>) -> Vec<T> {
let len = vec.len();
let cap = vec.capacity();
let ptr = mem::ManuallyDrop::new(vec).as_mut_ptr();
Self {
ptr: unsafe {
// Safety: `Vec` guarantees its pointer is nonnull.
ptr::NonNull::new_unchecked(ptr)
}
.into(),
len,
cap,
}
}
}
/// Convert a [`safer_ffi::Vec`] to a [`std::vec::Vec`].
impl<T> From<Vec<T>> for rust::Vec<T> {
#[inline]
fn from(value: Vec<T>) -> rust::Vec<T> {
let mut this = mem::ManuallyDrop::new(value);
unsafe {
// Safety: pointers originate from `Vec`.
rust::Vec::from_raw_parts(this.ptr.as_mut_ptr(), this.len, this.cap)
}
}
}

There is no guarantee that the same allocator is used across the FFI boundary.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions