Skip to content

Instantly share code, notes, and snippets.

@philippkeller
Created October 4, 2016 06:25
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/0c377a5c77d874cecd6b676d88970424 to your computer and use it in GitHub Desktop.
Save philippkeller/0c377a5c77d874cecd6b676d88970424 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 LibcResult<Sized> for Sized {
fn to_option<T:Sized>(&self) -> Option<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