factor out some utilities for pointer arrays

This commit is contained in:
Dustin J. Mitchell
2022-02-06 16:38:31 +00:00
parent b0f7850711
commit 3d248b55fd
2 changed files with 35 additions and 22 deletions

View File

@@ -1,5 +1,34 @@
use crate::string::TCString;
use crate::traits::*;
use std::ptr::NonNull;
pub(crate) fn err_to_tcstring(e: impl std::string::ToString) -> TCString<'static> {
TCString::from(e.to_string())
}
/// A version of Vec::into_raw_parts, which is still unstable. Returns ptr, len, cap.
pub(crate) fn vec_into_raw_parts<T>(vec: Vec<T>) -> (*mut T, usize, usize) {
// emulate Vec::into_raw_parts():
// - disable dropping the Vec with ManuallyDrop
// - extract ptr, len, and capacity using those methods
let mut vec = std::mem::ManuallyDrop::new(vec);
return (vec.as_mut_ptr(), vec.len(), vec.capacity());
}
/// Drop an array of PassByPointer values
pub(crate) fn drop_pointer_array<T>(mut array: Vec<NonNull<T>>)
where
T: 'static + PassByPointer,
{
// first, drop each of the elements in turn
for p in array.drain(..) {
// SAFETY:
// - p is not NULL (NonNull)
// - p was generated by Rust (true for all arrays)
// - p was not modified (all arrays are immutable from C)
// - caller will not use this pointer again (promised by caller; p has been drain'd from
// the vector)
drop(unsafe { PassByPointer::take_from_arg(p.as_ptr()) });
}
drop(array);
}