Skip to content

Commit a70ae2f

Browse files
committed
CStr::from_bytes
1 parent 37c6f28 commit a70ae2f

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/libstd/ffi/c_str.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,57 @@ impl CStr {
436436
mem::transmute(slice::from_raw_parts(ptr, len as usize + 1))
437437
}
438438

439+
/// Creates a C string wrapper from a byte slice.
440+
///
441+
/// This function will cast the provided `bytes` to a `CStr` wrapper after
442+
/// ensuring that it is null terminated but does not contain any interior
443+
/// nul bytes.
444+
///
445+
/// # Examples
446+
///
447+
/// ```
448+
/// # #![feature(cstr_from_bytes)]
449+
/// use std::ffi::CStr;
450+
///
451+
/// # fn main() {
452+
/// let cstr = CStr::from_bytes(b"hello\0");
453+
/// assert!(cstr.is_some());
454+
/// # }
455+
/// ```
456+
#[unstable(feature = "cstr_from_bytes", reason = "recently added", issue = "0")]
457+
pub fn from_bytes<'a>(bytes: &'a [u8]) -> Option<&'a CStr> {
458+
if bytes.is_empty() || memchr::memchr(0, &bytes) != Some(bytes.len() - 1) {
459+
None
460+
} else {
461+
Some(unsafe { Self::from_bytes_unchecked(bytes) })
462+
}
463+
}
464+
465+
/// Unsafely creates a C string wrapper from a byte slice.
466+
///
467+
/// This function will cast the provided `bytes` to a `CStr` wrapper without
468+
/// performing any sanity checks. The provided slice must be null terminated
469+
/// and not contain any interior nul bytes.
470+
///
471+
/// # Examples
472+
///
473+
/// ```
474+
/// # #![feature(cstr_from_bytes)]
475+
/// use std::ffi::{CStr, CString};
476+
///
477+
/// # fn main() {
478+
/// unsafe {
479+
/// let cstring = CString::new("hello").unwrap();
480+
/// let cstr = CStr::from_bytes_unchecked(cstring.to_bytes_with_nul());
481+
/// assert_eq!(cstr, &*cstring);
482+
/// }
483+
/// # }
484+
/// ```
485+
#[unstable(feature = "cstr_from_bytes", reason = "recently added", issue = "0")]
486+
pub unsafe fn from_bytes_unchecked<'a>(bytes: &'a [u8]) -> &'a CStr {
487+
mem::transmute(bytes)
488+
}
489+
439490
/// Returns the inner pointer to this C string.
440491
///
441492
/// The returned pointer will be valid for as long as `self` is and points

0 commit comments

Comments
 (0)