Skip to main content

saluki_io/buf/
vec.rs

1use std::{mem::ManuallyDrop, sync::Arc};
2
3use bytes::{buf::UninitSlice, Buf, BufMut};
4use saluki_core::pooling::{helpers::pooled_newtype, Clearable, ReclaimStrategy};
5use triomphe::{Arc as TriompheArc, UniqueArc};
6
7use super::{ClearableIoBuffer, CollapsibleReadWriteIoBuffer, ReadCursor, ReadIoBuffer};
8
9/// A fixed-size bytes buffer.
10///
11/// This is a simple wrapper around a `BytesMut` that provides fixed-size semantics by disallowing writes that extend
12/// beyond the initial capacity. `FixedSizeVec` can't be used directly, and must be interacted with via the
13/// [`Buf`] and [`BufMut`] traits.
14///
15/// Additionally, it's designed for use in object pools (implements [`Clearable`]).
16pub struct FixedSizeVec {
17    data: UniqueArc<Vec<u8>>,
18    read_idx: usize,
19}
20
21impl FixedSizeVec {
22    /// Creates a new `FixedSizeVec` with the given capacity.
23    ///
24    /// The vector won't grow once all available capacity has been consumed, and must be cleared to be reused.
25    pub fn with_capacity(capacity: usize) -> Self {
26        Self {
27            data: UniqueArc::new(Vec::with_capacity(capacity)),
28            read_idx: 0,
29        }
30    }
31
32    fn freeze(self) -> FrozenFixedSizeVec {
33        FrozenFixedSizeVec {
34            data: self.data.shareable(),
35            read_idx: self.read_idx,
36        }
37    }
38}
39
40impl Clearable for FixedSizeVec {
41    fn clear(&mut self) {
42        self.data.clear();
43        self.read_idx = 0;
44    }
45}
46
47struct FrozenFixedSizeVec {
48    data: TriompheArc<Vec<u8>>,
49    read_idx: usize,
50}
51
52impl FrozenFixedSizeVec {
53    fn into_unique(self) -> Option<FixedSizeVec> {
54        TriompheArc::into_unique(self.data).map(|data| FixedSizeVec { data, read_idx: 0 })
55    }
56}
57
58impl Clone for FrozenFixedSizeVec {
59    fn clone(&self) -> Self {
60        Self {
61            data: self.data.clone(),
62            read_idx: 0,
63        }
64    }
65}
66
67pooled_newtype! {
68    outer => BytesBuffer,
69    inner => FixedSizeVec,
70}
71
72impl BytesBuffer {
73    /// Returns a cursor over the unread bytes, which advances this buffer as bytes are taken.
74    pub fn cursor(&mut self) -> ReadCursor<'_> {
75        let FixedSizeVec { data, read_idx } = self.data_mut();
76        let capacity = data.capacity();
77        ReadCursor::new(&data[..], read_idx, capacity)
78    }
79
80    /// Consumes this buffer and returns a read-only version of it.
81    pub fn freeze(mut self) -> FrozenBytesBuffer {
82        let data = self.data.take().unwrap().freeze();
83
84        FrozenBytesBuffer {
85            strategy_ref: Arc::clone(&self.strategy_ref),
86            data: ManuallyDrop::new(data),
87        }
88    }
89}
90
91impl Buf for BytesBuffer {
92    fn remaining(&self) -> usize {
93        self.data().data.len() - self.data().read_idx
94    }
95
96    fn chunk(&self) -> &[u8] {
97        let data = self.data();
98        &data.data[data.read_idx..data.data.len()]
99    }
100
101    fn advance(&mut self, cnt: usize) {
102        let data = self.data_mut();
103        saluki_antithesis::always_le!(data.read_idx + cnt, data.data.len(), "buffer advance within bounds");
104        assert!(data.read_idx + cnt <= data.data.len());
105        data.read_idx += cnt;
106    }
107}
108
109unsafe impl BufMut for BytesBuffer {
110    fn remaining_mut(&self) -> usize {
111        let data = self.data();
112        data.data.capacity() - data.data.len()
113    }
114
115    fn chunk_mut(&mut self) -> &mut UninitSlice {
116        self.data_mut().data.spare_capacity_mut().into()
117    }
118
119    unsafe fn advance_mut(&mut self, cnt: usize) {
120        let new_len = self.data().data.len() + cnt;
121        self.data_mut().data.set_len(new_len);
122    }
123}
124
125impl ReadIoBuffer for BytesBuffer {
126    fn capacity(&self) -> usize {
127        self.data().data.capacity()
128    }
129}
130
131impl CollapsibleReadWriteIoBuffer for BytesBuffer {
132    fn collapse(&mut self) {
133        let remaining = self.remaining();
134
135        // If the buffer is empty, all we have to do is reset the buffer to its initial state.
136        if remaining == 0 {
137            let inner = self.data_mut();
138            inner.read_idx = 0;
139            inner.data.clear();
140            return;
141        }
142
143        // Otherwise, we have to actually shift the remaining data to the front of the buffer and then also update our
144        // buffer state.
145        let inner = self.data_mut();
146
147        let src_start = inner.read_idx;
148        let src_end = inner.data.len();
149        inner.data.copy_within(src_start..src_end, 0);
150        inner.data.truncate(remaining);
151        inner.read_idx = 0;
152    }
153}
154
155impl ClearableIoBuffer for BytesBuffer {
156    fn clear(&mut self) {
157        self.data_mut().clear();
158    }
159}
160
161/// A frozen, read-only version of [`BytesBuffer`].
162///
163/// `FrozenBytesBuffer` can be cheaply cloned, and allows for sharing an underlying [`BytesBuffer`] among multiple
164/// tasks while still maintaining all of the original buffer's object pooling semantics.
165// TODO: it's not great that we're manually emulating the internal structure of `BytesBuffer`, since the whole point is
166// that those bits are auto-generated for us and meant to be functionally transparent to using `BytesBuffer` in the
167// first place... it'd be interesting to consider if we could make this more ergonomic, perhaps by having some sort of
168// convenience helper method for converting pooled objects of type T to U where the `Poolable::Data` is identical
169// between them, almost along lines of `CoerceUnsized` where the underlying data isn't changing, just the representation
170// of it.
171#[derive(Clone)]
172pub struct FrozenBytesBuffer {
173    strategy_ref: Arc<dyn ReclaimStrategy<BytesBuffer> + Send + Sync>,
174    data: ManuallyDrop<FrozenFixedSizeVec>,
175}
176
177impl FrozenBytesBuffer {
178    /// Returns `true` if the buffer is empty.
179    pub fn is_empty(&self) -> bool {
180        self.data.read_idx == self.data.data.len()
181    }
182
183    /// Returns the number of bytes remaining in the buffer.
184    pub fn len(&self) -> usize {
185        self.data.data.len() - self.data.read_idx
186    }
187
188    /// Returns the total capacity of the buffer.
189    pub fn capacity(&self) -> usize {
190        self.data.data.capacity()
191    }
192}
193
194impl Buf for FrozenBytesBuffer {
195    fn remaining(&self) -> usize {
196        self.data.data.len() - self.data.read_idx
197    }
198
199    fn chunk(&self) -> &[u8] {
200        &self.data.data[self.data.read_idx..]
201    }
202
203    fn advance(&mut self, cnt: usize) {
204        saluki_antithesis::always_le!(
205            self.data.read_idx + cnt,
206            self.data.data.len(),
207            "buffer advance within bounds"
208        );
209        assert!(self.data.read_idx + cnt <= self.data.data.len());
210        self.data.read_idx += cnt;
211    }
212}
213
214impl Drop for FrozenBytesBuffer {
215    fn drop(&mut self) {
216        // If we're the last reference to the buffer, we need to reconstitute it back to a `FixedSizeVec`, and reclaim
217        // it to the object pool.
218        //
219        // SAFETY: Nothing else can be using `self.data` since we're dropping.
220        let data = unsafe { ManuallyDrop::take(&mut self.data) };
221        if let Some(data) = data.into_unique() {
222            self.strategy_ref.reclaim(data);
223        }
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use saluki_core::pooling::helpers::get_pooled_object_via_builder;
230
231    use super::*;
232
233    #[test]
234    fn basic() {
235        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(13));
236
237        let first_write = b"hello";
238        let second_write = b", worl";
239        let third_write = b"d!";
240
241        // We start out empty:
242        assert_eq!(buf.remaining(), 0);
243        assert_eq!(buf.remaining_mut(), 13);
244
245        // Write the first chunk:
246        buf.put_slice(first_write);
247        assert_eq!(buf.remaining(), 5);
248        assert_eq!(buf.remaining_mut(), 8);
249
250        // Write the second chunk:
251        buf.put_slice(second_write);
252        assert_eq!(buf.remaining(), 11);
253        assert_eq!(buf.remaining_mut(), 2);
254
255        // Read 7 bytes worth:
256        let first_chunk = buf.chunk();
257        assert_eq!(first_chunk.len(), 11);
258        assert_eq!(first_chunk, b"hello, worl");
259
260        buf.advance(7);
261        assert_eq!(buf.remaining(), 4);
262        assert_eq!(buf.remaining_mut(), 2);
263
264        // Write the third chunk:
265        buf.put_slice(third_write);
266        assert_eq!(buf.remaining(), 6);
267        assert_eq!(buf.remaining_mut(), 0);
268
269        // Read the rest:
270        let second_chunk = buf.chunk();
271        assert_eq!(second_chunk.len(), 6);
272        assert_eq!(second_chunk, b"world!");
273
274        buf.advance(6);
275        assert_eq!(buf.remaining(), 0);
276        assert_eq!(buf.remaining_mut(), 0);
277
278        // Clear the buffer:
279        buf.data_mut().clear();
280        assert_eq!(buf.remaining(), 0);
281        assert_eq!(buf.remaining_mut(), 13);
282    }
283
284    #[test]
285    fn cursor() {
286        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(16));
287        buf.put_slice(b"hello, world!");
288        buf.advance(2);
289
290        let taken = {
291            let mut cursor = buf.cursor();
292            assert_eq!(cursor.capacity(), 16);
293            assert_eq!(cursor.unread(), b"llo, world!");
294            cursor.take(5)
295        };
296        assert_eq!(taken, b"llo, ");
297        assert_eq!(buf.chunk(), b"world!");
298    }
299
300    #[test]
301    fn collapsible_empty() {
302        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(13));
303
304        // Buffer is empty.
305        assert_eq!(buf.remaining(), 0);
306        assert_eq!(buf.remaining_mut(), 13);
307
308        buf.collapse();
309
310        // Buffer is still empty.
311        assert_eq!(buf.remaining(), 0);
312        assert_eq!(buf.remaining_mut(), 13);
313    }
314
315    #[test]
316    fn collapsible_remaining_already_collapsed() {
317        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(24));
318
319        // Write a simple string to the buffer.
320        buf.put_slice(b"hello, world!");
321        assert_eq!(buf.remaining(), 13);
322        assert_eq!(buf.remaining_mut(), 11);
323
324        buf.collapse();
325
326        // Buffer is still the same since we never read anything from the buffer.
327        assert_eq!(buf.remaining(), 13);
328        assert_eq!(buf.remaining_mut(), 11);
329    }
330
331    #[test]
332    fn collapsible_remaining_not_collapsed_no_overlap() {
333        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(24));
334
335        // Write a simple string to the buffer.
336        buf.put_slice(b"hello, world!");
337        assert_eq!(buf.remaining(), 13);
338        assert_eq!(buf.remaining_mut(), 11);
339        assert_eq!(buf.chunk(), b"hello, world!");
340
341        // Write another simple string to the buffer.
342        buf.put_slice(b"huzzah!");
343        assert_eq!(buf.remaining(), 20);
344        assert_eq!(buf.remaining_mut(), 4);
345        assert_eq!(buf.chunk(), b"hello, world!huzzah!");
346
347        // Simulate reading the first string from the buffer, which will end up leaving a hole in the buffer, prior to
348        // the second string, that is big enough to fit the second string entirely.
349        buf.advance(13);
350        assert_eq!(buf.remaining(), 7);
351        assert_eq!(buf.remaining_mut(), 4);
352        assert_eq!(buf.chunk(), b"huzzah!");
353
354        buf.collapse();
355
356        // Buffer should now be collapsed, with the second string at the beginning of the buffer.
357        assert_eq!(buf.remaining(), 7);
358        assert_eq!(buf.remaining_mut(), 17);
359        assert_eq!(buf.chunk(), b"huzzah!");
360    }
361
362    #[test]
363    fn collapsible_remaining_not_collapsed_with_overlap() {
364        let mut buf = get_pooled_object_via_builder::<_, BytesBuffer>(|| FixedSizeVec::with_capacity(24));
365
366        // Write a simple string to the buffer.
367        buf.put_slice(b"huzzah!");
368        assert_eq!(buf.remaining(), 7);
369        assert_eq!(buf.remaining_mut(), 17);
370        assert_eq!(buf.chunk(), b"huzzah!");
371
372        // Write another simple string to the buffer.
373        buf.put_slice(b"hello, world!");
374        assert_eq!(buf.remaining(), 20);
375        assert_eq!(buf.remaining_mut(), 4);
376        assert_eq!(buf.chunk(), b"huzzah!hello, world!");
377
378        // Simulate reading the first string from the buffer, which will end up leaving a hole in the buffer, prior to
379        // the second string, that isn't big enough to fit the second string entirely.
380        buf.advance(7);
381        assert_eq!(buf.remaining(), 13);
382        assert_eq!(buf.remaining_mut(), 4);
383        assert_eq!(buf.chunk(), b"hello, world!");
384
385        buf.collapse();
386
387        // Buffer should now be collapsed, with the second string at the beginning of the buffer.
388        assert_eq!(buf.remaining(), 13);
389        assert_eq!(buf.remaining_mut(), 11);
390        assert_eq!(buf.chunk(), b"hello, world!");
391    }
392}