Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Created March 1, 2017 15:15
Show Gist options
  • Save alexcrichton/0489d44efb7b3a6aa96fae044dd1be23 to your computer and use it in GitHub Desktop.
Save alexcrichton/0489d44efb7b3a6aa96fae044dd1be23 to your computer and use it in GitHub Desktop.
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