Skip to main content

std\sys\pal\windows/
winsock.rs

1use super::c;
2use crate::ffi::c_int;
3use crate::sync::Once;
4use crate::{io, mem};
5
6static WSA_INIT: Once = Once::new();
7
8/// Checks whether the Windows socket interface has been started already, and
9/// if not, starts it.
10#[inline]
11pub fn startup() {
12    // Make sure to only call `WSAStartup` once, because it's not thread-safe
13    // on Wine: https://bugs.winehq.org/show_bug.cgi?id=60084.
14    WSA_INIT.call_once_force(|_| wsa_startup());
15}
16
17#[cold]
18fn wsa_startup() {
19    unsafe {
20        let mut data: c::WSADATA = mem::zeroed();
21        let ret = c::WSAStartup(
22            0x202, // version 2.2
23            &mut data,
24        );
25        assert_eq!(ret, 0);
26    }
27}
28
29pub fn cleanup() {
30    // We don't need to call WSACleanup here because exiting the process will cause
31    // the OS to clean everything for us, which is faster than doing it manually.
32    // See #141799.
33}
34
35/// Returns the last error from the Windows socket interface.
36pub fn last_error() -> io::Error {
37    io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
38}
39
40#[doc(hidden)]
41pub trait IsMinusOne {
42    fn is_minus_one(&self) -> bool;
43}
44
45macro_rules! impl_is_minus_one {
46    ($($t:ident)*) => ($(impl IsMinusOne for $t {
47        fn is_minus_one(&self) -> bool {
48            *self == -1
49        }
50    })*)
51}
52
53impl_is_minus_one! { i8 i16 i32 i64 isize }
54
55/// Checks if the signed integer is the Windows constant `SOCKET_ERROR` (-1)
56/// and if so, returns the last error from the Windows socket interface. This
57/// function must be called before another call to the socket API is made.
58pub fn cvt<T: IsMinusOne>(t: T) -> io::Result<T> {
59    if t.is_minus_one() { Err(last_error()) } else { Ok(t) }
60}
61
62/// A variant of `cvt` for `getaddrinfo` which return 0 for a success.
63pub fn cvt_gai(err: c_int) -> io::Result<()> {
64    if err == 0 { Ok(()) } else { Err(last_error()) }
65}
66
67/// Just to provide the same interface as sys/pal/unix/net.rs
68pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
69where
70    T: IsMinusOne,
71    F: FnMut() -> T,
72{
73    cvt(f())
74}