soyokaze 0.6.3

HTTP/1/2/3 Library 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
//! The content codings a message body may be carried in.
//!
//! [`Compression`] is both the vocabulary and the codec: the tokens
//! `Content-Encoding` and `Accept-Encoding` are written in, and the encoder
//! and decoder those tokens stand for. [`Coding`] is one entry of such a
//! field, which is how a list of them is read.
//!
//! Nothing here knows what a message is. [`Message::compress`] and
//! [`Message::decompress`] are what put a coding on one, and they are also
//! where the rules about which messages may be coded at all live.
//!
//! [`Message::compress`]: crate::models::Message::compress
//! [`Message::decompress`]: crate::models::Message::decompress

use std::fmt;
use std::io::Read;
use std::io::Write;
use std::str::FromStr;

use bytes::Bytes;

/// A content coding a body may be carried in.
///
/// [`Compression::Auto`] is a choice rather than a coding: it names nothing on
/// the wire and is settled against what the peer said it accepts, just before
/// the body goes out.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Compression {
    /// The best coding the peer accepts, settled before the body goes out.
    Auto,
    /// `zstd`, RFC 8878.
    Zstd,
    /// `br`, RFC 7932.
    Brotli,
    /// `gzip`, RFC 1952.
    Gzip,
    /// `deflate`, which is RFC 1950 zlib around RFC 1951 deflate.
    Deflate,
}

impl Compression {
    /// Every coding that names something, in the order one is preferred over the next.
    pub const CODINGS: &[Self] = &[Self::Zstd, Self::Brotli, Self::Gzip, Self::Deflate];
    /// The number of codings, [`Compression::Auto`] included.
    pub const COUNT: usize = Self::CODINGS.len() + 1;
    /// [`Compression::CODINGS`] written as an `Accept-Encoding` field value.
    pub const ACCEPTED: &str = "zstd, br, gzip, deflate";
    /// The token for a body that was not coded at all.
    pub const IDENTITY: &str = "identity";
    /// The deprecated token RFC 9110 §8.4.1 says must be read as `gzip`.
    pub const GZIP_ALIAS: &str = "x-gzip";

    /// The zstd level bodies are encoded at.
    pub const ZSTD_LEVEL: i32 = 3;
    /// The brotli quality bodies are encoded at.
    pub const BROTLI_QUALITY: i32 = 5;
    /// The log of the brotli window size bodies are encoded with.
    pub const BROTLI_WINDOW: i32 = 22;
    /// In bytes, the room a streaming codec is given to work in.
    pub const BUFFER: usize = 8192;

    /// The coding's token, as `Content-Encoding` spells it.
    ///
    /// [`Compression::Auto`] names no coding and so is empty: it stands for a
    /// choice that has yet to be made, and never appears on the wire.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Auto => "",
            Self::Zstd => "zstd",
            Self::Brotli => "br",
            Self::Gzip => "gzip",
            Self::Deflate => "deflate",
        }
    }

    /// The coding a token names, ignoring case.
    ///
    /// Never answers [`Compression::Auto`], which names nothing. `x-gzip` is
    /// read as `gzip`, as RFC 9110 §8.4.1 says it must be. A token this crate
    /// does not implement — `compress` and `identity` among them — names
    /// nothing here, so a body carried in one is left exactly as it arrived.
    pub fn parse(token: &str) -> Option<Self> {
        let token = token.trim_ascii();

        // The length and the first octet together name at most one candidate,
        // so a token naming no coding of ours is turned away without comparing
        // anything: a field lists several codings and every one of them is
        // looked up here, on every message that carries the field.
        match (token.len(), token.as_bytes().first()?.to_ascii_lowercase()) {
            (2, b'b') => token.eq_ignore_ascii_case(Self::Brotli.as_str()).then_some(Self::Brotli),
            (4, b'g') => token.eq_ignore_ascii_case(Self::Gzip.as_str()).then_some(Self::Gzip),
            (4, b'z') => token.eq_ignore_ascii_case(Self::Zstd.as_str()).then_some(Self::Zstd),
            (6, b'x') => token.eq_ignore_ascii_case(Self::GZIP_ALIAS).then_some(Self::Gzip),
            (7, b'd') => token.eq_ignore_ascii_case(Self::Deflate.as_str()).then_some(Self::Deflate),
            _ => None,
        }
    }

    /// The best coding an `Accept-Encoding` field permits.
    ///
    /// `values` is every `accept-encoding` field the message carries, each of
    /// which may list several codings. A coding at `q=0` is refused, `*` stands
    /// for every coding the field does not name, and among what is left the
    /// first of [`Compression::CODINGS`] wins — quality settles what is
    /// acceptable to the peer, while which of the acceptable ones to send is
    /// this end's own business.
    ///
    /// `None` when nothing is permitted, which is also what an absent field
    /// means. RFC 9110 §12.5.3 would let a sender code anything when the field
    /// is absent, but a peer that asked for nothing is far likelier to be one
    /// that cannot decode than one that did not bother to ask.
    pub fn accepted<'a>(values: impl Iterator<Item = &'a str>) -> Option<Self> {
        let mut quality = [None; Self::COUNT];
        let mut wildcard = None;

        // A field at a time and an entry at a time, rather than the two
        // flattened into one iterator: this is walked for every message that
        // carries the field, and the plain loops are what the flattening
        // costs more than.
        for value in values {
            for coding in Coding::list(value) {
                match coding.compression() {
                    Some(compression) => quality[compression as usize] = Some(coding.quality),
                    None if coding.wildcard() => wildcard = Some(coding.quality),
                    None => {}
                }
            }
        }

        let permitted = |coding: &Self| quality[*coding as usize].or(wildcard).unwrap_or(Coding::NONE) > Coding::NONE;
        Self::CODINGS.iter().copied().find(permitted)
    }

    /// The coding a `Content-Encoding` field says the body is already carried in.
    ///
    /// `None` when the field is absent, names only `identity`, names a coding
    /// this crate does not implement, or names more than one — in each of those
    /// cases the body cannot be decoded and must be handed on as it arrived.
    pub fn applied<'a>(values: impl Iterator<Item = &'a str>) -> Option<Self> {
        let mut applied = None;

        for value in values {
            for coding in Coding::list(value) {
                if coding.token.eq_ignore_ascii_case(Self::IDENTITY) {
                    continue;
                }

                if applied.is_some() {
                    return None;
                }

                applied = Some(coding.compression()?);
            }
        }

        applied
    }

    /// Whether a `Content-Encoding` field says the body is coded at all.
    ///
    /// Answers yes for a coding this crate does not implement, which is what
    /// makes it the question "is the body still compressed" rather than "can
    /// this crate decode it". `identity` codes nothing and so does not count.
    pub fn encoded<'a>(values: impl Iterator<Item = &'a str>) -> bool {
        for value in values {
            for coding in Coding::list(value) {
                if !coding.token.eq_ignore_ascii_case(Self::IDENTITY) {
                    return true;
                }
            }
        }

        false
    }

    /// Reads a decoder out, refusing to produce more than `max` octets.
    ///
    /// The ceiling is what stops a small body decoding into an enormous one:
    /// the decoder is read one octet past `max`, so passing it is noticed
    /// without ever holding more than that. `out` is left as it was found when
    /// anything goes wrong.
    ///
    /// # Errors
    ///
    /// Returns [`Error::TooLarge`] once the decoded body passes `max`, and
    /// [`Error::Coding`] when the stream will not decode.
    pub fn drain(reader: impl Read, max: u64, out: &mut Vec<u8>) -> Result<(), Error> {
        let start = out.len();
        let mut bounded = reader.take(max.saturating_add(1));

        // Read straight into the buffer. Copying between the two would stage
        // every block in a buffer of its own first, which is one whole extra
        // pass over the body for nothing.
        match bounded.read_to_end(out) {
            Ok(produced) if produced as u64 <= max => Ok(()),
            Ok(_) => {
                out.truncate(start);
                Err(Error::TooLarge(max))
            }
            Err(err) => {
                out.truncate(start);
                Err(Error::coding(err))
            }
        }
    }

    /// Encodes `input` in this coding.
    ///
    /// # Errors
    ///
    /// As [`Compression::encode_into`].
    pub fn encode(&self, input: &[u8]) -> Result<Bytes, Error> {
        let mut out = Vec::with_capacity(input.len() / 2 + Self::BUFFER.min(input.len() + 64));
        self.encode_into(input, &mut out)?;
        Ok(Bytes::from(out))
    }

    /// [`Compression::encode`], appending to a buffer the caller owns.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Settled`] for [`Compression::Auto`], which names no
    /// coding to encode in, and [`Error::Coding`] when the encoder fails.
    pub fn encode_into(&self, input: &[u8], out: &mut Vec<u8>) -> Result<(), Error> {
        match self {
            Self::Auto => Err(Error::Settled),

            Self::Zstd => zstd::stream::copy_encode(input, out, Self::ZSTD_LEVEL).map_err(Error::coding),

            Self::Brotli => {
                let params = brotli::enc::BrotliEncoderParams { quality: Self::BROTLI_QUALITY, lgwin: Self::BROTLI_WINDOW, ..Default::default() };
                let mut source = input;

                brotli::BrotliCompress(&mut source, out, &params).map(drop).map_err(Error::coding)
            }

            Self::Gzip => {
                let mut encoder = flate2::write::GzEncoder::new(out, flate2::Compression::default());
                encoder.write_all(input).map_err(Error::coding)?;
                encoder.finish().map(drop).map_err(Error::coding)
            }

            Self::Deflate => {
                let mut encoder = flate2::write::ZlibEncoder::new(out, flate2::Compression::default());
                encoder.write_all(input).map_err(Error::coding)?;
                encoder.finish().map(drop).map_err(Error::coding)
            }
        }
    }

    /// Decodes `input`, refusing to produce more than `max` octets.
    ///
    /// # Errors
    ///
    /// As [`Compression::decode_into`].
    pub fn decode(&self, input: &[u8], max: u64) -> Result<Bytes, Error> {
        let mut out = Vec::new();
        self.decode_into(input, max, &mut out)?;
        Ok(Bytes::from(out))
    }

    /// [`Compression::decode`], appending to a buffer the caller owns.
    ///
    /// A `deflate` body is tried as zlib first and then as raw deflate: RFC
    /// 9110 §8.4.1.2 names zlib, but enough deployed senders write the raw
    /// stream that refusing it would turn a readable body into an error.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Settled`] for [`Compression::Auto`], and otherwise as
    /// [`Compression::drain`].
    pub fn decode_into(&self, input: &[u8], max: u64, out: &mut Vec<u8>) -> Result<(), Error> {
        match self {
            Self::Auto => Err(Error::Settled),

            Self::Zstd => Self::drain(zstd::stream::read::Decoder::new(input).map_err(Error::coding)?, max, out),

            Self::Brotli => Self::drain(brotli::Decompressor::new(input, Self::BUFFER), max, out),

            Self::Gzip => Self::drain(flate2::read::GzDecoder::new(input), max, out),

            Self::Deflate => match Self::drain(flate2::read::ZlibDecoder::new(input), max, out) {
                Err(Error::Coding(_)) => Self::drain(flate2::read::DeflateDecoder::new(input), max, out),
                settled => settled,
            },
        }
    }
}

impl fmt::Display for Compression {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Compression {
    type Err = ();

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        Self::parse(text).ok_or(())
    }
}

/// One entry of a comma-separated content coding list.
///
/// Both `Content-Encoding` and `Accept-Encoding` are written this way, so both
/// are read through this; only the latter carries a quality, and an entry that
/// carries none is fully acceptable.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Coding<'a> {
    /// The token as it was written, which may be `*` or name nothing at all.
    pub token: &'a str,
    /// The quality the entry carries.
    pub quality: f32,
}

impl<'a> Coding<'a> {
    /// The token standing for every coding the field does not name.
    pub const WILDCARD: &'static str = "*";
    /// The quality of an entry that carries none, which is full acceptance.
    pub const FULL: f32 = 1.0;
    /// The quality at which an entry is a refusal.
    pub const NONE: f32 = 0.0;
    /// The parameter carrying an entry's quality.
    pub const QUALITY: &'static str = "q";
    /// What a quality is divided by, indexed by how many digits follow the point.
    pub const PLACES: [f32; 4] = [1.0, 10.0, 100.0, 1000.0];

    /// Reads a quality value, or `None` for anything outside its grammar.
    ///
    /// RFC 9110 §12.4.2 gives `qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "."
    /// 0*3("0") ] )`, which is five octets at the most and is read here
    /// directly rather than through the general float parser — which is most
    /// of what reading one entry of a field costs. Whatever the grammar does
    /// not admit answers `None`, so [`Coding::parse`] can fall back and a
    /// sender writing something else is read exactly as it was before.
    ///
    /// A whole part other than zero or one is not refused here: it parses to a
    /// quality above one, which is refused where the value is used, and that
    /// is the same answer by a shorter road.
    #[inline]
    pub fn qvalue(text: &str) -> Option<f32> {
        let (whole, fraction) = text.as_bytes().split_first()?;

        if !whole.is_ascii_digit() {
            return None;
        }

        let mut value = (whole - b'0') as u32;
        let mut places = 0;

        if let Some((point, digits)) = fraction.split_first() {
            if *point != b'.' || digits.len() >= Self::PLACES.len() {
                return None;
            }

            for digit in digits {
                if !digit.is_ascii_digit() {
                    return None;
                }

                value = value * 10 + (digit - b'0') as u32;
                places += 1;
            }
        }

        Some(value as f32 / Self::PLACES[places])
    }

    /// Reads one entry, with whatever parameters follow it.
    ///
    /// A quality outside zero to one is a refusal rather than an error: RFC
    /// 9110 §12.4.2 admits no such value, and reading it as full acceptance
    /// would let a malformed field talk this end into coding a body the peer
    /// cannot read.
    pub fn parse(entry: &'a str) -> Self {
        // Trimming is asked of ASCII whitespace rather than of every code
        // point the Unicode tables call whitespace: the surrounding space RFC
        // 9110 §5.6.3 admits is a space or a tab, and deciding that one octet
        // at a time is what a whole field of entries pays for.
        let (token, parameters) = match Coding::split(entry, Self::PARAMETER) {
            Some((token, parameters)) => (token.trim_ascii(), Some(parameters)),
            None => (entry.trim_ascii(), None),
        };

        let Some(parameters) = parameters else {
            return Self { token, quality: Self::FULL };
        };

        let written = parameters
            .split(Self::PARAMETER as char)
            .filter_map(|parameter| parameter.split_once('='))
            .find(|(name, _)| name.trim_ascii().eq_ignore_ascii_case(Self::QUALITY));

        let quality = match written {
            Some((_, value)) => {
                let value = value.trim_ascii();
                Self::qvalue(value).or_else(|| value.parse::<f32>().ok()).filter(|quality| (Self::NONE..=Self::FULL).contains(quality)).unwrap_or(Self::NONE)
            }
            None => Self::FULL,
        };

        Self { token, quality }
    }

    /// The octet separating one entry of a list from the next.
    pub const SEPARATOR: u8 = b',';
    /// The octet separating an entry from its parameters.
    pub const PARAMETER: u8 = b';';

    /// Splits `text` at the first `octet`, if it is there.
    ///
    /// `octet` must be ASCII, which every delimiter a field value is written
    /// with is, so the split always lands on a character boundary.
    ///
    /// # Panics
    ///
    /// Debug builds assert that `octet` is ASCII.
    pub fn split(text: &str, octet: u8) -> Option<(&str, &str)> {
        debug_assert!(octet.is_ascii(), "a delimiter outside ASCII can fall inside a character");

        let at = crate::helpers::scan::find(text.as_bytes(), octet)?;
        Some((&text[..at], &text[at + 1..]))
    }

    /// Reads every entry of a field value, in the order they were written.
    ///
    /// Entries naming nothing at all are dropped, so an empty field value
    /// yields nothing rather than one nameless entry.
    pub fn list(value: &'a str) -> Codings<'a> {
        Codings { rest: value }
    }

    /// The coding this entry names, or `None` for a wildcard or an unknown token.
    pub fn compression(&self) -> Option<Compression> {
        Compression::parse(self.token)
    }

    /// Whether this entry stands for every coding the field does not name.
    pub fn wildcard(&self) -> bool {
        self.token == Self::WILDCARD
    }

    /// Whether this entry permits what it names.
    pub fn accepts(&self) -> bool {
        self.quality > Self::NONE
    }
}

/// The entries of one content coding list, read as they are asked for.
///
/// Every message that carries an `Accept-Encoding` has it read through this,
/// so the entries are found with the crate's own word-at-a-time scan rather
/// than through the general pattern machinery a string split reaches for.
pub struct Codings<'a> {
    /// What is left of the field value.
    pub rest: &'a str,
}

impl<'a> Iterator for Codings<'a> {
    type Item = Coding<'a>;

    fn next(&mut self) -> Option<Coding<'a>> {
        loop {
            if self.rest.is_empty() {
                return None;
            }

            let entry = match Coding::split(self.rest, Coding::SEPARATOR) {
                Some((entry, rest)) => {
                    self.rest = rest;
                    entry
                }
                None => std::mem::take(&mut self.rest),
            };

            let coding = Coding::parse(entry);
            if !coding.token.is_empty() {
                return Some(coding);
            }
        }
    }
}

/// Why a body would not encode or decode.
#[derive(Debug, PartialEq, Eq)]
pub enum Error {
    /// The coding was [`Compression::Auto`], which names nothing to code in.
    Settled,
    /// The decoded body would pass the ceiling it was given.
    TooLarge(u64),
    /// The stream will not decode, or the encoder failed.
    Coding(String),
}

impl Error {
    /// Wraps a failure from one of the codecs underneath.
    pub fn coding(error: impl fmt::Display) -> Self {
        Self::Coding(error.to_string())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Settled => write!(f, "the content coding was never settled"),
            Self::TooLarge(max) => write!(f, "the decoded body exceeds {max} octets"),
            Self::Coding(reason) => write!(f, "the content coding failed: {reason}"),
        }
    }
}

impl std::error::Error for Error {}