|
11 | 11 | #![unstable(feature = "std_misc")]
|
12 | 12 |
|
13 | 13 | use borrow::{Cow, ToOwned};
|
14 |
| -use boxed::Box; |
| 14 | +use boxed::{self, Box}; |
15 | 15 | use clone::Clone;
|
16 | 16 | use convert::{Into, From};
|
17 | 17 | use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
|
@@ -202,6 +202,34 @@ impl CString {
|
202 | 202 | CString { inner: v.into_boxed_slice() }
|
203 | 203 | }
|
204 | 204 |
|
| 205 | + /// Retakes ownership of a CString that was transferred to C. |
| 206 | + /// |
| 207 | + /// The only appropriate argument is a pointer obtained by calling |
| 208 | + /// `into_ptr`. The length of the string will be recalculated |
| 209 | + /// using the pointer. |
| 210 | + #[unstable(feature = "cstr_memory", reason = "recently added")] |
| 211 | + pub unsafe fn from_ptr(ptr: *const libc::c_char) -> CString { |
| 212 | + let len = libc::strlen(ptr) + 1; // Including the NUL byte |
| 213 | + let slice = slice::from_raw_parts(ptr, len as usize); |
| 214 | + CString { inner: mem::transmute(slice) } |
| 215 | + } |
| 216 | + |
| 217 | + /// Transfers ownership of the string to a C caller. |
| 218 | + /// |
| 219 | + /// The pointer must be returned to Rust and reconstituted using |
| 220 | + /// `from_ptr` to be properly deallocated. Specifically, one |
| 221 | + /// should *not* use the standard C `free` function to deallocate |
| 222 | + /// this string. |
| 223 | + /// |
| 224 | + /// Failure to call `from_ptr` will lead to a memory leak. |
| 225 | + #[unstable(feature = "cstr_memory", reason = "recently added")] |
| 226 | + pub fn into_ptr(self) -> *const libc::c_char { |
| 227 | + // It is important that the bytes be sized to fit - we need |
| 228 | + // the capacity to be determinable from the string length, and |
| 229 | + // shrinking to fit is the only way to be sure. |
| 230 | + boxed::into_raw(self.inner) as *const libc::c_char |
| 231 | + } |
| 232 | + |
205 | 233 | /// Returns the contents of this `CString` as a slice of bytes.
|
206 | 234 | ///
|
207 | 235 | /// The returned slice does **not** contain the trailing nul separator and
|
|
0 commit comments