Skip to main content

moq_net/model/
frame.rs

1//! Frames are the leaf of the model: a sized, optionally timestamped payload within a group.
2//!
3//! A group is a single ordered stream, so at most one frame is ever in flight.
4//! Completed frames are plain data ([`Frame`]); the in-flight frame is written
5//! through [`Producer`], which borrows its parent [`group::Producer`] exclusively so
6//! the borrow checker enforces that only one frame is open at a time. A [`Consumer`]
7//! reads one frame, sharing the group's channel rather than a per-frame one.
8use std::mem::MaybeUninit;
9use std::ops::Range;
10use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
11use std::sync::{Arc, Weak};
12use std::sync::{Mutex, OnceLock, PoisonError};
13use std::task::{Poll, ready};
14
15#[cfg(any(test, feature = "fuzz"))]
16use arrayvec::ArrayVec;
17use bytes::{Buf, Bytes, BytesMut};
18
19use crate::cache;
20use crate::group::{self, GroupState};
21use crate::time::Instant;
22use crate::{Error, IntoBytes, Result, Timestamp, stats};
23
24/// A chunk of data with an upfront size and an optional presentation timestamp.
25///
26/// This is just the header; the payload is carried separately (as a completed
27/// [`Frame`] or streamed via [`Producer`] / [`Consumer`]).
28#[derive(Clone, Copy, Debug)]
29pub struct Info {
30	/// Total payload size in bytes. Declared up front so consumers can preallocate.
31	pub size: u64,
32	/// Presentation timestamp, or on a scale-less track [`Timestamp::unscaled`] at its
33	/// group's key. It must match the track ([`Error::TimestampMismatch`] otherwise).
34	///
35	/// [`group::Producer::create_frame`] converts it into the parent track's
36	/// timescale, so the scale you build it with doesn't have to match the track.
37	pub timestamp: Timestamp,
38}
39
40/// A completed frame: an optional timestamp, its full, contiguous payload, and when it
41/// was created in this node's cache.
42///
43/// Reading a frame whole is a zero-copy slice of what its group stores, except for a
44/// frame larger than a storage segment that arrived in pieces: the group keeps that as
45/// separate segments, so a whole read copies them into one buffer. Streaming it through
46/// [`Consumer::poll_read_chunk`] hands out each segment without a copy.
47#[derive(Clone, Debug)]
48pub struct Frame {
49	/// Presentation timestamp, at the parent track's timescale, or on a scale-less track
50	/// [`Timestamp::unscaled`] at its group's key.
51	pub timestamp: Timestamp,
52	/// The full frame payload.
53	pub payload: Bytes,
54	/// When the frame was created in this node's cache, as its last byte landed, on the
55	/// ambient clock; writing the frame to a group replaces any value set here.
56	pub created: Instant,
57}
58
59impl Frame {
60	/// A frame of `payload` presented at `timestamp`, or on a scale-less track at
61	/// [`Timestamp::unscaled`] of its group's key.
62	pub fn new(timestamp: Timestamp, payload: impl IntoBytes) -> Self {
63		Self {
64			timestamp,
65			payload: payload.into_bytes(),
66			// Stamped when written to a group, so building one never reads the clock.
67			created: Instant::ZERO,
68		}
69	}
70}
71
72/// Bytes in each sealed segment of a frame larger than one.
73///
74/// A frame within one segment is stored as a single buffer. A larger one that arrives in
75/// pieces is a chain of segments of exactly this size, the last shorter, so segment `i`
76/// always holds the frame's bytes from `i * SEGMENT`. Receiving it allocates at most one
77/// segment ahead of what arrived, and returns each segment's receive credit as it seals,
78/// so a connection window only has to fit a segment rather than a frame.
79///
80/// Sized from `benches/frame.rs`: smaller segments cost allocations per byte, and larger
81/// ones a bigger allocation and credit held ahead of the bytes. Most media frames fit in
82/// one, so a whole read of them never copies.
83pub(crate) const SEGMENT: usize = 1024 * 1024;
84
85/// `len` test bytes counting up from `seed` modulo 251, a prime, so the pattern never
86/// lines up with a [`SEGMENT`] and a segment out of place shows. Repeated rather than
87/// generated byte by byte, which takes Miri minutes for a few segments.
88#[cfg(test)]
89pub(crate) fn pattern(seed: usize, len: usize) -> Vec<u8> {
90	let period: Vec<u8> = (0..251).map(|i| ((seed + i) % 251) as u8).collect();
91	let mut bytes = period.repeat(len.div_ceil(period.len()));
92	bytes.truncate(len);
93	bytes
94}
95
96/// A completed frame's payload as its group stores it: one buffer, or the sealed
97/// segments of a frame larger than [`SEGMENT`] written in pieces.
98///
99/// A view, like [`Bytes`]: reading it as a [`Buf`] moves this copy past bytes, never the
100/// stored one.
101#[derive(Clone, Debug)]
102pub(crate) enum Payload {
103	Whole(Bytes),
104	Chain(Chain),
105}
106
107/// A frame's sealed segments, read from `start`.
108#[derive(Clone, Debug)]
109pub(crate) struct Chain {
110	// Each [`SEGMENT`] long but the last, and never empty.
111	segments: Arc<[Bytes]>,
112	// The frame offset this view starts at.
113	start: usize,
114}
115
116impl Chain {
117	/// The bytes from `start` to the end.
118	pub fn len(&self) -> usize {
119		self.end() - self.start
120	}
121
122	/// The whole chain copied into one buffer.
123	#[cold]
124	#[inline(never)]
125	pub fn concat(self) -> Bytes {
126		Payload::Chain(self).contiguous(0)
127	}
128
129	/// The frame's length, past which nothing is stored.
130	fn end(&self) -> usize {
131		let last = self.segments.last().map_or(0, Bytes::len);
132		self.segments.len().saturating_sub(1) * SEGMENT + last
133	}
134
135	/// The stored bytes from frame offset `at` to the end of its segment, zero-copy.
136	fn segment_at(&self, at: usize) -> Bytes {
137		let index = at / SEGMENT;
138		match self.segments.get(index) {
139			Some(segment) => segment.slice(at - index * SEGMENT..),
140			None => Bytes::new(),
141		}
142	}
143}
144
145// A chain costs a cached frame nothing over the one buffer it holds otherwise.
146const _: () = assert!(size_of::<Payload>() == size_of::<Bytes>());
147
148impl Default for Payload {
149	fn default() -> Self {
150		Self::Whole(Bytes::new())
151	}
152}
153
154impl From<Bytes> for Payload {
155	fn from(bytes: Bytes) -> Self {
156		Self::Whole(bytes)
157	}
158}
159
160impl Payload {
161	pub fn len(&self) -> usize {
162		match self {
163			Self::Whole(bytes) => bytes.len(),
164			Self::Chain(chain) => chain.len(),
165		}
166	}
167
168	#[cfg(feature = "async")]
169	pub fn is_empty(&self) -> bool {
170		self.len() == 0
171	}
172
173	/// The bytes from `offset` to the end of the segment holding it, zero-copy.
174	pub fn chunk_at(&self, offset: usize) -> Bytes {
175		match self {
176			Self::Whole(bytes) => bytes.slice(offset..),
177			Self::Chain(chain) => chain.segment_at(chain.start + offset),
178		}
179	}
180
181	/// The bytes from `offset` on in one buffer, copied only when they span segments.
182	pub fn contiguous(&self, offset: usize) -> Bytes {
183		let len = self.len();
184		let first = self.chunk_at(offset);
185		if offset + first.len() >= len {
186			return first;
187		}
188		let mut out = BytesMut::with_capacity(len - offset);
189		let mut at = offset;
190		while at < len {
191			let chunk = self.chunk_at(at);
192			at += chunk.len();
193			out.extend_from_slice(&chunk);
194		}
195		out.freeze()
196	}
197}
198
199impl Buf for Payload {
200	fn remaining(&self) -> usize {
201		self.len()
202	}
203
204	fn chunk(&self) -> &[u8] {
205		match self {
206			Self::Whole(bytes) => bytes,
207			Self::Chain(chain) => {
208				let index = chain.start / SEGMENT;
209				chain
210					.segments
211					.get(index)
212					.map_or(&[], |segment| &segment[chain.start - index * SEGMENT..])
213			}
214		}
215	}
216
217	fn advance(&mut self, cnt: usize) {
218		assert!(cnt <= self.len(), "advance past the end of a payload");
219		match self {
220			Self::Whole(bytes) => bytes.advance(cnt),
221			Self::Chain(chain) => chain.start += cnt,
222		}
223	}
224
225	// Zero-copy within a segment, which is what a transport taking `chunk()` asks for.
226	fn copy_to_bytes(&mut self, len: usize) -> Bytes {
227		let chunk = self.chunk_at(0);
228		let out = match len <= chunk.len() {
229			true => chunk.slice(..len),
230			false => self.contiguous(0).slice(..len),
231		};
232		self.advance(len);
233		out
234	}
235}
236
237/// A completed frame as its group stores it.
238#[derive(Clone, Debug)]
239pub(crate) struct Cached {
240	pub timestamp: Timestamp,
241	pub payload: Payload,
242	// When the frame's last byte landed in this node's cache; see [`Frame::created`].
243	pub created: Instant,
244}
245
246impl From<Frame> for Cached {
247	fn from(frame: Frame) -> Self {
248		Self {
249			timestamp: frame.timestamp,
250			payload: Payload::Whole(frame.payload),
251			created: frame.created,
252		}
253	}
254}
255
256/// A frame with the relay metadata its group keeps beside it, read only by wire egress.
257#[cfg(feature = "async")]
258#[derive(Clone, Debug)]
259pub(crate) struct Object {
260	pub frame: Cached,
261	pub fields: Option<Arc<super::object::Fields>>,
262	/// The inflated size of a compressed frame read in its stored form (see
263	/// [`group::Consumer::compressed`]), whose `payload` is then the DEFLATE slice.
264	pub inflated: Option<u64>,
265}
266
267#[cfg(feature = "async")]
268impl std::ops::Deref for Object {
269	type Target = Cached;
270	fn deref(&self) -> &Self::Target {
271		&self.frame
272	}
273}
274
275/// A streamed frame's private header, alongside the unchanged public header.
276pub(crate) struct Header {
277	pub info: Info,
278	pub fields: Option<Arc<super::object::Fields>>,
279	/// A received compressed frame's inflated size: `info.size` is then its DEFLATE
280	/// slice's. `None` for a plain frame, or one a local producer compresses itself.
281	pub inflated: Option<u64>,
282}
283
284impl From<Info> for Header {
285	fn from(info: Info) -> Self {
286		Self {
287			info,
288			fields: None,
289			inflated: None,
290		}
291	}
292}
293
294/// A reusable batch of frames, filled by [`group::Consumer::poll_read_frames`] and drained
295/// by [`group::Producer::write_frames`].
296///
297/// A fixed-capacity inline buffer: `N` frames of stack storage, never a heap
298/// allocation and never a spill. Allocate one per task and reuse it for the life of
299/// the group rather than one per read.
300///
301/// `N` defaults to 8. Most reads are not big batches: at the live edge a frame arrives
302/// at a time, so the capacity past the first frame or two is idle stack, and a
303/// publisher holds one buffer per in-flight group. 8 costs 448 bytes and still reads
304/// ~5x faster than a frame at a time (`benches/group.rs`). Ask for a larger `N` when
305/// you know you are draining a backlog: 32 is ~8x, for 1.75 KB.
306///
307/// A default on a const parameter only applies in type position, so name the type to
308/// get it: `let buf: frame::Buffer = Buffer::new()`.
309///
310/// A fill stamps the group's cache access once for the whole batch, which bounds
311/// frames rather than elapsed time. A reader that may take longer than the track's
312/// `max_age` to work through one batch calls
313/// [`group::Consumer::keep_alive`] between frames, or the rest of the group is
314/// expired out from under it.
315#[cfg(any(test, feature = "fuzz"))]
316#[derive(Debug, Default)]
317pub(crate) struct Buffer<const N: usize = 8>(ArrayVec<Frame, N>);
318
319#[cfg(any(test, feature = "fuzz"))]
320impl<const N: usize> Buffer<N> {
321	/// An empty buffer with room for `N` frames.
322	pub fn new() -> Self {
323		Self(ArrayVec::new())
324	}
325
326	/// How many frames a single fill can hold.
327	#[cfg(feature = "async")]
328	pub const fn capacity(&self) -> usize {
329		N
330	}
331
332	/// How many frames the buffer currently holds.
333	pub fn len(&self) -> usize {
334		self.0.len()
335	}
336
337	/// Whether the buffer holds no frames.
338	#[cfg(feature = "async")]
339	pub fn is_empty(&self) -> bool {
340		self.0.is_empty()
341	}
342
343	/// Whether the buffer is at capacity, so [`Self::push`] would refuse.
344	#[cfg(feature = "async")]
345	pub(crate) fn is_full(&self) -> bool {
346		self.0.is_full()
347	}
348
349	/// The frames from the most recent fill, in order.
350	pub fn filled(&self) -> &[Frame] {
351		&self.0
352	}
353
354	/// The frames from the most recent fill, mutably, for the batch a read hands back.
355	#[cfg(feature = "async")]
356	pub(crate) fn filled_mut(&mut self) -> &mut [Frame] {
357		&mut self.0
358	}
359
360	/// Append a frame, handing it back if the buffer is already full.
361	///
362	/// Fill a buffer this way to hand a whole batch to
363	/// [`group::Producer::write_frames`].
364	pub fn push(&mut self, frame: Frame) -> std::result::Result<(), Frame> {
365		self.0.try_push(frame).map_err(|err| err.element())
366	}
367
368	/// Move every frame out, leaving the buffer empty.
369	///
370	/// Frames left in the iterator when it drops are dropped with it, so the buffer
371	/// ends up empty either way.
372	pub fn drain(&mut self) -> impl ExactSizeIterator<Item = Frame> + '_ {
373		self.0.drain(..)
374	}
375
376	/// Drop the current batch, leaving the buffer empty.
377	#[cfg(feature = "async")]
378	pub fn clear(&mut self) {
379		self.0.clear();
380	}
381}
382
383/// Bytes the frames still being written through one origin handle may allocate up front.
384///
385/// A writer declares each frame's size before sending it, and allocating that size up
386/// front saves a reallocation and copy per doubling as the payload arrives. A peer's
387/// declaration costs it nothing, though, so without a bound it could commit a
388/// [`SEGMENT`] per stream for a single byte. A frame reserves what one segment of it
389/// takes, and while that fits what remains each segment is allocated whole; past that,
390/// it grows with the bytes received. Each frame returns its share once it completes or
391/// aborts.
392///
393/// Every broadcast, track, and group minted from an [`crate::origin::Producer`] handle shares
394/// its budget. The built-in sessions each ingest through a handle with its own.
395#[derive(Clone, Default)]
396pub(crate) struct Budget(Arc<Remaining>);
397
398struct Remaining(AtomicUsize);
399
400impl Default for Remaining {
401	fn default() -> Self {
402		Self(AtomicUsize::new(Budget::DEFAULT))
403	}
404}
405
406impl std::fmt::Debug for Budget {
407	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408		f.debug_tuple("Budget")
409			.field(&self.0.0.load(Ordering::Relaxed))
410			.finish()
411	}
412}
413
414impl Budget {
415	/// Enough for a handful of large keyframes in flight at once.
416	const DEFAULT: usize = 16 * 1024 * 1024;
417
418	/// A budget of `bytes`, for a benchmark sweeping it.
419	#[cfg(any(test, feature = "fuzz"))]
420	pub(crate) fn new(bytes: usize) -> Self {
421		Self(Arc::new(Remaining(AtomicUsize::new(bytes))))
422	}
423
424	/// Take `size` bytes of the budget, or `None` if that is more than remains.
425	pub(super) fn reserve(&self, size: usize) -> Option<Reservation> {
426		self.0
427			.0
428			.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |left| left.checked_sub(size))
429			.ok()?;
430		Some(Reservation {
431			budget: self.clone(),
432			size,
433		})
434	}
435}
436
437/// A frame's share of a [`Budget`], returned on drop.
438pub(super) struct Reservation {
439	budget: Budget,
440	size: usize,
441}
442
443impl Drop for Reservation {
444	fn drop(&mut self) {
445		self.budget.0.0.fetch_add(self.size, Ordering::Relaxed);
446	}
447}
448
449/// One delivery's progress over a frame's canonical payload storage.
450///
451/// A whole-frame [`Bytes`] write is stored directly. Chunked writes are copied into a
452/// heap [`Segment`], or a chain of them for a frame larger than [`SEGMENT`], each either
453/// allocated at its full length by its first byte or grown as bytes arrive (see
454/// [`Budget`]). Clones share delivery progress; [`Self::fork`] starts another delivery
455/// over the same content. Publication serializes their writes, never rewriting bytes
456/// already visible to readers, while each delivery advances only as its bytes arrive.
457///
458/// The delivery that creates the content keeps its progress in the content itself, so
459/// a frame with one delivery, nearly every frame, costs one allocation. Only a fork
460/// allocates a [`View`] of its own. Until anything else attaches to the content, that
461/// delivery is its only writer, so it publishes without the publication lock or an
462/// overlap check (see [`FrameContent::attach`]).
463#[derive(Clone)]
464pub(super) struct FrameBuf {
465	content: Arc<FrameContent>,
466	fork: Option<Arc<View>>,
467}
468
469/// A forked delivery's progress, shared by its clones.
470#[derive(Default)]
471struct View {
472	received: AtomicUsize,
473	bill: OnceLock<cache::Extra>,
474}
475
476struct FrameContent {
477	size: usize,
478	grow: AtomicBool,
479	written: AtomicUsize,
480	// The creating delivery's received bytes; a fork counts its own in its [`View`].
481	received: AtomicUsize,
482	storage: OnceLock<FrameStorage>,
483	// Copied storage frozen once, so every delivery shares one payload. Whole storage
484	// freezes as itself and leaves this empty.
485	frozen: OnceLock<Payload>,
486	publication: Mutex<Publication>,
487	// Set by the creating delivery around each write it makes without the publication
488	// lock, and by `attach`, after which every write takes the lock.
489	writing: AtomicBool,
490	attached: AtomicBool,
491	// Whether the creating delivery still holds the admission it took with the content,
492	// so attaching counts it among the publication's producers.
493	creator_admitted: AtomicBool,
494	bill: OnceLock<cache::Extra>,
495	identity: OnceLock<Identity>,
496}
497
498struct Identity {
499	owner: Arc<group::Content>,
500	key: group::ContentKey,
501}
502
503impl Drop for FrameContent {
504	fn drop(&mut self) {
505		if let Some(identity) = self.identity.get() {
506			identity.owner.forget_frame(
507				identity.key,
508				self as *const Self as usize,
509				self.bill.get().map_or(0, cache::Extra::size),
510			);
511		}
512	}
513}
514
515#[derive(Clone)]
516pub(super) struct Shared(Arc<FrameContent>);
517
518#[derive(Clone)]
519pub(super) struct SharedWeak(Weak<FrameContent>);
520
521impl SharedWeak {
522	pub(super) fn upgrade(&self) -> Option<Shared> {
523		self.0.upgrade().map(Shared)
524	}
525	pub(super) fn address(&self) -> usize {
526		self.0.as_ptr() as usize
527	}
528}
529
530impl Shared {
531	pub(super) fn from_payload(payload: Payload) -> Self {
532		let size = payload.len();
533		Self(Arc::new(FrameContent {
534			size,
535			grow: AtomicBool::new(false),
536			written: AtomicUsize::new(size),
537			received: AtomicUsize::new(size),
538			storage: OnceLock::from(FrameStorage::Shared(payload)),
539			frozen: OnceLock::new(),
540			publication: Mutex::default(),
541			writing: AtomicBool::new(false),
542			attached: AtomicBool::new(false),
543			creator_admitted: AtomicBool::new(false),
544			bill: OnceLock::new(),
545			identity: OnceLock::new(),
546		}))
547	}
548	pub(super) fn downgrade(&self) -> SharedWeak {
549		SharedWeak(Arc::downgrade(&self.0))
550	}
551	pub(super) fn fork(&self) -> FrameBuf {
552		if !self.0.attached.load(Ordering::Acquire) {
553			self.0
554				.attach(&mut self.0.publication.lock().unwrap_or_else(PoisonError::into_inner));
555		}
556		FrameBuf {
557			content: self.0.clone(),
558			fork: Some(Arc::default()),
559		}
560	}
561	pub(super) fn freeze(&self) -> Payload {
562		self.0.freeze()
563	}
564	pub(super) fn size(&self) -> usize {
565		self.0.size
566	}
567	#[cfg(test)]
568	pub(super) fn written(&self) -> usize {
569		self.0.written.load(Ordering::Acquire)
570	}
571	pub(super) fn bill_content(&self, bill: cache::Extra) {
572		self.0.bill_content(bill);
573	}
574	#[cfg(test)]
575	pub(super) fn content_size(&self) -> u64 {
576		self.0.bill.get().map_or(0, cache::Extra::size)
577	}
578	pub(super) fn identify(&self, owner: Arc<group::Content>, key: group::ContentKey) -> bool {
579		let mut publication = self.0.publication.lock().unwrap_or_else(PoisonError::into_inner);
580		self.0.attach(&mut publication);
581		if self
582			.0
583			.identity
584			.set(Identity {
585				owner: owner.clone(),
586				key,
587			})
588			.is_err()
589		{
590			return false;
591		}
592		owner.charge_frame(self.0.bill.get().map_or(0, cache::Extra::size));
593		true
594	}
595}
596
597impl FrameContent {
598	fn bill_content(&self, bill: cache::Extra) {
599		let content = self;
600		let mut publication = content.publication.lock().unwrap_or_else(PoisonError::into_inner);
601		// Billing reads the published bytes, which the creator's lock-free writes would race.
602		content.attach(&mut publication);
603		content.bill.get_or_init(|| {
604			let written = self.written.load(Ordering::Relaxed) as u64;
605			// A lazy owner may take already-billed payload from the original delivery.
606			let fresh = written
607				.checked_sub(bill.size())
608				.expect("transferred payload cannot exceed published bytes");
609			bill.add(fresh + FrameBuf::CONTENT_HEAP as u64);
610			if let Some(identity) = self.identity.get() {
611				identity.owner.charge_frame(bill.size());
612			}
613			bill
614		});
615	}
616
617	/// Let anything besides the creating delivery reach the content: another delivery, its
618	/// cache bill, or an admission taken through the publication. The creator's write in
619	/// flight finishes first, and every later one publishes under the lock.
620	///
621	/// Caller holds `publication`, so attachers are serialized.
622	fn attach(&self, publication: &mut Publication) {
623		if self.attached.load(Ordering::Relaxed) {
624			return;
625		}
626		// With the creator's SeqCst store to `writing` and load of `attached`, at least one
627		// side sees the other's store: either the creator takes the lock, or this waits.
628		self.attached.store(true, Ordering::SeqCst);
629		// A lock-free write is a bounded copy that never waits on anything, so this ends
630		// once its thread runs again.
631		while self.writing.load(Ordering::SeqCst) {
632			std::thread::yield_now();
633		}
634		// The creator's admission joins the shared count; its reservation stays with it
635		// until it ends, and passes to any producer still active then.
636		if self.creator_admitted.load(Ordering::Relaxed) {
637			publication.producers += 1;
638		}
639	}
640
641	/// Caller holds publication so attachment and growth update one aggregate.
642	fn add_charge(&self, bytes: u64) {
643		if let Some(bill) = self.bill.get() {
644			let before = bill.size();
645			bill.add(bytes);
646			if let Some(identity) = self.identity.get() {
647				identity.owner.charge_frame(bill.size() - before);
648			}
649		}
650	}
651
652	fn freeze(&self) -> Payload {
653		debug_assert_eq!(self.written.load(Ordering::Acquire), self.size);
654		// A whole payload is already its own frozen form; only copied storage builds one.
655		if let Some(FrameStorage::Shared(payload)) = self.storage.get() {
656			return payload.clone();
657		}
658		self.frozen
659			.get_or_init(|| match self.storage.get() {
660				Some(FrameStorage::Chain(segments)) => {
661					let segments = segments.lock().unwrap_or_else(PoisonError::into_inner);
662					debug_assert!(segments.open.is_none(), "froze a frame mid-segment");
663					Payload::Chain(Chain {
664						segments: segments.sealed.as_slice().into(),
665						start: 0,
666					})
667				}
668				_ => Payload::Whole(self.slice(0, self.size)),
669			})
670			.clone()
671	}
672
673	fn slice(&self, start: usize, end: usize) -> Bytes {
674		if start >= end {
675			return Bytes::new();
676		}
677		// Loaded only to build a new owner. The Acquire pairs with `store_written`'s
678		// Release, so every byte it covers is initialized. `Growing`/`Chain` also load it
679		// under the lock that holds their segment steady, so those bytes are in the
680		// segment being sliced; a `Fixed` segment never moves, and its writers never take
681		// the `shared` lock.
682		let published = || self.written.load(Ordering::Acquire);
683		match self.storage.get() {
684			Some(FrameStorage::Shared(payload)) => {
685				let chunk = payload.chunk_at(start);
686				chunk.slice(..chunk.len().min(end - start))
687			}
688			Some(FrameStorage::Fixed { segment, shared }) => {
689				let mut shared = shared.lock().unwrap_or_else(PoisonError::into_inner);
690				share(&mut shared, segment, start..end, published)
691			}
692			Some(FrameStorage::Growing(open)) => {
693				let mut open = open.lock().unwrap_or_else(PoisonError::into_inner);
694				let Open { segment, shared } = &mut *open;
695				share(shared, segment, start..end, published)
696			}
697			Some(FrameStorage::Chain(segments)) => {
698				let mut segments = segments.lock().unwrap_or_else(PoisonError::into_inner);
699				let index = start / SEGMENT;
700				let base = index * SEGMENT;
701				let range = start - base..end.min(base + SEGMENT) - base;
702				if let Some(sealed) = segments.sealed.get(index) {
703					return sealed.slice(range);
704				}
705				let Open { segment, shared } = segments.open.as_mut().expect("written bytes are sealed or open");
706				share(shared, segment, range, || published().min(base + SEGMENT) - base)
707			}
708			// Nothing written, so the range is empty.
709			None => Bytes::new(),
710		}
711	}
712}
713
714/// What a frame's concurrent deliveries share while publishing into its content.
715#[derive(Default)]
716struct Publication {
717	// Producers holding the frame's admission; the last one to end releases it.
718	producers: usize,
719	// The admission's share of the budget, if it got one. Even a failed reservation is
720	// shared, so overlapping deliveries use the same growth strategy without each
721	// attempting another admission.
722	reserved: Option<Reservation>,
723}
724
725/// One producer's hold on its frame's admission, ended by [`FrameBuf::release`]. The
726/// reservation returns to the budget once no producer of the frame remains active.
727///
728/// No admission allocates: every streamed frame takes one, and nearly all have a single
729/// producer.
730pub(super) enum Admission {
731	/// The creating delivery's, taken with its content. It keeps its reservation, and
732	/// counts among the publication's producers only once something attaches.
733	Creator(Option<Reservation>),
734	/// Counted in the [`Publication`], which holds the reservation.
735	Shared,
736}
737
738enum FrameStorage {
739	Shared(Payload),
740	// Allocated at the frame's size, so a write never takes the lock; only readers share
741	// the owner through it.
742	Fixed {
743		segment: Arc<Segment>,
744		shared: Mutex<Option<Bytes>>,
745	},
746	// Replaced by a larger copy whenever a write outgrows it.
747	Growing(Mutex<Open>),
748	// A frame larger than one segment. Boxed: it is rare, and every frame's content
749	// otherwise pays for its size.
750	Chain(Box<Mutex<Segments>>),
751}
752
753/// A segment that is still being written, and may still grow.
754struct Open {
755	segment: Arc<Segment>,
756	// The readers' owner of its published bytes; see [`share`].
757	shared: Option<Bytes>,
758}
759
760impl Open {
761	fn new(capacity: usize) -> Self {
762		Self {
763			segment: Arc::new(Segment::new(capacity)),
764			shared: None,
765		}
766	}
767
768	/// Replace the segment with a larger copy of its first `filled` bytes if it holds fewer
769	/// than `needed` of the `len` it grows to.
770	///
771	/// Doubling keeps the copies linear in `len`, and the cap makes the last copy exactly
772	/// `len`, so it seals without another. The readers' owner goes with the old segment,
773	/// which then lives only as long as the slices already cut from it.
774	fn reserve(&mut self, filled: usize, needed: usize, len: usize) {
775		if self.segment.capacity >= needed {
776			return;
777		}
778		let next = Segment::new(needed.max(self.segment.capacity * 2).min(len));
779		let filled = Filled {
780			segment: self.segment.clone(),
781			len: filled,
782		};
783		// Safety: `next` is new, so nothing reads it yet.
784		unsafe { next.write(0, filled.as_ref()) };
785		self.segment = Arc::new(next);
786		self.shared = None;
787	}
788}
789
790/// Slice `range` of `segment`, from the owner in `shared` if it covers the range, or else
791/// from a new one over the segment's first `published()` bytes that replaces it.
792///
793/// Readers reading up to the same published length share one owner, so reading a frame
794/// still arriving allocates once per publication rather than once per reader per read. An
795/// owner covers only published bytes, since the writer is still filling the rest.
796fn share(
797	shared: &mut Option<Bytes>,
798	segment: &Arc<Segment>,
799	range: Range<usize>,
800	published: impl FnOnce() -> usize,
801) -> Bytes {
802	if shared.as_ref().is_none_or(|owner| owner.len() < range.end) {
803		let len = published();
804		debug_assert!(range.end <= len && len <= segment.capacity);
805		*shared = Some(Bytes::from_owner(Filled {
806			segment: segment.clone(),
807			len,
808		}));
809	}
810	shared.as_ref().expect("covers the range").slice(range)
811}
812
813/// A frame larger than one [`SEGMENT`], as it streams in.
814#[derive(Default)]
815struct Segments {
816	// Every full segment so far, in order.
817	sealed: Vec<Bytes>,
818	// The segment being written, allocated by its first byte and grown like
819	// [`FrameStorage::Growing`].
820	open: Option<Open>,
821}
822
823impl Segments {
824	/// Copy `src` in at frame offset `offset`, sealing each segment it fills.
825	fn append(&mut self, mut offset: usize, mut src: &[u8], size: usize, grow: bool) {
826		while !src.is_empty() {
827			let base = offset - offset % SEGMENT;
828			let len = (size - base).min(SEGMENT);
829			let within = offset - base;
830			let take = src.len().min(len - within);
831			let open = self.open.get_or_insert_with(|| Open::new(if grow { 0 } else { len }));
832			open.reserve(within, within + take, len);
833			// Safety: sole writer, within the segment's length, past every byte handed out.
834			unsafe { open.segment.write(within, &src[..take]) };
835			if within + take == len {
836				let Open { segment, .. } = self.open.take().expect("written above");
837				self.sealed.push(Bytes::from_owner(Filled { segment, len }));
838			}
839			offset += take;
840			src = &src[take..];
841		}
842	}
843}
844
845/// An owned heap allocation that chunked writes are copied into.
846///
847/// Left uninitialized, since only its published prefix is ever read, and every byte of
848/// that was written before it was published. Reading past it would already race the
849/// writer filling those bytes.
850struct Segment {
851	data: *mut u8,
852	capacity: usize,
853}
854
855// Safety: `data` is owned (Box-allocated, freed in Drop). Publication serializes
856// writers, which never rewrite published bytes; consumers only read `< written`.
857unsafe impl Send for Segment {}
858unsafe impl Sync for Segment {}
859
860impl Drop for Segment {
861	fn drop(&mut self) {
862		// Safety: data was obtained from `Box::into_raw` of a `Box<[MaybeUninit<u8>]>` of
863		// length `capacity` and is not aliased at drop (Arc refcount hit 0).
864		unsafe {
865			let slice = std::ptr::slice_from_raw_parts_mut(self.data.cast::<MaybeUninit<u8>>(), self.capacity);
866			drop(Box::from_raw(slice));
867		}
868	}
869}
870
871impl Segment {
872	fn new(capacity: usize) -> Self {
873		let boxed = Box::<[u8]>::new_uninit_slice(capacity);
874		let capacity = boxed.len();
875		let data = Box::into_raw(boxed).cast::<u8>();
876		Self { data, capacity }
877	}
878
879	/// Copy `src` in at `offset`.
880	///
881	/// Safety: caller must be the sole writer, `offset + src.len()` must be within
882	/// `capacity`, and no reader may have been handed bytes at or past `offset`.
883	unsafe fn write(&self, offset: usize, src: &[u8]) {
884		debug_assert!(offset + src.len() <= self.capacity);
885		unsafe { std::ptr::copy_nonoverlapping(src.as_ptr(), self.data.add(offset), src.len()) };
886	}
887}
888
889/// The first `len` bytes of a [`Segment`], all written, so it can back a
890/// [`Bytes::from_owner`].
891struct Filled {
892	segment: Arc<Segment>,
893	len: usize,
894}
895
896impl AsRef<[u8]> for Filled {
897	fn as_ref(&self) -> &[u8] {
898		// Safety: `len` never exceeds what the producer had published when this was
899		// built, and the producer never rewrites published bytes. The Arc keeps the
900		// allocation alive while any reference to the slice lives.
901		unsafe { std::slice::from_raw_parts(self.segment.data, self.len) }
902	}
903}
904
905impl FrameBuf {
906	pub(super) const CONTENT_HEAP: usize = 2 * size_of::<usize>() + size_of::<FrameContent>();
907	pub(super) const VIEW_HEAP: usize = 2 * size_of::<usize>() + size_of::<View>();
908
909	/// A buffer for a frame of `size` bytes, allocated at that size on the first write.
910	///
911	/// The oversized-frame guard lives in [`group::Producer`], which rejects a declared
912	/// size larger than the group's byte budget before calling this.
913	pub(super) fn new(size: usize) -> Self {
914		Self::with_growth(size, false)
915	}
916
917	/// A buffer for a frame of `size` bytes that allocates only as bytes arrive.
918	#[cfg(test)]
919	pub(super) fn growing(size: usize) -> Self {
920		Self::with_growth(size, true)
921	}
922
923	/// A buffer for a frame of `size` bytes with its creating delivery's admission,
924	/// allocated at that size on the first write while `budget` covers it, and grown as
925	/// bytes arrive otherwise.
926	pub(super) fn admitted(size: usize, budget: &Budget) -> (Self, Option<Admission>) {
927		if size == 0 {
928			return (Self::new(0), None);
929		}
930		let reserved = budget.reserve(size.min(SEGMENT));
931		let buf = Self::with_growth(size, reserved.is_none());
932		// Nothing else holds the content yet.
933		buf.content.creator_admitted.store(true, Ordering::Relaxed);
934		(buf, Some(Admission::Creator(reserved)))
935	}
936
937	fn with_growth(size: usize, grow: bool) -> Self {
938		Self {
939			content: Arc::new(FrameContent {
940				size,
941				grow: AtomicBool::new(grow),
942				written: AtomicUsize::new(0),
943				received: AtomicUsize::new(0),
944				storage: OnceLock::new(),
945				frozen: OnceLock::new(),
946				publication: Mutex::default(),
947				writing: AtomicBool::new(false),
948				attached: AtomicBool::new(false),
949				creator_admitted: AtomicBool::new(false),
950				bill: OnceLock::new(),
951				identity: OnceLock::new(),
952			}),
953			fork: None,
954		}
955	}
956
957	/// Keep an already-complete payload without copying its buffers or segments.
958	#[cfg(test)]
959	pub(super) fn from_payload(payload: Payload) -> Self {
960		Self {
961			content: Shared::from_payload(payload).0,
962			fork: None,
963		}
964	}
965
966	pub(super) fn shared(&self) -> Shared {
967		Shared(self.content.clone())
968	}
969
970	/// Another delivery of the same immutable frame, starting before its first byte.
971	#[cfg(test)]
972	pub(super) fn fork(&self) -> Self {
973		self.shared().fork()
974	}
975
976	/// Bill physical content once, including bytes already received before attachment.
977	/// The charge follows its buffers even if a cached row lets go before a stream does.
978	#[cfg(test)]
979	pub(super) fn bill_content(&self, bill: cache::Extra) {
980		self.content.bill_content(bill);
981	}
982
983	/// One delivery's metadata, retained by its streaming readers and shared by clones.
984	/// The creating delivery's lives in its content, so only a fork's is billed here.
985	pub(super) fn bill_view(&self, bill: cache::Extra) {
986		if let Some(view) = &self.fork {
987			view.bill.get_or_init(|| {
988				bill.add(Self::VIEW_HEAP as u64);
989				bill
990			});
991		}
992	}
993
994	/// The canonical allocation's charge, counted once by its cache owner.
995	#[cfg(test)]
996	pub(super) fn content_size(&self) -> u64 {
997		self.content.bill.get().map_or(0, cache::Extra::size)
998	}
999
1000	/// This delivery's charge; clones retain the same view allocation.
1001	pub(super) fn view_size(&self) -> u64 {
1002		self.fork
1003			.as_ref()
1004			.and_then(|view| view.bill.get())
1005			.map_or(0, cache::Extra::size)
1006	}
1007
1008	/// This delivery's received bytes.
1009	fn received(&self) -> &AtomicUsize {
1010		match &self.fork {
1011			Some(view) => &view.received,
1012			None => &self.content.received,
1013		}
1014	}
1015
1016	/// Share the existing per-frame admission until its last active producer ends.
1017	/// Complete canonical data is replayed without reserving memory again.
1018	pub(super) fn admit(&self, budget: &Budget) -> Option<Admission> {
1019		let content = &self.content;
1020		let mut publication = content.publication.lock().unwrap_or_else(PoisonError::into_inner);
1021		content.attach(&mut publication);
1022		if self.shared_written(Ordering::Acquire) == self.size() {
1023			return None;
1024		}
1025		if publication.producers == 0 {
1026			let reserved = budget.reserve(self.size().min(SEGMENT));
1027			// Existing bytes keep their allocations. A later admission may only make
1028			// future growth more conservative once storage already exists.
1029			if reserved.is_none() || content.storage.get().is_none() {
1030				content.grow.store(reserved.is_none(), Ordering::Relaxed);
1031			}
1032			publication.reserved = reserved;
1033		}
1034		publication.producers += 1;
1035		Some(Admission::Shared)
1036	}
1037
1038	/// End `admission`, which this delivery took.
1039	pub(super) fn release(&self, admission: Admission) {
1040		let content = &self.content;
1041		let reserved = match admission {
1042			Admission::Creator(reserved) => {
1043				// Alone, the creator's reservation is the frame's; see `write_chunk`.
1044				content.writing.store(true, Ordering::SeqCst);
1045				if !content.attached.load(Ordering::SeqCst) {
1046					content.creator_admitted.store(false, Ordering::Relaxed);
1047					content.writing.store(false, Ordering::Release);
1048					return;
1049				}
1050				content.writing.store(false, Ordering::Release);
1051				reserved
1052			}
1053			Admission::Shared => None,
1054		};
1055		let mut publication = content.publication.lock().unwrap_or_else(PoisonError::into_inner);
1056		publication.producers -= 1;
1057		if publication.producers == 0 {
1058			publication.reserved = None;
1059		} else if publication.reserved.is_none() {
1060			// Producers still active keep the creator's reservation.
1061			publication.reserved = reserved;
1062		}
1063	}
1064
1065	/// Whether the frame's active producers hold a share of the budget.
1066	#[cfg(test)]
1067	fn reserved(&self) -> bool {
1068		self.content
1069			.publication
1070			.lock()
1071			.unwrap_or_else(PoisonError::into_inner)
1072			.reserved
1073			.is_some()
1074	}
1075
1076	/// The frame's declared size.
1077	pub(super) fn size(&self) -> usize {
1078		self.content.size
1079	}
1080
1081	/// Bytes this delivery received, independently of other copies' progress.
1082	pub(super) fn written(&self, ord: Ordering) -> usize {
1083		self.received().load(ord)
1084	}
1085
1086	/// Unique canonical bytes published so far, for shared-content accounting.
1087	pub(super) fn shared_written(&self, ord: Ordering) -> usize {
1088		self.content.written.load(ord)
1089	}
1090
1091	fn try_set_bytes(&self, bytes: Bytes) -> std::result::Result<(), Bytes> {
1092		if bytes.len() != self.size() || self.shared_written(Ordering::Acquire) != 0 {
1093			return Err(bytes);
1094		}
1095		self.content
1096			.storage
1097			.set(FrameStorage::Shared(Payload::Whole(bytes)))
1098			.map_err(|storage| match storage {
1099				FrameStorage::Shared(Payload::Whole(bytes)) => bytes,
1100				_ => unreachable!("try_set_bytes only installs shared storage"),
1101			})
1102	}
1103
1104	/// Safety: caller is the only publisher, holding the publication mutex or writing
1105	/// alone as the creator, and `new_written` is `<= size`.
1106	unsafe fn store_written(&self, new_written: usize) {
1107		let content = &self.content;
1108		let before = content.written.load(Ordering::Relaxed);
1109		content.add_charge((new_written - before) as u64);
1110		// Release pairs with consumers' Acquire load to publish prior writes.
1111		content.written.store(new_written, Ordering::Release);
1112	}
1113
1114	/// Validate this delivery's overlap, then publish only its unseen suffix.
1115	pub(super) fn append(&self, src: &[u8]) -> Result<()> {
1116		self.write_chunk(src)
1117	}
1118
1119	fn write_chunk<B: IntoBytes>(&self, chunk: B) -> Result<()> {
1120		let content = &self.content;
1121		if self.fork.is_none() {
1122			// The SeqCst store then load pairs with `FrameContent::attach`'s: a write that
1123			// misses the attachment finishes before the attacher continues.
1124			content.writing.store(true, Ordering::SeqCst);
1125			if !content.attached.load(Ordering::SeqCst) {
1126				let written = self.write_alone(chunk);
1127				content.writing.store(false, Ordering::Release);
1128				return written;
1129			}
1130			content.writing.store(false, Ordering::Release);
1131		}
1132		let _publication = content.publication.lock().unwrap_or_else(PoisonError::into_inner);
1133		let start = self.written(Ordering::Relaxed);
1134		let end = start
1135			.checked_add(chunk.as_ref().len())
1136			.filter(|end| *end <= self.size())
1137			.ok_or(Error::WrongSize)?;
1138		let published = self.shared_written(Ordering::Acquire);
1139		if start > published {
1140			return Err(Error::ProtocolViolation);
1141		}
1142		let overlap = end.min(published);
1143		let mut at = start;
1144		while at < overlap {
1145			let prior = self.slice(at, overlap);
1146			if prior.as_ref() != &chunk.as_ref()[at - start..at - start + prior.len()] {
1147				return Err(Error::ProtocolViolation);
1148			}
1149			at += prior.len();
1150		}
1151		if end > published {
1152			if published == 0 && end == self.size() {
1153				match self.try_set_bytes(chunk.into_bytes()) {
1154					Ok(()) => {
1155						// Safety: the mutex excludes other publishers; the full size was checked.
1156						unsafe { self.store_written(end) };
1157					}
1158					Err(chunk) => self.append_suffix(&chunk),
1159				}
1160			} else {
1161				self.append_suffix(&chunk.as_ref()[published - start..]);
1162			}
1163		}
1164		self.received().store(end, Ordering::Release);
1165		Ok(())
1166	}
1167
1168	/// Publish the creating delivery's chunk while nothing else can reach the content: its
1169	/// progress is the content's, so no published byte overlaps the chunk.
1170	fn write_alone<B: IntoBytes>(&self, chunk: B) -> Result<()> {
1171		let content = &self.content;
1172		let start = content.written.load(Ordering::Relaxed);
1173		let end = start
1174			.checked_add(chunk.as_ref().len())
1175			.filter(|end| *end <= self.size())
1176			.ok_or(Error::WrongSize)?;
1177		if end == start {
1178			return Ok(());
1179		}
1180		match start == 0 && end == self.size() {
1181			true => match self.try_set_bytes(chunk.into_bytes()) {
1182				// Safety: the creator writes alone; the full size was checked.
1183				Ok(()) => unsafe { self.store_written(end) },
1184				Err(chunk) => self.append_suffix(&chunk),
1185			},
1186			false => self.append_suffix(chunk.as_ref()),
1187		}
1188		content.received.store(end, Ordering::Release);
1189		Ok(())
1190	}
1191
1192	/// Append after the shared prefix as its only publisher: holding the publication
1193	/// mutex, or the creator writing alone.
1194	fn append_suffix(&self, src: &[u8]) {
1195		if src.is_empty() {
1196			return;
1197		}
1198		let prev = self.shared_written(Ordering::Relaxed);
1199		let size = self.size();
1200		let content = &self.content;
1201		let grow = content.grow.load(Ordering::Relaxed);
1202		let storage = content.storage.get_or_init(|| match grow {
1203			_ if size > SEGMENT => FrameStorage::Chain(Box::default()),
1204			true => FrameStorage::Growing(Mutex::new(Open::new(0))),
1205			false => FrameStorage::Fixed {
1206				segment: Arc::new(Segment::new(size)),
1207				shared: Mutex::default(),
1208			},
1209		});
1210		// Safety (every write below): the caller is the sole writer, checked the remaining
1211		// size, and consumers only read `[..written]`.
1212		match storage {
1213			// Only reachable if the frame is already complete via shared storage, which
1214			// `Producer::write` rejects for a non-empty chunk. Nothing to copy.
1215			FrameStorage::Shared(_) => return,
1216			FrameStorage::Fixed { segment, .. } => unsafe { segment.write(prev, src) },
1217			FrameStorage::Growing(open) => {
1218				let mut open = open.lock().unwrap_or_else(PoisonError::into_inner);
1219				open.reserve(prev, prev + src.len(), size);
1220				unsafe { open.segment.write(prev, src) };
1221			}
1222			FrameStorage::Chain(segments) => {
1223				let mut segments = segments.lock().unwrap_or_else(PoisonError::into_inner);
1224				segments.append(prev, src, size, grow);
1225			}
1226		}
1227		// Safety: the caller is the sole writer, and checked the size.
1228		unsafe { self.store_written(prev + src.len()) };
1229	}
1230
1231	/// The completed payload, shared by every delivery without copying its segments.
1232	/// Called only once the canonical payload is complete. Delivery completion is
1233	/// checked separately by [`Producer::finish`].
1234	pub(super) fn freeze(&self) -> Payload {
1235		self.content.freeze()
1236	}
1237
1238	/// A zero-copy slice of the written region from `start` to `end`, or to the end of
1239	/// `start`'s segment if that comes first.
1240	///
1241	/// `end` must not exceed a shared published value already loaded with `Acquire`.
1242	/// A delivery's own received count is always within that prefix too.
1243	fn slice(&self, start: usize, end: usize) -> Bytes {
1244		self.content.slice(start, end)
1245	}
1246
1247	/// Heap bytes the buffer currently holds for the payload.
1248	#[cfg(test)]
1249	pub(super) fn allocated(&self) -> usize {
1250		match self.content.storage.get() {
1251			Some(FrameStorage::Shared(payload)) => payload.len(),
1252			Some(FrameStorage::Fixed { segment, .. }) => segment.capacity,
1253			Some(FrameStorage::Growing(open)) => open.lock().unwrap_or_else(PoisonError::into_inner).segment.capacity,
1254			Some(FrameStorage::Chain(segments)) => {
1255				let segments = segments.lock().unwrap_or_else(PoisonError::into_inner);
1256				let sealed: usize = segments.sealed.iter().map(Bytes::len).sum();
1257				sealed + segments.open.as_ref().map_or(0, |open| open.segment.capacity)
1258			}
1259			None => 0,
1260		}
1261	}
1262}
1263
1264/// Writes the payload of a group's single in-flight frame in one or more chunks.
1265///
1266/// Created by [`group::Producer::create_frame`], which hands it the group's writer: no
1267/// other frame can be opened, and the group cannot finish, until [`Self::finish`] returns
1268/// the writer. Owned rather than borrowed, so a driver can hold it across polls while
1269/// the payload streams in. [`Self::group`] still reads the group meanwhile.
1270///
1271/// The total bytes written must exactly match [`Info::size`]; call [`Self::finish`] to
1272/// commit the frame (or [`Self::abort`] to fail it). Dropping it without either aborts
1273/// the group, since an unfinished frame leaves the group's stream broken.
1274///
1275/// A single whole-frame [`write`](Self::write) keeps the caller's allocation
1276/// (zero-copy). Chunked writes copy into one buffer, or a chain of fixed-size segments
1277/// for a large frame, each allocated whole by its first byte, or grown as bytes arrive
1278/// once the frames in flight pass the origin's budget. Nothing is allocated past the
1279/// segment being written, whatever size was declared.
1280pub struct Producer {
1281	group: Option<group::Producer>,
1282	buf: FrameBuf,
1283	info: Info,
1284	// Set once the frame is committed (finished) or aborted, so Drop is a no-op.
1285	done: bool,
1286	// A receive handler's cancellation cleanup, carried across polls.
1287	cancel_on_drop: bool,
1288	// Ingress payload meter, inherited from the parent group. Counts each written
1289	// chunk's bytes. Empty (no-op) for an untagged group.
1290	stats: stats::Meter,
1291	// The frame's share of the origin's [`Budget`], if it got one, held until it ends.
1292	admission: Option<Admission>,
1293}
1294
1295impl std::ops::Deref for Producer {
1296	type Target = Info;
1297
1298	fn deref(&self) -> &Self::Target {
1299		&self.info
1300	}
1301}
1302
1303impl Producer {
1304	pub(super) fn new(group: group::Producer, buf: FrameBuf, info: Info, admission: Option<Admission>) -> Self {
1305		Self {
1306			group: Some(group),
1307			buf,
1308			info,
1309			done: false,
1310			cancel_on_drop: false,
1311			stats: stats::Meter::default(),
1312			admission,
1313		}
1314	}
1315
1316	/// Attach the parent group's ingress meter, so written chunks bump `bytes`.
1317	pub(super) fn with_meter(mut self, meter: stats::Meter) -> Self {
1318		self.stats = meter;
1319		self
1320	}
1321
1322	/// Transfer a receive handler's cancellation cleanup into its in-flight frame.
1323	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1324	// A dropped receive handler cannot name its error; a public driver aborts explicitly.
1325	pub(crate) fn cancel_on_drop(mut self) -> Self {
1326		self.cancel_on_drop = true;
1327		self
1328	}
1329
1330	/// The group this frame belongs to, readable while the frame holds its writer.
1331	pub fn group(&self) -> &group::Producer {
1332		self.group.as_ref().expect("frame owns its group")
1333	}
1334
1335	/// Bytes still needed to complete the frame.
1336	pub fn remaining(&self) -> usize {
1337		self.buf.size() - self.buf.written(Ordering::Acquire)
1338	}
1339
1340	/// Bytes still needed to seal the segment being written, which for a frame within one
1341	/// segment is the rest of the frame.
1342	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1343	pub(crate) fn unsealed(&self) -> usize {
1344		self.unsealed_after(0)
1345	}
1346
1347	/// [`Self::unsealed`] once `more` bytes are written.
1348	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1349	pub(crate) fn unsealed_after(&self, more: usize) -> usize {
1350		let written = self.buf.written(Ordering::Acquire) + more;
1351		let end = (written / SEGMENT + 1).saturating_mul(SEGMENT).min(self.buf.size());
1352		end - written
1353	}
1354
1355	/// Write a chunk of data to the frame, waking its readers.
1356	///
1357	/// Returns [`Error::WrongSize`] if the chunk would exceed the remaining bytes.
1358	pub fn write<B: IntoBytes>(&mut self, chunk: B) -> Result<()> {
1359		self.write_deferred(chunk)?;
1360		self.notify();
1361		Ok(())
1362	}
1363
1364	/// Write a chunk of payload *without* waking consumers; pair it with [`Self::notify`].
1365	///
1366	/// The wake is split out because the wire ingest drains every chunk the transport
1367	/// has already buffered in one poll turn, and a consumer parked on the group cannot
1368	/// run until that turn yields. Waking per chunk pays a group lock and a clock read
1369	/// to publish bytes nobody can observe yet.
1370	///
1371	/// `coding::Reader::poll_read_frame` owns the pairing and is the only caller.
1372	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1373	pub(crate) fn write_deferred<B: IntoBytes>(&mut self, chunk: B) -> Result<()> {
1374		let len = chunk.as_ref().len();
1375		if len > self.remaining() {
1376			return Err(Error::WrongSize);
1377		}
1378		// Ingress payload: count the chunk's bytes as they're written.
1379		self.stats.bytes(len as u64);
1380		self.buf.write_chunk(chunk)
1381	}
1382
1383	/// Poll until the group's writer may take more of this frame from upstream, at most
1384	/// `window` bytes past its fastest reader; see [`group::Producer::poll_paced`].
1385	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1386	pub(crate) fn poll_ready(&self, waiter: &kio::Waiter, window: u64) -> Poll<()> {
1387		self.group()
1388			.poll_paced(waiter, self.buf.written(Ordering::Acquire) as u64, window)
1389	}
1390
1391	/// How many more bytes of this frame the group's writer may take before
1392	/// [`Self::poll_ready`] holds it at `window`, or `None` while nothing would, once `more`
1393	/// bytes are written.
1394	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1395	pub(crate) fn room(&self, window: u64, more: usize) -> Option<u64> {
1396		self.group()
1397			.room((self.buf.written(Ordering::Acquire) + more) as u64, window)
1398	}
1399
1400	/// Publish what has been written so far, waking consumers parked on the group.
1401	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1402	pub(crate) fn notify(&self) {
1403		self.group().frame_notify();
1404	}
1405
1406	/// Commit the frame, verifying that all bytes were written, and return the group's
1407	/// writer for its next frame or its finish.
1408	///
1409	/// Returns [`Error::WrongSize`] if the bytes written don't match [`Info::size`].
1410	pub fn finish(mut self) -> Result<group::Producer> {
1411		if self.buf.written(Ordering::Acquire) != self.buf.size() {
1412			return Err(Error::WrongSize);
1413		}
1414		let payload = self.buf.freeze();
1415		let mut group = self.group.take().expect("frame owns its group");
1416		let committed = group.frame_commit(Cached {
1417			timestamp: self.info.timestamp,
1418			payload,
1419			// Stamped by the commit, once readable.
1420			created: Instant::ZERO,
1421		});
1422		self.done = true;
1423		committed?;
1424		Ok(group)
1425	}
1426
1427	/// Abort the frame (and its group) with the given error.
1428	pub fn abort(mut self, err: Error) -> Result<()> {
1429		self.group.as_mut().expect("frame owns its group").frame_abort(err);
1430		self.done = true;
1431		Ok(())
1432	}
1433
1434	/// Heap bytes the frame's buffer currently holds for the payload.
1435	#[cfg(test)]
1436	pub(super) fn allocated(&self) -> usize {
1437		self.buf.allocated()
1438	}
1439}
1440
1441impl Drop for Producer {
1442	fn drop(&mut self) {
1443		// An unfinished frame leaves the group stream broken; fail the group so
1444		// consumers surface an error instead of hanging on the partial forever.
1445		// A group already aborted (superseded, evicted, cancelled) carries its own
1446		// reason, so cutting its in-flight frame short is expected.
1447		if !self.done
1448			&& let Some(group) = self.group.as_mut()
1449		{
1450			if !group.is_aborted() && !self.cancel_on_drop {
1451				tracing::warn!(group = group.start, "frame::Producer dropped before writing all bytes");
1452			}
1453			group.frame_abort(if self.cancel_on_drop {
1454				Error::Cancel
1455			} else {
1456				Error::Dropped
1457			});
1458		}
1459		if let Some(admission) = self.admission.take() {
1460			self.buf.release(admission);
1461		}
1462	}
1463}
1464
1465/// The source of a [`Consumer`]'s payload: a finished frame (whole) or the in-flight
1466/// tail (streamed).
1467#[derive(Clone)]
1468pub(super) enum Source {
1469	Complete(Payload),
1470	Partial(FrameBuf),
1471}
1472
1473/// Subscriber expiry state carried across the group-to-frame handoff.
1474#[derive(Clone)]
1475pub(super) struct Expiry {
1476	policy: Arc<dyn group::Expiry>,
1477	stale_stats: stats::Meter,
1478	delivery: Arc<group::Delivery>,
1479	tail: Range<usize>,
1480	count_payload: bool,
1481}
1482
1483impl Expiry {
1484	pub(super) fn new(
1485		policy: Arc<dyn group::Expiry>,
1486		stale_stats: stats::Meter,
1487		delivery: Arc<group::Delivery>,
1488	) -> Self {
1489		Self {
1490			policy,
1491			stale_stats,
1492			delivery,
1493			tail: 0..0,
1494			count_payload: false,
1495		}
1496	}
1497
1498	pub(super) fn for_frame(mut self, tail: Range<usize>, count_payload: bool) -> Self {
1499		self.tail = tail;
1500		self.count_payload = count_payload;
1501		self
1502	}
1503}
1504
1505/// Reads one frame's payload, streaming as bytes arrive for the in-flight tail.
1506///
1507/// Owns a handle to the parent group's channel (not a per-frame one), so a group with
1508/// many frames doesn't allocate a channel per frame. Cloning yields an independent
1509/// reader of the same frame.
1510#[derive(Clone)]
1511pub struct Consumer {
1512	// The group's channel, used to park while a partial frame fills.
1513	state: kio::Consumer<GroupState>,
1514	info: Info,
1515	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1516	pub(crate) fields: Option<Arc<super::object::Fields>>,
1517	/// The inflated size of a compressed frame read in its stored form (see
1518	/// [`group::Consumer::compressed`]), whose payload is then the DEFLATE slice.
1519	#[cfg_attr(not(feature = "async"), allow(dead_code, reason = "async-only"))]
1520	pub(crate) inflated: Option<u64>,
1521	source: Source,
1522	// Byte offset consumed so far.
1523	read_idx: usize,
1524	// Egress payload meter, so chunks bump `bytes` exactly once as they're read out.
1525	// Empty (no-op) for an untagged group.
1526	stats: stats::Meter,
1527	// The parent subscription can expire after this frame handle is returned.
1528	expiry: Option<Expiry>,
1529	expired: bool,
1530	// What continues the read once its copy fails.
1531	resume: Resume,
1532}
1533
1534/// What carries a frame's read past the copy it reads. The rare cases are boxed: a frame
1535/// handed out still arriving, as most a relay forwards are, allocates nothing until its copy
1536/// fails.
1537#[derive(Clone)]
1538enum Resume {
1539	/// Nothing: a failure ends the read.
1540	None,
1541	/// Handed out still arriving as frame `frame` of group `key`, which a flight of the group
1542	/// from it continues once the pool evicts the copy.
1543	Arriving { key: u64, frame: u64 },
1544	/// A front's logical track, across route changes.
1545	Route(Box<Routed>),
1546	/// The flight continuing it since the pool evicted the copy.
1547	Flight(Box<super::track::Refly>),
1548}
1549
1550/// A frame of a front's logical track.
1551#[derive(Clone)]
1552struct Routed {
1553	recover: super::resume::Recover,
1554	/// The frame's index in its group.
1555	index: u64,
1556	/// The flight continuing it since the pool evicted the copy, while the route serves on.
1557	flight: Option<super::track::Refly>,
1558}
1559
1560impl std::ops::Deref for Consumer {
1561	type Target = Info;
1562
1563	fn deref(&self) -> &Self::Target {
1564		&self.info
1565	}
1566}
1567
1568impl Consumer {
1569	pub(super) fn new(state: kio::Consumer<GroupState>, header: impl Into<Header>, source: Source) -> Self {
1570		let header = header.into();
1571		Self {
1572			state,
1573			info: header.info,
1574			fields: header.fields,
1575			inflated: header.inflated,
1576			source,
1577			read_idx: 0,
1578			stats: stats::Meter::default(),
1579			expiry: None,
1580			expired: false,
1581			resume: Resume::None,
1582		}
1583	}
1584
1585	/// Carry this frame across a front's route changes; see [`super::resume`].
1586	pub(super) fn with_recover(mut self, recover: super::resume::Recover, index: u64) -> Self {
1587		self.resume = Resume::Route(Box::new(Routed {
1588			recover,
1589			index,
1590			flight: None,
1591		}));
1592		self
1593	}
1594
1595	/// Continue this frame, handed out still arriving as frame `frame` of group `key`, on a
1596	/// flight of the group once the pool evicts its copy; see [`super::track::Refly`].
1597	pub(super) fn with_flight(mut self, key: u64, frame: u64) -> Self {
1598		self.resume = Resume::Arriving { key, frame };
1599		self
1600	}
1601
1602	/// The flight continuing this frame, asked of its track once the pool evicted the copy.
1603	fn flight(&mut self) -> Option<&mut super::track::Refly> {
1604		match &self.resume {
1605			Resume::Arriving { key, frame } => {
1606				let refly = self.refly(*key, *frame)?;
1607				self.resume = Resume::Flight(Box::new(refly));
1608			}
1609			Resume::Route(routed) if routed.flight.is_none() => {
1610				let refly = self.refly(routed.recover.key(), routed.index)?;
1611				if let Resume::Route(routed) = &mut self.resume {
1612					routed.flight = Some(refly);
1613				}
1614			}
1615			_ => {}
1616		}
1617		match &mut self.resume {
1618			Resume::Flight(refly) => Some(refly),
1619			Resume::Route(routed) => routed.flight.as_mut(),
1620			_ => None,
1621		}
1622	}
1623
1624	/// A flight of group `key` from frame `frame`, asked of the track holding this frame's copy.
1625	fn refly(&self, key: u64, frame: u64) -> Option<super::track::Refly> {
1626		let cache = self.state.read().account()?.clone();
1627		let asking = super::group::asking(self.expiry.as_ref().map(|expiry| &expiry.policy));
1628		Some(super::track::Refly::new(cache, key, frame, asking))
1629	}
1630
1631	/// Poll the flight continuing this frame for the frame and its index, `None` when nothing
1632	/// can ask one.
1633	fn poll_flight(&mut self, waiter: &kio::Waiter) -> Option<Poll<Result<(Consumer, u64)>>> {
1634		let refly = self.flight()?;
1635		let index = refly.frame();
1636		Some(refly.poll_frame(waiter).map(|res| res.map(|frame| (frame, index))))
1637	}
1638
1639	/// Run `read`, and once this copy fails with its route, or stalls while a newer route
1640	/// serves, continue from the serving route's copy of the same frame, past the bytes
1641	/// already read. A copy the pool evicted continues the same way on a flight.
1642	fn poll_resumed<T>(
1643		&mut self,
1644		waiter: &kio::Waiter,
1645		mut read: impl FnMut(&mut Self, &kio::Waiter) -> Poll<Result<T>>,
1646	) -> Poll<Result<T>> {
1647		// A flight evicted before it gave a byte would fare no better asked again now.
1648		let mut flown = false;
1649		loop {
1650			let res = read(self, waiter);
1651			if self.expired {
1652				return res;
1653			}
1654			// Read to its end: no route is needed for it any more.
1655			if matches!(res, Poll::Ready(Ok(_))) && self.read_idx >= self.size() {
1656				self.resume = Resume::None;
1657			}
1658			let failed = match &res {
1659				Poll::Ready(Ok(_)) => return res,
1660				Poll::Ready(Err(err)) => Some(err.clone()),
1661				Poll::Pending => None,
1662			};
1663			let evicted = failed.is_some() && self.evicted();
1664			let cause = failed.map_or(super::resume::Cause::Stalled, super::resume::Cause::Failed);
1665			let reroute = match &mut self.resume {
1666				Resume::Route(routed) => {
1667					routed.recover.wants(&cause, waiter)
1668						// A route that would only repeat the eviction, as one the front concluded on
1669						// this copy does, leaves the frame to its flight.
1670						&& !(evicted && cause.error().is_some_and(|err| routed.recover.repeats(err)))
1671				}
1672				_ => false,
1673			};
1674			let (route, frame, index) = match &mut self.resume {
1675				Resume::None => return res,
1676				Resume::Route(routed) if reroute => {
1677					let Routed { recover, index, .. } = &mut **routed;
1678					if self.state.read().sparse() {
1679						return Poll::Ready(Err(Error::Unsupported));
1680					}
1681					let mut replacement = match recover.poll(*index, &cause, waiter) {
1682						Poll::Ready(Ok(group)) => group,
1683						Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
1684						Poll::Pending => return Poll::Pending,
1685					};
1686					let index = *index;
1687					// A cached group can precede this frame's header. Keep the old generation
1688					// until the replacement frame is actually available.
1689					if let Some(expiry) = &mut self.expiry {
1690						expiry.policy = expiry.policy.for_track(&replacement.copy);
1691					}
1692					// A stored compressed frame continues from the replacement's stored form,
1693					// where the byte offset means the same thing. A flight never carries one.
1694					if self.inflated.is_some() {
1695						replacement.group = replacement.group.compressed();
1696					}
1697					match replacement.group.poll_next_frame(waiter) {
1698						Poll::Ready(Ok(Some(frame))) => (Some(replacement), frame, index),
1699						Poll::Ready(Ok(None)) => return Poll::Ready(Err(Error::WrongSize)),
1700						Poll::Ready(Err(err)) => return Poll::Ready(Err(err)),
1701						Poll::Pending => return self.poll_expired_or(waiter, Poll::Pending),
1702					}
1703				}
1704				// Only the pool's eviction: any other failure is the group's own. It is no route's
1705				// doing either, so a routed frame takes a flight too, until its route moves.
1706				Resume::Arriving { .. } | Resume::Flight(_) | Resume::Route(_) => {
1707					if !evicted || flown {
1708						return res;
1709					}
1710					match self.poll_flight(waiter) {
1711						Some(Poll::Ready(Ok((frame, index)))) => {
1712							flown = true;
1713							(None, frame, index)
1714						}
1715						// The flight's verdict, such as `Old` for a group refused as stale.
1716						Some(Poll::Ready(Err(err))) => return Poll::Ready(Err(err)),
1717						// A read waiting on its flight is stalled like one waiting on its bytes.
1718						Some(Poll::Pending) => return self.poll_expired_or(waiter, Poll::Pending),
1719						None => return res,
1720					}
1721				}
1722			};
1723			// This copy was dense through its frame, so the replacement's must be the same
1724			// Object ID: a copy that begins past a gap holds different content there. A timed
1725			// copy's are moq-timestamp IDs instead, the same on every copy aligned from frame 0
1726			// (see `group::GroupState::relayed`), whichever draft each route spoke.
1727			if let Some(fields) = frame.fields.as_ref()
1728				&& fields.id != index
1729				&& self.fields.as_ref().is_none_or(|own| own.id != fields.id)
1730			{
1731				let aligned = frame.info.timestamp.scale().is_some() && {
1732					let state = frame.state.read();
1733					state.offset == 0 && !state.sparse()
1734				};
1735				if !aligned {
1736					return Poll::Ready(Err(Error::Unsupported));
1737				}
1738			}
1739			// Same name, same content: a different size is the routes disagreeing.
1740			if frame.info.size != self.info.size || frame.inflated != self.inflated {
1741				return Poll::Ready(Err(Error::ProtocolViolation));
1742			}
1743			if let (Some(replacement), Resume::Route(routed)) = (&route, &mut self.resume) {
1744				routed.recover.adopt(replacement);
1745				// A flight of the replaced copy brings nothing the new copy lacks.
1746				routed.flight = None;
1747			}
1748			self.state = frame.state;
1749			self.source = frame.source;
1750		}
1751	}
1752
1753	/// Whether the pool evicted this frame's copy, which a flight continues only when dense:
1754	/// a flight asks from the frame's ordinal, which names the frame only on a dense copy.
1755	fn evicted(&self) -> bool {
1756		let state = self.state.read();
1757		state.outcome.evicted() && !state.sparse()
1758	}
1759
1760	/// `Old` once the drift budget gives up on a stalled read, else `res`.
1761	fn poll_expired_or<T>(&mut self, waiter: &kio::Waiter, res: Poll<Result<T>>) -> Poll<Result<T>> {
1762		match self.poll_expired(waiter) {
1763			true => Poll::Ready(Err(Error::Old)),
1764			false => res,
1765		}
1766	}
1767
1768	/// Attach an egress meter so read-out chunks bump `bytes`. Used only for frames
1769	/// read directly from the group (whose bytes weren't counted at a batch fill).
1770	pub(super) fn with_meter(mut self, meter: stats::Meter) -> Self {
1771		self.stats = meter;
1772		self
1773	}
1774
1775	pub(super) fn with_expiry(mut self, expiry: Expiry) -> Self {
1776		self.expiry = Some(expiry);
1777		self
1778	}
1779
1780	fn size(&self) -> usize {
1781		match &self.source {
1782			Source::Complete(payload) => payload.len(),
1783			Source::Partial(_) => self.info.size as usize,
1784		}
1785	}
1786
1787	/// Evaluate the parent subscription's drift budget.
1788	///
1789	/// Only called once a read has nothing buffered to return: the budget bounds a
1790	/// *stalled* payload, so bytes already in hand are always drained rather than
1791	/// truncated. `self.expired` is sticky, so the answer is only ever computed once.
1792	fn poll_expired(&mut self, waiter: &kio::Waiter) -> bool {
1793		if self.expired || self.read_idx >= self.size() {
1794			return self.expired;
1795		}
1796		let Some(expiry) = &self.expiry else {
1797			return false;
1798		};
1799		let recover = match &self.resume {
1800			Resume::Route(routed) => Some(&routed.recover),
1801			_ => None,
1802		};
1803		if expiry.policy.is_expired(recover, waiter).is_none() {
1804			return false;
1805		}
1806
1807		self.expired = true;
1808		if !expiry.delivery.stale_counted.swap(true, Ordering::Relaxed) {
1809			let mut stale = self.state.read().content_range(expiry.tail.start, expiry.tail.end);
1810			if expiry.count_payload {
1811				stale.bytes += self.size().saturating_sub(self.read_idx) as u64;
1812			}
1813			expiry.stale_stats.stale(stale);
1814		}
1815		true
1816	}
1817
1818	/// The next chunk of bytes since the last read.
1819	///
1820	/// Returns `None` once the frame is finished and all bytes have been consumed.
1821	#[cfg_attr(feature = "async", kio::wrapper)]
1822	pub fn poll_read_chunk(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Bytes>>> {
1823		if matches!(self.resume, Resume::None) {
1824			return self.poll_read_chunk_once(waiter);
1825		}
1826		self.poll_resumed(waiter, Self::poll_read_chunk_once)
1827	}
1828
1829	fn poll_read_chunk_once(&mut self, waiter: &kio::Waiter) -> Poll<Result<Option<Bytes>>> {
1830		if self.expired {
1831			return Poll::Ready(Err(Error::Old));
1832		}
1833		let size = self.info.size as usize;
1834		loop {
1835			// Borrowed rather than cloned: every reader of the frame shares its count.
1836			let buf = match &self.source {
1837				Source::Complete(payload) => {
1838					if self.read_idx >= payload.len() {
1839						return Poll::Ready(Ok(None));
1840					}
1841					let out = payload.chunk_at(self.read_idx);
1842					self.read_idx += out.len();
1843					self.stats.bytes(out.len() as u64);
1844					return Poll::Ready(Ok(Some(out)));
1845				}
1846				Source::Partial(buf) => buf,
1847			};
1848			let written = buf.written(Ordering::Acquire);
1849			if written > self.read_idx {
1850				let out = buf.slice(self.read_idx, written);
1851				self.read_idx += out.len();
1852				self.stats.bytes(out.len() as u64);
1853				return Poll::Ready(Ok(Some(out)));
1854			}
1855			if written >= size {
1856				return Poll::Ready(Ok(None));
1857			}
1858			// Nothing buffered and the frame isn't finished: this park is the stall the
1859			// drift budget exists to bound, and the only place it can apply.
1860			if self.poll_expired(waiter) {
1861				return Poll::Ready(Err(Error::Old));
1862			}
1863			let Source::Partial(buf) = &self.source else {
1864				unreachable!("only a partial frame waits for its bytes");
1865			};
1866			let read_idx = self.read_idx;
1867			// Park on the group's channel; the producer notifies it on each write and
1868			// on abort. Re-check the atomic on wake.
1869			ready!(poll_state(&self.state, waiter, |state| {
1870				if let Some(err) = state.outcome.error() {
1871					return Poll::Ready(Err(err.clone()));
1872				}
1873				let w = buf.written(Ordering::Acquire);
1874				if w > read_idx || w >= size {
1875					Poll::Ready(Ok(()))
1876				} else {
1877					Poll::Pending
1878				}
1879			})?);
1880		}
1881	}
1882
1883	/// Return all remaining bytes once the frame is finished.
1884	#[cfg_attr(feature = "async", kio::wrapper)]
1885	pub fn poll_read_all(&mut self, waiter: &kio::Waiter) -> Poll<Result<Bytes>> {
1886		if matches!(self.resume, Resume::None) {
1887			return self.poll_read_all_once(waiter);
1888		}
1889		self.poll_resumed(waiter, Self::poll_read_all_once)
1890	}
1891
1892	fn poll_read_all_once(&mut self, waiter: &kio::Waiter) -> Poll<Result<Bytes>> {
1893		if self.expired {
1894			return Poll::Ready(Err(Error::Old));
1895		}
1896		let buf = match &self.source {
1897			Source::Complete(payload) => {
1898				let out = payload.contiguous(self.read_idx);
1899				self.read_idx = payload.len();
1900				self.stats.bytes(out.len() as u64);
1901				return Poll::Ready(Ok(out));
1902			}
1903			Source::Partial(buf) => buf.clone(),
1904		};
1905
1906		let size = self.info.size as usize;
1907		let read_idx = self.read_idx;
1908		// Waiting on the rest of the payload is a stall; see `poll_read_chunk`.
1909		if buf.written(Ordering::Acquire) < size && self.poll_expired(waiter) {
1910			return Poll::Ready(Err(Error::Old));
1911		}
1912		ready!(poll_state(&self.state, waiter, |state| {
1913			if let Some(err) = state.outcome.error() {
1914				return Poll::Ready(Err(err.clone()));
1915			}
1916			if buf.written(Ordering::Acquire) >= size {
1917				Poll::Ready(Ok(()))
1918			} else {
1919				Poll::Pending
1920			}
1921		})?);
1922		let out = buf.freeze().contiguous(read_idx);
1923		self.read_idx = size;
1924		self.stats.bytes(out.len() as u64);
1925		Poll::Ready(Ok(out))
1926	}
1927}
1928
1929/// Poll the group channel, mapping a terminal close without an error to
1930/// [`Error::Dropped`]. Mirrors [`group::Consumer`]'s internal helper.
1931fn poll_state<F, R>(state: &kio::Consumer<GroupState>, waiter: &kio::Waiter, f: F) -> Poll<Result<R>>
1932where
1933	F: Fn(&kio::Ref<'_, GroupState>) -> Poll<Result<R>>,
1934{
1935	Poll::Ready(match ready!(state.poll(waiter, f)) {
1936		Ok(res) => res,
1937		Err(state) => Err(state.outcome.error().cloned().unwrap_or(Error::Dropped)),
1938	})
1939}
1940
1941#[cfg(test)]
1942mod tests {
1943	use super::*;
1944
1945	#[test]
1946	fn activating_shared_content_transfers_payload_without_recording_it_twice() {
1947		let pool = cache::Pool::unbounded();
1948		let account = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
1949		let mut delivery = account.charge();
1950		delivery.add(8);
1951		let before = pool.used();
1952		account.take_written();
1953		let content = FrameBuf::from_payload(Bytes::from_static(b"abcdefgh").into());
1954		content.bill_content(delivery.transfer(8));
1955		assert_eq!(content.content_size(), 8 + FrameBuf::CONTENT_HEAP as u64);
1956		assert_eq!(pool.used(), before + FrameBuf::CONTENT_HEAP as u64);
1957		assert_eq!(
1958			account.take_written(),
1959			FrameBuf::CONTENT_HEAP as u64,
1960			"old payload is not a new write"
1961		);
1962		delivery.add(8);
1963		account.take_written();
1964		content.bill_content(delivery.transfer(8));
1965		assert_eq!(
1966			account.take_written(),
1967			0,
1968			"an already-canonical owner records no second write"
1969		);
1970		assert_eq!(pool.used(), before + FrameBuf::CONTENT_HEAP as u64);
1971		delivery.clear();
1972		assert_eq!(pool.used(), content.content_size());
1973		drop(content);
1974		assert_eq!(pool.used(), 0);
1975	}
1976
1977	#[test]
1978	fn canonical_content_keeps_each_delivery_progress_independent() {
1979		let a = FrameBuf::growing(8);
1980		let b = a.fork();
1981		let b_reader = b.clone();
1982		a.append(b"abcd").unwrap();
1983		let early = a.slice(0, 4);
1984		b.append(b"ab").unwrap();
1985		b.append(b"cdef").unwrap();
1986		assert_eq!((a.written(Ordering::Acquire), b.written(Ordering::Acquire)), (4, 6));
1987		assert_eq!(
1988			b_reader.written(Ordering::Acquire),
1989			6,
1990			"clones follow their own delivery"
1991		);
1992		a.append(b"efgh").unwrap();
1993		assert_eq!(
1994			b.written(Ordering::Acquire),
1995			6,
1996			"another producer's completion credits no bytes"
1997		);
1998		assert_eq!(b.shared_written(Ordering::Acquire), 8);
1999		assert_eq!(b.allocated(), 8, "the overlapping payload is stored once");
2000		b.append(b"gh").unwrap();
2001		assert_eq!(early, b"abcd".as_slice());
2002		let (left, right) = (a.freeze().contiguous(0), b.freeze().contiguous(0));
2003		assert_eq!(left, b"abcdefgh".as_slice());
2004		assert_eq!(left.as_ptr(), right.as_ptr());
2005		eprintln!(
2006			"canonical frame metadata: content={}B, view={}B",
2007			FrameBuf::CONTENT_HEAP,
2008			FrameBuf::VIEW_HEAP
2009		);
2010	}
2011
2012	/// A disagreement late in the overlap cannot publish an otherwise new suffix.
2013	#[test]
2014	fn a_conflicting_delivery_leaves_shared_content_and_progress_unchanged() {
2015		let size = SEGMENT + 8;
2016		let payload = pattern(0, size);
2017		let a = FrameBuf::growing(size);
2018		a.append(&payload[..SEGMENT + 4]).unwrap();
2019		let b = a.fork();
2020		b.append(&payload[..SEGMENT - 2]).unwrap();
2021		let allocated = a.allocated();
2022		let mut conflict = payload[SEGMENT - 2..].to_vec();
2023		conflict[3] ^= 1;
2024		assert!(matches!(b.append(&conflict), Err(Error::ProtocolViolation)));
2025		assert_eq!(b.written(Ordering::Acquire), SEGMENT - 2);
2026		assert_eq!(a.shared_written(Ordering::Acquire), SEGMENT + 4);
2027		assert_eq!(a.allocated(), allocated);
2028		a.append(&payload[SEGMENT + 4..]).unwrap();
2029		assert_eq!(a.freeze().contiguous(0), payload, "the valid delivery remains usable");
2030		assert!(matches!(b.append(&vec![0; size]), Err(Error::WrongSize)));
2031		assert_eq!(b.written(Ordering::Acquire), SEGMENT - 2);
2032	}
2033
2034	#[test]
2035	fn a_complete_chain_replays_without_copying_or_readmitting_it() {
2036		let payload = Payload::Chain(Chain {
2037			segments: Arc::from([Bytes::from(vec![1; SEGMENT]), Bytes::from_static(b"tail")]),
2038			start: 0,
2039		});
2040		let canonical = FrameBuf::from_payload(payload.clone());
2041		let copy = canonical.fork();
2042		assert_eq!(copy.written(Ordering::Acquire), 0);
2043		assert!(copy.admit(&Budget::new(0)).is_none());
2044		let mut at = 0;
2045		while at < payload.len() {
2046			let chunk = payload.chunk_at(at);
2047			copy.append(&chunk).unwrap();
2048			at += chunk.len();
2049		}
2050		let (Payload::Chain(original), Payload::Chain(replayed)) = (&payload, copy.freeze()) else {
2051			panic!("the chain stays segmented");
2052		};
2053		assert!(Arc::ptr_eq(&original.segments, &replayed.segments));
2054		assert_eq!(copy.allocated(), payload.len());
2055	}
2056
2057	#[test]
2058	fn simultaneous_deliveries_publish_one_segmented_payload() {
2059		const SIZE: usize = 2 * SEGMENT + 37;
2060		const ROUNDS: usize = 12;
2061		let payload = pattern(0, SIZE);
2062		for grow in [false, true] {
2063			let a = FrameBuf::with_growth(SIZE, grow);
2064			let b = a.fork();
2065			let barrier = std::sync::Barrier::new(2);
2066			std::thread::scope(|scope| {
2067				for (buf, chunk) in [(&a, SIZE.div_ceil(7)), (&b, SIZE.div_ceil(11))] {
2068					let (payload, barrier) = (&payload, &barrier);
2069					scope.spawn(move || {
2070						let mut at = 0;
2071						for round in 0..ROUNDS {
2072							barrier.wait();
2073							let end = ((round + 1) * chunk).min(SIZE);
2074							buf.append(&payload[at..end]).unwrap();
2075							assert_eq!(buf.written(Ordering::Acquire), end);
2076							at = end;
2077							barrier.wait();
2078						}
2079					});
2080				}
2081			});
2082			let (Payload::Chain(left), Payload::Chain(right)) = (a.freeze(), b.freeze()) else {
2083				panic!("chunked content stays segmented");
2084			};
2085			assert!(
2086				Arc::ptr_eq(&left.segments, &right.segments),
2087				"even the segment list is shared"
2088			);
2089			assert_eq!(a.allocated(), SIZE);
2090			assert_eq!(Payload::Chain(left).contiguous(0), payload);
2091		}
2092	}
2093
2094	#[test]
2095	fn admission_ends_with_active_producers_not_cached_views() {
2096		let budget = Budget::new(SEGMENT);
2097		let (a, a_active) = FrameBuf::admitted(SEGMENT + 1, &budget);
2098		let b = a.fork();
2099		let b_active = b.admit(&budget).unwrap();
2100		assert!(
2101			budget.reserve(1).is_none(),
2102			"the second producer shares the first's reservation"
2103		);
2104		a.append(&vec![7; SEGMENT + 1]).unwrap();
2105		let replay = a.fork();
2106		assert!(
2107			replay.admit(&budget).is_none(),
2108			"complete content reserves nothing on replay"
2109		);
2110		a.release(a_active.unwrap());
2111		assert!(
2112			budget.reserve(1).is_none(),
2113			"another active delivery owns the same reservation"
2114		);
2115		b.release(b_active);
2116		let returned = budget.reserve(SEGMENT).expect("cached views keep no admission alive");
2117		assert_eq!(b.written(Ordering::Acquire), 0);
2118		assert_eq!(replay.written(Ordering::Acquire), 0);
2119		drop(returned);
2120	}
2121
2122	/// The creator writes and ends alone without the publication, and a delivery that
2123	/// attaches later still shares its reservation.
2124	#[test]
2125	fn a_creator_alone_publishes_and_releases_without_attaching() {
2126		let budget = Budget::new(8);
2127		let (a, active) = FrameBuf::admitted(8, &budget);
2128		assert!(budget.reserve(1).is_none(), "the creator reserved its frame");
2129		a.append(b"abcd").unwrap();
2130		assert_eq!(a.shared_written(Ordering::Acquire), 4);
2131		a.release(active.unwrap());
2132		assert!(!a.content.attached.load(Ordering::Relaxed));
2133		drop(budget.reserve(8).expect("the creator's reservation returned"));
2134
2135		let (a, active) = FrameBuf::admitted(8, &budget);
2136		a.append(b"abcd").unwrap();
2137		let b = a.fork();
2138		let copy = b.admit(&budget).unwrap();
2139		assert!(budget.reserve(1).is_none(), "the attached copy shares the reservation");
2140		b.release(copy);
2141		assert!(
2142			budget.reserve(1).is_none(),
2143			"the attached creator still holds its reservation"
2144		);
2145		a.append(b"efgh").unwrap();
2146		assert!(matches!(b.append(b"abcdefgx"), Err(Error::ProtocolViolation)));
2147		a.release(active.unwrap());
2148		drop(budget.reserve(8).expect("the last producer returned it"));
2149	}
2150
2151	/// A delivery attaching while the creator streams without the lock never overlaps a
2152	/// write in flight: both see one payload, and a mismatch is still caught.
2153	#[test]
2154	fn a_delivery_attaching_mid_write_publishes_one_payload() {
2155		const SIZE: usize = SEGMENT + 4093;
2156		// Repeating one period spares Miri a fill it would step through byte by byte,
2157		// half this test's time there.
2158		let mut payload = (0..251).collect::<Vec<u8>>().repeat(SIZE.div_ceil(251));
2159		payload.truncate(SIZE);
2160		for grow in [false, true] {
2161			let budget = Budget::new(if grow { 0 } else { SEGMENT });
2162			let (a, active) = FrameBuf::admitted(SIZE, &budget);
2163			let attached = std::sync::Barrier::new(2);
2164			std::thread::scope(|scope| {
2165				scope.spawn(|| {
2166					for chunk in payload.chunks(97) {
2167						a.append(chunk).unwrap();
2168						if a.written(Ordering::Relaxed) == 97 * 64 {
2169							attached.wait();
2170						}
2171					}
2172				});
2173				attached.wait();
2174				let b = a.fork();
2175				for chunk in payload.chunks(1021) {
2176					b.append(chunk).unwrap();
2177				}
2178				assert_eq!(b.written(Ordering::Acquire), SIZE);
2179			});
2180			a.release(active.unwrap());
2181			assert_eq!(a.freeze().contiguous(0), payload);
2182			assert_eq!(a.allocated(), SIZE);
2183		}
2184	}
2185
2186	#[test]
2187	fn unadmitted_deliveries_share_the_same_growing_frame() {
2188		let budget = Budget::new(0);
2189		let a = FrameBuf::new(SEGMENT);
2190		let b = a.fork();
2191		let _left = a.admit(&budget).unwrap();
2192		let _right = b.admit(&budget).unwrap();
2193		assert!(!a.reserved());
2194		a.append(b"a").unwrap();
2195		assert_eq!(a.allocated(), 1, "failed admission grows only with received bytes");
2196		b.append(b"ab").unwrap();
2197		assert_eq!(a.allocated(), 2);
2198		assert_eq!((a.written(Ordering::Acquire), b.written(Ordering::Acquire)), (1, 2));
2199	}
2200
2201	#[test]
2202	fn canonical_and_delivery_charges_follow_their_last_owners() {
2203		let pool = cache::Pool::unbounded();
2204		let account = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2205		let charge = account.charge();
2206		let baseline = pool.used();
2207		let a = FrameBuf::growing(8);
2208		let active = a.admit(&Budget::new(0)).unwrap();
2209		a.append(b"abcd").unwrap();
2210		assert_eq!(pool.used(), baseline, "the content has not attached its account yet");
2211		a.bill_content(charge.extra());
2212		a.bill_view(charge.extra());
2213		assert_eq!(
2214			pool.used(),
2215			baseline + FrameBuf::CONTENT_HEAP as u64 + 4,
2216			"the creating delivery's progress is billed with its content"
2217		);
2218		let b = a.fork();
2219		b.bill_content(charge.extra());
2220		b.bill_view(charge.extra());
2221		let reader = b.clone();
2222		reader.bill_view(charge.extra());
2223		let metadata = (FrameBuf::CONTENT_HEAP + FrameBuf::VIEW_HEAP) as u64;
2224		assert_eq!(
2225			pool.used(),
2226			baseline + metadata + 4,
2227			"late attachment and clones charge once"
2228		);
2229		b.append(b"abcdef").unwrap();
2230		assert_eq!(
2231			pool.used(),
2232			baseline + metadata + 6,
2233			"overlap contributes only two new bytes"
2234		);
2235		a.append(b"efgh").unwrap();
2236		assert_eq!(pool.used(), baseline + metadata + 8);
2237		a.release(active);
2238		drop(a);
2239		assert_eq!(pool.used(), baseline + metadata + 8, "the fork still holds the content");
2240		drop(b);
2241		assert_eq!(
2242			pool.used(),
2243			baseline + metadata + 8,
2244			"the streaming clone owns its view and content"
2245		);
2246		drop(reader);
2247		assert_eq!(pool.used(), baseline, "all intrinsic charges release with content");
2248	}
2249
2250	#[test]
2251	fn admission_allocates_nothing_and_completed_payload_needs_none() {
2252		let pool = cache::Pool::unbounded();
2253		let account = cache::Track::new(pool.clone(), Default::default(), Default::default(), kio::Weak::new());
2254		let charge = account.charge();
2255		let baseline = pool.used();
2256		let a = FrameBuf::new(8);
2257		a.bill_content(charge.extra());
2258		a.bill_view(charge.extra());
2259		let metadata = FrameBuf::CONTENT_HEAP as u64;
2260		assert_eq!(pool.used(), baseline + metadata);
2261		let budget = Budget::new(0);
2262		let first = a.admit(&budget).unwrap();
2263		let copy = a.fork();
2264		let second = copy.admit(&budget).unwrap();
2265		assert_eq!(
2266			pool.used(),
2267			baseline + metadata,
2268			"an admission lives in its content, allocating nothing"
2269		);
2270		a.release(first);
2271		copy.release(second);
2272		let resumed = a.admit(&budget).unwrap();
2273		assert_eq!(
2274			pool.used(),
2275			baseline + metadata,
2276			"a renewed admission allocates nothing either"
2277		);
2278		a.append(b"abcdefgh").unwrap();
2279		assert_eq!(a.content_size(), (FrameBuf::CONTENT_HEAP + 8) as u64);
2280		assert_eq!(a.view_size(), 0, "the creating delivery's view is part of its content");
2281		assert_eq!(copy.view_size(), 0, "a fork starts without a delivery charge");
2282		a.release(resumed);
2283		drop(a);
2284		drop(copy);
2285		assert_eq!(pool.used(), baseline);
2286
2287		let payload = Bytes::from_static(b"complete");
2288		let complete = FrameBuf::from_payload(payload.clone().into());
2289		complete.bill_content(charge.extra());
2290		complete.bill_view(charge.extra());
2291		assert!(complete.admit(&budget).is_none());
2292		assert_eq!(complete.content_size(), (FrameBuf::CONTENT_HEAP + payload.len()) as u64);
2293		assert_eq!(pool.used(), baseline + metadata + payload.len() as u64);
2294		assert_eq!(complete.freeze().contiguous(0).as_ptr(), payload.as_ptr());
2295		drop(complete);
2296		assert_eq!(pool.used(), baseline);
2297	}
2298
2299	/// Each reallocation leaves the slices already handed out intact, and the last
2300	/// segment is exactly the frame, so the payload freezes without another copy.
2301	#[test]
2302	fn growing_buffer_keeps_handed_out_slices() {
2303		let buf = FrameBuf::growing(10);
2304		buf.append(b"abc").unwrap();
2305		assert_eq!(buf.allocated(), 3);
2306		let early = buf.slice(0, 3);
2307
2308		buf.append(b"defg").unwrap();
2309		assert_eq!(buf.allocated(), 7);
2310		buf.append(b"hij").unwrap();
2311		assert_eq!(buf.allocated(), 10, "doubling stops at the declared size");
2312
2313		assert_eq!(early, &b"abc"[..]);
2314		assert_eq!(buf.slice(3, 7), &b"defg"[..]);
2315		assert_eq!(buf.freeze().contiguous(0), &b"abcdefghij"[..]);
2316	}
2317
2318	/// A reader on another thread slicing while the writer reallocates only ever sees
2319	/// the bytes that were written.
2320	#[test]
2321	fn growing_buffer_reads_across_threads() {
2322		const SIZE: usize = 256 * 1024;
2323		let buf = FrameBuf::growing(SIZE);
2324		let reader = std::thread::spawn({
2325			let buf = buf.clone();
2326			move || {
2327				let mut read = 0;
2328				while read < SIZE {
2329					let written = buf.written(Ordering::Acquire);
2330					let chunk = buf.slice(read, written);
2331					for (i, byte) in chunk.iter().enumerate() {
2332						assert_eq!(*byte, ((read + i) % 251) as u8);
2333					}
2334					read = written;
2335					std::thread::yield_now();
2336				}
2337			}
2338		});
2339
2340		let payload = pattern(0, SIZE);
2341		for chunk in payload.chunks(1000) {
2342			buf.append(chunk).unwrap();
2343		}
2344		reader.join().unwrap();
2345		assert_eq!(buf.freeze().contiguous(0), payload);
2346	}
2347
2348	/// The segment a buffer is writing into, wherever its storage keeps it.
2349	fn open_segment(buf: &FrameBuf) -> Weak<Segment> {
2350		let segment = match buf.content.storage.get() {
2351			Some(FrameStorage::Fixed { segment, .. }) => segment.clone(),
2352			Some(FrameStorage::Growing(open)) => open.lock().unwrap().segment.clone(),
2353			Some(FrameStorage::Chain(segments)) => segments.lock().unwrap().open.as_ref().unwrap().segment.clone(),
2354			_ => panic!("no segment is being written"),
2355		};
2356		Arc::downgrade(&segment)
2357	}
2358
2359	/// Readers reading up to the same published length share one owner of its segment, so
2360	/// a read allocates per publication rather than per reader. Growth drops that owner,
2361	/// so the old segment lives only as long as the slices already cut from it.
2362	#[test]
2363	fn readers_share_one_owner_per_publication() {
2364		for (size, grow) in [(16, false), (16, true), (SEGMENT + 16, false), (SEGMENT + 16, true)] {
2365			let case = format!("size={size} grow={grow}");
2366			let buf = FrameBuf::with_growth(size, grow);
2367			buf.append(b"abcd").unwrap();
2368			let segment = open_segment(&buf);
2369			let first: Vec<Bytes> = (0..8).map(|_| buf.slice(0, 4)).collect();
2370			assert!(first.iter().all(|slice| slice == &b"abcd"[..]), "{case}");
2371			// A reader behind the published length shares the owner too.
2372			assert_eq!(buf.slice(1, 3), &b"bc"[..], "{case}");
2373			// The storage's reference and the readers' one owner.
2374			assert_eq!(segment.strong_count(), 2, "{case}");
2375
2376			buf.append(b"efgh").unwrap();
2377			let second: Vec<Bytes> = (0..8).map(|_| buf.slice(4, 8)).collect();
2378			assert!(second.iter().all(|slice| slice == &b"efgh"[..]), "{case}");
2379			if grow {
2380				assert!(!open_segment(&buf).ptr_eq(&segment), "{case}: outgrew its segment");
2381				// Only the owner the first readers hold.
2382				assert_eq!(segment.strong_count(), 1, "{case}");
2383				drop(first);
2384				assert_eq!(segment.strong_count(), 0, "{case}");
2385			} else {
2386				// The storage's, the first readers' owner, and the second readers' owner.
2387				assert_eq!(segment.strong_count(), 3, "{case}");
2388			}
2389		}
2390	}
2391
2392	/// A frame larger than a segment allocates only the segment being written, whatever it
2393	/// declared, and seals each at the same fixed boundary. Reads never cross one, and a
2394	/// whole read copies the chain into one buffer.
2395	#[test]
2396	fn chain_allocates_a_segment_at_a_time() {
2397		const SIZE: usize = 2 * SEGMENT + 100;
2398		// Straddles every segment boundary.
2399		const CHUNK: usize = 300_000;
2400		let payload = pattern(0, SIZE);
2401
2402		for grow in [false, true] {
2403			let buf = FrameBuf::with_growth(SIZE, grow);
2404			let mut read = 0;
2405			for chunk in payload.chunks(CHUNK) {
2406				buf.append(chunk).unwrap();
2407				let written = buf.written(Ordering::Acquire);
2408				let ahead = written.next_multiple_of(SEGMENT).min(SIZE);
2409				assert!(
2410					buf.allocated() <= ahead,
2411					"grow={grow}: {} past {written}",
2412					buf.allocated()
2413				);
2414
2415				while read < written {
2416					let slice = buf.slice(read, written);
2417					assert_eq!(slice, payload[read..read + slice.len()]);
2418					assert!(
2419						read / SEGMENT == (read + slice.len() - 1) / SEGMENT,
2420						"a read crossed a segment"
2421					);
2422					read += slice.len();
2423				}
2424			}
2425
2426			let Payload::Chain(chain) = buf.freeze() else {
2427				panic!("grow={grow}: a frame past one segment is a chain");
2428			};
2429			let lens: Vec<usize> = chain.segments.iter().map(Bytes::len).collect();
2430			assert_eq!(lens, [SEGMENT, SEGMENT, 100]);
2431			assert_eq!(buf.freeze().contiguous(0), payload);
2432			assert_eq!(buf.freeze().contiguous(SEGMENT + 1), payload[SEGMENT + 1..]);
2433		}
2434	}
2435
2436	/// A chain read as a [`Buf`] hands out each segment without a copy and advances only
2437	/// its own view.
2438	#[test]
2439	fn chain_reads_as_a_buf() {
2440		let first = Bytes::from(vec![1u8; SEGMENT]);
2441		let stored = Payload::Chain(Chain {
2442			segments: Arc::from([first.clone(), Bytes::from_static(b"tail")]),
2443			start: 0,
2444		});
2445
2446		let mut view = stored.clone();
2447		assert_eq!(view.chunk().len(), SEGMENT);
2448		let head = view.copy_to_bytes(SEGMENT - 1);
2449		assert_eq!(head.as_ptr(), first.as_ptr(), "a read within a segment copied");
2450		assert_eq!(view.copy_to_bytes(3), &[1, b't', b'a'][..], "a read across segments");
2451		assert_eq!(view.chunk(), b"il");
2452		assert_eq!(view.remaining(), 2);
2453		assert_eq!(stored.len(), SEGMENT + 4, "the stored payload never moved");
2454	}
2455
2456	/// A reservation holds its bytes until it drops, and a request larger than what
2457	/// remains takes nothing.
2458	#[test]
2459	fn budget_returns_reservations() {
2460		let budget = Budget::new(100);
2461		let a = budget.reserve(60).unwrap();
2462		assert!(budget.reserve(41).is_none());
2463		let b = budget.reserve(40).unwrap();
2464		assert!(budget.reserve(1).is_none());
2465
2466		drop(a);
2467		drop(b);
2468		assert!(budget.reserve(100).is_some());
2469	}
2470}