tokio_quiche/buf_factory.rs
1// Copyright (C) 2025, Cloudflare, Inc.
2// All rights reserved.
3//
4// Redistribution and use in source and binary forms, with or without
5// modification, are permitted provided that the following conditions are
6// met:
7//
8// * Redistributions of source code must retain the above copyright notice,
9// this list of conditions and the following disclaimer.
10//
11// * Redistributions in binary form must reproduce the above copyright
12// notice, this list of conditions and the following disclaimer in the
13// documentation and/or other materials provided with the distribution.
14//
15// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
16// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
17// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
19// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
22// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
23// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
24// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27//! Buffers for zero-copy packet handling and for allowing copying into
28//! uninitialized memory.
29
30use bytes::Bytes;
31use datagram_socket::DgramBuffer;
32
33#[derive(Default, Clone, Debug)]
34pub struct BufFactory;
35
36impl BufFactory {
37 /// Sized to hold two QUIC varints (max 8 bytes each).
38 pub const DGRAM_HEADROOM: usize = 16;
39 pub const MAX_BUF_SIZE: usize = 64 * 1024;
40
41 /// Return a `DgramBuffer` with enough capacity for `MAX_DATAGRAM_SIZE`
42 /// payload bytes and enough headroom for two QUIC varints.
43 pub fn get_max_dgram_buf() -> DgramBuffer {
44 DgramBuffer::with_capacity_and_headroom(
45 datagram_socket::MAX_DATAGRAM_SIZE + BufFactory::DGRAM_HEADROOM,
46 BufFactory::DGRAM_HEADROOM,
47 )
48 }
49}
50
51impl quiche::BufFactory for BufFactory {
52 type Buf = Bytes;
53 type DgramBuf = DgramBuffer;
54
55 fn buf_from_slice(buf: &[u8]) -> Bytes {
56 Bytes::copy_from_slice(buf)
57 }
58
59 fn dgram_buf_from_slice(buf: &[u8]) -> DgramBuffer {
60 DgramBuffer::from_slice(buf)
61 }
62}