Debian Codegraph @

third_party/rust/quinn-udp/src/cmsg/windows.rs

raw
1 use std::{
2 ffi::{c_int, c_uchar},
3 mem, ptr,
4 };
5
6 use windows_sys::Win32::Networking::WinSock;
7
8 use super::{CMsgHdr, MsgHdr};
9
10 #[derive(Copy, Clone)]
11 #[repr(align(8))] // Conservative bound for align_of<WinSock::CMSGHDR>
12 pub(crate) struct Aligned<T>(pub(crate) T);
13
14 /// Helpers for [`WinSock::WSAMSG`]
15 // https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsamsg
16 // https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Networking/WinSock/struct.WSAMSG.html
17 impl MsgHdr for WinSock::WSAMSG {
18 type ControlMessage = WinSock::CMSGHDR;
19
20 fn cmsg_first_hdr(&self) -> *mut Self::ControlMessage {
21 if self.Control.len as usize >= mem::size_of::<WinSock::CMSGHDR>() {
22 self.Control.buf as *mut WinSock::CMSGHDR
23 } else {
24 ptr::null_mut::<WinSock::CMSGHDR>()
25 }
26 }
27
28 fn cmsg_nxt_hdr(&self, cmsg: &Self::ControlMessage) -> *mut Self::ControlMessage {
29 let next =
30 (cmsg as *const _ as usize + cmsghdr_align(cmsg.cmsg_len)) as *mut WinSock::CMSGHDR;
31 let max = self.Control.buf as usize + self.Control.len as usize;
32 if unsafe { next.offset(1) } as usize > max {
33 ptr::null_mut()
34 } else {
35 next
36 }
37 }
38
39 fn set_control_len(&mut self, len: usize) {
40 self.Control.len = len as _;
41 }
42
43 fn control_len(&self) -> usize {
44 self.Control.len as _
45 }
46 }
47
48 /// Helpers for [`WinSock::CMSGHDR`]
49 // https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsacmsghdr
50 // https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/Networking/WinSock/struct.CMSGHDR.html
51 impl CMsgHdr for WinSock::CMSGHDR {
52 fn cmsg_len(length: usize) -> usize {
53 cmsgdata_align(mem::size_of::<Self>()) + length
54 }
55
56 fn cmsg_space(length: usize) -> usize {
57 cmsgdata_align(mem::size_of::<Self>() + cmsghdr_align(length))
58 }
59
60 fn cmsg_data(&self) -> *mut c_uchar {
61 (self as *const _ as usize + cmsgdata_align(mem::size_of::<Self>())) as *mut c_uchar
62 }
63
64 fn set(&mut self, level: c_int, ty: c_int, len: usize) {
65 self.cmsg_level = level as _;
66 self.cmsg_type = ty as _;
67 self.cmsg_len = len as _;
68 }
69
70 fn len(&self) -> usize {
71 self.cmsg_len as _
72 }
73 }
74
75 // Helpers functions for `WinSock::WSAMSG` and `WinSock::CMSGHDR` are based on C macros from
76 // https://github.com/microsoft/win32metadata/blob/main/generation/WinSDK/RecompiledIdlHeaders/shared/ws2def.h#L741
77 fn cmsghdr_align(length: usize) -> usize {
78 (length + mem::align_of::<WinSock::CMSGHDR>() - 1) & !(mem::align_of::<WinSock::CMSGHDR>() - 1)
79 }
80
81 fn cmsgdata_align(length: usize) -> usize {
82 (length + mem::align_of::<usize>() - 1) & !(mem::align_of::<usize>() - 1)
83 }