Skip to content

Commit

Permalink
Add methods for handing allocated strings back to C
Browse files Browse the repository at this point in the history
  • Loading branch information
shepmaster committed May 25, 2015
1 parent 893e416 commit ff86ab6
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/libstd/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,28 @@ impl CString {
CString { inner: v }
}

/// Retakes ownership from a Rust string that has been returned to C.
pub unsafe fn from_raw_ptr(ptr: *const libc::c_char) -> CString {
let len = libc::strlen(ptr);
let len_with_nul = len as usize + 1;
let vec = Vec::from_raw_parts(ptr as *mut u8, len_with_nul, len_with_nul);
CString::from_vec_unchecked(vec)
}

/// Transfers ownership from Rust to C. Be warned that the string
/// must be returned to Rust and reconstituted via `from_raw_ptr`
/// to be properly deallocated.
pub fn into_raw_ptr(self) -> *const libc::c_char {
// Resize the vector to fit - we need the capacity to be
// determinable from the string length, and shrinking to fit
// is the only way to be sure.
let mut vec = self.inner;
vec.shrink_to_fit();
let ptr = vec.as_ptr() as *const libc::c_char;
mem::forget(vec);
ptr
}

/// Returns the contents of this `CString` as a slice of bytes.
///
/// The returned slice does **not** contain the trailing nul separator and
Expand Down

0 comments on commit ff86ab6

Please sign in to comment.