Skip to content

Commit 3c98d6a

Browse files
committed
---
yaml --- r: 212446 b: refs/heads/master c: e20a6db h: refs/heads/master v: v3
1 parent 3f09497 commit 3c98d6a

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
refs/heads/master: 97294be30c8712a91060d0ce043adefb4f867db8
2+
refs/heads/master: e20a6dbeed095427e5d5487844f65e7eb1599651
33
refs/heads/snap-stage1: e33de59e47c5076a89eadeb38f4934f58a3618a6
44
refs/heads/snap-stage3: ba0e1cd8147d452c356aacb29fb87568ca26f111
55
refs/heads/try: 1864973ae17213c5a58c4dd3f9af6d1b6c7d2e05

trunk/src/libstd/ffi/c_str.rs

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#![unstable(feature = "std_misc")]
1212

1313
use borrow::{Cow, ToOwned};
14-
use boxed::Box;
14+
use boxed::{self, Box};
1515
use clone::Clone;
1616
use convert::{Into, From};
1717
use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
@@ -202,6 +202,34 @@ impl CString {
202202
CString { inner: v.into_boxed_slice() }
203203
}
204204

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+
205233
/// Returns the contents of this `CString` as a slice of bytes.
206234
///
207235
/// The returned slice does **not** contain the trailing nul separator and

0 commit comments

Comments
 (0)