Skip to content

Commit 569f13a

Browse files
committed
c_str: move .unwrap & document it more clearly.
This should be called rarely, but it was placed first in the list of methods, making it very tempting to call.
1 parent d4d4bc4 commit 569f13a

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/librustrt/c_str.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -122,17 +122,6 @@ impl CString {
122122
CString { buf: buf, owns_buffer_: owns_buffer }
123123
}
124124

125-
/// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
126-
///
127-
/// The original object is destructed after this method is called, and if
128-
/// the underlying pointer was previously allocated, care must be taken to
129-
/// ensure that it is deallocated properly.
130-
pub unsafe fn unwrap(self) -> *const libc::c_char {
131-
let mut c_str = self;
132-
c_str.owns_buffer_ = false;
133-
c_str.buf
134-
}
135-
136125
/// Return a pointer to the NUL-terminated string data.
137126
///
138127
/// `.as_ptr` returns an internal pointer into the `CString`, and
@@ -289,6 +278,22 @@ impl CString {
289278
marker: marker::ContravariantLifetime,
290279
}
291280
}
281+
282+
/// Unwraps the wrapped `*libc::c_char` from the `CString` wrapper.
283+
///
284+
/// Any ownership of the buffer by the `CString` wrapper is
285+
/// forgotten, meaning that the backing allocation of this
286+
/// `CString` is not automatically freed if it owns the
287+
/// allocation. In this case, a user of `.unwrap()` should ensure
288+
/// the allocation is freed, to avoid leaking memory.
289+
///
290+
/// Prefer `.as_ptr()` when just retrieving a pointer to the
291+
/// string data, as that does not relinquish ownership.
292+
pub unsafe fn unwrap(mut self) -> *const libc::c_char {
293+
self.owns_buffer_ = false;
294+
self.buf
295+
}
296+
292297
}
293298

294299
impl Drop for CString {

0 commit comments

Comments
 (0)