rig-http 0.47.0

Rig's transport contracts: the HTTP client and websocket traits a transport implements, and the wasm-compatible bounds they are written with.
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
//! Incremental SSE and newline-delimited framing of response bytes.
//! SSE dispatch requires a blank line; incomplete events are not flushed at EOF.
//! NDJSON permits a final unterminated line through [`NdjsonFramer::finish`].
//! A framer holds at most its limit ([`FRAME_LIMIT`] unless given another)
//! plus one byte of a frame: a larger frame is refused as [`TooLarge`].
//!
//! ```
//! use rig_http::http_client::framing::NdjsonFramer;
//!
//! let mut framer = NdjsonFramer::new();
//! assert_eq!(framer.push(b"{}\n").collect::<Vec<_>>(), vec![Ok(b"{}".to_vec())]);
//! ```

use std::borrow::Cow;

/// The most bytes one frame of a streamed reply may hold: an SSE event's
/// lines since the last blank line that a framer keeps (its data and any
/// unfinished line), or an NDJSON line. Far above any real frame, and
/// below what would exhaust memory.
pub const FRAME_LIMIT: usize = 64 * 1024 * 1024;

/// A frame, line or input larger than its reader's limit, refused before
/// the reader's buffer grew past it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("more than {limit} bytes")]
pub struct TooLarge {
    /// The most bytes the reader takes.
    pub limit: usize,
    /// The bytes it held when it refused: past `limit`, and the whole size
    /// only when the input ended there.
    pub asked: usize,
}

/// How a reply's bytes are split into wire frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Framing {
    /// `text/event-stream`: WHATWG event-stream grammar ([`SseFramer`]).
    Sse,
    /// Newline-delimited JSON ([`NdjsonFramer`]).
    Ndjson,
    /// The whole body is one frame.
    Whole,
}

impl Framing {
    /// The incremental framer of a streamed reply. A whole body is one
    /// frame, so it has none.
    pub fn framer(self) -> Option<Framer> {
        self.framer_with_limit(FRAME_LIMIT)
    }

    /// The incremental framer of a streamed reply, refusing a frame past
    /// `limit`.
    fn framer_with_limit(self, limit: usize) -> Option<Framer> {
        let lines = match self {
            Self::Sse => Lines::Sse(SseFramer::with_limit(limit)),
            Self::Ndjson => Lines::Ndjson(NdjsonFramer::with_limit(limit)),
            Self::Whole => return None,
        };
        Some(Framer { lines })
    }

    /// Split a whole reply body into the frames a decoder reads: one per SSE
    /// event with a non-blank `data` field, one per NDJSON line, or the
    /// whole body. The body is in memory already, so no frame of it is
    /// refused for its size.
    ///
    /// ```
    /// use rig_http::http_client::framing::{Framing, WireFrame};
    ///
    /// let frames = Framing::Sse.split(b"data: {}\n\ndata: [DONE]\n\n");
    /// assert_eq!(frames.len(), 2);
    /// assert_eq!(frames[1].as_str(), "[DONE]");
    /// ```
    pub fn split(&self, bytes: &[u8]) -> Vec<WireFrame> {
        let Some(mut framer) = self.framer_with_limit(usize::MAX) else {
            return (!bytes.is_empty())
                .then(|| WireFrame::from_bytes(bytes.to_vec()))
                .into_iter()
                .collect();
        };
        let mut frames: Vec<WireFrame> = framer.push(bytes).flatten().collect();
        frames.extend(framer.finish());
        frames
    }
}

/// One transport frame, after framing but before decoding.
///
/// The transport layer (SSE framer, NDJSON splitter, websocket reader) owns
/// byte splitting and yields these; a decoder never splits bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WireFrame {
    /// Text payload, such as an SSE `data:` field or WebSocket message.
    Text(String),
    /// Byte payload, such as an NDJSON line or binary frame.
    Bytes(Vec<u8>),
}

impl WireFrame {
    /// The frame payload as text (lossy for byte frames).
    pub fn as_str(&self) -> Cow<'_, str> {
        match self {
            Self::Text(text) => Cow::Borrowed(text),
            Self::Bytes(bytes) => String::from_utf8_lossy(bytes),
        }
    }

    /// The frame payload's bytes.
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Text(text) => text.as_bytes(),
            Self::Bytes(bytes) => bytes,
        }
    }

    /// The frame payload's bytes, owned.
    pub fn into_bytes(self) -> Vec<u8> {
        match self {
            Self::Text(text) => text.into_bytes(),
            Self::Bytes(bytes) => bytes,
        }
    }

    /// A frame of `bytes`: text when they are UTF-8.
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        match String::from_utf8(bytes) {
            Ok(text) => Self::Text(text),
            Err(error) => Self::Bytes(error.into_bytes()),
        }
    }
}

/// The incremental framer of one streamed reply, from [`Framing::framer`].
#[derive(Debug)]
pub struct Framer {
    lines: Lines,
}

#[derive(Debug)]
enum Lines {
    Sse(SseFramer),
    Ndjson(NdjsonFramer),
}

impl Framer {
    /// Feed one transport chunk; yields every frame it completed, and
    /// [`TooLarge`] in the place of a frame past the limit: SSE yields
    /// nothing after it, NDJSON reads on after that line. An SSE event whose
    /// data is only whitespace is a heartbeat, not a frame.
    pub fn push(&mut self, chunk: &[u8]) -> impl Iterator<Item = Result<WireFrame, TooLarge>> + '_ {
        let (sse, ndjson) = match &mut self.lines {
            Lines::Sse(framer) => (Some(framer.push(chunk)), None),
            Lines::Ndjson(framer) => (None, Some(framer.push(chunk))),
        };
        let events = sse.into_iter().flatten();
        let events = events.filter(|event| {
            event
                .as_ref()
                .map_or(true, |event| !event.data.trim().is_empty())
        });
        let events = events.map(|event| event.map(|event| WireFrame::Text(event.data)));
        let lines = ndjson.into_iter().flatten();
        events.chain(lines.map(|line| line.map(WireFrame::from_bytes)))
    }

    /// The stream ended: NDJSON's unterminated last line. SSE dispatches
    /// only on a blank line, so an unterminated event is never a frame.
    pub fn finish(&mut self) -> Option<WireFrame> {
        match &mut self.lines {
            Lines::Sse(_) => None,
            Lines::Ndjson(framer) => framer.finish().map(WireFrame::from_bytes),
        }
    }

    /// Bytes pushed but not yet part of a frame, for truncation
    /// diagnostics: [`SseFramer::pending`] or [`NdjsonFramer::pending`].
    pub fn pending(&self) -> usize {
        match &self.lines {
            Lines::Sse(framer) => framer.pending(),
            Lines::Ndjson(framer) => framer.pending(),
        }
    }
}

/// One dispatched `text/event-stream` event.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SseEvent {
    /// The `event:` field, `"message"` when the stream named none.
    pub event: Cow<'static, str>,
    /// The joined `data:` fields, without the terminating newline.
    pub data: String,
    /// The stream's last event id, empty when none was ever set.
    pub id: String,
    /// Most recent parsed `retry:` value since the previous emitted event,
    /// saturating at `u64::MAX`. This value does not trigger automatic
    /// reconnection.
    pub retry: Option<u64>,
}

/// A field recognized by the SSE grammar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SseField {
    /// A payload line.
    Data,
    /// An event type.
    Event,
    /// An accepted event id.
    Id,
    /// A blank dispatch line.
    Blank,
    /// A comment, retry, ignored id or unknown field.
    Other,
}

/// Original byte ranges of one line consumed by [`SseFramer`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SseLine {
    /// Whole line, including its line ending, at saturating stream offsets.
    pub span: std::ops::Range<usize>,
    /// Line content without its ending or an initial BOM.
    pub content: std::ops::Range<usize>,
    /// Field value after a colon and optional space, when present.
    pub value: Option<std::ops::Range<usize>>,
    /// The field accepted by the grammar.
    pub field: SseField,
}

/// A parsed event and the byte offset where it became dispatchable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordedSseEvent {
    /// The grammar's parsed event.
    pub event: SseEvent,
    /// Saturating stream offset of its completing line ending or retained EOF.
    pub end: usize,
}

/// Parsed events and source lines consumed by a recording operation.
#[derive(Debug, Default)]
pub struct SseBatch {
    /// Events emitted in order, with their completion offsets.
    pub events: Vec<RecordedSseEvent>,
    /// Source lines in order, including non-dispatching lines.
    pub lines: Vec<SseLine>,
}

/// The optional leading byte-order mark, which the grammar ignores.
const BOM: [u8; 3] = [0xef, 0xbb, 0xbf];

/// A push parser for the WHATWG `text/event-stream` grammar, which holds at
/// most its limit plus one byte of an event ([`TooLarge`]).
#[derive(Debug)]
pub struct SseFramer {
    /// Bytes not yet consumed as a complete line.
    buffer: Vec<u8>,
    /// How many bytes at the start of `buffer` hold no line end.
    scanned: usize,
    /// The last line ended at a CR that was the last byte pushed, so an LF
    /// opening the next chunk completes that CRLF.
    after_cr: bool,
    /// Events completed by the current `push`, and its refusal.
    ready: Vec<Result<SseEvent, TooLarge>>,
    event_type: String,
    data: String,
    last_event_id: String,
    retry: Option<u64>,
    /// How many BOM bytes have matched so far, while the prefix is undecided.
    bom_prefix: usize,
    bom_done: bool,
    /// Bytes of complete lines consumed since the last blank line.
    since_dispatch: usize,
    /// Absolute byte position after the last consumed line or BOM.
    offset: usize,
    /// The most bytes of an event it holds: its unfinished line and its data.
    limit: usize,
    /// The bytes of the ids copied into the events of the current push.
    copied: usize,
    /// Whether it refused an event, after which it reads nothing more.
    refused: bool,
    /// Whether it parses a recording: text in memory already, which no
    /// limit applies to.
    recording: bool,
}

impl Default for SseFramer {
    fn default() -> Self {
        Self::with_limit(FRAME_LIMIT)
    }
}

impl SseFramer {
    /// A framer at the start of a stream, refusing an event past
    /// [`FRAME_LIMIT`].
    pub fn new() -> Self {
        Self::default()
    }

    /// A framer at the start of a stream, refusing an event that holds more
    /// than `limit` bytes.
    pub fn with_limit(limit: usize) -> Self {
        Self {
            buffer: Vec::new(),
            scanned: 0,
            after_cr: false,
            ready: Vec::new(),
            event_type: String::new(),
            data: String::new(),
            last_event_id: String::new(),
            retry: None,
            bom_prefix: 0,
            bom_done: false,
            since_dispatch: 0,
            offset: 0,
            limit,
            copied: 0,
            refused: false,
            recording: false,
        }
    }

    /// Feed one transport chunk; yields every event it completed, then
    /// [`TooLarge`] once an event holds more than the limit, after which it
    /// yields nothing. The chunk goes in by pieces no larger than the room
    /// left, so the framer never holds more than one byte past the limit.
    /// An event holds its unfinished line, data, type and its copies of the
    /// last id; comments and heartbeats hold nothing.
    pub fn push(&mut self, chunk: &[u8]) -> std::vec::Drain<'_, Result<SseEvent, TooLarge>> {
        let mut rest = chunk;
        self.copied = 0;
        while !self.refused && !rest.is_empty() {
            let room = self.limit.saturating_sub(self.held()).saturating_add(1);
            let (piece, after) = rest.split_at(room.min(rest.len()));
            self.push_inner(piece, None);
            rest = after;
            if self.held() > self.limit {
                self.refuse(self.held());
            }
        }
        self.ready.drain(..)
    }

    /// The bytes of the current event it holds: its unfinished line, its
    /// data, type and last id, and the ids copied into the events of this
    /// push.
    fn held(&self) -> usize {
        self.buffer
            .len()
            .saturating_add(self.data.len())
            .saturating_add(self.event_type.len())
            .saturating_add(self.last_event_id.len())
            .saturating_add(self.copied)
    }

    /// Refuses the current event, keeping the events before it.
    fn refuse(&mut self, asked: usize) {
        self.refused = true;
        self.buffer = Vec::new();
        self.data = String::new();
        self.ready.push(Err(TooLarge {
            limit: self.limit,
            asked,
        }));
    }

    /// Feed a chunk and retain parsed events with source ranges for recording.
    pub fn push_recording(&mut self, chunk: &[u8]) -> SseBatch {
        self.recording = true;
        let mut batch = SseBatch::default();
        self.push_inner(chunk, Some(&mut batch));
        batch
    }

    /// Retain an incomplete final event for a recording, without changing
    /// the normal SSE rule that EOF does not dispatch it.
    pub fn finish_recording(&mut self) -> SseBatch {
        self.recording = true;
        let mut batch = SseBatch::default();
        if self.bom_prefix > 0 {
            self.buffer
                .extend_from_slice(BOM.get(..self.bom_prefix).unwrap_or_default());
            self.bom_prefix = 0;
            self.bom_done = true;
        }
        if !self.buffer.is_empty() {
            let buffer = std::mem::take(&mut self.buffer);
            let start = self.offset;
            self.offset = self.offset.saturating_add(buffer.len());
            let (field, value) = self.line(&String::from_utf8_lossy(&buffer));
            batch.lines.push(SseLine {
                span: start..self.offset,
                content: start..self.offset,
                value: value.map(|at| start.saturating_add(at)..self.offset),
                field,
            });
        }
        self.dispatch();
        if let Some(Ok(event)) = self.ready.pop() {
            batch.events.push(RecordedSseEvent {
                event,
                end: self.offset,
            });
        }
        batch
    }

    fn push_inner(&mut self, chunk: &[u8], mut recording: Option<&mut SseBatch>) {
        let mut chunk = self.strip_bom(chunk);
        if self.after_cr
            && let Some((&first, rest)) = chunk.split_first()
        {
            self.after_cr = false;
            if first == b'\n' {
                chunk = rest;
                self.offset = self.offset.saturating_add(1);
                // Pending bytes are counted as if the CRLF had arrived whole.
                if self.since_dispatch > 0 {
                    self.since_dispatch = self.since_dispatch.saturating_add(1);
                }
            }
        }
        self.buffer.extend_from_slice(chunk);
        // Taken out, so its lines are read in place while `line` changes the rest.
        let buffer = std::mem::take(&mut self.buffer);
        let mut rest = buffer.as_slice();
        while let Some((line, next)) = terminated_line(rest, self.scanned) {
            self.scanned = 0;
            let start = self.offset;
            self.offset = self.offset.saturating_add(rest.len() - next.len());
            self.since_dispatch = self.since_dispatch.saturating_add(rest.len() - next.len());
            self.after_cr = next.is_empty() && rest.last() == Some(&b'\r');
            // A byte that is not UTF-8 becomes a three-byte replacement:
            // refuse before a line grows past the limit that way.
            let decoded = self.held().saturating_add(decoded_len(line));
            if recording.is_none() && decoded > self.limit {
                self.refuse(decoded);
                return;
            }
            let (field, value) = self.line(&String::from_utf8_lossy(line));
            if self.refused {
                return;
            }
            // Past the limit, read no further line, so `push` refuses.
            if recording.is_none() && self.held() > self.limit {
                rest = next;
                break;
            }
            if let Some(batch) = recording.as_deref_mut() {
                batch.lines.push(SseLine {
                    span: start..self.offset,
                    content: start..start.saturating_add(line.len()),
                    value: value
                        .map(|at| start.saturating_add(at)..start.saturating_add(line.len())),
                    field,
                });
                if let Some(Ok(event)) = self.ready.pop() {
                    batch.events.push(RecordedSseEvent {
                        event,
                        end: self.offset,
                    });
                }
            }
            rest = next;
        }
        self.scanned = rest.len();
        let consumed = buffer.len() - rest.len();
        self.buffer = buffer;
        self.buffer.drain(..consumed);
    }

    /// Saturating count of buffered bytes and complete lines since the last
    /// blank line. Excludes any undecided leading BOM prefix; exposes no frame data.
    pub fn pending(&self) -> usize {
        self.since_dispatch.saturating_add(self.buffer.len())
    }

    /// Consume the stream's optional leading BOM, which may itself be split
    /// across chunks. Returns the chunk with any BOM bytes removed.
    fn strip_bom<'a>(&mut self, chunk: &'a [u8]) -> &'a [u8] {
        if self.bom_done {
            return chunk;
        }
        let mut rest = chunk;
        while let Some(&byte) = rest.first() {
            if BOM.get(self.bom_prefix) != Some(&byte) {
                // Not a BOM after all: replay the bytes that matched so far.
                let matched = std::mem::take(&mut self.bom_prefix);
                self.bom_done = true;
                self.buffer
                    .extend_from_slice(BOM.get(..matched).unwrap_or_default());
                return rest;
            }
            self.bom_prefix += 1;
            rest = rest.get(1..).unwrap_or_default();
            if self.bom_prefix == BOM.len() {
                self.offset = self.offset.saturating_add(BOM.len());
                self.bom_prefix = 0;
                self.bom_done = true;
                return rest;
            }
        }
        rest
    }

    /// Process one complete line of the grammar.
    fn line(&mut self, line: &str) -> (SseField, Option<usize>) {
        if line.is_empty() {
            self.dispatch();
            return (SseField::Blank, None);
        }
        // A line starting with a colon is a comment.
        if line.starts_with(':') {
            return (SseField::Other, None);
        }
        let (field, value, at) = match line.split_once(':') {
            Some((field, value)) => {
                let trimmed = value.strip_prefix(' ').unwrap_or(value);
                (
                    field,
                    trimmed,
                    Some(field.len() + 1 + value.len() - trimmed.len()),
                )
            }
            None => (line, "", None),
        };
        let field = match field {
            "event" => {
                self.event_type.clear();
                self.event_type.push_str(value);
                SseField::Event
            }
            "data" => {
                self.data.push_str(value);
                self.data.push('\n');
                SseField::Data
            }
            // A NUL in an id is ignored outright, per the grammar.
            "id" if !value.contains('\0') => {
                self.last_event_id.clear();
                self.last_event_id.push_str(value);
                SseField::Id
            }
            "retry" if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) => {
                // Digits only is a valid field, so a value past `u64` saturates.
                self.retry = Some(value.parse().unwrap_or(u64::MAX));
                SseField::Other
            }
            _ => SseField::Other,
        };
        (field, at)
    }

    /// A blank line ends an event. An event with no data is not dispatched:
    /// it only resets the event type, as the grammar says.
    fn dispatch(&mut self) {
        self.since_dispatch = 0;
        if self.data.is_empty() {
            self.event_type.clear();
            return;
        }
        self.data.pop();
        // The event copies the last id: refuse before a copy passes the
        // limit.
        let asked = self.held().saturating_add(self.last_event_id.len());
        if !self.recording && asked > self.limit {
            return self.refuse(asked);
        }
        let event = if self.event_type.is_empty() {
            Cow::Borrowed("message")
        } else {
            Cow::Owned(std::mem::take(&mut self.event_type))
        };
        self.copied = self.copied.saturating_add(self.last_event_id.len());
        self.ready.push(Ok(SseEvent {
            event,
            data: std::mem::take(&mut self.data),
            id: self.last_event_id.clone(),
            retry: self.retry.take(),
        }));
        self.event_type.clear();
    }
}

/// Splits nonempty newline-delimited payloads without validating JSON.
/// A nonempty unterminated last line is available through [`Self::finish`].
/// A line counts its bytes before its line end, LF or CRLF.
#[derive(Debug)]
pub struct NdjsonFramer {
    buffer: Vec<u8>,
    /// How many bytes at the start of `buffer` hold no line end.
    scanned: usize,
    ready: Vec<Result<Vec<u8>, TooLarge>>,
    /// The most bytes of a line it holds.
    limit: usize,
    /// Whether it refused the line it reads, whose rest it skips.
    skipping: bool,
}

impl Default for NdjsonFramer {
    fn default() -> Self {
        Self::with_limit(FRAME_LIMIT)
    }
}

impl NdjsonFramer {
    /// A framer at the start of a stream, refusing a line past
    /// [`FRAME_LIMIT`].
    pub fn new() -> Self {
        Self::default()
    }

    /// A framer at the start of a stream, refusing a line of more than
    /// `limit` bytes.
    pub fn with_limit(limit: usize) -> Self {
        Self {
            buffer: Vec::new(),
            scanned: 0,
            ready: Vec::new(),
            limit,
            skipping: false,
        }
    }

    /// Feed one transport chunk; yields every line it completed, and
    /// [`TooLarge`] in the place of a line longer than the limit, whose
    /// rest up to its LF it skips. Blank lines are not frames. The chunk
    /// goes in by pieces no larger than the room left, so the framer never
    /// holds more than one byte past the limit.
    pub fn push(&mut self, chunk: &[u8]) -> std::vec::Drain<'_, Result<Vec<u8>, TooLarge>> {
        let mut rest = chunk;
        while !rest.is_empty() {
            if self.skipping {
                let Some(end) = rest.iter().position(|byte| *byte == b'\n') else {
                    break;
                };
                self.skipping = false;
                rest = rest.get(end + 1..).unwrap_or_default();
                continue;
            }
            let room = self.limit.saturating_sub(self.held()).saturating_add(1);
            let (piece, after) = rest.split_at(room.min(rest.len()));
            self.lines(piece);
            rest = after;
            if self.held() > self.limit {
                let asked = self.held();
                self.buffer = Vec::new();
                self.scanned = 0;
                self.skipping = true;
                self.ready.push(Err(TooLarge {
                    limit: self.limit,
                    asked,
                }));
            }
        }
        self.ready.drain(..)
    }

    /// The bytes of the line it holds; a CR at its end may be half of its
    /// line end, so it does not count yet.
    fn held(&self) -> usize {
        let cr = self.buffer.last() == Some(&b'\r');
        self.buffer.len() - usize::from(cr)
    }

    /// Takes the lines `chunk` completes, keeping its unterminated end.
    fn lines(&mut self, chunk: &[u8]) {
        self.buffer.extend_from_slice(chunk);
        let mut rest = self.buffer.as_slice();
        while let Some((line, end)) = split_line(rest, self.scanned, |byte| *byte == b'\n') {
            self.scanned = 0;
            let line = line.strip_suffix(b"\r").unwrap_or(line);
            // A CR that was not the line's end counts after all.
            if line.len() > self.limit {
                self.ready.push(Err(TooLarge {
                    limit: self.limit,
                    asked: line.len(),
                }));
            } else if !line.is_empty() {
                self.ready.push(Ok(line.to_vec()));
            }
            rest = end.get(1..).unwrap_or_default();
        }
        self.scanned = rest.len();
        let consumed = self.buffer.len() - rest.len();
        self.buffer.drain(..consumed);
    }

    /// The unterminated last line, if the stream ended with a nonempty one,
    /// none after a refused one. A CR ending it is part of the line end, as
    /// in [`Self::push`].
    pub fn finish(&mut self) -> Option<Vec<u8>> {
        let mut line = std::mem::take(&mut self.buffer);
        if line.last() == Some(&b'\r') {
            line.pop();
        }
        (!line.is_empty()).then_some(line)
    }

    /// Bytes of an unterminated trailing line, for truncation diagnostics.
    pub fn pending(&self) -> usize {
        self.buffer.len()
    }
}

/// The bytes `line` takes once decoded, each run that is not UTF-8 as one
/// replacement character.
fn decoded_len(line: &[u8]) -> usize {
    let replacement = char::REPLACEMENT_CHARACTER.len_utf8();
    line.utf8_chunks().fold(0, |len, chunk| {
        let invalid = if chunk.invalid().is_empty() {
            0
        } else {
            replacement
        };
        len.saturating_add(chunk.valid().len())
            .saturating_add(invalid)
    })
}

/// The first complete line in `buffer`, without its line end, and the
/// bytes after that line end; the first `scanned` bytes hold no line end.
///
/// A CR ends a line at once, as the grammar says; an LF right after it in
/// `buffer` belongs to the same line end.
fn terminated_line(buffer: &[u8], scanned: usize) -> Option<(&[u8], &[u8])> {
    let (line, end) = split_line(buffer, scanned, |byte| *byte == b'\n' || *byte == b'\r')?;
    let rest = end.strip_prefix(b"\r\n").or_else(|| end.get(1..));
    Some((line, rest.unwrap_or_default()))
}

/// `buffer` split before its first byte that `ends` a line, if it has one;
/// the first `scanned` bytes hold none.
fn split_line(buffer: &[u8], scanned: usize, ends: impl Fn(&u8) -> bool) -> Option<(&[u8], &[u8])> {
    buffer.split_at_checked(scanned + buffer.iter().skip(scanned).position(ends)?)
}

#[cfg(test)]
mod tests;