]> git.proxmox.com Git - rustc.git/blame - src/libstd/sys/windows/handle.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / libstd / sys / windows / handle.rs
CommitLineData
85aaf69f
SL
1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11use prelude::v1::*;
12
85aaf69f 13use io::ErrorKind;
c34b1796
AL
14use io;
15use libc::{self, HANDLE};
16use mem;
85aaf69f
SL
17use ptr;
18use sys::cvt;
19
20pub struct Handle(HANDLE);
21
22unsafe impl Send for Handle {}
23unsafe impl Sync for Handle {}
24
25impl Handle {
26 pub fn new(handle: HANDLE) -> Handle {
27 Handle(handle)
28 }
29
30 pub fn raw(&self) -> HANDLE { self.0 }
31
c34b1796
AL
32 pub fn into_raw(self) -> HANDLE {
33 let ret = self.0;
34 unsafe { mem::forget(self) }
35 return ret;
36 }
37
85aaf69f 38 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
9346a6ac
AL
39 let mut read = 0;
40 let res = cvt(unsafe {
41 libc::ReadFile(self.0, buf.as_ptr() as libc::LPVOID,
42 buf.len() as libc::DWORD, &mut read,
43 ptr::null_mut())
44 });
45
46 match res {
47 Ok(_) => Ok(read as usize),
48
49 // The special treatment of BrokenPipe is to deal with Windows
50 // pipe semantics, which yields this error when *reading* from
51 // a pipe after the other end has closed; we interpret that as
52 // EOF on the pipe.
53 Err(ref e) if e.kind() == ErrorKind::BrokenPipe => Ok(0),
54
55 Err(e) => Err(e)
56 }
85aaf69f
SL
57 }
58
59 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
9346a6ac
AL
60 let mut amt = 0;
61 try!(cvt(unsafe {
62 libc::WriteFile(self.0, buf.as_ptr() as libc::LPVOID,
63 buf.len() as libc::DWORD, &mut amt,
64 ptr::null_mut())
65 }));
66 Ok(amt as usize)
85aaf69f
SL
67 }
68}
69
70impl Drop for Handle {
71 fn drop(&mut self) {
72 unsafe { let _ = libc::CloseHandle(self.0); }
73 }
74}