| 1 |
//! Bindings to IOCP, I/O Completion Ports |
| 2 |
|
| 3 |
use super::{Handle, Overlapped}; |
| 4 |
use std::cmp; |
| 5 |
use std::fmt; |
| 6 |
use std::io; |
| 7 |
use std::mem; |
| 8 |
use std::os::windows::io::*; |
| 9 |
use std::ptr::null_mut; |
| 10 |
use std::time::Duration; |
| 11 |
|
| 12 |
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE}; |
| 13 |
use windows_sys::Win32::System::IO::{ |
| 14 |
CreateIoCompletionPort, GetQueuedCompletionStatusEx, PostQueuedCompletionStatus, OVERLAPPED, |
| 15 |
OVERLAPPED_ENTRY, |
| 16 |
}; |
| 17 |
|
| 18 |
/// A handle to an Windows I/O Completion Port. |
| 19 |
#[derive(Debug)] |
| 20 |
pub(crate) struct CompletionPort { |
| 21 |
handle: Handle, |
| 22 |
} |
| 23 |
|
| 24 |
// SAFETY: `Handles`s are, in general, not thread-safe. However, we only used `Handle`s for |
| 25 |
// resources that are thread-safe in `CompletionPort`. |
| 26 |
unsafe impl Send for CompletionPort {} |
| 27 |
|
| 28 |
// SAFETY: `Handles`s are, in general, not thread-safe. However, we only used `Handle`s for |
| 29 |
// resources that are thread-safe in `CompletionPort`. |
| 30 |
unsafe impl Sync for CompletionPort {} |
| 31 |
|
| 32 |
/// A status message received from an I/O completion port. |
| 33 |
/// |
| 34 |
/// These statuses can be created via the `new` or `empty` constructors and then |
| 35 |
/// provided to a completion port, or they are read out of a completion port. |
| 36 |
/// The fields of each status are read through its accessor methods. |
| 37 |
#[derive(Clone, Copy)] |
| 38 |
#[repr(transparent)] |
| 39 |
pub struct CompletionStatus(OVERLAPPED_ENTRY); |
| 40 |
|
| 41 |
impl fmt::Debug for CompletionStatus { |
| 42 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 43 |
write!(f, "CompletionStatus(OVERLAPPED_ENTRY)") |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
unsafe impl Send for CompletionStatus {} |
| 48 |
unsafe impl Sync for CompletionStatus {} |
| 49 |
|
| 50 |
impl CompletionPort { |
| 51 |
/// Creates a new I/O completion port with the specified concurrency value. |
| 52 |
/// |
| 53 |
/// The number of threads given corresponds to the level of concurrency |
| 54 |
/// allowed for threads associated with this port. Consult the Windows |
| 55 |
/// documentation for more information about this value. |
| 56 |
pub fn new(threads: u32) -> io::Result<CompletionPort> { |
| 57 |
let ret = unsafe { CreateIoCompletionPort(INVALID_HANDLE_VALUE, null_mut(), 0, threads) }; |
| 58 |
if ret.is_null() { |
| 59 |
Err(io::Error::last_os_error()) |
| 60 |
} else { |
| 61 |
Ok(CompletionPort { |
| 62 |
handle: Handle::new(ret), |
| 63 |
}) |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
/// Associates a new `HANDLE` to this I/O completion port. |
| 68 |
/// |
| 69 |
/// This function will associate the given handle to this port with the |
| 70 |
/// given `token` to be returned in status messages whenever it receives a |
| 71 |
/// notification. |
| 72 |
/// |
| 73 |
/// Any object which is convertible to a `HANDLE` via the `AsRawHandle` |
| 74 |
/// trait can be provided to this function, such as `std::fs::File` and |
| 75 |
/// friends. |
| 76 |
#[cfg(any(feature = "net", feature = "os-ext"))] |
| 77 |
pub fn add_handle<T: AsRawHandle + ?Sized>(&self, token: usize, t: &T) -> io::Result<()> { |
| 78 |
let ret = unsafe { |
| 79 |
CreateIoCompletionPort(t.as_raw_handle() as HANDLE, self.handle.raw(), token, 0) |
| 80 |
}; |
| 81 |
if ret.is_null() { |
| 82 |
Err(io::Error::last_os_error()) |
| 83 |
} else { |
| 84 |
Ok(()) |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
/// Dequeues a number of completion statuses from this I/O completion port. |
| 89 |
/// |
| 90 |
/// This function is the same as `get` except that it may return more than |
| 91 |
/// one status. A buffer of "zero" statuses is provided (the contents are |
| 92 |
/// not read) and then on success this function will return a sub-slice of |
| 93 |
/// statuses which represent those which were dequeued from this port. This |
| 94 |
/// function does not wait to fill up the entire list of statuses provided. |
| 95 |
/// |
| 96 |
/// Like with `get`, a timeout may be specified for this operation. |
| 97 |
pub fn get_many<'a>( |
| 98 |
&self, |
| 99 |
list: &'a mut [CompletionStatus], |
| 100 |
timeout: Option<Duration>, |
| 101 |
) -> io::Result<&'a mut [CompletionStatus]> { |
| 102 |
debug_assert_eq!( |
| 103 |
mem::size_of::<CompletionStatus>(), |
| 104 |
mem::size_of::<OVERLAPPED_ENTRY>() |
| 105 |
); |
| 106 |
let mut removed = 0; |
| 107 |
let timeout = duration_millis(timeout); |
| 108 |
let len = cmp::min(list.len(), u32::MAX as usize) as u32; |
| 109 |
let ret = unsafe { |
| 110 |
GetQueuedCompletionStatusEx( |
| 111 |
self.handle.raw(), |
| 112 |
list.as_ptr() as *mut _, |
| 113 |
len, |
| 114 |
&mut removed, |
| 115 |
timeout, |
| 116 |
0, |
| 117 |
) |
| 118 |
}; |
| 119 |
|
| 120 |
if ret == 0 { |
| 121 |
Err(io::Error::last_os_error()) |
| 122 |
} else { |
| 123 |
Ok(&mut list[..removed as usize]) |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
/// Posts a new completion status onto this I/O completion port. |
| 128 |
/// |
| 129 |
/// This function will post the given status, with custom parameters, to the |
| 130 |
/// port. Threads blocked in `get` or `get_many` will eventually receive |
| 131 |
/// this status. |
| 132 |
pub fn post(&self, status: CompletionStatus) -> io::Result<()> { |
| 133 |
let ret = unsafe { |
| 134 |
PostQueuedCompletionStatus( |
| 135 |
self.handle.raw(), |
| 136 |
status.0.dwNumberOfBytesTransferred, |
| 137 |
status.0.lpCompletionKey, |
| 138 |
status.0.lpOverlapped, |
| 139 |
) |
| 140 |
}; |
| 141 |
|
| 142 |
if ret == 0 { |
| 143 |
Err(io::Error::last_os_error()) |
| 144 |
} else { |
| 145 |
Ok(()) |
| 146 |
} |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
impl AsRawHandle for CompletionPort { |
| 151 |
fn as_raw_handle(&self) -> RawHandle { |
| 152 |
self.handle.raw() as RawHandle |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
impl FromRawHandle for CompletionPort { |
| 157 |
unsafe fn from_raw_handle(handle: RawHandle) -> CompletionPort { |
| 158 |
CompletionPort { |
| 159 |
handle: Handle::new(handle as HANDLE), |
| 160 |
} |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
impl IntoRawHandle for CompletionPort { |
| 165 |
fn into_raw_handle(self) -> RawHandle { |
| 166 |
self.handle.into_raw() |
| 167 |
} |
| 168 |
} |
| 169 |
|
| 170 |
impl CompletionStatus { |
| 171 |
/// Creates a new completion status with the provided parameters. |
| 172 |
/// |
| 173 |
/// This function is useful when creating a status to send to a port with |
| 174 |
/// the `post` method. The parameters are opaquely passed through and not |
| 175 |
/// interpreted by the system at all. |
| 176 |
pub(crate) fn new(bytes: u32, token: usize, overlapped: *mut Overlapped) -> Self { |
| 177 |
CompletionStatus(OVERLAPPED_ENTRY { |
| 178 |
dwNumberOfBytesTransferred: bytes, |
| 179 |
lpCompletionKey: token, |
| 180 |
lpOverlapped: overlapped as *mut _, |
| 181 |
Internal: 0, |
| 182 |
}) |
| 183 |
} |
| 184 |
|
| 185 |
/// Creates a new borrowed completion status from the borrowed |
| 186 |
/// `OVERLAPPED_ENTRY` argument provided. |
| 187 |
/// |
| 188 |
/// This method will wrap the `OVERLAPPED_ENTRY` in a `CompletionStatus`, |
| 189 |
/// returning the wrapped structure. |
| 190 |
#[cfg(feature = "os-ext")] |
| 191 |
pub fn from_entry(entry: &OVERLAPPED_ENTRY) -> &Self { |
| 192 |
// Safety: CompletionStatus is repr(transparent) w/ OVERLAPPED_ENTRY, so |
| 193 |
// a reference to one is guaranteed to be layout compatible with the |
| 194 |
// reference to another. |
| 195 |
unsafe { &*(entry as *const _ as *const _) } |
| 196 |
} |
| 197 |
|
| 198 |
/// Creates a new "zero" completion status. |
| 199 |
/// |
| 200 |
/// This function is useful when creating a stack buffer or vector of |
| 201 |
/// completion statuses to be passed to the `get_many` function. |
| 202 |
pub fn zero() -> Self { |
| 203 |
Self::new(0, 0, null_mut()) |
| 204 |
} |
| 205 |
|
| 206 |
/// Returns the number of bytes that were transferred for the I/O operation |
| 207 |
/// associated with this completion status. |
| 208 |
pub fn bytes_transferred(&self) -> u32 { |
| 209 |
self.0.dwNumberOfBytesTransferred |
| 210 |
} |
| 211 |
|
| 212 |
/// Returns the completion key value associated with the file handle whose |
| 213 |
/// I/O operation has completed. |
| 214 |
/// |
| 215 |
/// A completion key is a per-handle key that is specified when it is added |
| 216 |
/// to an I/O completion port via `add_handle` or `add_socket`. |
| 217 |
pub fn token(&self) -> usize { |
| 218 |
self.0.lpCompletionKey as usize |
| 219 |
} |
| 220 |
|
| 221 |
/// Returns a pointer to the `Overlapped` structure that was specified when |
| 222 |
/// the I/O operation was started. |
| 223 |
pub fn overlapped(&self) -> *mut OVERLAPPED { |
| 224 |
self.0.lpOverlapped |
| 225 |
} |
| 226 |
|
| 227 |
/// Returns a pointer to the internal `OVERLAPPED_ENTRY` object. |
| 228 |
pub fn entry(&self) -> &OVERLAPPED_ENTRY { |
| 229 |
&self.0 |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
#[inline] |
| 234 |
fn duration_millis(dur: Option<Duration>) -> u32 { |
| 235 |
if let Some(dur) = dur { |
| 236 |
// `Duration::as_millis` truncates, so round up. This avoids |
| 237 |
// turning sub-millisecond timeouts into a zero timeout, unless |
| 238 |
// the caller explicitly requests that by specifying a zero |
| 239 |
// timeout. |
| 240 |
let dur_ms = dur |
| 241 |
.checked_add(Duration::from_nanos(999_999)) |
| 242 |
.unwrap_or(dur) |
| 243 |
.as_millis(); |
| 244 |
cmp::min(dur_ms, u32::MAX as u128) as u32 |
| 245 |
} else { |
| 246 |
u32::MAX |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
#[cfg(test)] |
| 251 |
mod tests { |
| 252 |
use super::{CompletionPort, CompletionStatus}; |
| 253 |
|
| 254 |
#[test] |
| 255 |
fn is_send_sync() { |
| 256 |
fn is_send_sync<T: Send + Sync>() {} |
| 257 |
is_send_sync::<CompletionPort>(); |
| 258 |
} |
| 259 |
|
| 260 |
#[test] |
| 261 |
fn get_many() { |
| 262 |
let c = CompletionPort::new(1).unwrap(); |
| 263 |
|
| 264 |
c.post(CompletionStatus::new(1, 2, 3 as *mut _)).unwrap(); |
| 265 |
c.post(CompletionStatus::new(4, 5, 6 as *mut _)).unwrap(); |
| 266 |
|
| 267 |
let mut s = vec![CompletionStatus::zero(); 4]; |
| 268 |
{ |
| 269 |
let s = c.get_many(&mut s, None).unwrap(); |
| 270 |
assert_eq!(s.len(), 2); |
| 271 |
assert_eq!(s[0].bytes_transferred(), 1); |
| 272 |
assert_eq!(s[0].token(), 2); |
| 273 |
assert_eq!(s[0].overlapped(), 3 as *mut _); |
| 274 |
assert_eq!(s[1].bytes_transferred(), 4); |
| 275 |
assert_eq!(s[1].token(), 5); |
| 276 |
assert_eq!(s[1].overlapped(), 6 as *mut _); |
| 277 |
} |
| 278 |
assert_eq!(s[2].bytes_transferred(), 0); |
| 279 |
assert_eq!(s[2].token(), 0); |
| 280 |
assert_eq!(s[2].overlapped(), 0 as *mut _); |
| 281 |
} |
| 282 |
} |