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
9pub struct FixedSizeVec {
17 data: UniqueArc<Vec<u8>>,
18 read_idx: usize,
19}
20
21impl FixedSizeVec {
22 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 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 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 remaining == 0 {
137 let inner = self.data_mut();
138 inner.read_idx = 0;
139 inner.data.clear();
140 return;
141 }
142
143 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#[derive(Clone)]
172pub struct FrozenBytesBuffer {
173 strategy_ref: Arc<dyn ReclaimStrategy<BytesBuffer> + Send + Sync>,
174 data: ManuallyDrop<FrozenFixedSizeVec>,
175}
176
177impl FrozenBytesBuffer {
178 pub fn is_empty(&self) -> bool {
180 self.data.read_idx == self.data.data.len()
181 }
182
183 pub fn len(&self) -> usize {
185 self.data.data.len() - self.data.read_idx
186 }
187
188 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 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 assert_eq!(buf.remaining(), 0);
243 assert_eq!(buf.remaining_mut(), 13);
244
245 buf.put_slice(first_write);
247 assert_eq!(buf.remaining(), 5);
248 assert_eq!(buf.remaining_mut(), 8);
249
250 buf.put_slice(second_write);
252 assert_eq!(buf.remaining(), 11);
253 assert_eq!(buf.remaining_mut(), 2);
254
255 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 buf.put_slice(third_write);
266 assert_eq!(buf.remaining(), 6);
267 assert_eq!(buf.remaining_mut(), 0);
268
269 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 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 assert_eq!(buf.remaining(), 0);
306 assert_eq!(buf.remaining_mut(), 13);
307
308 buf.collapse();
309
310 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 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 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 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 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 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 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 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 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 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 assert_eq!(buf.remaining(), 13);
389 assert_eq!(buf.remaining_mut(), 11);
390 assert_eq!(buf.chunk(), b"hello, world!");
391 }
392}