Skip to content

Instantly share code, notes, and snippets.

@alexcrichton
Created Mar 1, 2017
Embed
What would you like to do?
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