psicose 0.4.3

no_std heapless reliable link motor: 4-byte frame, ACK/CRC, window N≤8, P2P Node/PeerLink, LinkFace — zero crate dependencies
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! One physical duplex wire, two readers on each end.
//!
//! A real UART has one incoming stream. The sender needs ACK/NACK from
//! it; the receiver needs DATA/START/FINISH/ABORT. This type demuxes
//! complete frames so the two readers do not steal each other's bytes.
//!
//! ```text
//! Peer A                         Peer B
//! TX.write ──┐                 ┌── RX.read  (DATA/START/…)
//! RX.write ──┼── a_to_b ───────┤
//!            │                 └── TX.read  (ACK/NACK)
//! TX.read  ◄─┤
//! RX.read  ◄─┼── b_to_a ───────┤
//!            │                 └── TX.write / RX.write
//! ```

use core::cell::RefCell;

use crate::error::Error;
use crate::protocol::{FrameAssembler, FrameType, FRAME_LEN};
use crate::pump::{Pump, PumpEvent, WindowedPump};
use crate::timeout::RetryPolicy;
use crate::transport::{ByteSink, ByteSource, ByteTransport};
use crate::tx::TxState;
use crate::window::MAX_WINDOW;

const RING: usize = 64;

#[derive(Clone, Copy)]
struct Ring {
    buf: [u8; RING],
    head: usize,
    tail: usize,
    len: usize,
}

impl Ring {
    const fn new() -> Self {
        Ring {
            buf: [0; RING],
            head: 0,
            tail: 0,
            len: 0,
        }
    }

    fn push(&mut self, byte: u8) -> bool {
        if self.len == RING {
            return false;
        }
        self.buf[self.tail] = byte;
        self.tail = (self.tail + 1) % RING;
        self.len += 1;
        true
    }

    fn pop(&mut self) -> Option<u8> {
        if self.len == 0 {
            return None;
        }
        let byte = self.buf[self.head];
        self.head = (self.head + 1) % RING;
        self.len -= 1;
        Some(byte)
    }

    fn push_frame(&mut self, bytes: [u8; FRAME_LEN]) -> bool {
        if self.len > RING - FRAME_LEN {
            return false;
        }
        let mut i = 0;
        while i < FRAME_LEN {
            self.buf[self.tail] = bytes[i];
            self.tail = (self.tail + 1) % RING;
            self.len += 1;
            i += 1;
        }
        true
    }
}

#[derive(Clone, Copy)]
struct Held {
    bytes: [u8; FRAME_LEN],
    control: bool,
}

struct Lane {
    wire: Ring,
    assembler: FrameAssembler,
    control: Ring,
    payload: Ring,
    pending: Option<Held>,
}

impl Lane {
    const fn new() -> Self {
        Lane {
            wire: Ring::new(),
            assembler: FrameAssembler::resyncing(),
            control: Ring::new(),
            payload: Ring::new(),
            pending: None,
        }
    }

    fn store(&mut self, held: Held) -> bool {
        if held.control {
            self.control.push_frame(held.bytes)
        } else {
            self.payload.push_frame(held.bytes)
        }
    }

    fn ingest(&mut self) {
        if let Some(held) = self.pending {
            if self.store(held) {
                self.pending = None;
            } else {
                return;
            }
        }
        while let Some(byte) = self.wire.pop() {
            let Some(result) = self.assembler.push(byte) else {
                continue;
            };
            let held = Held {
                bytes: match &result {
                    Ok(frame) => frame.to_bytes(),
                    Err(_) => self.assembler.last_bytes(),
                },
                control: matches!(
                    result,
                    Ok(frame) if matches!(frame.frame_type(), FrameType::Ack | FrameType::Nack)
                ),
            };
            if !self.store(held) {
                self.pending = Some(held);
                return;
            }
        }
    }
}

/// Two lanes (A→B and B→A). Interior mutability so four ports share it.
pub struct DuplexWire {
    lanes: RefCell<Lanes>,
}

struct Lanes {
    a_to_b: Lane,
    b_to_a: Lane,
}

impl DuplexWire {
    /// Empty wire.
    pub const fn new() -> Self {
        DuplexWire {
            lanes: RefCell::new(Lanes {
                a_to_b: Lane::new(),
                b_to_a: Lane::new(),
            }),
        }
    }

    /// Four ports: A's TX, A's RX, B's TX, B's RX.
    pub fn ends(
        &self,
    ) -> (
        DuplexPort<'_>,
        DuplexPort<'_>,
        DuplexPort<'_>,
        DuplexPort<'_>,
    ) {
        (
            DuplexPort {
                wire: self,
                is_a: true,
                for_tx: true,
            },
            DuplexPort {
                wire: self,
                is_a: true,
                for_tx: false,
            },
            DuplexPort {
                wire: self,
                is_a: false,
                for_tx: true,
            },
            DuplexPort {
                wire: self,
                is_a: false,
                for_tx: false,
            },
        )
    }

    /// Two stop-and-wait pumps: `let (a, b) = wire.pumps();`
    pub fn pumps(
        &self,
    ) -> (
        Pump<DuplexPort<'_>, DuplexPort<'_>>,
        Pump<DuplexPort<'_>, DuplexPort<'_>>,
    ) {
        let (a_tx, a_rx, b_tx, b_rx) = self.ends();
        (Pump::on(a_tx, a_rx), Pump::on(b_tx, b_rx))
    }

    /// [`Self::pumps`] with an explicit [`RetryPolicy`].
    pub fn pumps_with(
        &self,
        policy: RetryPolicy,
    ) -> (
        Pump<DuplexPort<'_>, DuplexPort<'_>>,
        Pump<DuplexPort<'_>, DuplexPort<'_>>,
    ) {
        let (a_tx, a_rx, b_tx, b_rx) = self.ends();
        (
            Pump::on_with(a_tx, a_rx, policy),
            Pump::on_with(b_tx, b_rx, policy),
        )
    }

    /// Two windowed pumps for [`super::PeerLink`] (`N = MAX_WINDOW`).
    ///
    /// Handshake runs with limit 1; after negotiate + `WINDOW`, the link
    /// raises the runtime limit to the agreed `max_window`.
    pub fn link_pumps(
        &self,
    ) -> (
        WindowedPump<DuplexPort<'_>, DuplexPort<'_>, MAX_WINDOW>,
        WindowedPump<DuplexPort<'_>, DuplexPort<'_>, MAX_WINDOW>,
    ) {
        let (a_tx, a_rx, b_tx, b_rx) = self.ends();
        let mut a = WindowedPump::on(a_tx, a_rx);
        let mut b = WindowedPump::on(b_tx, b_rx);
        a.set_window_limit(1);
        b.set_window_limit(1);
        (a, b)
    }

    /// [`Self::link_pumps`] with an explicit [`RetryPolicy`].
    pub fn link_pumps_with(
        &self,
        policy: RetryPolicy,
    ) -> (
        WindowedPump<DuplexPort<'_>, DuplexPort<'_>, MAX_WINDOW>,
        WindowedPump<DuplexPort<'_>, DuplexPort<'_>, MAX_WINDOW>,
    ) {
        let (a_tx, a_rx, b_tx, b_rx) = self.ends();
        let mut a = WindowedPump::on_with(a_tx, a_rx, policy);
        let mut b = WindowedPump::on_with(b_tx, b_rx, policy);
        a.set_window_limit(1);
        b.set_window_limit(1);
        (a, b)
    }

    /// Framework motor: stop-and-wait copy **A → B** on this wire.
    ///
    /// Examples call this instead of inventing their own UART ring. The
    /// pumps, ACKs, and CRC path are entirely PSICOSE.
    pub fn copy<S, K>(&self, src: &mut S, sink: &mut K) -> Result<usize, WireCopyError>
    where
        S: ByteSource,
        K: ByteSink,
    {
        let (mut a, mut b) = self.pumps();
        let mut hold: Option<u8> = None;
        let mut exhausted = false;
        let mut finish_offered = false;
        let mut n = 0usize;

        for _ in 0..1_000_000 {
            if hold.is_none() && !exhausted {
                match src.read_byte() {
                    Ok(Some(byte)) => hold = Some(byte),
                    Ok(None) => exhausted = true,
                    Err(_) => return Err(WireCopyError::Source),
                }
            }

            if a.sender().state() == TxState::Idle {
                if let Some(byte) = hold.take() {
                    if a.sender_mut().offer(byte).is_err() {
                        hold = Some(byte);
                    }
                } else if exhausted && !finish_offered {
                    match a.sender_mut().offer_finish() {
                        Ok(()) => finish_offered = true,
                        Err(Error::NotIdle) => {}
                        Err(_) => return Err(WireCopyError::Protocol),
                    }
                }
            }

            match a.poll() {
                Ok(PumpEvent::Aborted) => return Err(WireCopyError::Protocol),
                Ok(PumpEvent::Completed) if finish_offered => {}
                Ok(_) => {}
                Err(_) => return Err(WireCopyError::Protocol),
            }

            match b.poll() {
                Ok(PumpEvent::Received(byte)) => {
                    if sink.write_byte(byte).is_err() {
                        return Err(WireCopyError::Sink);
                    }
                    n = n.saturating_add(1);
                }
                Ok(PumpEvent::Completed) => return Ok(n),
                Ok(PumpEvent::Aborted) => return Err(WireCopyError::Protocol),
                Ok(_) => {}
                Err(_) => return Err(WireCopyError::Protocol),
            }
        }

        Err(WireCopyError::Stalled)
    }
}

/// Why [`DuplexWire::copy`] stopped early.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WireCopyError {
    /// [`ByteSource`] failed.
    Source,
    /// [`ByteSink`] failed.
    Sink,
    /// Protocol / transport error (ABORT, retries, …).
    Protocol,
    /// Idle budget style stall (too many polls, no progress).
    Stalled,
}

impl core::fmt::Display for WireCopyError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            WireCopyError::Source => write!(f, "wire copy: source error"),
            WireCopyError::Sink => write!(f, "wire copy: sink error"),
            WireCopyError::Protocol => write!(f, "wire copy: protocol error"),
            WireCopyError::Stalled => write!(f, "wire copy: stalled"),
        }
    }
}

impl Default for DuplexWire {
    fn default() -> Self {
        Self::new()
    }
}

/// One half of one peer: either the sender port or the receiver port.
pub struct DuplexPort<'a> {
    wire: &'a DuplexWire,
    is_a: bool,
    for_tx: bool,
}

/// The heapless ring had no room.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DuplexFull;

impl ByteTransport for DuplexPort<'_> {
    type Error = DuplexFull;

    fn write_byte(&mut self, byte: u8) -> Result<(), Self::Error> {
        let mut d = self.wire.lanes.borrow_mut();
        let lane = if self.is_a {
            &mut d.a_to_b
        } else {
            &mut d.b_to_a
        };
        if lane.wire.push(byte) {
            Ok(())
        } else {
            Err(DuplexFull)
        }
    }

    fn read_byte(&mut self) -> Result<Option<u8>, Self::Error> {
        let mut d = self.wire.lanes.borrow_mut();
        let lane = if self.is_a {
            &mut d.b_to_a
        } else {
            &mut d.a_to_b
        };
        lane.ingest();
        Ok(if self.for_tx {
            lane.control.pop()
        } else {
            lane.payload.pop()
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::Frame;

    #[test]
    fn ack_goes_to_tx_data_goes_to_rx() {
        let wire = DuplexWire::new();
        let (mut a_tx, mut a_rx, mut b_tx, mut b_rx) = wire.ends();

        for b in Frame::data(0, 0x42).to_bytes() {
            assert_eq!(a_tx.write_byte(b), Ok(()));
        }
        for b in Frame::ack(0).to_bytes() {
            assert_eq!(b_rx.write_byte(b), Ok(()));
        }

        let mut data = [0u8; 4];
        let mut i = 0;
        while i < 4 {
            data[i] = match b_rx.read_byte() {
                Ok(Some(b)) => b,
                _ => 0,
            };
            i += 1;
        }
        assert_eq!(data, Frame::data(0, 0x42).to_bytes());

        let mut ack = [0u8; 4];
        i = 0;
        while i < 4 {
            ack[i] = match a_tx.read_byte() {
                Ok(Some(b)) => b,
                _ => 0,
            };
            i += 1;
        }
        assert_eq!(ack, Frame::ack(0).to_bytes());

        assert_eq!(a_rx.read_byte(), Ok(None));
        assert_eq!(b_tx.read_byte(), Ok(None));
    }

    #[test]
    fn crc_miss_reaches_rx_not_tx() {
        let wire = DuplexWire::new();
        let (mut a_tx, _a_rx, _b_tx, mut b_rx) = wire.ends();

        let mut bad = Frame::data(0, 0x42).to_bytes();
        bad[3] ^= 0xFF;
        for b in bad {
            assert_eq!(a_tx.write_byte(b), Ok(()));
        }

        let mut got = [0u8; 4];
        let mut i = 0;
        while i < 4 {
            got[i] = match b_rx.read_byte() {
                Ok(Some(b)) => b,
                _ => 0,
            };
            i += 1;
        }
        assert_eq!(got, bad);
        assert_eq!(a_tx.read_byte(), Ok(None));
    }

    #[test]
    fn a_full_ring_keeps_the_next_frame_whole() {
        let wire = DuplexWire::new();
        let (mut a_tx, _a_rx, _b_tx, mut b_rx) = wire.ends();
        let mut i = 0;
        while i < 16 {
            for byte in Frame::data(i as u8, i as u8).to_bytes() {
                assert_eq!(a_tx.write_byte(byte), Ok(()));
            }
            i += 1;
        }
        let first = match b_rx.read_byte() {
            Ok(Some(byte)) => byte,
            other => panic!("expected the first byte, got {other:?}"),
        };
        for byte in Frame::data(16, 16).to_bytes() {
            assert_eq!(a_tx.write_byte(byte), Ok(()));
        }

        let mut got = [0u8; 17 * 4];
        got[0] = first;
        let mut n = 1;
        while n < got.len() {
            match b_rx.read_byte() {
                Ok(Some(byte)) => {
                    got[n] = byte;
                    n += 1;
                }
                other => panic!("short read at {n}: {other:?}"),
            }
        }
        let mut expect = [0u8; 17 * 4];
        let mut f = 0;
        while f < 17 {
            expect[f * 4..f * 4 + 4].copy_from_slice(&Frame::data(f as u8, f as u8).to_bytes());
            f += 1;
        }
        assert_eq!(got, expect);
    }
}