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
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Types for performing vectored I/O.

use http::header::HeaderName;
use std::{
    collections::VecDeque,
    fmt,
    hash::{Hash, Hasher},
    ops::Deref,
    rc::Rc,
    str::Utf8Error,
};

use crate::{Roll, RollStr};

/// A piece of data (arbitrary bytes) with a stable address, suitable for
/// passing to the kernel (io_uring writes).
#[derive(Clone)]
pub enum Piece {
    Full {
        core: PieceCore,
    },
    Slice {
        core: PieceCore,
        start: usize,
        len: usize,
    },
}

impl<T: AsRef<[u8]>> PartialEq<T> for Piece {
    fn eq(&self, other: &T) -> bool {
        let s: &[u8] = self.as_ref();
        s.eq(other.as_ref())
    }
}

impl Eq for Piece {}

impl Hash for Piece {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_ref().hash(state)
    }
}

impl Piece {
    /// Returns an empty piece
    pub fn empty() -> Self {
        Self::Full {
            core: PieceCore::Static(&[]),
        }
    }
}

#[derive(Clone, Hash)]
pub enum PieceCore {
    Static(&'static [u8]),
    Vec(Rc<Vec<u8>>),
    Roll(Roll),
    HeaderName(HeaderName),
}

impl<T> From<T> for Piece
where
    T: Into<PieceCore>,
{
    #[inline(always)]
    fn from(t: T) -> Self {
        Piece::Full { core: t.into() }
    }
}

impl<const N: usize> From<&'static [u8; N]> for PieceCore {
    #[inline(always)]
    fn from(slie: &'static [u8; N]) -> Self {
        PieceCore::Static(slie)
    }
}

impl From<&'static [u8]> for PieceCore {
    #[inline(always)]
    fn from(slice: &'static [u8]) -> Self {
        PieceCore::Static(slice)
    }
}

impl From<&'static str> for PieceCore {
    #[inline(always)]
    fn from(slice: &'static str) -> Self {
        PieceCore::Static(slice.as_bytes())
    }
}

impl From<Vec<u8>> for PieceCore {
    #[inline(always)]
    fn from(vec: Vec<u8>) -> Self {
        PieceCore::Vec(Rc::new(vec))
    }
}

impl From<Roll> for PieceCore {
    #[inline(always)]
    fn from(roll: Roll) -> Self {
        PieceCore::Roll(roll)
    }
}

impl From<()> for PieceCore {
    #[inline(always)]
    fn from(_empty: ()) -> Self {
        PieceCore::Static(&[])
    }
}

impl From<PieceStr> for Piece {
    fn from(s: PieceStr) -> Self {
        s.piece
    }
}

impl From<HeaderName> for PieceCore {
    #[inline(always)]
    fn from(name: HeaderName) -> Self {
        PieceCore::HeaderName(name)
    }
}

impl Deref for PieceCore {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl Deref for Piece {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl AsRef<[u8]> for PieceCore {
    fn as_ref(&self) -> &[u8] {
        match self {
            PieceCore::Static(slice) => slice,
            PieceCore::Vec(vec) => vec.as_ref(),
            PieceCore::Roll(roll) => roll.as_ref(),
            PieceCore::HeaderName(name) => name.as_str().as_bytes(),
        }
    }
}

impl Piece {
    fn core(&self) -> &PieceCore {
        match self {
            Piece::Full { core } => core,
            Piece::Slice { core, .. } => core,
        }
    }

    /// Split the piece into two at the given index.
    /// The original piece will be consumed.
    /// Returns a tuple of the two pieces.
    pub fn split_at(self, middle: usize) -> (Self, Self) {
        let len = self.len();
        assert!(middle <= len);

        match self {
            Piece::Full { core } => (
                Self::Slice {
                    core: core.clone(),
                    start: 0,
                    len: middle,
                },
                Self::Slice {
                    core,
                    start: middle,
                    len: len - middle,
                },
            ),
            Piece::Slice { core, start, len } => (
                Self::Slice {
                    core: core.clone(),
                    start,
                    len: middle,
                },
                Self::Slice {
                    core,
                    start: start + middle,
                    len: len - middle,
                },
            ),
        }
    }
}

impl AsRef<[u8]> for Piece {
    fn as_ref(&self) -> &[u8] {
        let ptr = self.core().as_ref();
        if let Piece::Slice { start, len, .. } = self {
            &ptr[*start..][..*len]
        } else {
            ptr
        }
    }
}

impl Piece {
    // Decode as utf-8 (owned)
    pub fn to_str(self) -> Result<PieceStr, Utf8Error> {
        _ = std::str::from_utf8(&self[..])?;
        Ok(PieceStr { piece: self })
    }

    /// Convert to [PieceStr].
    ///
    /// # Safety
    /// UB if not utf-8. Typically only used in parsers.
    pub unsafe fn to_string_unchecked(self) -> PieceStr {
        PieceStr { piece: self }
    }
}

impl Piece {
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.as_ref().len()
    }

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

/// A list of [Piece], suitable for issuing vectored writes via io_uring.
#[derive(Default)]
pub struct PieceList {
    // note: we can't use smallvec here, because the address of
    // the piece list must be stable for the kernel to take
    // ownership of it.
    //
    // we could however do our own memory pooling.
    pub(crate) pieces: VecDeque<Piece>,
}

impl PieceList {
    /// Create a new piece list with a single chunk
    pub fn single(piece: impl Into<Piece>) -> Self {
        Self {
            pieces: [piece.into()].into(),
        }
    }

    /// Add a single chunk to the back of the list
    pub fn push_back(&mut self, chunk: impl Into<Piece>) {
        let chunk = chunk.into();
        if !chunk.is_empty() {
            self.pieces.push_back(chunk);
        }
    }

    /// Add a single chunk to the front of the list
    pub fn push_front(&mut self, chunk: impl Into<Piece>) {
        let chunk = chunk.into();
        if !chunk.is_empty() {
            self.pieces.push_front(chunk);
        }
    }

    /// Add a single chunk to the back list and return self
    pub fn followed_by(mut self, chunk: impl Into<Piece>) -> Self {
        self.push_back(chunk);
        self
    }

    /// Add a single chunk to the front of the list and return self
    pub fn preceded_by(mut self, chunk: impl Into<Piece>) -> Self {
        self.push_front(chunk);
        self
    }

    /// Returns total length
    pub fn len(&self) -> usize {
        self.pieces.iter().map(|c| c.len()).sum()
    }

    pub fn num_pieces(&self) -> usize {
        self.pieces.len()
    }

    pub fn is_empty(&self) -> bool {
        self.pieces.is_empty() || self.len() == 0
    }

    pub fn clear(&mut self) {
        self.pieces.clear();
    }

    pub fn into_vec_deque(self) -> VecDeque<Piece> {
        self.pieces
    }
}

impl From<VecDeque<Piece>> for PieceList {
    fn from(pieces: VecDeque<Piece>) -> Self {
        Self { pieces }
    }
}
impl From<PieceList> for VecDeque<Piece> {
    fn from(list: PieceList) -> Self {
        list.pieces
    }
}

/// A piece of data with a stable address that's _also_
/// valid utf-8.
#[derive(Clone)]
pub struct PieceStr {
    piece: Piece,
}

impl PartialEq for PieceStr {
    fn eq(&self, other: &Self) -> bool {
        self.piece == other.piece
    }
}

impl Eq for PieceStr {}

impl fmt::Debug for PieceStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        fmt::Debug::fmt(&self[..], f)
    }
}

impl fmt::Display for PieceStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        f.pad(self)
    }
}

impl Deref for PieceStr {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        unsafe { std::str::from_utf8_unchecked(&self.piece) }
    }
}

impl AsRef<str> for PieceStr {
    fn as_ref(&self) -> &str {
        self
    }
}

impl PieceStr {
    /// Returns the underlying bytes (borrowed)
    pub fn as_bytes(&self) -> &[u8] {
        self.piece.as_ref()
    }

    /// Returns the underlying bytes (owned)
    pub fn into_inner(self) -> Piece {
        self.piece
    }
}

impl From<&'static str> for PieceStr {
    fn from(s: &'static str) -> Self {
        PieceStr {
            piece: PieceCore::Static(s.as_bytes()).into(),
        }
    }
}

impl From<String> for PieceStr {
    fn from(s: String) -> Self {
        PieceStr {
            piece: PieceCore::Vec(Rc::new(s.into_bytes())).into(),
        }
    }
}

impl From<RollStr> for PieceStr {
    fn from(s: RollStr) -> Self {
        PieceStr {
            piece: PieceCore::Roll(s.into_inner()).into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{Piece, PieceCore};

    #[test]
    fn test_slice() {
        // test that slicing works correctly for a
        // piece made from a &'static u8
        let piece: Piece = PieceCore::Static("französisch".as_bytes()).into();
        // split so that "l" is "franz"
        let (first_name, last_name) = piece.split_at(5);
        assert_eq!(&first_name[..], "franz".as_bytes());
        assert_eq!(&last_name[..], "ösisch".as_bytes());

        // test edge cases, zero-length left
        let piece: Piece = PieceCore::Static("französisch".as_bytes()).into();
        let (first_name, last_name) = piece.split_at(0);
        assert_eq!(&first_name[..], "".as_bytes());
        assert_eq!(&last_name[..], "französisch".as_bytes());

        // test edge cases, zero-length right
        let piece: Piece = PieceCore::Static("französisch".as_bytes()).into();
        let (first_name, last_name) = piece.split_at(12);
        assert_eq!(&first_name[..], "französisch".as_bytes());
        assert_eq!(&last_name[..], "".as_bytes());

        // edge case: empty piece being split into two
        let piece: Piece = PieceCore::Static(b"").into();
        let (first_name, last_name) = piece.split_at(0);
        assert_eq!(&first_name[..], "".as_bytes());
        assert_eq!(&last_name[..], "".as_bytes());
    }
}