Skip to content

Instantly share code, notes, and snippets.

@philippkeller
Created October 4, 2016 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philippkeller/52f593634010502bbc11890b8a261cec to your computer and use it in GitHub Desktop.
Save philippkeller/52f593634010502bbc11890b8a261cec to your computer and use it in GitHub Desktop.
pub trait LibcResult<T> {
/// returns None if the result is empty (-1 if an integer, Null if a pointer)
/// and Some otherwise
///
/// # Example
/// if let Some(fd) = libc::creat(fd1, FILE_MODE).to_option() {
/// fd
/// } else {
/// panic!("{}", io::Error::last_os_error());
/// }
fn to_option(&self) -> Option<T>;
}
impl LibcResult<c_int> for c_int {
fn to_option(&self) -> Option<c_int> {
if *self < 0 { None } else { Some(*self) }
}
}
impl<T: ?Sized> LibcResult<*const T> for *const T {
fn to_option(&self) -> Option<*const T> {
if *self.is_null() { None } else { Some(*self) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment