forked from compio-rs/compio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
297 lines (260 loc) · 7.97 KB
/
mod.rs
File metadata and controls
297 lines (260 loc) · 7.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//! Ancillary data (control message) support for connected streams.
//!
//! Ancillary messages are used to pass out-of-band information such as file
//! descriptors (Unix domain sockets), credentials, or kTLS record types.
//!
//! # Types
//!
//! - [`AncillaryRef`]: A reference to a single ancillary data entry.
//! - [`AncillaryIter`]: An iterator over a buffer of ancillary messages.
//! - [`AncillaryBuilder`]: A builder for constructing ancillary messages into a
//! caller-supplied send buffer.
//! - [`AncillaryBuf`]: A fixed-size, properly aligned stack buffer for
//! ancillary data
//!
//! # Example
//!
//! ```
//! use compio_io::ancillary::{AncillaryBuf, AncillaryIter, ancillary_space};
//!
//! const LEVEL: i32 = 1;
//! const TYPE: i32 = 2;
//!
//! // Build a buffer containing two `u32` ancillary messages.
//! let mut buf = AncillaryBuf::<{ ancillary_space::<u32>() * 2 }>::new();
//! let mut builder = buf.builder();
//! builder.try_push(LEVEL, TYPE, 42u32).unwrap();
//! builder.try_push(LEVEL, TYPE, 43u32).unwrap();
//! assert!(builder.try_push(LEVEL, TYPE, 44u32).is_none()); // buffer is full
//!
//! // Read it back.
//! unsafe {
//! let mut iter = AncillaryIter::new(&buf);
//! let msg = iter.next().unwrap();
//! assert_eq!(msg.level(), LEVEL);
//! assert_eq!(msg.ty(), TYPE);
//! assert_eq!(*msg.data::<u32>(), 42u32);
//! assert_eq!(iter.next().unwrap().data::<u32>(), &43u32);
//! assert!(iter.next().is_none());
//! }
//! ```
use std::{
marker::PhantomData,
mem::MaybeUninit,
ops::{Deref, DerefMut},
};
use compio_buf::{IoBuf, IoBufMut, SetLen};
#[cfg(windows)]
use windows_sys::Win32::Networking::WinSock;
cfg_if::cfg_if! {
if #[cfg(windows)] {
#[path = "windows.rs"]
mod sys;
} else if #[cfg(unix)] {
#[path = "unix.rs"]
mod sys;
}
}
/// Reference to an ancillary (control) message.
pub struct AncillaryRef<'a>(sys::CMsgRef<'a>);
impl AncillaryRef<'_> {
/// Returns the level of the control message.
pub fn level(&self) -> i32 {
self.0.level()
}
/// Returns the type of the control message.
pub fn ty(&self) -> i32 {
self.0.ty()
}
/// Returns the length of the control message.
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.0.len() as _
}
/// Returns a reference to the data of the control message.
///
/// # Safety
///
/// The data part must be properly aligned and contains an initialized
/// instance of `T`.
pub unsafe fn data<T>(&self) -> &T {
unsafe { self.0.data() }
}
}
/// An iterator for ancillary (control) messages.
pub struct AncillaryIter<'a> {
inner: sys::CMsgIter,
_p: PhantomData<&'a ()>,
}
impl<'a> AncillaryIter<'a> {
/// Create [`AncillaryIter`] with the given buffer.
///
/// # Panics
///
/// This function will panic if the buffer is too short or not properly
/// aligned.
///
/// # Safety
///
/// The buffer should contain valid control messages.
pub unsafe fn new(buffer: &'a [u8]) -> Self {
Self {
inner: sys::CMsgIter::new(buffer.as_ptr(), buffer.len()),
_p: PhantomData,
}
}
}
impl<'a> Iterator for AncillaryIter<'a> {
type Item = AncillaryRef<'a>;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let cmsg = self.inner.current();
self.inner.next();
cmsg.map(AncillaryRef)
}
}
}
/// Helper to construct ancillary (control) messages.
pub struct AncillaryBuilder<'a, const N: usize> {
inner: sys::CMsgIter,
buffer: &'a mut AncillaryBuf<N>,
}
impl<'a, const N: usize> AncillaryBuilder<'a, N> {
fn new(buffer: &'a mut AncillaryBuf<N>) -> Self {
// TODO: optimize zeroing
buffer.as_uninit().fill(MaybeUninit::new(0));
buffer.len = 0;
let inner = sys::CMsgIter::new(buffer.as_ptr(), buffer.buf_capacity());
Self { inner, buffer }
}
/// Try to append a control message entry into the buffer. If the buffer
/// does not have enough space or is not properly aligned with the value
/// type, returns `None`.
pub fn try_push<T>(&mut self, level: i32, ty: i32, value: T) -> Option<()> {
if !self.inner.is_aligned::<T>() || !self.inner.is_space_enough::<T>() {
return None;
}
// SAFETY: the buffer is zeroed and the pointer is valid and aligned
unsafe {
let mut cmsg = self.inner.current_mut()?;
cmsg.set_level(level);
cmsg.set_ty(ty);
self.buffer.len += cmsg.set_data(value);
self.inner.next();
}
Some(())
}
}
/// A fixed-size, stack-allocated buffer for ancillary (control) messages.
///
/// Properly aligned for the platform's control message header type
/// (`cmsghdr` on Unix, `CMSGHDR` on Windows), so it can be passed directly
/// to [`AncillaryIter`] and [`AncillaryBuilder`].
pub struct AncillaryBuf<const N: usize> {
inner: [u8; N],
len: usize,
#[cfg(unix)]
_align: [libc::cmsghdr; 0],
#[cfg(windows)]
_align: [WinSock::CMSGHDR; 0],
}
impl<const N: usize> AncillaryBuf<N> {
/// Create a new zeroed [`AncillaryBuf`].
pub fn new() -> Self {
Self {
inner: [0u8; N],
len: 0,
_align: [],
}
}
/// Create [`AncillaryBuilder`] with this buffer. The buffer will be zeroed
/// on creation.
///
/// # Panics
///
/// This function will panic if this buffer is too short.
pub fn builder(&mut self) -> AncillaryBuilder<'_, N> {
AncillaryBuilder::new(self)
}
}
impl<const N: usize> Default for AncillaryBuf<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> IoBuf for AncillaryBuf<N> {
fn as_init(&self) -> &[u8] {
&self.inner[..self.len]
}
}
impl<const N: usize> SetLen for AncillaryBuf<N> {
unsafe fn set_len(&mut self, len: usize) {
debug_assert!(len <= N);
self.len = len;
}
}
impl<const N: usize> IoBufMut for AncillaryBuf<N> {
fn as_uninit(&mut self) -> &mut [MaybeUninit<u8>] {
self.inner.as_uninit()
}
}
impl<const N: usize> Deref for AncillaryBuf<N> {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.inner[0..self.len]
}
}
impl<const N: usize> DerefMut for AncillaryBuf<N> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner[0..self.len]
}
}
// Deprecated compio_net::CMsgBuilder
#[doc(hidden)]
pub struct CMsgBuilder<'a> {
inner: sys::CMsgIter,
len: usize,
_p: PhantomData<&'a mut ()>,
}
impl<'a> CMsgBuilder<'a> {
pub fn new(buffer: &'a mut [MaybeUninit<u8>]) -> Self {
buffer.fill(MaybeUninit::new(0));
Self {
inner: sys::CMsgIter::new(buffer.as_ptr().cast(), buffer.len()),
len: 0,
_p: PhantomData,
}
}
pub fn finish(self) -> usize {
self.len
}
pub fn try_push<T>(&mut self, level: i32, ty: i32, value: T) -> Option<()> {
if !self.inner.is_aligned::<T>() || !self.inner.is_space_enough::<T>() {
return None;
}
// SAFETY: the buffer is zeroed and the pointer is valid and aligned
unsafe {
let mut cmsg = self.inner.current_mut()?;
cmsg.set_level(level);
cmsg.set_ty(ty);
self.len += cmsg.set_data(value);
self.inner.next();
}
Some(())
}
}
/// Returns the buffer size required to hold one ancillary message carrying a
/// value of type `T`.
///
/// This is the platform-appropriate equivalent of `CMSG_SPACE(sizeof(T))` on
/// Unix or `WSA_CMSG_SPACE(sizeof(T))` on Windows, and can be used as a const
/// generic argument for [`AncillaryBuf`].
pub const fn ancillary_space<T>() -> usize {
#[cfg(unix)]
// SAFETY: CMSG_SPACE is always safe
unsafe {
libc::CMSG_SPACE(size_of::<T>() as libc::c_uint) as usize
}
#[cfg(windows)]
sys::wsa_cmsg_space(size_of::<T>())
}