Skip to main content

ntex/http/encoding/
mod.rs

1//! Content-Encoding support
2//!
3//! Supports `gzip`, `deflate` and `zstd`. Large chunks are encoded and
4//! decoded on the blocking thread pool, smaller ones on the current thread.
5//!
6//! ## Memory
7//!
8//! Each compressed response keeps its encoder until the body ends: about
9//! 1.5MiB for a `zstd` body of unknown or large size, less for small bodies
10//! of known size, and about 370KiB for `gzip` and `deflate`. There is no
11//! global limit, many concurrent streaming responses can use a lot of
12//! memory. Responses that gain little from compression can be sent with
13//! `ContentEncoding::Identity` through the `web::BodyEncoding` trait.
14use zstd::zstd_safe::WriteBuf;
15
16use crate::rt::{BlockingResult, spawn_blocking};
17use crate::util::{BufMut, BytesMut};
18
19mod decoder;
20mod encoder;
21
22pub use self::decoder::Decoder;
23pub use self::encoder::Encoder;
24
25#[cfg(test)]
26thread_local! {
27    static OFFLOADED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
28}
29
30/// Run `f` on the blocking thread pool.
31fn offload<F, R>(f: F) -> BlockingResult<R>
32where
33    F: FnOnce() -> R + Send + 'static,
34    R: Send + 'static,
35{
36    #[cfg(test)]
37    OFFLOADED.with(|n| n.set(n.get() + 1));
38    spawn_blocking(f)
39}
40
41#[cfg(test)]
42fn offloaded() -> usize {
43    OFFLOADED.with(std::cell::Cell::get)
44}
45
46fn zstd_error(code: usize) -> std::io::Error {
47    std::io::Error::other(zstd::zstd_safe::get_error_name(code))
48}
49
50/// The spare capacity of a buffer, `zstd` writes its output directly into it.
51struct Spare<'a> {
52    buf: &'a mut BytesMut,
53    start: usize,
54    ptr: *mut u8,
55    capacity: usize,
56}
57
58impl<'a> Spare<'a> {
59    fn new(buf: &'a mut BytesMut) -> Self {
60        let start = buf.len();
61        let spare = buf.chunk_mut();
62        let (ptr, capacity) = (spare.as_mut_ptr(), spare.len());
63        Spare {
64            buf,
65            start,
66            ptr,
67            capacity,
68        }
69    }
70}
71
72// SAFETY: `ptr` points to `capacity` bytes of the buffer's spare capacity, and
73// `filled_until` only extends the buffer over bytes zstd has written.
74unsafe impl WriteBuf for Spare<'_> {
75    fn as_slice(&self) -> &[u8] {
76        &self.buf[self.start..]
77    }
78
79    fn capacity(&self) -> usize {
80        self.capacity
81    }
82
83    fn as_mut_ptr(&mut self) -> *mut u8 {
84        self.ptr
85    }
86
87    unsafe fn filled_until(&mut self, n: usize) {
88        // SAFETY: The caller guarantees `n` bytes of the exposed spare capacity have been initialized.
89        unsafe { self.buf.set_len(self.start + n) }
90    }
91}