Skip to main content

rusty_rtos_kernel_core/
stream.rs

1//! `stream_buffer.c`: a byte ring one task writes and another reads.
2//!
3//! A stream buffer is the only kernel object here that is not built on a
4//! queue and not built on an event list. It is a ring of bytes plus two
5//! task handles, and a task waiting on one blocks on a **task
6//! notification** rather than on an event list — which is why the
7//! notification API had to exist before this file could.
8//!
9//! Two shapes share the code:
10//!
11//! * a **stream buffer** passes bytes, and a reader wakes when at least
12//!   the trigger level of them have arrived;
13//! * a **message buffer** passes whole messages, by writing the length in
14//!   front of each one. A read returns one message or nothing.
15//!
16//! The length prefix is `sizeof( configMESSAGE_BUFFER_LENGTH_TYPE )` wide,
17//! which is `size_t` unless a configuration says otherwise — eight bytes on
18//! the machine the oracle runs on. That width is in the arithmetic of every
19//! message send, so it is a [`Config`] const here rather than a guess.
20
21use rusty_rtos_core::config::Config;
22use rusty_rtos_core::error::{Error, Result};
23use rusty_rtos_core::handle::{StreamBufferHandle, TaskHandle};
24use rusty_rtos_core::hooks::TickHook;
25use rusty_rtos_core::isr::Woken;
26use rusty_rtos_core::port::Port;
27use rusty_rtos_core::trace::{Event, Trace};
28
29use crate::kernel::{Kernel, NotifyAction, OwedTrace};
30use crate::queue::{Blocked, Ready, Wait};
31
32/// One stream or message buffer.
33#[derive(Debug, Clone, Copy, Default)]
34pub(crate) struct StreamBuffer {
35    /// Where this buffer's bytes start in the kernel's byte arena.
36    pub(crate) base: usize,
37    /// `xLength`: the ring is one byte longer than the buffer asked for,
38    /// because a ring that is full and a ring that is empty would otherwise
39    /// look the same.
40    pub(crate) length: usize,
41    /// `xTriggerLevelBytes`.
42    pub(crate) trigger: usize,
43    /// `xHead`: where the next byte is written.
44    pub(crate) head: usize,
45    /// `xTail`: where the next byte is read.
46    pub(crate) tail: usize,
47    /// `xTaskWaitingToReceive`.
48    pub(crate) waiting_to_receive: TaskHandle,
49    /// `xTaskWaitingToSend`.
50    pub(crate) waiting_to_send: TaskHandle,
51    /// `sbFLAGS_IS_MESSAGE_BUFFER`.
52    pub(crate) is_message: bool,
53    /// `uxNotificationIndex`.
54    pub(crate) notify_index: usize,
55}
56
57impl StreamBuffer {
58    /// `prvBytesInBuffer`.
59    ///
60    /// The C adds the length before subtracting the tail so the unsigned
61    /// arithmetic cannot go below zero, then folds the extra length back
62    /// out. These are the C's own operations, and they need no checks for
63    /// the same reason the C's do not.
64    ///
65    /// `head` and `tail` are kept below `length` by the wrap arithmetic that
66    /// writes them, and `length` is at least 1. So `length + head` is at
67    /// most `2 * length - 1` and cannot overflow; `length + head - tail` is
68    /// at least `head + 1` and cannot underflow; and the fold only runs when
69    /// `count >= length`, where `count` is at most `2 * length - 1`, so it
70    /// lands back inside `0..length`.
71    #[inline]
72    pub(crate) const fn bytes_in_buffer(&self) -> usize {
73        let mut count = self.length.wrapping_add(self.head).wrapping_sub(self.tail);
74        if count >= self.length {
75            count = count.wrapping_sub(self.length);
76        }
77        count
78    }
79
80    /// `xStreamBufferSpacesAvailable`: one less than the gap, because the
81    /// ring keeps a spare byte so full and empty do not look alike.
82    ///
83    /// Bounded as [`StreamBuffer::bytes_in_buffer`] is, with one more step:
84    /// `length + tail - head` is at least 1, because `head` is at most
85    /// `length - 1`, so taking the spare byte off it cannot underflow.
86    #[inline]
87    pub(crate) const fn spaces_available(&self) -> usize {
88        let mut space = self
89            .length
90            .wrapping_add(self.tail)
91            .wrapping_sub(self.head)
92            .wrapping_sub(1);
93        if space >= self.length {
94            space = space.wrapping_sub(self.length);
95        }
96        space
97    }
98
99    /// `prvBytesInBufferMeetTriggerLevel`, for the two shapes that are not
100    /// a batching buffer.
101    pub(crate) const fn meets_trigger(&self, bytes: usize) -> bool {
102        bytes >= self.trigger
103    }
104}
105
106impl<
107    C: Config,
108    P: Port,
109    T: Trace,
110    H,
111    const TASKS: usize,
112    const ITEMS: usize,
113    const LISTS: usize,
114    const QUEUES: usize,
115    const SLOTS: usize,
116    const BUFFERS: usize,
117    const BYTES: usize,
118    const TIMERS: usize,
119    const GROUPS: usize,
120    const TIMER_CMDS: usize,
121> Kernel<C, P, T, H, TASKS, ITEMS, LISTS, QUEUES, SLOTS, BUFFERS, BYTES, TIMERS, GROUPS, TIMER_CMDS>
122where
123    H: TickHook<Self>,
124{
125    /// How many bytes a message buffer spends on each message's length.
126    pub const MESSAGE_LENGTH_BYTES: usize = C::MESSAGE_LENGTH_BYTES;
127
128    /// `xStreamBufferCreate`.
129    ///
130    /// A trigger level of zero becomes one, as the C does: a reader that
131    /// woke on nothing would spin.
132    ///
133    /// # Errors
134    /// [`Error::Full`] when the buffer arena or the byte arena is full;
135    /// [`Error::InvalidArgument`] for a zero-length buffer.
136    pub fn stream_buffer_create(
137        &mut self,
138        size: usize,
139        trigger: usize,
140    ) -> Result<StreamBufferHandle> {
141        self.new_stream_buffer(size, trigger, false)
142    }
143
144    /// `xMessageBufferCreate`.
145    ///
146    /// # Errors
147    /// As [`Kernel::stream_buffer_create`]; a message buffer must also be
148    /// longer than one length prefix.
149    pub fn message_buffer_create(&mut self, size: usize) -> Result<StreamBufferHandle> {
150        if size <= Self::MESSAGE_LENGTH_BYTES {
151            return Err(Error::InvalidArgument);
152        }
153        self.new_stream_buffer(size, 1, true)
154    }
155
156    fn new_stream_buffer(
157        &mut self,
158        size: usize,
159        trigger: usize,
160        is_message: bool,
161    ) -> Result<StreamBufferHandle> {
162        let caller = self.current;
163        if size == 0 || trigger > size {
164            return Err(Error::InvalidArgument);
165        }
166        let trigger = if trigger == 0 { 1 } else { trigger };
167        // `xBufferSizeBytes++` before the allocation: the spare byte.
168        let length = size.saturating_add(1);
169        let base = self.take_bytes(length).ok_or(Error::Full)?;
170        let handle = self
171            .buffers
172            .try_insert(StreamBuffer {
173                base,
174                length,
175                trigger,
176                head: 0,
177                tail: 0,
178                waiting_to_receive: TaskHandle::NULL,
179                waiting_to_send: TaskHandle::NULL,
180                is_message,
181                notify_index: 0,
182            })
183            .map_err(|_| Error::Full)?;
184        self.account_for_allocation();
185        // The malloc's `xTaskResumeAll` can release a tick and switch us
186        // away, and the C's thread then stops there with
187        // `traceSTREAM_BUFFER_CREATE` still ahead of it -- so the line
188        // belongs to this task's NEXT run, not to whoever took the CPU.
189        self.trace_failure_or_owe(
190            caller,
191            OwedTrace::StreamBufferCreate {
192                buffer: handle,
193                is_message_buffer: is_message,
194            },
195        );
196        Ok(handle)
197    }
198
199    /// Take `length` bytes of the arena: first fit from what deleted
200    /// buffers gave back, and only then from the untouched end.
201    ///
202    /// First fit rather than best fit because the pattern that needs an
203    /// allocator at all is create-then-delete of the *same size*, which
204    /// first fit serves exactly and without fragmenting.
205    fn take_bytes(&mut self, length: usize) -> Option<usize> {
206        for i in 0..self.free_count {
207            let (base, free) = *self.free_blocks.get(i)?;
208            if free < length {
209                continue;
210            }
211            if free == length {
212                self.drop_free_block(i);
213            } else if let Some(slot) = self.free_blocks.get_mut(i) {
214                *slot = (base.saturating_add(length), free.wrapping_sub(length));
215            }
216            return Some(base);
217        }
218        let end = self.bytes_used.checked_add(length)?;
219        if end > BYTES {
220            return None;
221        }
222        let base = self.bytes_used;
223        self.bytes_used = end;
224        Some(base)
225    }
226
227    /// Give a block back, coalescing with whichever neighbours touch it so
228    /// the list cannot grow past one entry per hole.
229    fn give_bytes(&mut self, base: usize, length: usize) {
230        let mut base = base;
231        let mut length = length;
232        let mut i = 0;
233        while i < self.free_count {
234            let Some(&(other_base, other_len)) = self.free_blocks.get(i) else {
235                break;
236            };
237            if other_base.saturating_add(other_len) == base {
238                base = other_base;
239                length = length.saturating_add(other_len);
240                self.drop_free_block(i);
241                continue;
242            }
243            if base.saturating_add(length) == other_base {
244                length = length.saturating_add(other_len);
245                self.drop_free_block(i);
246                continue;
247            }
248            i = i.wrapping_add(1);
249        }
250        // A block at the very end goes back to the bump pointer instead of
251        // the list, which is what keeps a create/delete loop free.
252        if base.saturating_add(length) == self.bytes_used {
253            self.bytes_used = base;
254            return;
255        }
256        if let Some(slot) = self.free_blocks.get_mut(self.free_count) {
257            *slot = (base, length);
258            self.free_count = self.free_count.wrapping_add(1);
259        }
260    }
261
262    fn drop_free_block(&mut self, index: usize) {
263        let last = self.free_count.saturating_sub(1);
264        if index < last {
265            if let Some(&moved) = self.free_blocks.get(last) {
266                if let Some(slot) = self.free_blocks.get_mut(index) {
267                    *slot = moved;
268                }
269            }
270        }
271        self.free_count = last;
272    }
273
274    /// `vStreamBufferDelete`: the handle goes stale and the ring's bytes go
275    /// back to the arena.
276    ///
277    /// # Errors
278    /// [`Error::Gone`] for a stale handle.
279    pub fn stream_buffer_delete(&mut self, buffer: StreamBufferHandle) -> Result<()> {
280        let b = *self.buffers.resolve(buffer)?;
281        let _ = self.buffers.discard(buffer);
282        self.give_bytes(b.base, b.length);
283        // `vStreamBufferDelete` ends in `vPortFree` (stream_buffer.c:582),
284        // and `heap_4` brackets that with `vTaskSuspendAll` /
285        // `xTaskResumeAll` -- which takes a critical section, and on the sim
286        // a critical-section exit is the clock. The create paid for its
287        // `pvPortMalloc` and the delete did not, so every deleted buffer
288        // lost one exit. `StreamBufferDemo`'s trigger-level test deletes one
289        // per pass and drifted by exactly 1 at its second `vTaskDelay`.
290        //
291        // The timer service's `Delete` arm had the identical defect.
292        self.account_for_allocation();
293        Ok(())
294    }
295
296    /// `xStreamBufferBytesAvailable`. No critical section, as in the C.
297    ///
298    /// # Errors
299    /// [`Error::Gone`] for a stale handle.
300    pub fn stream_buffer_bytes_available(&self, buffer: StreamBufferHandle) -> Result<usize> {
301        Ok(self.buffers.resolve(buffer)?.bytes_in_buffer())
302    }
303
304    /// `xStreamBufferSpacesAvailable`. No critical section, as in the C.
305    ///
306    /// # Errors
307    /// [`Error::Gone`] for a stale handle.
308    pub fn stream_buffer_spaces_available(&self, buffer: StreamBufferHandle) -> Result<usize> {
309        Ok(self.buffers.resolve(buffer)?.spaces_available())
310    }
311
312    /// `xStreamBufferIsEmpty`: head and tail in the same place.
313    ///
314    /// # Errors
315    /// [`Error::Gone`] for a stale handle.
316    pub fn stream_buffer_is_empty(&self, buffer: StreamBufferHandle) -> Result<bool> {
317        let b = self.buffers.resolve(buffer)?;
318        Ok(b.head == b.tail)
319    }
320
321    /// `xStreamBufferIsFull`: no room for another message.
322    ///
323    /// For a message buffer "another message" means at least one more byte
324    /// than its length prefix, so a buffer with exactly a prefix's worth of
325    /// room left is already full. A stream buffer compares against zero.
326    ///
327    /// # Errors
328    /// [`Error::Gone`] for a stale handle.
329    pub fn stream_buffer_is_full(&self, buffer: StreamBufferHandle) -> Result<bool> {
330        let b = self.buffers.resolve(buffer)?;
331        let prefix = if b.is_message {
332            Self::MESSAGE_LENGTH_BYTES
333        } else {
334            0
335        };
336        Ok(b.spaces_available() <= prefix)
337    }
338
339    /// `xStreamBufferSetTriggerLevel`.
340    ///
341    /// # Errors
342    /// [`Error::Gone`] for a stale handle.
343    pub fn stream_buffer_set_trigger_level(
344        &mut self,
345        buffer: StreamBufferHandle,
346        trigger: usize,
347    ) -> Result<bool> {
348        let length = self.buffers.resolve(buffer)?.length;
349        // Coerce first, then bounds-check, which is the order the C uses:
350        //
351        //     if( xTriggerLevel == ( size_t ) 0 ) { xTriggerLevel = 1; }
352        //     if( xTriggerLevel < pxStreamBuffer->xLength ) { ...pdPASS }
353        //     else { xReturn = pdFALSE; }
354        //
355        // The two orders disagree on exactly one input: a zero trigger
356        // against a length of ONE. Coercing first makes it 1, finds `1 < 1`
357        // false, and refuses without storing; bounds-checking first lets 0
358        // through and stores the coerced 1.
359        //
360        // THAT INPUT IS UNREACHABLE HERE, and the ordering is matched anyway
361        // rather than left to depend on it. `length` is `size + 1` -- the
362        // spare byte a ring buffer needs to tell full from empty, the C's
363        // own `xBufferSizeBytes++` -- and `size == 0` is refused at
364        // creation, so no buffer has a length of 1 and the orders agree on
365        // every input a caller can construct.
366        //
367        // Written down because the first version of this comment claimed a
368        // live divergence. It is not one; it is an inconsistency with the C
369        // that one arithmetic detail in a different function is keeping
370        // harmless.
371        let trigger = if trigger == 0 { 1 } else { trigger };
372        if trigger >= length {
373            return Ok(false);
374        }
375        self.buffers.resolve_mut(buffer)?.trigger = trigger;
376        Ok(true)
377    }
378
379    /// `xStreamBufferReset`: empty it, unless a task is waiting on it.
380    ///
381    /// # Errors
382    /// [`Error::Gone`] for a stale handle.
383    pub fn stream_buffer_reset(&mut self, buffer: StreamBufferHandle) -> Result<bool> {
384        self.enter_critical();
385        let done = match self.buffers.resolve_mut(buffer) {
386            Ok(b)
387                if b.waiting_to_receive.is_null()
388                    && b.waiting_to_send.is_null() =>
389            {
390                b.head = 0;
391                b.tail = 0;
392                true
393            }
394            _ => false,
395        };
396        self.exit_critical();
397        Ok(done)
398    }
399
400    /// `xStreamBufferNextMessageLengthBytes`.
401    ///
402    /// # Errors
403    /// [`Error::Gone`] for a stale handle.
404    pub fn stream_buffer_next_message_length(&self, buffer: StreamBufferHandle) -> Result<usize> {
405        let b = *self.buffers.resolve(buffer)?;
406        if !b.is_message {
407            return Ok(0);
408        }
409        let available = b.bytes_in_buffer();
410        if available <= Self::MESSAGE_LENGTH_BYTES {
411            return Ok(0);
412        }
413        Ok(Self::read_length_prefix_from(&self.bytes, b.base, b.length, b.tail).0)
414    }
415
416    // ---------------------------------------------------------- sending --
417
418    /// `xTaskCheckForTimeOut`, the tail of `xStreamBufferSend`'s do-while.
419    ///
420    /// The C wraps the sample-and-wait in
421    /// `do { ... } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait )
422    /// == pdFALSE )`, and that call takes a critical section of its own
423    /// (tasks.c:5703) -- so on the sim it is one more exit, and one more
424    /// sixteenth of a tick.
425    ///
426    /// It runs **only when the wait actually blocked**: a send that finds
427    /// the space it needs on the first pass leaves the loop with a `break`
428    /// from inside the sampling section and never reaches the condition.
429    /// `xStreamBufferReceive` has no loop and no such call, which is why
430    /// this is on the send alone.
431    fn check_for_time_out(&mut self) {
432        self.enter_critical();
433        self.exit_critical();
434    }
435
436    /// `xStreamBufferSend`.
437    ///
438    /// Returns how many bytes went in. `Blocked` means the caller must
439    /// make the same call again: the C loops here waiting for space, and a
440    /// kernel with no stacks returns between passes.
441    ///
442    /// # Errors
443    /// [`Error::Gone`] for a stale handle.
444    /// Sim contract v2: what a kernel call costs when it took no critical
445    /// section.
446    ///
447    /// v1 had two tick sources, the idle hook and every 16th outermost
448    /// critical-section exit. Both are kernel-visible points, and between
449    /// them they left one hole: a task that is always ready and whose
450    /// no-progress path takes no critical section takes NO TIME, never
451    /// yields, and stops the clock for every other task.
452    ///
453    /// `xStreamBufferSend` and `xStreamBufferReceive` are the only calls in
454    /// this corpus that can return that way -- the zero-wait path reads the
455    /// ring and leaves. Every other object closes the hole by accident:
456    /// `uxQueueMessagesWaiting`, `eTaskGetState` and `uxTaskPriorityGet`
457    /// all take a section. `StreamBufferDemo`'s `prvNonBlockingReceiverTask`
458    /// is the task that found it, and under v1 the whole run froze at
459    /// `ticks=1 exits=16` (`docs/HOLES.md`, H9).
460    ///
461    /// So a blind call costs exactly one empty critical section. Not a new
462    /// clock -- the SAME one, so the count, the every-16th rule, the
463    /// running-task test and the switch all reuse paths v1 already proved,
464    /// and `exits` keeps its meaning: the number of kernel-visible points.
465    /// The C port does the identical thing from
466    /// `traceRETURN_xStreamBufferSend` / `..._Receive`; see
467    /// `vPortKairosApiReturn`.
468    ///
469    /// A call that BLOCKED is not blind: the C's thread stops inside it,
470    /// other tasks run, and the counter has moved by the time the return
471    /// hook is reached. Comparing the count is what says so on both sides.
472    ///
473    /// Gated on `T::EMITS`, for the same reason [`Kernel::note_exits`] is, and
474    /// to MATCH the C rather than diverge from it. In the C this bracket is
475    /// `traceRETURN_xStreamBufferSend`, which `FreeRTOS.h` defines as **empty**
476    /// unless a config wires it. Only `oracle/harness/FreeRTOSConfig.h` does --
477    /// the sim. `bench/kernel-ram/c/FreeRTOSConfig.h`, which the rv32 flash arm
478    /// compiles against, defines no `traceRETURN_*` at all, so **C pays zero
479    /// bytes for it in the arm we measure** while we were paying for it
480    /// unconditionally. Same defect class as relaxation being off on our arm
481    /// only (scorecard 14).
482    ///
483    /// Nothing observes the bracket under a silent sink: the exits counter it
484    /// samples is read by no one, and the critical section it takes is a closed
485    /// window that restores the mask it found. Under an emitting sink -- which
486    /// is every `conform` scenario -- the gate is true and the behaviour is
487    /// exactly as before, which is why 26/26 is unchanged.
488    fn blind_call(&mut self, exits_at_entry: u64) {
489        if !T::EMITS {
490            return;
491        }
492        if self.port.exits() != exits_at_entry {
493            return;
494        }
495        self.enter_critical();
496        self.exit_critical();
497    }
498
499    /// `xStreamBufferSend`, with the contract-v2 bracket around it.
500    ///
501    /// # Errors
502    /// As [`Kernel::stream_buffer_send_inner`].
503    pub fn stream_buffer_send(
504        &mut self,
505        buffer: StreamBufferHandle,
506        data: &[u8],
507        ticks: u64,
508    ) -> Result<Wait<usize>> {
509        let entry = if T::EMITS { self.port.exits() } else { 0 };
510        let out = self.stream_buffer_send_inner(buffer, data, ticks);
511        self.blind_call(entry);
512        out
513    }
514
515    fn stream_buffer_send_inner(
516        &mut self,
517        buffer: StreamBufferHandle,
518        data: &[u8],
519        ticks: u64,
520    ) -> Result<Wait<usize>> {
521        let caller = self.current;
522        // ONLY the fields this body reads. It was `*self.buffers.resolve(..)`
523        // -- the whole nine-field descriptor, about thirty-two bytes on rv32 --
524        // to reach three of them. `notify_index` is read at four
525        // points spread across the body, each behind an `&mut self` call, so
526        // the descriptor had to stay LIVE across all of them and was spilled
527        // for it. Two scalars live in registers. Same finding as `queue_take`:
528        // the cost was the live range, not the copy.
529        let (is_message, length, notify_index) = {
530            let b = self.buffers.resolve(buffer)?;
531            (b.is_message, b.length, b.notify_index)
532        };
533        let max_reported = length.saturating_sub(1);
534        let mut required = data.len();
535        let mut ticks = ticks;
536        if is_message {
537            required = required.saturating_add(Self::MESSAGE_LENGTH_BYTES);
538            if required > max_reported {
539                // It will never fit, so do not wait for it to.
540                ticks = 0;
541            }
542        } else if required > max_reported {
543            required = max_reported;
544        }
545
546        let mut sampled = self.take_stream_resume(caller);
547        if let Some(space) = sampled {
548            // Resuming after the exit that sampled the space. The same
549            // point as in `stream_buffer_receive`: the C tests `xSpace <
550            // xRequiredSpace` below the exit, against the sample taken
551            // inside it, so a task preempted there still blocks.
552            if space < required {
553                match self.notify_wait(notify_index, 0, 0, ticks)? {
554                    Blocked => return Ok(Blocked),
555                    Ready(_) => {
556                        self.buffers.resolve_mut(buffer)?.waiting_to_send = TaskHandle::NULL;
557                        self.check_for_time_out();
558                        // The sample it went to sleep on is stale now, and
559                        // the C re-reads whenever that sample was zero.
560                        sampled = None;
561                    }
562                }
563            }
564        } else if self.notify_wait_pending(caller) {
565            match self.notify_wait(notify_index, 0, 0, ticks)? {
566                Blocked => return Ok(Blocked),
567                Ready(_) => {}
568            }
569            // Spelled out at all three resume arms rather than factored into a
570            // helper the way the receive side's `after_stream_wait` is. Factoring
571            // it measured **+28 B** on 2026-09-25, identical with and without
572            // `#[inline(never)]` -- so LLVM outlines it either way, and one shared
573            // body plus three calls costs more than three copies that each fold
574            // against their own arm.
575            self.buffers.resolve_mut(buffer)?.waiting_to_send = TaskHandle::NULL;
576            self.check_for_time_out();
577        } else if ticks > 0 {
578            // `vTaskSetTimeOutState( &xTimeOut )` (stream_buffer.c:878),
579            // which the C runs before it looks at the buffer at all.
580            //
581            // It is the PUBLIC entry point, so it takes a critical section
582            // of its own -- unlike the queue calls, which reach the same
583            // state through `vTaskInternalSetTimeOutState` from inside one.
584            // One exit per blocking send, and `StreamBufferDemo` makes the
585            // first of them 350 ticks in.
586            //
587            // ... and only once per call: a task preempted at this very
588            // exit resumes BELOW it, so re-entry must not buy it again.
589            if !self.take_stream_timed(caller) {
590                self.enter_critical();
591                self.exit_critical();
592                if self.current != caller {
593                    self.set_stream_timed(caller);
594                    return Ok(Blocked);
595                }
596            }
597            self.enter_critical();
598            let space = self.buffers.resolve(buffer)?.spaces_available();
599            let must_block = space < required;
600            if must_block {
601                let _ = self.notify_state_clear(None, notify_index);
602                self.buffers.resolve_mut(buffer)?.waiting_to_send = caller;
603            }
604            self.exit_critical();
605            // That exit can release a tick, and a tick can switch this task
606            // away. The C's thread stops inside the exit and everything
607            // below it runs when the task is resumed — with the sample it
608            // already took, and without paying for the section twice.
609            if self.current != caller {
610                self.set_stream_resume(caller, space);
611                return Ok(Blocked);
612            }
613            if must_block {
614                // `traceBLOCKING_ON_STREAM_BUFFER_SEND` is not one of the
615                // harness's hooks, so blocking says nothing on either side.
616                match self.notify_wait(notify_index, 0, 0, ticks)? {
617                    Blocked => return Ok(Blocked),
618                    Ready(_) => {
619                        self.buffers.resolve_mut(buffer)?.waiting_to_send = TaskHandle::NULL;
620                        self.check_for_time_out();
621                    }
622                }
623            }
624        }
625
626        let space = match sampled.take() {
627            Some(space) => space,
628            None => self.buffers.resolve(buffer)?.spaces_available(),
629        };
630        let written = self.write_message(buffer, data, space, required)?;
631        if written > 0 {
632            let tick = self.tick;
633            self.note_exits();
634            self.trace.event(
635                tick,
636                Event::StreamBufferSend {
637                    buffer,
638                    bytes: written,
639                },
640            );
641            // One resolve, not two: nothing moves between the byte count and
642            // the trigger test, and both read the same buffer. The block ends
643            // the borrow before the completion call needs `self` mutably.
644            let trigger = {
645                let b = self.buffers.resolve(buffer)?;
646                b.meets_trigger(b.bytes_in_buffer())
647            };
648            if trigger {
649                self.send_completed(buffer)?;
650            }
651        }
652        Ok(Ready(written))
653    }
654
655    /// `xStreamBufferSendFromISR`.
656    ///
657    /// # Errors
658    /// [`Error::Gone`] for a stale handle.
659    pub fn stream_buffer_send_from_isr(
660        &mut self,
661        buffer: StreamBufferHandle,
662        data: &[u8],
663    ) -> Result<(usize, Woken)> {
664        let snapshot = *self.buffers.resolve(buffer)?;
665        let max_reported = snapshot.length.saturating_sub(1);
666        let mut required = data.len();
667        if snapshot.is_message {
668            required = required.saturating_add(Self::MESSAGE_LENGTH_BYTES);
669        } else if required > max_reported {
670            required = max_reported;
671        }
672        let space = snapshot.spaces_available();
673        let written = self.write_message(buffer, data, space, required)?;
674        let mut woken = Woken::NO;
675        if written > 0 {
676            // `traceSTREAM_BUFFER_SEND_FROM_ISR` is a different macro from
677            // `traceSTREAM_BUFFER_SEND`, and the harness hooks only the
678            // latter — so an interrupt's send says nothing on either side.
679            // One resolve, not two: nothing moves between the byte count and
680            // the trigger test, and both read the same buffer. The block ends
681            // the borrow before the completion call needs `self` mutably.
682            let trigger = {
683                let b = self.buffers.resolve(buffer)?;
684                b.meets_trigger(b.bytes_in_buffer())
685            };
686            if trigger {
687                woken = self.send_completed_from_isr(buffer)?;
688            }
689        }
690        Ok((written, woken))
691    }
692
693    // -------------------------------------------------------- receiving --
694
695    /// What `xStreamBufferReceive` runs once its notify wait returns.
696    ///
697    /// `xTaskNotifyWaitIndexed`'s own trailing critical section can release
698    /// a tick and switch the caller away, and the C's thread then stops
699    /// THERE -- with `prvReadMessageFromBuffer` and
700    /// `traceSTREAM_BUFFER_RECEIVE` still ahead of it. So the bytes move,
701    /// and the line appears, on this task's next run and not inside
702    /// whoever took the CPU. `StreamBufferDemo`'s echo clients showed it
703    /// four times in a 2,000-tick run, each a receive traced six exits
704    /// early.
705    ///
706    /// `None` means "stop here"; the caller returns `Blocked` and the body
707    /// makes the same call again, which then takes the resume path.
708    // In line at all THREE callers, which are all inside
709    // `stream_buffer_receive_inner`.
710    //
711    // This said "A3: ONE caller in the linked kernel, so this pays a prologue
712    // and epilogue for a single call" until 2026-09-25. The caller count was
713    // simply wrong -- there are three -- so the A3 argument did not apply, and
714    // with three callers `#[inline]` DUPLICATES the body rather than moving it,
715    // which is the opposite of what the comment claimed.
716    //
717    // The decision survives the correction, measured: `#[inline(never)]` costs
718    // **+100 B** (receive 732 -> 686, but a 146 B symbol appears). Each inlined
719    // copy folds to roughly fifteen bytes against the surrounding control flow,
720    // while a standalone body pays a frame and two real handle resolves. Right
721    // answer, wrong reason, now with a number.
722    #[inline(always)]
723    fn after_stream_wait(
724        &mut self,
725        caller: TaskHandle,
726        buffer: StreamBufferHandle,
727    ) -> Result<Option<usize>> {
728        self.buffers.resolve_mut(buffer)?.waiting_to_receive = TaskHandle::NULL;
729        let available = self.buffers.resolve(buffer)?.bytes_in_buffer();
730        if self.current != caller {
731            // Merging these two into one accessor that resolves the TCB once
732            // measured **0 B** on 2026-09-25: `&mut self` is `noalias`, so LLVM
733            // had already shared the resolve across both setters. `list.rs`'s
734            // fourth pass says exactly this, and it applies to the TCB flag
735            // accessors too. Merging adjacent accessors only pays when an
736            // `&mut self` call stands BETWEEN them.
737            self.set_stream_waited(caller);
738            self.set_stream_resume(caller, available);
739            return Ok(None);
740        }
741        Ok(Some(available))
742    }
743
744    /// `xStreamBufferReceive`: bytes into `out`, and how many arrived.
745    ///
746    /// # Errors
747    /// [`Error::Gone`] for a stale handle.
748    /// `xStreamBufferReceive`, with the contract-v2 bracket around it.
749    /// See [`Kernel::blind_call`].
750    ///
751    /// # Errors
752    /// As [`Kernel::stream_buffer_receive_inner`].
753    pub fn stream_buffer_receive(
754        &mut self,
755        buffer: StreamBufferHandle,
756        out: &mut [u8],
757        ticks: u64,
758    ) -> Result<Wait<usize>> {
759        let entry = if T::EMITS { self.port.exits() } else { 0 };
760        let received = self.stream_buffer_receive_inner(buffer, out, ticks);
761        self.blind_call(entry);
762        received
763    }
764
765    fn stream_buffer_receive_inner(
766        &mut self,
767        buffer: StreamBufferHandle,
768        out: &mut [u8],
769        ticks: u64,
770    ) -> Result<Wait<usize>> {
771        let caller = self.current;
772        // ONLY the fields this body reads. It was `*self.buffers.resolve(..)`
773        // -- the whole nine-field descriptor, about thirty-two bytes on rv32 --
774        // to reach two of them. `notify_index` is read at four
775        // points spread across the body, each behind an `&mut self` call, so
776        // the descriptor had to stay LIVE across all of them and was spilled
777        // for it. Two scalars live in registers. Same finding as `queue_take`:
778        // the cost was the live range, not the copy.
779        let (is_message, notify_index) = {
780            let b = self.buffers.resolve(buffer)?;
781            (b.is_message, b.notify_index)
782        };
783        let prefix = if is_message {
784            Self::MESSAGE_LENGTH_BYTES
785        } else {
786            0
787        };
788        let mut available;
789        if let Some(local) = self.take_stream_resume(caller) {
790            // Resuming after the exit that sampled the buffer.
791            //
792            // The C's thread stops inside `taskEXIT_CRITICAL`, and when it
793            // runs again it still evaluates the `if( xBytesAvailable <=
794            // xBytesToStoreMessageLength )` BELOW that exit -- against the
795            // sample it took inside the section. So a task preempted there
796            // goes on to block exactly like one that was not.
797            //
798            // Falling straight through to the read instead returns 0 from a
799            // call that was told to wait 350 ticks, which is what
800            // `StreamBufferDemo`'s lower-priority echo server caught: the C
801            // blocked at tick 1 and the sim created its client instead.
802            available = local;
803            if !self.take_stream_waited(caller) && available <= prefix {
804                match self.notify_wait(notify_index, 0, 0, ticks)? {
805                    Blocked => return Ok(Blocked),
806                    Ready(_) => match self.after_stream_wait(caller, buffer)? {
807                        Some(now) => available = now,
808                        None => return Ok(Blocked),
809                    },
810                }
811            }
812        } else if self.notify_wait_pending(caller) {
813            // Resuming: the C's wait returns here, so its second half runs
814            // whatever the buffer now holds.
815            match self.notify_wait(notify_index, 0, 0, ticks)? {
816                Blocked => return Ok(Blocked),
817                Ready(_) => {}
818            }
819            match self.after_stream_wait(caller, buffer)? {
820                Some(now) => available = now,
821                None => return Ok(Blocked),
822            }
823        } else if ticks > 0 {
824            self.enter_critical();
825            available = self.buffers.resolve(buffer)?.bytes_in_buffer();
826            let must_block = available <= prefix;
827            if must_block {
828                let _ = self.notify_state_clear(None, notify_index);
829                self.buffers.resolve_mut(buffer)?.waiting_to_receive = caller;
830            }
831            self.exit_critical();
832            // That exit can release a tick, and a tick can switch this task
833            // away. The C's thread stops inside the exit and everything
834            // below it runs when the task is resumed — with the sample it
835            // already took, and without paying for the section twice.
836            if self.current != caller {
837                self.set_stream_resume(caller, available);
838                return Ok(Blocked);
839            }
840            if must_block {
841                match self.notify_wait(notify_index, 0, 0, ticks)? {
842                    Blocked => return Ok(Blocked),
843                    Ready(_) => match self.after_stream_wait(caller, buffer)? {
844                        Some(now) => available = now,
845                        None => return Ok(Blocked),
846                    },
847                }
848            }
849        } else {
850            available = self.buffers.resolve(buffer)?.bytes_in_buffer();
851        }
852
853        let mut received = 0;
854        if available > prefix {
855            received = self.read_message(buffer, out, available)?;
856            if received != 0 {
857                let tick = self.tick;
858                self.note_exits();
859                self.trace.event(
860                    tick,
861                    Event::StreamBufferReceive {
862                        buffer,
863                        bytes: received,
864                    },
865                );
866                self.receive_completed(buffer)?;
867            }
868        }
869        Ok(Ready(received))
870    }
871
872    /// `xStreamBufferReceiveFromISR`.
873    ///
874    /// # Errors
875    /// [`Error::Gone`] for a stale handle.
876    pub fn stream_buffer_receive_from_isr(
877        &mut self,
878        buffer: StreamBufferHandle,
879        out: &mut [u8],
880    ) -> Result<(usize, Woken)> {
881        let snapshot = *self.buffers.resolve(buffer)?;
882        let prefix = if snapshot.is_message {
883            Self::MESSAGE_LENGTH_BYTES
884        } else {
885            0
886        };
887        let available = snapshot.bytes_in_buffer();
888        let mut received = 0;
889        let mut woken = Woken::NO;
890        if available > prefix {
891            received = self.read_message(buffer, out, available)?;
892            if received != 0 {
893                // `traceSTREAM_BUFFER_RECEIVE_FROM_ISR`, likewise unhooked.
894                woken = self.receive_completed_from_isr(buffer)?;
895            }
896        }
897        Ok((received, woken))
898    }
899
900    // --------------------------------------------------- the completions --
901
902    /// `sbSEND_COMPLETED`: tell a waiting reader, with the scheduler
903    /// suspended so the notify cannot switch away mid-update.
904    ///
905    /// The application may replace it — that is what the macro is for, and
906    /// `MessageBufferAMP` is the demo that does — so the hook gets first
907    /// refusal and `true` means it handled the whole thing.
908    // No `inline`: one was tried and cost 323,801 instructions on
909    // `StreamBufferDemo`. The body is small but it is reached from inside
910    // `stream_buffer_send`, which is already large.
911    // A3: ONE caller in the linked kernel, so this pays a prologue and epilogue
912    // for a single call. Inlining moves the body rather than duplicating it.
913    #[inline(always)]
914    fn send_completed(&mut self, buffer: StreamBufferHandle) -> Result<()> {
915        if H::send_completed(self, buffer) {
916            return Ok(());
917        }
918        self.suspend_all();
919        let waiting = self.buffers.resolve(buffer)?.waiting_to_receive;
920        if !waiting.is_null() {
921            let index = self.buffers.resolve(buffer)?.notify_index;
922            let _ = self.notify(waiting, index, 0, NotifyAction::None)?;
923            self.buffers.resolve_mut(buffer)?.waiting_to_receive = TaskHandle::NULL;
924        }
925        let _ = self.resume_all();
926        Ok(())
927    }
928
929    /// `xStreamBufferSendCompletedFromISR` / `sbSEND_COMPLETED_FROM_ISR`.
930    ///
931    /// Public because an application that replaced [`TickHook::send_completed`]
932    /// has to be able to do the notify itself, later and from interrupt
933    /// context — which is exactly what `MessageBufferAMP` does once its
934    /// stand-in interrupt has read the handle back off the control buffer.
935    ///
936    /// # Errors
937    /// [`Error::Gone`] for a stale handle.
938    pub fn send_completed_from_isr(&mut self, buffer: StreamBufferHandle) -> Result<Woken> {
939        let waiting = self.buffers.resolve(buffer)?.waiting_to_receive;
940        if waiting.is_null() {
941            return Ok(Woken::NO);
942        }
943        let index = self.buffers.resolve(buffer)?.notify_index;
944        let (_, woken) = self.notify_from_isr(waiting, index, 0, NotifyAction::None)?;
945        self.buffers.resolve_mut(buffer)?.waiting_to_receive = TaskHandle::NULL;
946        Ok(woken)
947    }
948
949    /// `sbRECEIVE_COMPLETED`.
950    fn receive_completed(&mut self, buffer: StreamBufferHandle) -> Result<()> {
951        self.suspend_all();
952        let waiting = self.buffers.resolve(buffer)?.waiting_to_send;
953        if !waiting.is_null() {
954            let index = self.buffers.resolve(buffer)?.notify_index;
955            let _ = self.notify(waiting, index, 0, NotifyAction::None)?;
956            self.buffers.resolve_mut(buffer)?.waiting_to_send = TaskHandle::NULL;
957        }
958        let _ = self.resume_all();
959        Ok(())
960    }
961
962    /// `sbRECEIVE_COMPLETED_FROM_ISR`.
963    fn receive_completed_from_isr(&mut self, buffer: StreamBufferHandle) -> Result<Woken> {
964        let waiting = self.buffers.resolve(buffer)?.waiting_to_send;
965        if waiting.is_null() {
966            return Ok(Woken::NO);
967        }
968        let index = self.buffers.resolve(buffer)?.notify_index;
969        let (_, woken) = self.notify_from_isr(waiting, index, 0, NotifyAction::None)?;
970        self.buffers.resolve_mut(buffer)?.waiting_to_send = TaskHandle::NULL;
971        Ok(woken)
972    }
973
974    // ------------------------------------------------ the ring itself --
975
976    /// `prvWriteMessageToBuffer`.
977    fn write_message(
978        &mut self,
979        buffer: StreamBufferHandle,
980        data: &[u8],
981        space: usize,
982        required: usize,
983    ) -> Result<usize> {
984        // ONE resolve, and the descriptor is written through in place.
985        //
986        // This used to copy the whole nine-field descriptor out
987        // (`*self.buffers.resolve(..)`) and then resolve a SECOND time to store
988        // the new head, because `write_bytes` wanted `&mut self` and so nothing
989        // borrowed from `self` could be alive across it. Destructuring `self`
990        // into disjoint field borrows removes both the copy and the second
991        // resolve: `buffers` and `bytes` are different fields, so the borrow
992        // checker allows what C does with one pointer.
993        let Self { buffers, bytes, .. } = self;
994        let b = buffers.resolve_mut(buffer)?;
995        let (base, ring, is_message) = (b.base, b.length, b.is_message);
996        let mut next_head = b.head;
997        let mut length = data.len();
998        let mut space = space;
999        if is_message {
1000            if space >= required {
1001                // `write_length_prefix`, folded in: it was a one-caller wrapper
1002                // whose whole body was this.
1003                // `length.to_le_bytes()`, not `(length as u64).to_le_bytes()`:
1004                // the widening wrote eight bytes on a target whose `size_t` is
1005                // four, and the top half was never sent.
1006                let raw = length.to_le_bytes();
1007                let prefix = raw.get(..Self::MESSAGE_LENGTH_BYTES).unwrap_or(&raw);
1008                next_head = Self::write_bytes_into(bytes, base, ring, prefix, next_head);
1009            } else {
1010                length = 0;
1011            }
1012            space = space.saturating_sub(Self::MESSAGE_LENGTH_BYTES);
1013        }
1014        let length = length.min(space);
1015        if length != 0 {
1016            let chunk = data.get(..length).unwrap_or(data);
1017            b.head = Self::write_bytes_into(bytes, base, ring, chunk, next_head);
1018        }
1019        Ok(length)
1020    }
1021
1022    /// `prvReadMessageFromBuffer`.
1023    fn read_message(
1024        &mut self,
1025        buffer: StreamBufferHandle,
1026        out: &mut [u8],
1027        available: usize,
1028    ) -> Result<usize> {
1029        // ONE resolve, and the descriptor is written through in place -- the
1030        // mirror of `write_message`. Two resolves and a nine-field copy were
1031        // needed only while the helpers took `&self`/`&mut self`; giving them
1032        // the arena as a SLICE lets `buffers` and `bytes` be borrowed disjointly.
1033        let Self { buffers, bytes, .. } = self;
1034        let b = buffers.resolve_mut(buffer)?;
1035        let (base, ring, is_message) = (b.base, b.length, b.is_message);
1036        let mut next_tail = b.tail;
1037        let mut available = available;
1038        let next_length;
1039        if is_message {
1040            let (message_length, tail) = Self::read_length_prefix_from(bytes, base, ring, next_tail);
1041            next_tail = tail;
1042            available = available.saturating_sub(Self::MESSAGE_LENGTH_BYTES);
1043            next_length = if message_length > out.len() {
1044                // The C returns nothing rather than half a message.
1045                0
1046            } else {
1047                message_length
1048            };
1049        } else {
1050            next_length = out.len();
1051        }
1052        let count = next_length.min(available);
1053        if count != 0 {
1054            b.tail = match out.get_mut(..count) {
1055                Some(slot) => Self::read_bytes_from(bytes, base, ring, slot, next_tail),
1056                None => next_tail,
1057            };
1058        }
1059        Ok(count)
1060    }
1061
1062    /// `prvWriteBytesToBuffer`: the ring wrap, in two `memcpy`s.
1063    ///
1064    /// The index arithmetic here is `wrapping_*`, because the geometry has
1065    /// already bounded every term: `head` is below `length`, `base + length`
1066    /// is at most `BYTES`, `first` is `min(len, upto)` so `len - first`
1067    /// cannot go below zero, and `head + first` is at most `length` -- which
1068    /// the fold on the line after turns back into 0, exactly as `wrap_next`
1069    /// does. Each index then passes through a `get_mut` that refuses
1070    /// anything the ring does not own.
1071    /// Takes the byte arena as a SLICE rather than `&mut self`, so a caller can
1072    /// hold `&mut` to a descriptor in `self.buffers` at the same time. It asked
1073    /// for `&mut self` until 2026-09-25, and that is why `write_message` had to
1074    /// copy the whole descriptor out before calling it: under `forbid(unsafe)`
1075    /// a `&StreamBuffer` borrowed from `self` cannot coexist with `&mut self`.
1076    /// Destructuring `self` into disjoint field borrows is the safe form of what
1077    /// C gets for free by holding one pointer.
1078    fn write_bytes_into(bytes: &mut [u8], base: usize, ring: usize, data: &[u8], head: usize) -> usize {
1079        // The two copies, and the two the C makes. A payload longer than the
1080        // ring is refused before this, so that case cannot arrive.
1081        if data.len() <= ring {
1082            let upto = ring.wrapping_sub(head);
1083            let first = data.len().min(upto);
1084            let from = base.wrapping_add(head);
1085            if let (Some(dst), Some(src)) =
1086                (bytes.get_mut(from..from.wrapping_add(first)), data.get(..first))
1087            {
1088                dst.copy_from_slice(src);
1089            }
1090            let rest = data.len().wrapping_sub(first);
1091            if rest > 0 {
1092                if let (Some(dst), Some(src)) =
1093                    (bytes.get_mut(base..base.wrapping_add(rest)), data.get(first..))
1094                {
1095                    dst.copy_from_slice(src);
1096                }
1097                return rest;
1098            }
1099            let next = head.wrapping_add(first);
1100            return if next >= ring { 0 } else { next };
1101        }
1102        head
1103    }
1104
1105    /// `prvReadBytesFromBuffer`.
1106    ///
1107    /// Bounded as [`Kernel::write_bytes`] is, and for the same reasons.
1108    /// The mirror of [`Self::write_bytes_into`], and takes the arena the same
1109    /// way -- as a slice, so a caller can hold `&mut` to a descriptor in
1110    /// `self.buffers` across it. A request longer than the ring cannot arrive:
1111    /// `read_message` clamps `count` to `available`, which the ring's spare byte
1112    /// holds below `ring`.
1113    ///
1114    /// It asked for `&mut self` until 2026-09-25 while only ever READING the
1115    /// arena, and that single word is why `read_length_prefix` carried its own
1116    /// copy of this whole ring walk: with `&self` it could not call this.
1117    ///
1118    /// In line at both callers: out of line it became a shared symbol and cost
1119    /// +12 B, because each caller freezes a different length.
1120    #[inline(always)]
1121    fn read_bytes_from(bytes: &[u8], base: usize, ring: usize, out: &mut [u8], tail: usize) -> usize {
1122        if out.len() <= ring {
1123            let upto = ring.wrapping_sub(tail);
1124            let first = out.len().min(upto);
1125            let from = base.wrapping_add(tail);
1126            if let (Some(dst), Some(src)) =
1127                (out.get_mut(..first), bytes.get(from..from.wrapping_add(first)))
1128            {
1129                dst.copy_from_slice(src);
1130            }
1131            let rest = out.len().wrapping_sub(first);
1132            if rest > 0 {
1133                if let (Some(dst), Some(src)) =
1134                    (out.get_mut(first..), bytes.get(base..base.wrapping_add(rest)))
1135                {
1136                    dst.copy_from_slice(src);
1137                }
1138                return rest;
1139            }
1140            let next = tail.wrapping_add(first);
1141            return if next >= ring { 0 } else { next };
1142        }
1143        tail
1144    }
1145
1146    /// The message length, written little-endian across
1147    /// [`Kernel::MESSAGE_LENGTH_BYTES`] bytes of the ring.
1148
1149    /// The message length back out, and where the message starts.
1150    /// Bounded as [`Kernel::read_bytes`] is, and converted for the same
1151    /// reasons: `tail` is below `length`, `base + length` is at most
1152    /// `BYTES`, `first` is `min(want, upto)`, and every index passes through
1153    /// a `get` that refuses anything the ring does not own.
1154    /// The prefix is converted at the TARGET's width, not always through `u64`.
1155    ///
1156    /// This used `[0_u8; 8]` and `u64::from_le_bytes(..) as usize`. On rv32 that
1157    /// reads eight bytes as two words and throws the top one away, because
1158    /// `configMESSAGE_BUFFER_LENGTH_TYPE` is `size_t` and `size_t` is FOUR bytes
1159    /// there. `usize` is the width the C's type actually has on whichever target
1160    /// this is, so it is the right one to build.
1161    fn read_length_prefix_from(bytes: &[u8], base: usize, ring: usize, tail: usize) -> (usize, usize) {
1162        let mut raw = [0_u8; core::mem::size_of::<usize>()];
1163        // Delegated. This held its OWN two-copy ring walk plus a byte-at-a-time
1164        // fallback -- a third hand-rolled version of the same walk -- and the
1165        // only reason was that `read_bytes` asked for `&mut self` when it never
1166        // needed it.
1167        // A prefix wider than the target's `usize` cannot be represented, and
1168        // on the oracle host the two are equal, so this clamp is the identity
1169        // wherever the arms are matched.
1170        let want = Self::MESSAGE_LENGTH_BYTES.min(raw.len());
1171        let next = match raw.get_mut(..want) {
1172            Some(slot) => Self::read_bytes_from(bytes, base, ring, slot, tail),
1173            None => tail,
1174        };
1175        (usize::from_le_bytes(raw), next)
1176    }
1177}
1178
1179// ================================================================ tests ==
1180
1181/// `stream.rs` had no unit test at all, and six of its APIs are also the
1182/// ones no conformance scenario reaches (`docs/HOLES.md`, H2 and H3). For
1183/// those, the only evidence available is a semantic audit against the C
1184/// source plus tests that pin what it says.
1185///
1186/// So every test here quotes the `stream_buffer.c` line it is pinning, and
1187/// pins **the C's contract** rather than this kernel's behaviour. A test
1188/// written the other way round proves only that the code still does what it
1189/// did, which is worth having and is not evidence of conformance.
1190#[cfg(test)]
1191#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
1192mod tests {
1193    use rusty_rtos_core::config::Config;
1194    use rusty_rtos_core::hooks::NoTickHook;
1195
1196    use crate::queue::Wait;
1197    use crate::system::tests::{NoTrace, TestConfig, TestPort};
1198
1199    /// A kernel with buffers, which `system!` never declares: the macro
1200    /// sizes `BUFFERS` and `BYTES` at zero. Four tasks is the idle task,
1201    /// the timer daemon and one of our own, with room to spare.
1202    type K = crate::Kernel<
1203        TestConfig,
1204        TestPort,
1205        NoTrace,
1206        NoTickHook,
1207        4,
1208        { crate::list_slots_for(4, 0, crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0)) },
1209        { crate::lists_for(TestConfig::MAX_PRIORITIES, 1, 0) },
1210        1,
1211        1,
1212        2,
1213        64,
1214        0,
1215        0,
1216        { <TestConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
1217    >;
1218
1219    fn kernel() -> K {
1220        K::new(TestPort::default(), NoTrace).expect("the declared geometry adds up")
1221    }
1222
1223    /// The header a message buffer writes in front of every message.
1224    const HDR: usize = K::MESSAGE_LENGTH_BYTES;
1225
1226    /// `xStreamBufferIsEmpty`:
1227    ///
1228    /// ```c
1229    /// if( pxStreamBuffer->xHead == xTail ) { xReturn = pdTRUE; }
1230    /// ```
1231    ///
1232    /// Head-equals-tail, which is emptiness and NOT "nothing readable" --
1233    /// the two differ on a message buffer holding only a header, which the
1234    /// zero-length-message test below pins.
1235    #[test]
1236    fn is_empty_is_head_equals_tail() {
1237        let mut k = kernel();
1238        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1239        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1240
1241        k.stream_buffer_send(b, b"abc", 0).expect("send");
1242        assert_eq!(k.stream_buffer_is_empty(b), Ok(false));
1243
1244        let mut out = [0_u8; 8];
1245        k.stream_buffer_receive(b, &mut out, 0).expect("receive");
1246        assert_eq!(
1247            k.stream_buffer_is_empty(b),
1248            Ok(true),
1249            "drained is empty again, wherever head and tail have walked to"
1250        );
1251    }
1252
1253    /// `xStreamBufferIsFull` on a STREAM buffer:
1254    ///
1255    /// ```c
1256    /// xBytesToStoreMessageLength = 0;   /* not a message buffer */
1257    /// if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength )
1258    /// ```
1259    ///
1260    /// so full is exactly "no spaces left".
1261    #[test]
1262    fn is_full_on_a_stream_buffer_means_no_spaces_at_all() {
1263        let mut k = kernel();
1264        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1265        assert_eq!(k.stream_buffer_spaces_available(b), Ok(8));
1266        assert_eq!(k.stream_buffer_is_full(b), Ok(false));
1267
1268        k.stream_buffer_send(b, b"1234567", 0).expect("send seven");
1269        assert_eq!(k.stream_buffer_spaces_available(b), Ok(1));
1270        assert_eq!(
1271            k.stream_buffer_is_full(b),
1272            Ok(false),
1273            "one free byte is not full on a STREAM buffer"
1274        );
1275
1276        k.stream_buffer_send(b, b"8", 0).expect("send the last");
1277        assert_eq!(k.stream_buffer_spaces_available(b), Ok(0));
1278        assert_eq!(k.stream_buffer_is_full(b), Ok(true));
1279    }
1280
1281    /// `xStreamBufferIsFull` on a MESSAGE buffer, which is the one that
1282    /// surprises:
1283    ///
1284    /// ```c
1285    /// if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != 0 )
1286    ///     xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH;
1287    /// if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength )
1288    /// ```
1289    ///
1290    /// `<=`, against the size of the LENGTH HEADER rather than against
1291    /// zero. So a message buffer reports FULL while it still has free
1292    /// bytes, because those bytes could not hold even a zero-length
1293    /// message's header.
1294    ///
1295    /// A caller that polls `is_full` and expects `spaces_available() == 0`
1296    /// is wrong by up to a header, and only on message buffers.
1297    #[test]
1298    fn is_full_on_a_message_buffer_leaves_a_header_of_bytes_free() {
1299        let mut k = kernel();
1300        let b = k.message_buffer_create(8).expect("a message buffer");
1301        assert_eq!(k.stream_buffer_spaces_available(b), Ok(8));
1302        assert_eq!(k.stream_buffer_is_full(b), Ok(false));
1303
1304        // One three-byte message costs the header plus the payload.
1305        k.stream_buffer_send(b, b"abc", 0).expect("send");
1306        let spaces = k.stream_buffer_spaces_available(b).expect("spaces");
1307        assert_eq!(spaces, 8 - (HDR + 3));
1308        assert!(spaces > 0, "there ARE free bytes");
1309        assert!(spaces <= HDR, "but not enough for another header");
1310        assert_eq!(
1311            k.stream_buffer_is_full(b),
1312            Ok(true),
1313            "full with {spaces} byte(s) free: the C compares against the header, not zero"
1314        );
1315    }
1316
1317    /// `xStreamBufferNextMessageLengthBytes` on a stream buffer:
1318    ///
1319    /// ```c
1320    /// if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != 0 ) { ... }
1321    /// else { xReturn = 0; }
1322    /// ```
1323    ///
1324    /// Zero for a stream buffer NO MATTER WHAT IT HOLDS. That is not "no
1325    /// message waiting", it is "the question does not apply" -- and the
1326    /// return type cannot tell a caller which of the two it got.
1327    #[test]
1328    fn next_message_length_is_zero_on_a_stream_buffer_however_full() {
1329        let mut k = kernel();
1330        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1331        assert_eq!(k.stream_buffer_next_message_length(b), Ok(0));
1332
1333        k.stream_buffer_send(b, b"abcde", 0).expect("send");
1334        assert_eq!(k.stream_buffer_bytes_available(b), Ok(5));
1335        assert_eq!(
1336            k.stream_buffer_next_message_length(b),
1337            Ok(0),
1338            "five bytes waiting and still zero, because it is not a message buffer"
1339        );
1340    }
1341
1342    /// The same call on a message buffer PEEKS:
1343    ///
1344    /// ```c
1345    /// ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ..., pxStreamBuffer->xTail );
1346    /// ```
1347    ///
1348    /// It reads at the tail without advancing it, so asking twice answers
1349    /// twice and the message is still there to be received.
1350    #[test]
1351    fn next_message_length_peeks_and_does_not_consume() {
1352        let mut k = kernel();
1353        let b = k.message_buffer_create(16).expect("a message buffer");
1354        k.stream_buffer_send(b, b"hello", 0).expect("send");
1355
1356        assert_eq!(k.stream_buffer_next_message_length(b), Ok(5));
1357        assert_eq!(
1358            k.stream_buffer_next_message_length(b),
1359            Ok(5),
1360            "asking did not consume it"
1361        );
1362
1363        let mut out = [0_u8; 16];
1364        assert_eq!(k.stream_buffer_receive(b, &mut out, 0), Ok(Wait::Ready(5)));
1365        assert_eq!(&out[..5], b"hello");
1366        assert_eq!(k.stream_buffer_next_message_length(b), Ok(0), "drained");
1367    }
1368
1369    /// A zero-length message is a NO-OP that is indistinguishable from a
1370    /// send that failed -- which is not visible from the call site, and is
1371    /// the sort of thing only a source audit finds.
1372    ///
1373    /// `prvWriteMessageToBuffer`:
1374    ///
1375    /// ```c
1376    /// if( message buffer ) {
1377    ///     xMessageLength = ( configMESSAGE_BUFFER_LENGTH_TYPE ) xDataLengthBytes;  /* 0 */
1378    ///     if( xSpace >= xRequiredSpace ) {
1379    ///         xNextHead = prvWriteBytesToBuffer( pxStreamBuffer, &xMessageLength,
1380    ///                                            sbBYTES_TO_STORE_MESSAGE_LENGTH, xNextHead );
1381    ///     }
1382    /// }
1383    /// if( xDataLengthBytes != ( size_t ) 0 ) {
1384    ///     pxStreamBuffer->xHead = prvWriteBytesToBuffer( ..., xNextHead );
1385    /// }
1386    /// return xDataLengthBytes;
1387    /// ```
1388    ///
1389    /// The header IS written into the storage array -- but the new position
1390    /// goes into `xNextHead`, a LOCAL. `pxStreamBuffer->xHead` is only
1391    /// committed inside the `xDataLengthBytes != 0` branch, which a
1392    /// zero-length message does not take.
1393    ///
1394    /// So the bytes are in the array and the buffer does not know it: the
1395    /// head never moves, the buffer stays empty, the call returns 0, and
1396    /// the next send writes over them. A caller cannot tell this apart from
1397    /// a send that was refused for want of space.
1398    ///
1399    /// Pinned because the earlier version of this test asserted the
1400    /// opposite -- that the header would show up in `bytes_available` --
1401    /// and the kernel was right.
1402    #[test]
1403    fn a_zero_length_message_is_a_no_op_that_looks_like_a_failed_send() {
1404        let mut k = kernel();
1405        let b = k.message_buffer_create(16).expect("a message buffer");
1406        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1407
1408        assert_eq!(
1409            k.stream_buffer_send(b, b"", 0),
1410            Ok(Wait::Ready(0)),
1411            "zero bytes written, which is also what a refused send answers"
1412        );
1413        assert_eq!(
1414            k.stream_buffer_bytes_available(b),
1415            Ok(0),
1416            "the header went into the array and the head was never committed"
1417        );
1418        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1419        assert_eq!(k.stream_buffer_next_message_length(b), Ok(0));
1420
1421        // And a real message lands in the same place, over the top of it.
1422        k.stream_buffer_send(b, b"ok", 0).expect("a real message");
1423        assert_eq!(k.stream_buffer_next_message_length(b), Ok(2));
1424        let mut out = [0_u8; 16];
1425        assert_eq!(k.stream_buffer_receive(b, &mut out, 0), Ok(Wait::Ready(2)));
1426        assert_eq!(&out[..2], b"ok");
1427        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1428    }
1429
1430    /// `xStreamBufferReset`:
1431    ///
1432    /// ```c
1433    /// if( ( pxStreamBuffer->xTaskWaitingToReceive == NULL ) &&
1434    ///     ( pxStreamBuffer->xTaskWaitingToSend == NULL ) )
1435    /// {
1436    ///     prvInitialiseNewStreamBuffer( ..., pxStreamBuffer->xTriggerLevelBytes, ... );
1437    ///     xReturn = pdPASS;
1438    /// }
1439    /// ```
1440    ///
1441    /// The buffer's own trigger level is passed straight back in, so a
1442    /// reset empties the buffer and KEEPS the trigger. It is not a return
1443    /// to the creation default, which is what the name suggests.
1444    #[test]
1445    fn reset_empties_the_buffer_and_keeps_the_trigger_level() {
1446        let mut k = kernel();
1447        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1448        assert_eq!(k.stream_buffer_set_trigger_level(b, 5), Ok(true));
1449        k.stream_buffer_send(b, b"abcd", 0).expect("send");
1450        assert_eq!(k.stream_buffer_bytes_available(b), Ok(4));
1451
1452        assert_eq!(k.stream_buffer_reset(b), Ok(true));
1453        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1454        assert_eq!(k.stream_buffer_bytes_available(b), Ok(0));
1455        assert_eq!(
1456            k.stream_buffer_spaces_available(b),
1457            Ok(8),
1458            "the whole usable length is back"
1459        );
1460    }
1461
1462    /// The other half of that guard: a reset must REFUSE while a task is
1463    /// blocked on the buffer, because reinitialising would drop the handle
1464    /// that task is waiting on.
1465    #[test]
1466    fn reset_refuses_while_a_task_is_waiting_to_receive() {
1467        let mut k = kernel();
1468        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1469        k.create_task("rx", 1).expect("a task");
1470        let started = k.start_scheduler().expect("start");
1471        k.suspend(Some(started.timer)).expect("park the daemon");
1472
1473        // Run until our task is the one on the CPU, then block it.
1474        let mut out = [0_u8; 8];
1475        let mut blocked = false;
1476        for _ in 0..50_u32 {
1477            let running = k.name_of(k.current()).expect("a running task has a name");
1478            if running.as_str() == "rx" {
1479                assert_eq!(
1480                    k.stream_buffer_receive(b, &mut out, 20),
1481                    Ok(Wait::Blocked),
1482                    "an empty buffer with a timeout blocks"
1483                );
1484                blocked = true;
1485                break;
1486            }
1487            k.switch_context();
1488        }
1489        assert!(blocked, "never got the task onto the CPU");
1490
1491        assert_eq!(
1492            k.stream_buffer_reset(b),
1493            Ok(false),
1494            "a waiting receiver refuses the reset"
1495        );
1496    }
1497
1498    /// `xStreamBufferReceiveFromISR` never blocks: it takes a whole
1499    /// message, or nothing.
1500    #[test]
1501    fn receive_from_isr_takes_a_whole_message_or_nothing() {
1502        let mut k = kernel();
1503        let b = k.message_buffer_create(16).expect("a message buffer");
1504        let mut out = [0_u8; 16];
1505
1506        let (n, _) = k.stream_buffer_receive_from_isr(b, &mut out).expect("isr");
1507        assert_eq!(n, 0, "nothing waiting, and it did not block");
1508
1509        k.stream_buffer_send(b, b"xy", 0).expect("send");
1510        let (n, _) = k.stream_buffer_receive_from_isr(b, &mut out).expect("isr");
1511        assert_eq!(n, 2);
1512        assert_eq!(&out[..2], b"xy");
1513        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1514    }
1515
1516    /// `bytes_available` and `spaces_available` partition the USABLE
1517    /// length, which is one less than the ring's own -- the spare byte that
1518    /// tells full from empty, the C's `xBufferSizeBytes++` at creation.
1519    #[test]
1520    fn bytes_and_spaces_partition_the_usable_length() {
1521        let mut k = kernel();
1522        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1523        for n in 0..=8_usize {
1524            let bytes = k.stream_buffer_bytes_available(b).expect("bytes");
1525            let spaces = k.stream_buffer_spaces_available(b).expect("spaces");
1526            assert_eq!(
1527                bytes.saturating_add(spaces),
1528                8,
1529                "at {n} byte(s) in: {bytes} + {spaces} should be the usable 8"
1530            );
1531            if n < 8 {
1532                k.stream_buffer_send(b, b"z", 0).expect("send one");
1533            }
1534        }
1535    }
1536    /// A STREAM buffer takes a partial write; a MESSAGE buffer is
1537    /// all-or-nothing. `prvWriteMessageToBuffer`:
1538    ///
1539    /// ```c
1540    /// if( message buffer ) {
1541    ///     if( xSpace >= xRequiredSpace ) { ...write the header... }
1542    ///     else { xDataLengthBytes = 0; }          /* nothing at all */
1543    /// } else {
1544    ///     xDataLengthBytes = configMIN( xDataLengthBytes, xSpace );   /* as much as fits */
1545    /// }
1546    /// ```
1547    ///
1548    /// So the same call with the same arguments loses the tail on one kind
1549    /// and loses everything on the other, and the return value is the only
1550    /// way to tell which happened.
1551    #[test]
1552    fn a_stream_takes_a_partial_write_and_a_message_is_all_or_nothing() {
1553        let mut k = kernel();
1554        let s = k.stream_buffer_create(8, 1).expect("a stream buffer");
1555        k.stream_buffer_send(s, b"123456", 0).expect("six");
1556        assert_eq!(
1557            k.stream_buffer_send(s, b"789", 0),
1558            Ok(Wait::Ready(2)),
1559            "two of the three fit, and two is what it took"
1560        );
1561        assert_eq!(k.stream_buffer_spaces_available(s), Ok(0));
1562
1563        let mut k = kernel();
1564        let m = k.message_buffer_create(8).expect("a message buffer");
1565        // One message of two costs the header plus two: six of the eight.
1566        k.stream_buffer_send(m, b"xy", 0)
1567            .expect("the first message");
1568        assert_eq!(
1569            k.stream_buffer_send(m, b"zzz", 0),
1570            Ok(Wait::Ready(0)),
1571            "the header plus three does not fit, so NOTHING was written"
1572        );
1573        assert_eq!(
1574            k.stream_buffer_next_message_length(m),
1575            Ok(2),
1576            "and the message already there is untouched"
1577        );
1578    }
1579
1580    /// `xStreamBufferSendFromISR` writes what fits and never blocks -- the
1581    /// same body as the task-side send with the block time forced to zero.
1582    #[test]
1583    fn send_from_isr_writes_what_fits_and_never_blocks() {
1584        let mut k = kernel();
1585        let b = k.stream_buffer_create(8, 1).expect("a buffer");
1586
1587        let (n, _) = k.stream_buffer_send_from_isr(b, b"abc").expect("isr");
1588        assert_eq!(n, 3);
1589        assert_eq!(k.stream_buffer_bytes_available(b), Ok(3));
1590
1591        // Past the end: it takes the five that fit rather than waiting.
1592        let (n, _) = k.stream_buffer_send_from_isr(b, b"defghijkl").expect("isr");
1593        assert_eq!(n, 5, "five of the nine fit");
1594        assert_eq!(k.stream_buffer_is_full(b), Ok(true));
1595
1596        let (n, _) = k.stream_buffer_send_from_isr(b, b"m").expect("isr");
1597        assert_eq!(n, 0, "full, and it still did not block");
1598    }
1599
1600    /// A round trip through the two ISR halves, which is what an
1601    /// interrupt-driven driver actually does.
1602    #[test]
1603    fn a_message_survives_a_round_trip_through_both_isr_halves() {
1604        let mut k = kernel();
1605        let b = k.message_buffer_create(16).expect("a message buffer");
1606        let (n, _) = k.stream_buffer_send_from_isr(b, b"ping").expect("isr");
1607        assert_eq!(n, 4);
1608
1609        let mut out = [0_u8; 16];
1610        let (n, _) = k.stream_buffer_receive_from_isr(b, &mut out).expect("isr");
1611        assert_eq!(n, 4);
1612        assert_eq!(&out[..4], b"ping");
1613        assert_eq!(k.stream_buffer_is_empty(b), Ok(true));
1614    }
1615}