buffet 0.3.3

Thread-local buffer pool for the `loona` crate.
Documentation
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use std::{
    marker::PhantomData,
    ops::{self, Bound, RangeBounds},
};

mod privatepool;

pub type BufResult<T, B> = (std::io::Result<T>, B);

pub use privatepool::{
    initialize_allocator_with_num_bufs, is_allocator_initialized, num_free, Error, Result, BUF_SIZE,
};

/// Initialize the allocator. Must be called before any other
/// allocation function.
pub fn initialize_allocator() -> Result<()> {
    if is_allocator_initialized() {
        return Ok(());
    }

    // 64 * 1024 * 4096 bytes = 256 MiB
    #[cfg(not(feature = "miri"))]
    let default_num_bufs = 64 * 1024;

    #[cfg(feature = "miri")]
    let default_num_bufs = 1024;

    let mut num_bufs = default_num_bufs;

    if let Ok(env_num_bufs) = std::env::var("BUFFET_NUM_BUFS") {
        if let Ok(parsed_num_bufs) = env_num_bufs.parse::<usize>() {
            num_bufs = parsed_num_bufs;
        }
    }

    let mem_usage_in_mb: f64 = num_bufs as f64 * (BUF_SIZE as usize) as f64 / 1024.0 / 1024.0;
    eprintln!(
        "==== buffet will use {} buffers, for a constant {:.2} MiB usage (override with $BUFFET_NUM_BUFS)",
        num_bufs, mem_usage_in_mb
    );
    initialize_allocator_with_num_bufs(default_num_bufs as _)
}

impl BufMut {
    #[inline(always)]
    pub fn alloc() -> Result<BufMut, Error> {
        privatepool::alloc()
    }

    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len as _
    }

    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Turn this buffer immutable. The reference count doesn't change, but the
    /// immutable view can be cloned.
    #[inline]
    pub fn freeze(self) -> Buf {
        let b = Buf {
            index: self.index,
            off: self.off,
            len: self.len,

            _non_send: PhantomData,
        };
        std::mem::forget(self); // don't decrease ref count

        b
    }

    /// Dangerous: freeze a slice of this.
    ///
    /// # Safety
    /// Must only be used if you can guarantee this portion won't be written to
    /// anymore.
    #[inline]
    pub(crate) unsafe fn freeze_slice(&self, range: impl RangeBounds<usize>) -> Buf {
        let b = Buf {
            index: self.index,
            off: self.off,
            len: self.len,

            _non_send: PhantomData,
        };

        b.slice(range)
    }

    /// Split this buffer in twain. Both parts can be written to.  Panics if
    /// `at` is out of bounds.
    #[inline]
    pub fn split_at(self, at: usize) -> (Self, Self) {
        assert!(at <= self.len as usize);

        let left = BufMut {
            index: self.index,
            off: self.off,
            len: at as _,

            _non_send: PhantomData,
        };

        let right = BufMut {
            index: self.index,
            off: self.off + at as u16,
            len: (self.len - at as u16),

            _non_send: PhantomData,
        };

        std::mem::forget(self); // don't decrease ref count
        privatepool::inc(left.index); // in fact, increase it by 1

        (left, right)
    }

    /// Skip over the first `n` bytes, panics if out of bound
    pub fn skip(&mut self, n: usize) {
        assert!(n <= self.len as usize);

        let u16_n: u16 = n.try_into().unwrap();
        self.off += u16_n;
        self.len -= u16_n;
    }
}

/// A mutable buffer. Cannot be cloned, but can be written to
pub struct BufMut {
    pub(crate) index: u32,
    pub(crate) off: u16,
    pub(crate) len: u16,

    // makes this type non-Send, which we do want
    _non_send: PhantomData<*mut ()>,
}

impl ops::Deref for BufMut {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(
                privatepool::base_ptr_with_offset(self.index, self.off as _),
                self.len as _,
            )
        }
    }
}

impl ops::DerefMut for BufMut {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe {
            std::slice::from_raw_parts_mut(
                privatepool::base_ptr_with_offset(self.index, self.off as _),
                self.len as _,
            )
        }
    }
}

mod iobufmut {
    use crate::{ReadInto, RollMut};

    use super::BufMut;
    pub trait Sealed {}
    impl Sealed for BufMut {}
    impl Sealed for RollMut {}
    impl Sealed for ReadInto {}
    impl Sealed for Vec<u8> {}
}

/// The IoBufMut trait is implemented by buffer types that can be passed to
/// io-uring operations.
///
/// # Safety
///
/// If the address returned by `io_buf_mut_stable_mut_ptr` is not actually
/// stable and moves while an io_uring operation is in-flight, the kernel might
/// write to the wrong memory location.
pub unsafe trait IoBufMut: iobufmut::Sealed {
    /// Gets a pointer to the start of the buffer
    fn io_buf_mut_stable_mut_ptr(&mut self) -> *mut u8;

    /// Gets the capacity of the buffer
    fn io_buf_mut_capacity(&self) -> usize;

    /// Gets a mutable slice of the buffer
    ///
    /// # Safety
    ///
    /// An arbitrary implementor may return invalid pointers or lengths.
    unsafe fn slice_mut(&mut self) -> &mut [u8] {
        std::slice::from_raw_parts_mut(self.io_buf_mut_stable_mut_ptr(), self.io_buf_mut_capacity())
    }
}

unsafe impl IoBufMut for BufMut {
    fn io_buf_mut_stable_mut_ptr(&mut self) -> *mut u8 {
        unsafe { privatepool::base_ptr_with_offset(self.index, self.off as _) }
    }

    fn io_buf_mut_capacity(&self) -> usize {
        self.len as usize
    }
}

unsafe impl IoBufMut for Vec<u8> {
    fn io_buf_mut_stable_mut_ptr(&mut self) -> *mut u8 {
        self.as_mut_ptr()
    }

    fn io_buf_mut_capacity(&self) -> usize {
        self.capacity()
    }
}

impl Drop for BufMut {
    fn drop(&mut self) {
        privatepool::dec(self.index);
    }
}

/// A read-only buffer. Can be cloned, but cannot be written to.
pub struct Buf {
    pub(crate) index: u32,
    pub(crate) off: u16,
    pub(crate) len: u16,

    // makes this type non-Send, which we do want
    _non_send: PhantomData<*mut ()>,
}

impl Buf {
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.len as _
    }

    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Take an owned slice of this
    pub fn slice(mut self, range: impl RangeBounds<usize>) -> Self {
        let mut new_start = 0;
        let mut new_end = self.len();

        match range.start_bound() {
            Bound::Included(&n) => new_start = n,
            Bound::Excluded(&n) => new_start = n + 1,
            Bound::Unbounded => {}
        }

        match range.end_bound() {
            Bound::Included(&n) => new_end = n + 1,
            Bound::Excluded(&n) => new_end = n,
            Bound::Unbounded => {}
        }

        assert!(new_start <= new_end);
        assert!(new_end <= self.len());

        self.off += new_start as u16;
        self.len = (new_end - new_start) as u16;
        self
    }

    /// Split this buffer in twain.
    /// Panics if `at` is out of bounds.
    #[inline]
    pub fn split_at(self, at: usize) -> (Self, Self) {
        assert!(at <= self.len as usize);

        let left = Buf {
            index: self.index,
            off: self.off,
            len: at as _,

            _non_send: PhantomData,
        };

        let right = Buf {
            index: self.index,
            off: self.off + at as u16,
            len: (self.len - at as u16),

            _non_send: PhantomData,
        };

        std::mem::forget(self); // don't decrease ref count
        privatepool::inc(left.index); // in fact, increase it by 1

        (left, right)
    }
}

impl ops::Deref for Buf {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &[u8] {
        unsafe {
            std::slice::from_raw_parts(
                privatepool::base_ptr_with_offset(self.index, self.off as _),
                self.len as _,
            )
        }
    }
}

impl Clone for Buf {
    fn clone(&self) -> Self {
        privatepool::inc(self.index);
        Self {
            index: self.index,
            off: self.off,
            len: self.len,
            _non_send: PhantomData,
        }
    }
}

impl Drop for Buf {
    fn drop(&mut self) {
        privatepool::dec(self.index);
    }
}

#[cfg(test)]
mod tests {
    use crate::{num_free, Buf, BufMut};
    use std::rc::Rc;

    #[test]
    fn size_test() {
        crate::bufpool::initialize_allocator().unwrap();

        assert_eq!(8, std::mem::size_of::<BufMut>());
        assert_eq!(8, std::mem::size_of::<Buf>());
        assert_eq!(16, std::mem::size_of::<Box<[u8]>>());

        assert_eq!(16, std::mem::size_of::<&[u8]>());

        #[allow(dead_code)]
        enum BufOrBox {
            Buf(Buf),
            Box((Rc<Box<[u8]>>, u32, u32)),
        }
        assert_eq!(16, std::mem::size_of::<BufOrBox>());

        #[allow(dead_code)]
        enum Chunk {
            Buf(Buf),
            Box(Box<[u8]>),
            Static(&'static [u8]),
        }
        assert_eq!(24, std::mem::size_of::<Chunk>());
    }

    #[test]
    fn freeze_test() {
        crate::bufpool::initialize_allocator().unwrap();

        let total_bufs = num_free();
        let mut bm = BufMut::alloc().unwrap();

        assert_eq!(total_bufs - 1, num_free());
        assert_eq!(bm.len(), 4096);

        bm[..11].copy_from_slice(b"hello world");
        assert_eq!(&bm[..11], b"hello world");

        let b = bm.freeze();
        assert_eq!(&b[..11], b"hello world");
        assert_eq!(total_bufs - 1, num_free());

        let b2 = b.clone();
        assert_eq!(&b[..11], b"hello world");
        assert_eq!(total_bufs - 1, num_free());

        drop(b);
        assert_eq!(total_bufs - 1, num_free());

        drop(b2);
        assert_eq!(total_bufs, num_free());
    }

    #[test]
    fn split_test() {
        crate::bufpool::initialize_allocator().unwrap();

        let total_bufs = num_free();
        let mut bm = BufMut::alloc().unwrap();

        bm[..12].copy_from_slice(b"yellowjacket");
        let (a, b) = bm.split_at(6);

        assert_eq!(total_bufs - 1, num_free());
        assert_eq!(&a[..], b"yellow");
        assert_eq!(&b[..6], b"jacket");

        drop((a, b));
    }
}