Skip to main content

utopia_compression/
sink.rs

1//! Where an algorithm writes its output, and where its codec's working memory comes from.
2
3use std::ffi::c_void;
4
5/// The allocator a codec's working state (zstd's contexts, brotli's encoder and decoder) comes
6/// from during one call, in the C libraries' own shape: `alloc(opaque, size)` and
7/// `free(opaque, address)`. A block must be aligned as `malloc()` aligns one.
8///
9/// The state is created and freed within the call, as PHP's extensions create and free
10/// theirs, so no state outlives it: a codec behaves as on its first call, even on corrupt
11/// input.
12#[derive(Debug, Clone, Copy)]
13pub struct Allocator {
14    /// Allocates `size` bytes, or returns null.
15    pub alloc: extern "C" fn(opaque: *mut c_void, size: usize) -> *mut c_void,
16    /// Frees a block `alloc` returned.
17    pub free: extern "C" fn(opaque: *mut c_void, address: *mut c_void),
18    /// Passed to both.
19    pub opaque: *mut c_void,
20}
21
22/// A growable byte buffer an algorithm writes its output into, in place.
23///
24/// `Vec<u8>` is one. A caller with its own string type implements it so the output is written
25/// once, where it ends up: the PHP extension writes straight into a PHP string, which a `Vec`
26/// would cost a second copy of (and twice the memory, for a moment).
27///
28/// The `*_into` methods of each algorithm ([`Gzip::compress_into`](crate::Gzip::compress_into),
29/// ...) append to the sink; [`Algorithm::compress`](crate::Algorithm::compress) is
30/// `compress_into` a new `Vec`. On an error, what the sink holds is unspecified.
31///
32/// # Safety
33///
34/// [`Sink::as_mut_ptr`] points to [`Sink::capacity`] writable bytes, the first [`Sink::len`] of
35/// them the output so far; [`Sink::grow`] and [`Sink::reserve`] keep those bytes (the pointer
36/// may change).
37pub unsafe trait Sink {
38    /// How many bytes were written.
39    fn len(&self) -> usize;
40
41    /// Whether nothing was written.
42    fn is_empty(&self) -> bool {
43        self.len() == 0
44    }
45
46    /// How many bytes fit without growing.
47    fn capacity(&self) -> usize;
48
49    /// Makes room for `capacity` bytes in all (nothing to do when there is). `false` when the
50    /// memory is not there, which the algorithm reports as its codec would. The algorithms ask
51    /// for what PHP's function would have at that point, so a sink that grows to exactly that
52    /// (reallocating in place, as PHP's allocator does for a large block) holds no more.
53    fn grow(&mut self, capacity: usize) -> bool;
54
55    /// [`Sink::grow`] to `capacity` when that is cheap to do: a guess at the final size (a gzip
56    /// trailer's length, a bound) that saves growing step by step. Declining (`false`) is
57    /// never an error; the algorithm then grows as it needs to.
58    fn reserve(&mut self, capacity: usize) -> bool {
59        self.grow(capacity)
60    }
61
62    /// The start of the buffer.
63    fn as_mut_ptr(&mut self) -> *mut u8;
64
65    /// Records that the first `len` bytes are written.
66    ///
67    /// # Safety
68    ///
69    /// `len <= capacity()`, and the first `len` bytes were written.
70    unsafe fn set_len(&mut self, len: usize);
71
72    /// The allocator for the codec's working state during the call; `None` (the default) for
73    /// the C library's own, `malloc()`.
74    fn allocator(&self) -> Option<Allocator> {
75        None
76    }
77}
78
79// SAFETY: a `Vec`'s pointer covers its capacity, and growing keeps its contents.
80unsafe impl Sink for Vec<u8> {
81    fn len(&self) -> usize {
82        Vec::len(self)
83    }
84
85    fn capacity(&self) -> usize {
86        Vec::capacity(self)
87    }
88
89    /// Amortized, as a `Vec` grows: the algorithms grow step by step, as PHP's buffers do.
90    fn grow(&mut self, capacity: usize) -> bool {
91        capacity <= Vec::capacity(self) || self.try_reserve(capacity - Vec::len(self)).is_ok()
92    }
93
94    fn as_mut_ptr(&mut self) -> *mut u8 {
95        Vec::as_mut_ptr(self)
96    }
97
98    unsafe fn set_len(&mut self, len: usize) {
99        // SAFETY: the caller's contract.
100        unsafe { Vec::set_len(self, len) }
101    }
102}
103
104/// The free room of `sink` after what it holds: its address and size.
105pub(crate) fn spare<S: Sink + ?Sized>(sink: &mut S) -> (*mut u8, usize) {
106    let (len, capacity) = (sink.len(), sink.capacity());
107    // SAFETY: `len <= capacity`, so the offset stays within the buffer.
108    (unsafe { sink.as_mut_ptr().add(len) }, capacity - len)
109}
110
111/// Appends `bytes` to `sink`; `false` when it cannot grow.
112pub(crate) fn append<S: Sink + ?Sized>(sink: &mut S, bytes: &[u8]) -> bool {
113    let len = sink.len();
114    if !sink.grow(len + bytes.len()) {
115        return false;
116    }
117    let (at, _) = spare(sink);
118    // SAFETY: room for `bytes` was made after the `len` bytes written.
119    unsafe {
120        std::ptr::copy_nonoverlapping(bytes.as_ptr(), at, bytes.len());
121        sink.set_len(len + bytes.len());
122    }
123    true
124}