Skip to content

Implement CString::from_reader #59314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 7 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/libstd/ffi/c_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,42 @@ impl CString {
CString { inner: v.into_boxed_slice() }
}

/// Creates a C-compatible string by reading from an object that implements ```Read```.
/// It reads all characters including the null character.
///
/// Because bytes are checked on null characters during the reading process,
/// no extra checks are required to ensure that no null characters precede the
/// terminating null character.
///
/// # Examples
///
/// ```
/// #![feature(cstring_from_reader)]
/// use std::ffi::CString;
///
/// let test = "Example\0";
/// let string = CString::from_reader(test.as_bytes()).unwrap();
/// ```
///
#[unstable(feature = "cstring_from_reader", issue = "59229")]
pub fn from_reader(mut reader: impl io::Read) -> Result<CString, io::Error>
{
let mut buffer = Vec::new();
let mut character: u8 = 0;

loop {
// Read a new character from reader and insert it into the buffer.
let slice = slice::from_mut(&mut character);
reader.read_exact(slice)?;
buffer.push(character);

// Construct a CString if a null character has been found.
if character == 0 {
return Ok(CString { inner: buffer.into_boxed_slice() });
}
}
}

/// Retakes ownership of a `CString` that was transferred to C via [`into_raw`].
///
/// Additionally, the length of the string will be recalculated from the pointer.
Expand Down