Skip to main content

rns_embedded_mininode/
adapters.rs

1use alloc::{collections::VecDeque, vec::Vec};
2
3use crate::error::MiniNodeError;
4
5pub trait FrameLink {
6    fn is_up(&self) -> bool;
7    fn mtu(&self) -> usize;
8    fn send_frame(&mut self, frame: &[u8]) -> Result<(), MiniNodeError>;
9    fn poll_frame(&mut self) -> Result<Option<Vec<u8>>, MiniNodeError>;
10}
11
12#[derive(Debug, Clone)]
13pub struct MemoryLink {
14    mtu: usize,
15    online: bool,
16    inbound: VecDeque<Vec<u8>>,
17    outbound: VecDeque<Vec<u8>>,
18}
19
20impl Default for MemoryLink {
21    fn default() -> Self {
22        Self::new(512)
23    }
24}
25
26impl MemoryLink {
27    pub fn new(mtu: usize) -> Self {
28        Self { mtu, online: true, inbound: VecDeque::new(), outbound: VecDeque::new() }
29    }
30
31    pub fn set_online(&mut self, online: bool) {
32        self.online = online;
33    }
34
35    pub fn push_inbound(&mut self, frame: Vec<u8>) {
36        self.inbound.push_back(frame);
37    }
38
39    pub fn drain_outbound(&mut self) -> Vec<Vec<u8>> {
40        self.outbound.drain(..).collect()
41    }
42}
43
44impl FrameLink for MemoryLink {
45    fn is_up(&self) -> bool {
46        self.online
47    }
48
49    fn mtu(&self) -> usize {
50        self.mtu
51    }
52
53    fn send_frame(&mut self, frame: &[u8]) -> Result<(), MiniNodeError> {
54        if !self.online {
55            return Err(MiniNodeError::LinkDown);
56        }
57        if frame.len() > self.mtu {
58            return Err(MiniNodeError::MtuExceeded { frame_len: frame.len(), mtu: self.mtu });
59        }
60        self.outbound.push_back(frame.to_vec());
61        Ok(())
62    }
63
64    fn poll_frame(&mut self) -> Result<Option<Vec<u8>>, MiniNodeError> {
65        if !self.online {
66            return Ok(None);
67        }
68        Ok(self.inbound.pop_front())
69    }
70}