Created
March 1, 2017 15:15
-
-
Save alexcrichton/0489d44efb7b3a6aa96fae044dd1be23 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fs::File; | |
use std::io; | |
use std::mem; | |
pub fn close(file: &mut File) -> io::Result<()> { | |
imp::close(mem::replace(file, imp::invalid_file())) | |
} | |
#[cfg(unix)] | |
mod imp { | |
extern crate libc; | |
use std::fs::File; | |
use std::os::unix::prelude::*; | |
use std::io; | |
pub fn close(file: File) -> io::Result<()> { | |
let fd = file.into_raw_fd(); | |
let rc = unsafe { | |
libc::close(fd) | |
}; | |
if rc == -1 { | |
Ok(()) | |
} else { | |
Err(io::Error::last_os_error()) | |
} | |
} | |
pub fn invalid_file() -> File { | |
unsafe { File::from_raw_fd(-1) } | |
} | |
} | |
#[cfg(windows)] | |
mod imp { | |
extern crate winapi; | |
extern crate kernel32; | |
use std::fs::File; | |
use std::os::windows::prelude::*; | |
use std::io; | |
pub fn close(file: File) -> io::Result<()> { | |
let handle = file.into_raw_handle(); | |
let rc = unsafe { | |
kernel32::CloseHandle(handle) | |
}; | |
if rc != 0 { | |
Ok(()) | |
} else { | |
Err(io::Error::last_os_error()) | |
} | |
} | |
pub fn invalid_file() -> File { | |
unsafe { File::from_raw_handle(winapi::INVALID_HANDLE_VALUE) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment