Skip to main content

rtci_sctp/queue/
reassembly_queue.rs

1use crate::StreamId;
2use crate::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier};
3use crate::util::*;
4use shared::error::{Error, Result};
5
6use bytes::{Bytes, BytesMut};
7use std::collections::VecDeque;
8
9/// A chunk of data from the stream
10#[derive(Debug, PartialEq)]
11pub struct Chunk {
12    /// The contents of the chunk
13    pub bytes: Bytes,
14}
15
16/// Chunks is a set of chunks that share the same SSN
17#[derive(Debug, Clone)]
18pub struct Chunks {
19    /// used only with the ordered chunks
20    pub ssn: u16,
21    /// The Message Identifier, when the message came in I-DATA chunks (RFC 8260): counted
22    /// per stream, separately for ordered and unordered messages. Zero otherwise.
23    pub mid: u32,
24    /// The payload protocol identifier shared by every fragment of this message.
25    pub ppi: PayloadProtocolIdentifier,
26    /// The Payload Protocol Identifier as the number the peer sent (RFC 9260 3.3.1): the
27    /// value of `ppi` when that has a name for it, and the only way to tell apart the values
28    /// it calls `Unknown`.
29    pub ppid: u32,
30    /// The fragments, in order, that make up one complete message.
31    pub chunks: Vec<ChunkPayloadData>,
32    offset: usize,
33    index: usize,
34    /// Arrival order, used only to decide which of two ready messages came first.
35    /// A counter rather than an instant: this is sequencing, not time.
36    arrival: u64,
37    /// The fragments are I-DATA chunks: ordered and checked by their Fragment Sequence
38    /// Number, not by their TSN (RFC 8260 2.2.3).
39    by_fsn: bool,
40    /// The message is in partial delivery (RFC 9260 6.9): its fragments up to this one were
41    /// handed to the application, and `chunks` holds those received after them. The Fragment
42    /// Sequence Number with I-DATA, the TSN otherwise.
43    next_part: Option<u32>,
44}
45
46impl Chunks {
47    /// Whether the reassembled message carries no bytes.
48    pub fn is_empty(&self) -> bool {
49        self.len() == 0
50    }
51
52    /// The total length in bytes of the reassembled message.
53    pub fn len(&self) -> usize {
54        let mut l = 0;
55        for c in &self.chunks {
56            l += c.user_data.len();
57        }
58        l
59    }
60
61    /// Reassemble all fragments into a single freshly-allocated, exactly-sized
62    /// buffer with one copy.
63    ///
64    /// Unlike [`read`](Self::read), this does not round-trip through a
65    /// caller-provided scratch buffer, eliminating one full-payload copy on the
66    /// receive path (the reassembled message would otherwise be copied into the
67    /// scratch buffer and then again into the delivered `BytesMut`). Returns
68    /// [`Error::ErrShortBuffer`] when the message exceeds `max_len`, mirroring
69    /// `read`'s bound so oversized inbound messages are still rejected.
70    pub fn to_payload(&self, max_len: usize) -> Result<BytesMut> {
71        let total = self.len();
72        if total > max_len {
73            return Err(Error::ErrShortBuffer);
74        }
75        let mut buf = BytesMut::with_capacity(total);
76        for c in &self.chunks {
77            buf.extend_from_slice(&c.user_data);
78        }
79        Ok(buf)
80    }
81
82    /// Concatenates every fragment into `buf`, returning the number of bytes written.
83    ///
84    /// # Errors
85    ///
86    /// Returns [`Error::ErrShortBuffer`](shared::error::Error::ErrShortBuffer) if `buf` cannot
87    /// hold the whole message; the partial copy is left in place.
88    pub fn read(&self, buf: &mut [u8]) -> Result<usize> {
89        let mut n_written = 0;
90        for c in &self.chunks {
91            let to_copy = c.user_data.len();
92            let n = std::cmp::min(to_copy, buf.len() - n_written);
93            buf[n_written..n_written + n].copy_from_slice(&c.user_data[..n]);
94            n_written += n;
95            if n < to_copy {
96                return Err(Error::ErrShortBuffer);
97            }
98        }
99        Ok(n_written)
100    }
101
102    /// Yields the next slice of the reassembled message, up to `max_length` bytes.
103    ///
104    /// Advances an internal cursor, so repeated calls walk the message; returns `None` once it is
105    /// exhausted.
106    pub fn next(&mut self, max_length: usize) -> Option<Chunk> {
107        if self.index >= self.chunks.len() {
108            return None;
109        }
110
111        let mut buf = BytesMut::with_capacity(max_length);
112
113        let mut n_written = 0;
114        while self.index < self.chunks.len() {
115            let to_copy = self.chunks[self.index].user_data[self.offset..].len();
116            let n = std::cmp::min(to_copy, max_length - n_written);
117            buf.extend_from_slice(&self.chunks[self.index].user_data[self.offset..self.offset + n]);
118            n_written += n;
119            if n < to_copy {
120                self.offset += n;
121                return Some(Chunk {
122                    bytes: buf.freeze(),
123                });
124            }
125            self.index += 1;
126            self.offset = 0;
127        }
128
129        Some(Chunk {
130            bytes: buf.freeze(),
131        })
132    }
133
134    pub(crate) fn new(
135        arrival: u64,
136        ssn: u16,
137        ppi: PayloadProtocolIdentifier,
138        chunks: Vec<ChunkPayloadData>,
139    ) -> Self {
140        Chunks {
141            ssn,
142            mid: 0,
143            ppi,
144            ppid: chunks.first().map_or(ppi.number(), ChunkPayloadData::ppid),
145            chunks,
146            offset: 0,
147            index: 0,
148            arrival,
149            by_fsn: false,
150            next_part: None,
151        }
152    }
153
154    /// An empty set for the I-DATA fragments of message `mid`.
155    fn new_interleaved(arrival: u64, mid: u32) -> Self {
156        Chunks {
157            ssn: mid as u16,
158            mid,
159            ppi: PayloadProtocolIdentifier::default(),
160            ppid: 0,
161            chunks: vec![],
162            offset: 0,
163            index: 0,
164            arrival,
165            by_fsn: true,
166            next_part: None,
167        }
168    }
169
170    /// Adds an I-DATA fragment at its place by Fragment Sequence Number. `false` for a
171    /// fragment already held.
172    fn insert_fragment(&mut self, chunk: ChunkPayloadData) -> bool {
173        let idx = self.chunks.partition_point(|c| sna32lt(c.fsn, chunk.fsn));
174        if idx < self.chunks.len() && self.chunks[idx].fsn == chunk.fsn {
175            return false;
176        }
177        if chunk.beginning_fragment {
178            // Only the first fragment carries the Payload Protocol Identifier.
179            self.ppi = chunk.payload_type;
180            self.ppid = chunk.ppid();
181        }
182        self.chunks.insert(idx, chunk);
183        true
184    }
185
186    pub(crate) fn push(&mut self, chunk: ChunkPayloadData) -> bool {
187        // Binary-search the insertion point (fragments are kept in TSN order),
188        // which also detects duplicates -- instead of an O(n) dup scan plus a
189        // full re-sort of every fragment on each push.
190        let idx = self.chunks.partition_point(|c| sna32lt(c.tsn, chunk.tsn));
191        if idx < self.chunks.len() && self.chunks[idx].tsn == chunk.tsn {
192            return false;
193        }
194        if self.chunks.is_empty() && self.next_part.is_none() {
195            self.ppid = chunk.ppid();
196        }
197        self.chunks.insert(idx, chunk);
198
199        // Check if we now have a complete set
200        self.is_complete()
201    }
202
203    pub(crate) fn is_complete(&self) -> bool {
204        // A message in partial delivery is never whole again: part of it was read.
205        if self.next_part.is_some() {
206            return false;
207        }
208        // Condition for complete set
209        //   0. Has at least one chunk.
210        //   1. Begins with beginningFragment set to true
211        //   2. Ends with endingFragment set to true
212        //   3. TSN monotinically increase by 1 from beginning to end
213
214        // 0.
215        let n_chunks = self.chunks.len();
216        if n_chunks == 0 {
217            return false;
218        }
219
220        // 1.
221        if !self.chunks[0].beginning_fragment {
222            return false;
223        }
224
225        // 2.
226        if !self.chunks[n_chunks - 1].ending_fragment {
227            return false;
228        }
229
230        if self.by_fsn {
231            // RFC 8260 2.2.3: by the Fragment Sequence Numbers, whatever the TSNs are.
232            return contiguous_span(self.chunks[0].fsn, self.chunks[n_chunks - 1].fsn, n_chunks);
233        }
234
235        // 3. Fragments must have contiguous TSN
236        // From RFC 4960 Section 3.3.1:
237        //   When a user message is fragmented into multiple chunks, the TSNs are
238        //   used by the receiver to reassemble the message.  This means that the
239        //   TSNs for each fragment of a fragmented user message MUST be strictly
240        //   sequential.
241        // The fragments are kept sorted by TSN with no duplicates (`push`), so they are
242        // contiguous exactly when the first and last TSNs span one less than their count.
243        // Checking that in constant time keeps a message of many fragments from costing a
244        // full rescan on every arrival.
245        contiguous_span(self.chunks[0].tsn, self.chunks[n_chunks - 1].tsn, n_chunks)
246    }
247}
248
249impl Chunks {
250    /// The number that orders this message's fragments: the FSN with I-DATA, the TSN
251    /// otherwise.
252    fn key(&self, c: &ChunkPayloadData) -> u32 {
253        if self.by_fsn { c.fsn } else { c.tsn }
254    }
255
256    /// The fragments that can be handed on now, in order: from the first fragment (or the
257    /// one after the last part read) through those that follow it without a gap, and no
258    /// further than the last fragment. Their count, their bytes, and whether the last of them
259    /// ends the message. `None` when the first of them is missing.
260    pub(crate) fn leading_run(&self) -> Option<(usize, usize, bool)> {
261        let first = self.chunks.first()?;
262        let starts = match self.next_part {
263            Some(next) => self.key(first) == next,
264            None => first.beginning_fragment,
265        };
266        if !starts {
267            return None;
268        }
269        let start = self.key(first);
270        let (mut count, mut bytes) = (0usize, 0usize);
271        for (i, c) in self.chunks.iter().enumerate() {
272            if self.key(c) != start.wrapping_add(i as u32) || (i > 0 && c.beginning_fragment) {
273                break;
274            }
275            count += 1;
276            bytes += c.user_data.len();
277            if c.ending_fragment {
278                return Some((count, bytes, true));
279            }
280        }
281        Some((count, bytes, false))
282    }
283
284    /// Whether every fragment of a message in partial delivery that is still to be read has
285    /// arrived, its last fragment included.
286    pub(crate) fn remaining_complete(&self) -> bool {
287        self.next_part.is_some() && self.leading_run().is_some_and(|(_, _, ends)| ends)
288    }
289
290    /// Takes out the fragments [`leading_run`](Self::leading_run) names and puts the message
291    /// in partial delivery from the next one on. Returns them and whether they end it.
292    fn take_leading(&mut self) -> Option<(Vec<ChunkPayloadData>, bool)> {
293        let (count, _, ends) = self.leading_run()?;
294        let taken: Vec<ChunkPayloadData> = self.chunks.drain(..count).collect();
295        let last = taken.last().map(|c| self.key(c)).unwrap_or_default();
296        self.next_part = Some(last.wrapping_add(1));
297        Some((taken, ends))
298    }
299
300    /// The next fragment of a message in partial delivery when every one before it is held:
301    /// after the last held, or the one after the last part read.
302    fn expected_tail(&self) -> Option<u32> {
303        let next = self.next_part?;
304        match self.leading_run() {
305            Some((_, _, true)) => None,
306            Some((count, _, false)) => Some(next.wrapping_add(count as u32)),
307            None => Some(next),
308        }
309    }
310
311    /// A part of this message made of `chunks`.
312    fn part(&self, chunks: Vec<ChunkPayloadData>) -> Chunks {
313        Chunks {
314            ssn: self.ssn,
315            mid: self.mid,
316            ppi: self.ppi,
317            ppid: self.ppid,
318            chunks,
319            offset: 0,
320            index: 0,
321            arrival: self.arrival,
322            by_fsn: self.by_fsn,
323            next_part: None,
324        }
325    }
326}
327
328/// Part of a message, read with [`Stream::read_part`](crate::Stream::read_part): the partial
329/// delivery API of RFC 9260 section 6.9 (the RECEIVE primitive's "partial flag", section
330/// 11.1.7; `MSG_EOR` of RFC 6458 section 3.1.4).
331///
332/// A message that is complete when it is read is one part with `end_of_record` set. One the
333/// receive buffer cannot hold whole is read in several, in order: the first with `first`
334/// set, the last with `end_of_record` set, all of them from the same stream with no part of
335/// another message of that stream between them (RFC 6458 section 3.1.4: "Only one message at
336/// a time can be partially delivered in any stream"). If the sender abandons the message
337/// before its last part (RFC 3758, RFC 8260 section 2.3.1), no part with `end_of_record`
338/// follows: [`StreamEvent::PartialDeliveryAborted`](crate::StreamEvent::PartialDeliveryAborted)
339/// says so instead.
340#[derive(Debug)]
341pub struct MessagePart {
342    /// The bytes of this part, as the fragments that carried them. Its `ssn`, `mid`, `ppi` and
343    /// `ppid` are the message's.
344    pub chunks: Chunks,
345    /// The message was sent unordered.
346    pub unordered: bool,
347    /// This part starts the message.
348    pub first: bool,
349    /// This part ends the message ("no more deliveries will be received for this stream
350    /// sequence number", RFC 9260 section 11.1.7; RFC 6458 `MSG_EOR`).
351    pub end_of_record: bool,
352}
353
354/// The message of a stream that is in partial delivery.
355#[derive(Debug)]
356struct Partial {
357    set: Chunks,
358    unordered: bool,
359}
360
361/// A message whose partial delivery ended without its last part: the sender abandoned it
362/// (RFC 3758 section 3.6, RFC 8260 section 2.3.1), or the stream's sequence numbers were
363/// reset (RFC 6525).
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub(crate) struct PartialAbort {
366    pub(crate) unordered: bool,
367    /// The Stream Sequence Number with DATA, the Message Identifier with I-DATA.
368    pub(crate) sequence: u32,
369}
370
371/// Where the message a stream can start delivering in parts is.
372enum PartCandidate {
373    /// The ordered message that is due, at the front of `ordered`.
374    Ordered,
375    /// An unordered I-DATA message, at this index of `unordered_partial`.
376    UnorderedInterleaved(usize),
377    /// An unordered DATA message whose first fragment is at this index of `unordered_chunks`.
378    UnorderedData(usize),
379}
380
381/// Whether `n` distinct TSNs, sorted, running from `first` to `last` are contiguous.
382fn contiguous_span(first: u32, last: u32, n: usize) -> bool {
383    n > 0 && last.wrapping_sub(first) as usize == n - 1
384}
385
386/// Where a chunk held for reordering is in a [`ReassemblyQueue`]: the index of its message
387/// (where it has one) and its own index in it.
388enum HeldAt {
389    Ordered { set: usize, chunk: usize },
390    Unordered { chunk: usize },
391    UnorderedInterleaved { set: usize, chunk: usize },
392}
393
394#[derive(Default, Debug)]
395pub(crate) struct ReassemblyQueue {
396    pub(crate) si: StreamId,
397    pub(crate) next_ssn: u16,
398    /// expected SSN for next ordered chunk
399    ///
400    /// `ordered`/`unordered` are consumed strictly from the front by `read`;
401    /// `VecDeque` makes that O(1) instead of `Vec::remove(0)`'s full shift.
402    pub(crate) ordered: VecDeque<Chunks>,
403    pub(crate) unordered: VecDeque<Chunks>,
404    pub(crate) unordered_chunks: Vec<ChunkPayloadData>,
405    /// TSNs of the beginning fragments in `unordered_chunks`, sorted, so the message a new
406    /// fragment may complete is found without rescanning every fragment held.
407    unordered_begins: Vec<u32>,
408    /// TSNs of the ending fragments in `unordered_chunks`, sorted.
409    unordered_ends: Vec<u32>,
410    pub(crate) n_bytes: usize,
411    /// Monotonic counter stamped onto each reassembled message so `read` can tell which of a
412    /// ready ordered and a ready unordered message arrived first.
413    next_arrival: u64,
414    /// The association uses I-DATA (RFC 8260): messages are told apart by their Message
415    /// Identifier and put together by Fragment Sequence Number. `ordered` is then kept in
416    /// Message Identifier order.
417    pub(crate) interleaved: bool,
418    /// The Message Identifier of the next ordered message to deliver.
419    pub(crate) next_mid: u32,
420    /// The unordered I-DATA messages still incomplete, in Message Identifier order.
421    unordered_partial: Vec<Chunks>,
422    /// The message of this stream in partial delivery, if one is (RFC 9260 6.9): at most one
423    /// per stream, and no other message of the stream is read until it ends (RFC 6458 3.1.4).
424    partial: Option<Partial>,
425    /// A partial delivery that ended without its last part, until the association reports it.
426    partial_aborted: Option<PartialAbort>,
427    /// Fragments dropped because they could never be part of a complete message
428    /// ([`discard_orphans`](Self::discard_orphans)).
429    pub(crate) orphans_dropped: usize,
430    /// Passes over the queue for a FORWARD TSN or I-FORWARD-TSN entry
431    /// ([`forward_tsn_for_ordered`](Self::forward_tsn_for_ordered),
432    /// [`forward_mid`](Self::forward_mid)): the work a chunk costs, one pass per stream.
433    pub(crate) forward_passes: usize,
434}
435
436impl ReassemblyQueue {
437    /// From RFC 4960 Sec 6.5:
438    ///   The Stream Sequence Number in all the streams MUST start from 0 when
439    ///   the association is Established.  Also, when the Stream Sequence
440    ///   Number reaches the value 65535 the next Stream Sequence Number MUST
441    ///   be set to 0.
442    pub(crate) fn new(si: StreamId) -> Self {
443        ReassemblyQueue {
444            si,
445            next_ssn: 0, // From RFC 4960 Sec 6.5:
446            ordered: VecDeque::new(),
447            unordered: VecDeque::new(),
448            unordered_chunks: vec![],
449            unordered_begins: vec![],
450            unordered_ends: vec![],
451            n_bytes: 0,
452            next_arrival: 0,
453            interleaved: false,
454            next_mid: 0,
455            unordered_partial: vec![],
456            partial: None,
457            partial_aborted: None,
458            orphans_dropped: 0,
459            forward_passes: 0,
460        }
461    }
462
463    /// RFC 8260 2.2.3: an I-DATA chunk goes to the message its stream, U bit and Message
464    /// Identifier name, at the place its Fragment Sequence Number gives it. Returns whether
465    /// the message is complete with it.
466    fn push_interleaved(&mut self, chunk: ChunkPayloadData) -> bool {
467        let (mid, len) = (chunk.mid, chunk.user_data.len());
468        if chunk.unordered {
469            let idx = self
470                .unordered_partial
471                .partition_point(|s| sna32lt(s.mid, mid));
472            if self.unordered_partial.get(idx).is_none_or(|s| s.mid != mid) {
473                self.unordered_partial
474                    .insert(idx, Chunks::new_interleaved(0, mid));
475            }
476            let set = &mut self.unordered_partial[idx];
477            if !set.insert_fragment(chunk) {
478                return false;
479            }
480            self.n_bytes += len;
481            if !set.is_complete() {
482                return false;
483            }
484            let mut set = self.unordered_partial.remove(idx);
485            set.arrival = self.next_arrival;
486            self.next_arrival += 1;
487            self.unordered.push_back(set);
488            return true;
489        }
490
491        if sna32lt(mid, self.next_mid) {
492            return false;
493        }
494        if chunk.beginning_fragment {
495            self.drop_superseded(chunk.tsn, |set| {
496                if set.mid == mid {
497                    std::cmp::Ordering::Equal
498                } else if sna32gt(set.mid, mid) {
499                    std::cmp::Ordering::Greater
500                } else {
501                    std::cmp::Ordering::Less
502                }
503            });
504        }
505        let idx = self.ordered.partition_point(|s| sna32lt(s.mid, mid));
506        if self.ordered.get(idx).is_none_or(|s| s.mid != mid) {
507            self.ordered
508                .insert(idx, Chunks::new_interleaved(self.next_arrival, mid));
509            self.next_arrival += 1;
510        }
511        let set = &mut self.ordered[idx];
512        if !set.insert_fragment(chunk) {
513            return false;
514        }
515        self.n_bytes += len;
516        set.is_complete()
517    }
518
519    /// The first fragment of an ordered message has arrived, with TSN `tsn`: drops what is held
520    /// in front of it that a sender could not have sent. A sender transmits the ordered
521    /// messages of a stream in the order of their numbers, each from its first fragment on, so
522    /// within one use of a stream a message numbered after this one has TSNs above `tsn`, and
523    /// this message has none below it. What is held against that came before a reset of the
524    /// stream from a peer that sent queued data after its Sender's Last Assigned TSN with the
525    /// stream's old numbers (RFC 6525 5.2.2 E2/E4 make it data of the stream as reset): kept,
526    /// a message of it would be delivered in place of the next use's message with the same
527    /// number, or be put together with it and never complete. `place` says where a set's
528    /// number is against this message's: `Equal` for its own, `Greater` after it.
529    fn drop_superseded(&mut self, tsn: u32, place: impl Fn(&Chunks) -> std::cmp::Ordering) {
530        use std::cmp::Ordering::{Equal, Greater};
531        let lowest = |set: &Chunks| {
532            set.chunks
533                .iter()
534                .map(|c| c.tsn)
535                .reduce(|a, b| if sna32lt(b, a) { b } else { a })
536        };
537        let (mut dropped, mut dropped_bytes) = (0, 0);
538        for set in self.ordered.iter_mut() {
539            if set.next_part.is_some() {
540                continue;
541            }
542            match place(set) {
543                Greater if lowest(set).is_some_and(|t| sna32lt(t, tsn)) => {
544                    dropped += set.chunks.len();
545                    dropped_bytes += set.len();
546                    set.chunks.clear();
547                }
548                Equal => set.chunks.retain(|c| {
549                    let stale = sna32lt(c.tsn, tsn);
550                    if stale {
551                        dropped += 1;
552                        dropped_bytes += c.user_data.len();
553                    }
554                    !stale
555                }),
556                _ => {}
557            }
558        }
559        if dropped > 0 {
560            self.ordered.retain(|s| !s.chunks.is_empty());
561            self.subtract_num_bytes(dropped_bytes);
562            self.orphans_dropped += dropped;
563        }
564    }
565
566    /// Whether `chunk`, which no message in partial delivery takes, does not begin a message
567    /// while the fragment that would come before it in its message has been received (every
568    /// TSN up to `cum` has) and is not held with it: the start of its message went somewhere
569    /// else, and nothing that can still arrive completes it.
570    fn is_orphan(&self, chunk: &ChunkPayloadData, cum: u32) -> bool {
571        if chunk.beginning_fragment || !sna32lte(chunk.tsn.wrapping_sub(1), cum) {
572            return false;
573        }
574        let before = chunk.tsn.wrapping_sub(1);
575        if self.interleaved {
576            // A fragment of a message of which nothing is held: its earlier fragments, the
577            // first included, have TSNs below its own, all received, and none is here.
578            let mid = chunk.mid;
579            return if chunk.unordered {
580                !self.unordered_partial.iter().any(|s| s.mid == mid)
581            } else {
582                !self.ordered.iter().any(|s| s.mid == mid)
583            };
584        }
585        if chunk.unordered {
586            let idx = self
587                .unordered_chunks
588                .partition_point(|c| sna32lt(c.tsn, before));
589            return self
590                .unordered_chunks
591                .get(idx)
592                .is_none_or(|c| c.tsn != before);
593        }
594        let ssn = chunk.stream_sequence_number;
595        let idx = self.ordered.partition_point(|s| sna16lt(s.ssn, ssn));
596        match self.ordered.get(idx) {
597            Some(s) if s.ssn == ssn => {
598                let i = s.chunks.partition_point(|c| sna32lt(c.tsn, before));
599                s.chunks.get(i).is_none_or(|c| c.tsn != before)
600            }
601            _ => true,
602        }
603    }
604
605    /// Whether an ordered message is the next one to deliver, or one before it.
606    fn is_due(&self, set: &Chunks) -> bool {
607        if self.interleaved {
608            sna32lte(set.mid, self.next_mid)
609        } else {
610            sna16lte(set.ssn, self.next_ssn)
611        }
612    }
613
614    /// The ordered message `set` is delivered: the one after it is expected next.
615    fn delivered(&mut self, ssn: u16, mid: u32) {
616        if self.interleaved {
617            if mid == self.next_mid {
618                self.next_mid = self.next_mid.wrapping_add(1);
619            }
620        } else if ssn == self.next_ssn {
621            self.next_ssn = self.next_ssn.wrapping_add(1);
622        }
623    }
624
625    /// RFC 8260 2.3.1: an I-FORWARD-TSN entry. The messages of this stream up to `mid`,
626    /// ordered or unordered as the entry says, will not be completed: their fragments are
627    /// dropped, and the ordered messages after them are no longer held back.
628    pub(crate) fn forward_mid(&mut self, unordered: bool, mid: u32) {
629        self.forward_passes += 1;
630        if self.partial.as_ref().is_some_and(|p| {
631            p.unordered == unordered && sna32lte(p.set.mid, mid) && !p.set.remaining_complete()
632        }) {
633            self.abort_partial();
634        }
635        let mut dropped = 0;
636        if unordered {
637            self.unordered_partial.retain(|s| {
638                let keep = sna32gt(s.mid, mid);
639                if !keep {
640                    dropped += s.len();
641                }
642                keep
643            });
644        } else {
645            self.ordered.retain(|s| {
646                let keep = sna32gt(s.mid, mid) || s.is_complete();
647                if !keep {
648                    dropped += s.len();
649                }
650                keep
651            });
652            if sna32lte(self.next_mid, mid) {
653                self.next_mid = mid.wrapping_add(1);
654            }
655        }
656        self.subtract_num_bytes(dropped);
657    }
658
659    pub(crate) fn push(&mut self, chunk: ChunkPayloadData) -> bool {
660        self.push_received(chunk, None)
661    }
662
663    /// As [`push`](Self::push), with the receiver's cumulative TSN before `chunk`: a fragment
664    /// that can never be part of a complete message (see
665    /// [`discard_orphans`](Self::discard_orphans)) is dropped instead of being held.
666    pub(crate) fn push_received(
667        &mut self,
668        chunk: ChunkPayloadData,
669        cumulative_tsn: Option<u32>,
670    ) -> bool {
671        if chunk.stream_identifier != self.si {
672            return false;
673        }
674        let Some(chunk) = self.push_to_partial(chunk) else {
675            return false;
676        };
677        if let Some(cum) = cumulative_tsn
678            && self.is_orphan(&chunk, cum)
679        {
680            self.orphans_dropped += 1;
681            return false;
682        }
683        if self.interleaved {
684            return self.push_interleaved(chunk);
685        }
686
687        if chunk.unordered {
688            // First, insert into unordered_chunks array
689            let tsn = chunk.tsn;
690            let idx = self
691                .unordered_chunks
692                .partition_point(|c| sna32lt(c.tsn, tsn));
693            if idx < self.unordered_chunks.len() && self.unordered_chunks[idx].tsn == tsn {
694                return false;
695            }
696            self.n_bytes += chunk.user_data.len();
697            if chunk.beginning_fragment {
698                let i = self.unordered_begins.partition_point(|&t| sna32lt(t, tsn));
699                self.unordered_begins.insert(i, tsn);
700            }
701            if chunk.ending_fragment {
702                let i = self.unordered_ends.partition_point(|&t| sna32lt(t, tsn));
703                self.unordered_ends.insert(i, tsn);
704            }
705            self.unordered_chunks.insert(idx, chunk);
706
707            // Find the message this chunk completes, if any, and append it to the
708            // unordered array.
709            if let Some(cset) = self.find_complete_unordered_chunk_set(tsn) {
710                self.unordered.push_back(cset);
711                return true;
712            }
713
714            false
715        } else {
716            // This is an ordered chunk
717            if sna16lt(chunk.stream_sequence_number, self.next_ssn) {
718                return false;
719            }
720
721            if chunk.beginning_fragment {
722                let ssn = chunk.stream_sequence_number;
723                self.drop_superseded(chunk.tsn, |set| {
724                    if set.ssn == ssn {
725                        std::cmp::Ordering::Equal
726                    } else if sna16gt(set.ssn, ssn) {
727                        std::cmp::Ordering::Greater
728                    } else {
729                        std::cmp::Ordering::Less
730                    }
731                });
732            }
733
734            self.n_bytes += chunk.user_data.len();
735
736            // `ordered` is kept sorted by SSN, so binary-search for the chunk
737            // set instead of scanning linearly (O(N) per arriving chunk when
738            // the application drains slower than data arrives).
739            let ssn = chunk.stream_sequence_number;
740            let idx = self.ordered.partition_point(|s| sna16lt(s.ssn, ssn));
741            if let Some(s) = self.ordered.get_mut(idx)
742                && s.ssn == ssn
743            {
744                return s.push(chunk);
745            }
746
747            // If not found, create a new chunkSet and insert it in SSN order
748            // (this branch is only reached for ordered chunks).
749            let mut cset = Chunks::new(self.next_arrival, ssn, chunk.payload_type, vec![]);
750            self.next_arrival += 1;
751            let ok = cset.push(chunk);
752            self.ordered.insert(idx, cset);
753
754            ok
755        }
756    }
757
758    /// A fragment of the message in partial delivery goes to it; any other is given back.
759    ///
760    /// With I-DATA the message is named by its U bit and Message Identifier, and with DATA an
761    /// ordered one by its Stream Sequence Number. An unordered DATA message has no number of
762    /// its own, so a fragment belongs to it when it is the next TSN after the fragments it
763    /// holds (RFC 9260 6.9: a message's fragments have consecutive TSNs) and does not begin
764    /// a message; the fragments after it that are already held join it.
765    fn push_to_partial(&mut self, chunk: ChunkPayloadData) -> Option<ChunkPayloadData> {
766        let Some(p) = self.partial.as_mut() else {
767            return Some(chunk);
768        };
769        let len = chunk.user_data.len();
770        let next = p.set.next_part.unwrap_or_default();
771        if self.interleaved {
772            if chunk.unordered != p.unordered || chunk.mid != p.set.mid {
773                return Some(chunk);
774            }
775            if sna32gte(chunk.fsn, next) && p.set.insert_fragment(chunk) {
776                self.n_bytes += len;
777            }
778            return None;
779        }
780        if !p.unordered {
781            if chunk.unordered || chunk.stream_sequence_number != p.set.ssn {
782                return Some(chunk);
783            }
784            let before = p.set.chunks.len();
785            if sna32gte(chunk.tsn, next) {
786                p.set.push(chunk);
787            }
788            if p.set.chunks.len() > before {
789                self.n_bytes += len;
790            }
791            return None;
792        }
793        if !chunk.unordered || chunk.beginning_fragment || p.set.expected_tail() != Some(chunk.tsn)
794        {
795            return Some(chunk);
796        }
797        p.set.chunks.push(chunk);
798        self.n_bytes += len;
799        // The fragments after it may have come first.
800        while let Some(tsn) = p.set.expected_tail() {
801            let idx = self
802                .unordered_chunks
803                .partition_point(|c| sna32lt(c.tsn, tsn));
804            if self
805                .unordered_chunks
806                .get(idx)
807                .is_none_or(|c| c.tsn != tsn || c.beginning_fragment)
808            {
809                break;
810            }
811            let c = self.unordered_chunks.remove(idx);
812            if c.ending_fragment {
813                let i = self.unordered_ends.partition_point(|&t| sna32lt(t, tsn));
814                if self.unordered_ends.get(i) == Some(&tsn) {
815                    self.unordered_ends.remove(i);
816                }
817            }
818            p.set.chunks.push(c);
819        }
820        None
821    }
822
823    /// Takes out the complete message that holds the fragment with `tsn`, if there is one.
824    ///
825    /// Every complete message is taken out as soon as its last fragment arrives, so a new
826    /// fragment can complete only the message it belongs to: the one from the nearest
827    /// beginning fragment at or before it to the nearest ending fragment at or after it, if
828    /// the TSNs between them are all held. Each step is a binary search, so a peer sending
829    /// many fragments that never complete costs no rescan of what is already held.
830    pub(crate) fn find_complete_unordered_chunk_set(&mut self, tsn: u32) -> Option<Chunks> {
831        let bi = self.unordered_begins.partition_point(|&t| sna32lte(t, tsn));
832        if bi == 0 {
833            return None;
834        }
835        let begin_tsn = self.unordered_begins[bi - 1];
836        let ei = self.unordered_ends.partition_point(|&t| sna32lt(t, tsn));
837        if ei == self.unordered_ends.len() {
838            return None;
839        }
840        let end_tsn = self.unordered_ends[ei];
841
842        let start_idx = self
843            .unordered_chunks
844            .partition_point(|c| sna32lt(c.tsn, begin_tsn));
845        let end_idx = self
846            .unordered_chunks
847            .partition_point(|c| sna32lt(c.tsn, end_tsn));
848        if end_idx >= self.unordered_chunks.len()
849            || self.unordered_chunks[start_idx].tsn != begin_tsn
850            || self.unordered_chunks[end_idx].tsn != end_tsn
851            || !contiguous_span(begin_tsn, end_tsn, end_idx - start_idx + 1)
852        {
853            return None;
854        }
855
856        // Extract the range of chunks
857        self.unordered_begins.remove(bi - 1);
858        self.unordered_ends.remove(ei);
859        let chunks: Vec<ChunkPayloadData> =
860            self.unordered_chunks.drain(start_idx..=end_idx).collect();
861        let arrival = self.next_arrival;
862        self.next_arrival += 1;
863        Some(Chunks::new(arrival, 0, chunks[0].payload_type, chunks))
864    }
865
866    pub(crate) fn is_readable(&self) -> bool {
867        // No other message of a stream is read while one is in partial delivery (RFC 6458
868        // 3.1.4, 8.1.20).
869        if self.partial.is_some() {
870            return false;
871        }
872        // Check unordered first
873        if !self.unordered.is_empty() {
874            // The chunk sets in self.unordered should all be complete.
875            return true;
876        }
877
878        // Check ordered sets
879        if !self.ordered.is_empty() {
880            let cset = &self.ordered[0];
881            if cset.is_complete() && self.is_due(cset) {
882                return true;
883            }
884        }
885        false
886    }
887
888    fn readable_unordered_chunks(&self) -> Option<&Chunks> {
889        self.unordered.front()
890    }
891
892    fn readable_ordered_chunks(&self) -> Option<&Chunks> {
893        let ordered = self.ordered.front();
894        if let Some(chunks) = ordered {
895            if !chunks.is_complete() {
896                return None;
897            }
898            if !self.is_due(chunks) {
899                return None;
900            }
901            Some(chunks)
902        } else {
903            None
904        }
905    }
906
907    pub(crate) fn read(&mut self) -> Option<Chunks> {
908        if self.partial.is_some() {
909            return None;
910        }
911        let chunks = if let (Some(unordered_chunks), Some(ordered_chunks)) = (
912            self.readable_unordered_chunks(),
913            self.readable_ordered_chunks(),
914        ) {
915            if unordered_chunks.arrival < ordered_chunks.arrival {
916                self.unordered.pop_front().unwrap()
917            } else {
918                let (ssn, mid) = (ordered_chunks.ssn, ordered_chunks.mid);
919                self.delivered(ssn, mid);
920                self.ordered.pop_front().unwrap()
921            }
922        } else {
923            // Check unordered first
924            if !self.unordered.is_empty() {
925                self.unordered.pop_front().unwrap()
926            } else if !self.ordered.is_empty() {
927                // Now, check ordered
928                let chunks = &self.ordered[0];
929                if !chunks.is_complete() {
930                    return None;
931                }
932                if !self.is_due(chunks) {
933                    return None;
934                }
935                let (ssn, mid) = (chunks.ssn, chunks.mid);
936                self.delivered(ssn, mid);
937                self.ordered.pop_front().unwrap()
938            } else {
939                return None;
940            }
941        };
942
943        self.subtract_num_bytes(chunks.len());
944
945        Some(chunks)
946    }
947
948    /// Use last_ssn to locate a chunkSet then remove it if the set has
949    /// not been complete
950    pub(crate) fn forward_tsn_for_ordered(&mut self, last_ssn: u16) {
951        self.forward_passes += 1;
952        if self.partial.as_ref().is_some_and(|p| {
953            !p.unordered && sna16lte(p.set.ssn, last_ssn) && !p.set.remaining_complete()
954        }) {
955            self.abort_partial();
956        }
957        let num_bytes = self
958            .ordered
959            .iter()
960            .filter(|s| sna16lte(s.ssn, last_ssn) && !s.is_complete())
961            .fold(0, |n, s| {
962                n + s.chunks.iter().fold(0, |acc, c| acc + c.user_data.len())
963            });
964        self.subtract_num_bytes(num_bytes);
965
966        self.ordered
967            .retain(|s| !sna16lte(s.ssn, last_ssn) || s.is_complete());
968
969        // Finally, forward next_ssn
970        if sna16lte(self.next_ssn, last_ssn) {
971            self.next_ssn = last_ssn.wrapping_add(1);
972        }
973    }
974
975    /// Remove all fragments in the unordered sets that contains chunks
976    /// equal to or older than `new_cumulative_tsn`.
977    /// We know all sets in the r.unordered are complete ones.
978    /// Just remove chunks that are equal to or older than new_cumulative_tsn
979    /// from the unordered_chunks
980    pub(crate) fn forward_tsn_for_unordered(&mut self, new_cumulative_tsn: u32) {
981        // RFC 3758 3.6: the fragment the unordered message in partial delivery needs next is
982        // skipped (were it received, it would be with the message), so it will not be
983        // completed.
984        if self.partial.as_ref().is_some_and(|p| {
985            p.unordered
986                && !p.set.by_fsn
987                && p.set
988                    .expected_tail()
989                    .is_some_and(|tsn| sna32lte(tsn, new_cumulative_tsn))
990        }) {
991            self.abort_partial();
992        }
993        let mut last_idx: isize = -1;
994        for (i, c) in self.unordered_chunks.iter().enumerate() {
995            if sna32gt(c.tsn, new_cumulative_tsn) {
996                break;
997            }
998            last_idx = i as isize;
999        }
1000        if last_idx >= 0 {
1001            for i in 0..(last_idx + 1) as usize {
1002                self.subtract_num_bytes(self.unordered_chunks[i].user_data.len());
1003            }
1004            self.unordered_chunks.drain(..(last_idx + 1) as usize);
1005        }
1006        let n = self
1007            .unordered_begins
1008            .partition_point(|&t| sna32lte(t, new_cumulative_tsn));
1009        self.unordered_begins.drain(..n);
1010        let n = self
1011            .unordered_ends
1012            .partition_point(|&t| sna32lte(t, new_cumulative_tsn));
1013        self.unordered_ends.drain(..n);
1014    }
1015
1016    /// RFC 6525 5.2.4 G4, G5 and 5.2.7 H5: the TSNs and Stream Sequence Numbers start over.
1017    /// As after a FORWARD TSN past everything received, the messages that are complete are
1018    /// delivered, in their order, and the fragments of the others are dropped; the next
1019    /// ordered message expected has sequence number 0.
1020    pub(crate) fn reset_sequence_numbers(&mut self) {
1021        if self
1022            .partial
1023            .as_ref()
1024            .is_some_and(|p| !p.set.remaining_complete())
1025        {
1026            self.abort_partial();
1027        }
1028        let mut dropped = 0;
1029        for set in std::mem::take(&mut self.ordered) {
1030            if set.is_complete() {
1031                // Readable whatever its number: the numbers before it will not come.
1032                self.unordered.push_back(set);
1033            } else {
1034                dropped += set.len();
1035            }
1036        }
1037        dropped += self
1038            .unordered_chunks
1039            .drain(..)
1040            .map(|c| c.user_data.len())
1041            .sum::<usize>();
1042        dropped += self
1043            .unordered_partial
1044            .drain(..)
1045            .map(|s| s.len())
1046            .sum::<usize>();
1047        self.unordered_begins.clear();
1048        self.unordered_ends.clear();
1049        self.subtract_num_bytes(dropped);
1050        self.next_ssn = 0;
1051        self.next_mid = 0;
1052    }
1053
1054    /// Drops the fragments that can never be part of a complete message, `cumulative_tsn`
1055    /// being the receiver's cumulative TSN, and returns how many fragments were dropped.
1056    ///
1057    /// A message's first fragment has the B bit and the lowest TSN of the message: with DATA
1058    /// its fragments take consecutive TSNs (RFC 9260 6.9, step 2), with I-DATA they are sent in
1059    /// Fragment Sequence Number order, each with a TSN above the one before (RFC 8260 2.1).
1060    /// So a fragment that does not begin a message, when every TSN below it has been received
1061    /// and none of them is held with it, belongs to a message whose start went somewhere else:
1062    /// nothing that can still arrive completes it. A peer that resets a stream before the
1063    /// message it is sending on it has all its TSNs sends exactly that: the rest of the message
1064    /// comes after the reset's Sender's Last Assigned TSN, and RFC 6525 5.2.2 E2/E4 makes it
1065    /// data of the stream as it is after the reset. Kept, such fragments would sit in front of
1066    /// the messages of whatever uses the stream next: the next message with the same Stream
1067    /// Sequence Number (or Message Identifier) would be put together with them and never
1068    /// complete, and every ordered message after it would wait behind it for good, all of
1069    /// them acknowledged.
1070    ///
1071    /// The message in partial delivery is not looked at: its earlier fragments were read.
1072    pub(crate) fn discard_orphans(&mut self, cumulative_tsn: u32) -> usize {
1073        // Every TSN below `tsn` has been received (or skipped by a FORWARD TSN).
1074        let below_received = |tsn: u32| sna32lte(tsn.wrapping_sub(1), cumulative_tsn);
1075        let mut dropped_bytes = 0;
1076        let mut dropped = 0;
1077
1078        if self.interleaved {
1079            // One set is one message (one Message Identifier): its fragment with the lowest
1080            // FSN is the earliest sent of those held. Without the B bit, and with every TSN
1081            // below it received, the first fragment went elsewhere.
1082            let orphaned = |s: &Chunks| {
1083                s.next_part.is_none()
1084                    && s.chunks
1085                        .first()
1086                        .is_some_and(|c| !c.beginning_fragment && below_received(c.tsn))
1087            };
1088            self.unordered_partial.retain(|s| {
1089                let keep = !orphaned(s);
1090                if !keep {
1091                    dropped += s.chunks.len();
1092                    dropped_bytes += s.len();
1093                }
1094                keep
1095            });
1096            self.ordered.retain(|s| {
1097                let keep = !orphaned(s);
1098                if !keep {
1099                    dropped += s.chunks.len();
1100                    dropped_bytes += s.len();
1101                }
1102                keep
1103            });
1104        } else {
1105            // Ordered: a set holds the fragments with one Stream Sequence Number, and may hold
1106            // the orphaned rest of an earlier message that had the same number in front of a
1107            // later message's fragments. Its leading fragments up to the first B bit go when
1108            // the TSN before the first of them has been received: it is not in the set.
1109            for set in self.ordered.iter_mut() {
1110                if set.next_part.is_some() {
1111                    continue;
1112                }
1113                let Some(first) = set.chunks.first() else {
1114                    continue;
1115                };
1116                if first.beginning_fragment || !below_received(first.tsn) {
1117                    continue;
1118                }
1119                let n = set
1120                    .chunks
1121                    .iter()
1122                    .position(|c| c.beginning_fragment)
1123                    .unwrap_or(set.chunks.len());
1124                for c in set.chunks.drain(..n) {
1125                    dropped += 1;
1126                    dropped_bytes += c.user_data.len();
1127                }
1128                if let Some(c) = set.chunks.first() {
1129                    // What is left is another message: its own protocol identifier.
1130                    set.ppi = c.payload_type;
1131                    set.ppid = c.ppid();
1132                }
1133            }
1134            self.ordered.retain(|s| !s.chunks.is_empty());
1135
1136            // Unordered: a fragment without the B bit whose TSN before it was received and is
1137            // not held here, or was itself dropped as an orphan, and the fragments that follow
1138            // it without a gap or a B bit.
1139            let mut prev_kept: Option<u32> = None;
1140            let mut prev_dropped: Option<u32> = None;
1141            let mut drop_tsns = vec![];
1142            for c in &self.unordered_chunks {
1143                let before = c.tsn.wrapping_sub(1);
1144                let orphan = !c.beginning_fragment
1145                    && (prev_dropped == Some(before)
1146                        || (prev_kept != Some(before) && below_received(c.tsn)));
1147                if orphan {
1148                    drop_tsns.push(c.tsn);
1149                    prev_dropped = Some(c.tsn);
1150                } else {
1151                    prev_kept = Some(c.tsn);
1152                }
1153            }
1154            if !drop_tsns.is_empty() {
1155                let mut i = 0;
1156                self.unordered_chunks.retain(|c| {
1157                    if drop_tsns.get(i) == Some(&c.tsn) {
1158                        i += 1;
1159                        dropped += 1;
1160                        dropped_bytes += c.user_data.len();
1161                        false
1162                    } else {
1163                        true
1164                    }
1165                });
1166                self.unordered_ends.retain(|t| !drop_tsns.contains(t));
1167            }
1168        }
1169        self.subtract_num_bytes(dropped_bytes);
1170        self.orphans_dropped += dropped;
1171        dropped
1172    }
1173
1174    /// Where the chunk with `tsn` is held for reordering, if it is: in a message that is not
1175    /// readable whole (incomplete, or complete but not the next ordered message) and not in
1176    /// partial delivery (RFC 9260 6.9). A chunk of a message the application can read now,
1177    /// or has read part of, is not.
1178    fn held_for_reordering(&self, tsn: u32) -> Option<HeldAt> {
1179        let at = |chunks: &[ChunkPayloadData]| {
1180            let i = chunks.partition_point(|c| sna32lt(c.tsn, tsn));
1181            (chunks.get(i).is_some_and(|c| c.tsn == tsn)).then_some(i)
1182        };
1183        for (set, s) in self.ordered.iter().enumerate() {
1184            // With I-DATA the fragments are in FSN order, which is their TSN order too: the
1185            // sender numbers a message's fragments in sequence (RFC 8260 2.1).
1186            if let Some(chunk) = at(&s.chunks) {
1187                let readable = set == 0 && s.is_complete() && self.is_due(s);
1188                return (!readable && s.next_part.is_none())
1189                    .then_some(HeldAt::Ordered { set, chunk });
1190            }
1191        }
1192        if let Some(chunk) = at(&self.unordered_chunks) {
1193            return Some(HeldAt::Unordered { chunk });
1194        }
1195        for (set, s) in self.unordered_partial.iter().enumerate() {
1196            if let Some(chunk) = at(&s.chunks) {
1197                return Some(HeldAt::UnorderedInterleaved { set, chunk });
1198            }
1199        }
1200        None
1201    }
1202
1203    /// Whether the chunk with `tsn` is held for reordering (see `held_for_reordering`).
1204    pub(crate) fn is_held_for_reordering(&self, tsn: u32) -> bool {
1205        self.held_for_reordering(tsn).is_some()
1206    }
1207
1208    /// Drops the chunk with `tsn` if it is held for reordering (see `held_for_reordering`):
1209    /// RFC 9260 6.2, a receiver whose window is closed dropping "the largest TSN held for
1210    /// reordering" to take a chunk that fills a gap. Returns its user data's length.
1211    pub(crate) fn remove_held(&mut self, tsn: u32) -> Option<usize> {
1212        let chunk = match self.held_for_reordering(tsn)? {
1213            HeldAt::Ordered { set, chunk } => {
1214                let c = self.ordered[set].chunks.remove(chunk);
1215                if self.ordered[set].chunks.is_empty() {
1216                    self.ordered.remove(set);
1217                }
1218                c
1219            }
1220            HeldAt::Unordered { chunk } => {
1221                let c = self.unordered_chunks.remove(chunk);
1222                if c.beginning_fragment
1223                    && let Some(i) = self.unordered_begins.iter().position(|&t| t == tsn)
1224                {
1225                    self.unordered_begins.remove(i);
1226                }
1227                if c.ending_fragment
1228                    && let Some(i) = self.unordered_ends.iter().position(|&t| t == tsn)
1229                {
1230                    self.unordered_ends.remove(i);
1231                }
1232                c
1233            }
1234            HeldAt::UnorderedInterleaved { set, chunk } => {
1235                let c = self.unordered_partial[set].chunks.remove(chunk);
1236                if self.unordered_partial[set].chunks.is_empty() {
1237                    self.unordered_partial.remove(set);
1238                }
1239                c
1240            }
1241        };
1242        let n = chunk.user_data.len();
1243        self.subtract_num_bytes(n);
1244        Some(n)
1245    }
1246
1247    pub(crate) fn subtract_num_bytes(&mut self, n_bytes: usize) {
1248        if self.n_bytes >= n_bytes {
1249            self.n_bytes -= n_bytes;
1250        } else {
1251            self.n_bytes = 0;
1252        }
1253    }
1254
1255    pub(crate) fn get_num_bytes(&self) -> usize {
1256        self.n_bytes
1257    }
1258
1259    /// Ends the partial delivery under way without its last part, dropping what is held of it.
1260    fn abort_partial(&mut self) {
1261        if let Some(p) = self.partial.take() {
1262            self.subtract_num_bytes(p.set.len());
1263            self.partial_aborted = Some(PartialAbort {
1264                unordered: p.unordered,
1265                sequence: if p.set.by_fsn {
1266                    p.set.mid
1267                } else {
1268                    u32::from(p.set.ssn)
1269                },
1270            });
1271        }
1272    }
1273
1274    /// The partial delivery that ended without its last part since the last call, if one did.
1275    pub(crate) fn take_partial_abort(&mut self) -> Option<PartialAbort> {
1276        self.partial_aborted.take()
1277    }
1278
1279    /// Whether a message of this stream is in partial delivery.
1280    pub(crate) fn in_partial_delivery(&self) -> bool {
1281        self.partial.is_some()
1282    }
1283
1284    /// Whether the queue holds a message the application has not read all of and that is all
1285    /// here: a complete message that is readable, or the rest of the one in partial delivery.
1286    pub(crate) fn holds_whole_message(&self) -> bool {
1287        self.is_readable()
1288            || self
1289                .partial
1290                .as_ref()
1291                .is_some_and(|p| p.set.remaining_complete())
1292    }
1293
1294    /// The message that can start delivering in parts: one whose fragments from the first
1295    /// on, without a gap, come to `threshold` bytes or more. Ordered, only the one that is
1296    /// due (the next Stream Sequence Number or Message Identifier); unordered, the first such.
1297    fn part_candidate(&self, threshold: usize) -> Option<PartCandidate> {
1298        if let Some(set) = self.ordered.front()
1299            && self.is_due(set)
1300            && set
1301                .leading_run()
1302                .is_some_and(|(_, bytes, ends)| !ends && bytes >= threshold)
1303        {
1304            return Some(PartCandidate::Ordered);
1305        }
1306        if let Some(i) = self.unordered_partial.iter().position(|set| {
1307            set.leading_run()
1308                .is_some_and(|(_, bytes, ends)| !ends && bytes >= threshold)
1309        }) {
1310            return Some(PartCandidate::UnorderedInterleaved(i));
1311        }
1312        for &begin in &self.unordered_begins {
1313            let start = self
1314                .unordered_chunks
1315                .partition_point(|c| sna32lt(c.tsn, begin));
1316            let mut bytes = 0;
1317            for (i, c) in self.unordered_chunks[start..].iter().enumerate() {
1318                if c.tsn != begin.wrapping_add(i as u32)
1319                    || (i > 0 && c.beginning_fragment)
1320                    || c.ending_fragment
1321                {
1322                    break;
1323                }
1324                bytes += c.user_data.len();
1325            }
1326            if bytes >= threshold && bytes > 0 {
1327                return Some(PartCandidate::UnorderedData(start));
1328            }
1329        }
1330        None
1331    }
1332
1333    /// Whether [`read_part`](Self::read_part) with this `threshold` has something to return.
1334    pub(crate) fn part_readable(&self, threshold: usize) -> bool {
1335        match &self.partial {
1336            Some(p) => p.set.leading_run().is_some(),
1337            None => self.is_readable() || self.part_candidate(threshold.max(1)).is_some(),
1338        }
1339    }
1340
1341    /// RFC 9260 6.9, the partial delivery API: the next part of a message on this stream.
1342    ///
1343    /// While a message is in partial delivery, the fragments of it that follow the last part
1344    /// read without a gap. Otherwise a complete message, whole, as [`read`](Self::read) gives
1345    /// it; and failing that the first fragments of a message that come to `threshold` bytes
1346    /// (the partial delivery point, RFC 6458 8.1.21), which puts it in partial delivery.
1347    pub(crate) fn read_part(&mut self, threshold: usize) -> Option<MessagePart> {
1348        if let Some(p) = self.partial.as_mut() {
1349            let (taken, ends) = p.set.take_leading()?;
1350            let chunks = p.set.part(taken);
1351            let unordered = p.unordered;
1352            if ends {
1353                self.partial = None;
1354            }
1355            self.subtract_num_bytes(chunks.len());
1356            return Some(MessagePart {
1357                chunks,
1358                unordered,
1359                first: false,
1360                end_of_record: ends,
1361            });
1362        }
1363        if self.is_readable() {
1364            let chunks = self.read()?;
1365            let unordered = chunks.chunks.first().is_some_and(|c| c.unordered);
1366            return Some(MessagePart {
1367                chunks,
1368                unordered,
1369                first: true,
1370                end_of_record: true,
1371            });
1372        }
1373        let (mut set, unordered) = match self.part_candidate(threshold.max(1))? {
1374            PartCandidate::Ordered => {
1375                let set = self.ordered.pop_front()?;
1376                // The messages after it are due once it ends.
1377                self.delivered(set.ssn, set.mid);
1378                (set, false)
1379            }
1380            PartCandidate::UnorderedInterleaved(i) => (self.unordered_partial.remove(i), true),
1381            PartCandidate::UnorderedData(start) => {
1382                let begin = self.unordered_chunks[start].tsn;
1383                let mut end = start;
1384                while self.unordered_chunks.get(end + 1).is_some_and(|c| {
1385                    c.tsn == begin.wrapping_add((end + 1 - start) as u32)
1386                        && !c.beginning_fragment
1387                        && !c.ending_fragment
1388                }) {
1389                    end += 1;
1390                }
1391                let run: Vec<ChunkPayloadData> = self.unordered_chunks.drain(start..=end).collect();
1392                let bi = self
1393                    .unordered_begins
1394                    .partition_point(|&t| sna32lt(t, begin));
1395                if self.unordered_begins.get(bi) == Some(&begin) {
1396                    self.unordered_begins.remove(bi);
1397                }
1398                let arrival = self.next_arrival;
1399                self.next_arrival += 1;
1400                (Chunks::new(arrival, 0, run[0].payload_type, run), true)
1401            }
1402        };
1403        let (taken, ends) = set.take_leading()?;
1404        let chunks = set.part(taken);
1405        self.subtract_num_bytes(chunks.len());
1406        if !ends {
1407            self.partial = Some(Partial { set, unordered });
1408        }
1409        Some(MessagePart {
1410            chunks,
1411            unordered,
1412            first: true,
1413            end_of_record: ends,
1414        })
1415    }
1416
1417    /// Whether the queue holds no fragment and no message, and no message is in partial
1418    /// delivery (one whose next fragment is still to come has to hear of a FORWARD TSN).
1419    pub(crate) fn is_empty(&self) -> bool {
1420        self.n_bytes == 0
1421            && self.partial.is_none()
1422            && self.ordered.is_empty()
1423            && self.unordered.is_empty()
1424            && self.unordered_chunks.is_empty()
1425            && self.unordered_partial.is_empty()
1426    }
1427}