|
21 | 21 | //! const TYPE: i32 = 2; |
22 | 22 | //! |
23 | 23 | //! // Build a buffer containing two `u32` ancillary messages. |
24 | | -//! let mut builder = AncillaryBuf::<{ ancillary_space::<u32>() * 2 }>::builder(); |
| 24 | +//! let mut buf = AncillaryBuf::<{ ancillary_space::<u32>() * 2 }>::new(); |
| 25 | +//! let mut builder = buf.builder(); |
25 | 26 | //! builder.try_push(LEVEL, TYPE, 42u32).unwrap(); |
26 | 27 | //! builder.try_push(LEVEL, TYPE, 43u32).unwrap(); |
27 | 28 | //! assert!(builder.try_push(LEVEL, TYPE, 44u32).is_none()); // buffer is full |
28 | | -//! let buf = builder.finish(); |
29 | 29 | //! |
30 | 30 | //! // Read it back. |
31 | 31 | //! unsafe { |
@@ -128,22 +128,18 @@ impl<'a> Iterator for AncillaryIter<'a> { |
128 | 128 | } |
129 | 129 |
|
130 | 130 | /// Helper to construct ancillary (control) messages. |
131 | | -pub struct AncillaryBuilder<const N: usize> { |
132 | | - buffer: Box<AncillaryBuf<N>>, |
| 131 | +pub struct AncillaryBuilder<'a, const N: usize> { |
133 | 132 | inner: sys::CMsgIter, |
| 133 | + buffer: &'a mut AncillaryBuf<N>, |
134 | 134 | } |
135 | 135 |
|
136 | | -impl<const N: usize> AncillaryBuilder<N> { |
137 | | - fn new() -> Self { |
138 | | - let mut buffer = Box::new(AncillaryBuf::new()); |
139 | | - let inner = sys::CMsgIter::new(buffer.as_uninit().as_ptr().cast(), buffer.buf_capacity()); |
140 | | - Self { buffer, inner } |
141 | | - } |
142 | | - |
143 | | - /// Finishes building, returns the ancillary buffer containing the |
144 | | - /// constructed control messages. |
145 | | - pub fn finish(self) -> AncillaryBuf<N> { |
146 | | - *self.buffer |
| 136 | +impl<'a, const N: usize> AncillaryBuilder<'a, N> { |
| 137 | + fn new(buffer: &'a mut AncillaryBuf<N>) -> Self { |
| 138 | + // TODO: optimize zeroing |
| 139 | + buffer.as_uninit().fill(MaybeUninit::new(0)); |
| 140 | + buffer.len = 0; |
| 141 | + let inner = sys::CMsgIter::new(buffer.as_ptr(), buffer.buf_capacity()); |
| 142 | + Self { inner, buffer } |
147 | 143 | } |
148 | 144 |
|
149 | 145 | /// Try to append a control message entry into the buffer. If the buffer |
@@ -192,15 +188,14 @@ impl<const N: usize> AncillaryBuf<N> { |
192 | 188 | } |
193 | 189 | } |
194 | 190 |
|
195 | | - /// Creates an [`AncillaryBuilder`] for constructing ancillary messages into |
196 | | - /// this buffer. |
| 191 | + /// Create [`AncillaryBuilder`] with this buffer. The buffer will be zeroed |
| 192 | + /// on creation. |
197 | 193 | /// |
198 | 194 | /// # Panics |
199 | 195 | /// |
200 | | - /// This function will panic if the buffer size `N` is too small to hold at |
201 | | - /// least one control message header. |
202 | | - pub fn builder() -> AncillaryBuilder<N> { |
203 | | - AncillaryBuilder::new() |
| 196 | + /// This function will panic if this buffer is too short. |
| 197 | + pub fn builder(&mut self) -> AncillaryBuilder<'_, N> { |
| 198 | + AncillaryBuilder::new(self) |
204 | 199 | } |
205 | 200 | } |
206 | 201 |
|
|
0 commit comments