1use std::io::{Read, Write};
4
5use msrt::endpoint::{EngineConfig, PassiveEndpoint, PeerState};
6
7use crate::error::Result;
8use crate::event::AdapterEvent;
9use crate::io::IoState;
10
11#[derive(Debug)]
13pub struct StdBackend<T> {
14 io: T,
15 endpoint: PassiveEndpoint,
16 state: IoState,
17}
18
19impl<T> StdBackend<T>
20where
21 T: Read + Write,
22{
23 pub fn new(io: T) -> Self {
25 Self::with_config(io, EngineConfig::default())
26 }
27
28 pub fn with_config(io: T, config: EngineConfig) -> Self {
30 Self {
31 io,
32 endpoint: PassiveEndpoint::new(config),
33 state: IoState::new(),
34 }
35 }
36
37 pub fn peer_state(&self) -> PeerState {
39 self.endpoint.peer().state()
40 }
41
42 pub const fn io(&self) -> &T {
44 &self.io
45 }
46
47 pub fn io_mut(&mut self) -> &mut T {
49 &mut self.io
50 }
51
52 pub fn into_inner(self) -> T {
54 self.io
55 }
56
57 pub fn disconnect(&mut self) {
59 self.endpoint.disconnect();
60 }
61
62 pub fn send(&mut self, message: &[u8]) -> Result<bool> {
64 Ok(self.endpoint.send(message)?.is_some())
65 }
66
67 pub fn receive_available(&mut self) -> Result<usize> {
72 self.state.receive_available(&mut self.io, |now_ms, bytes| {
73 self.endpoint.receive(now_ms, bytes)
74 })
75 }
76
77 pub fn poll(&mut self) -> Result<AdapterEvent> {
79 self.state.poll(&mut self.io, |now_ms, tx_buf| {
80 self.endpoint.poll(now_ms, tx_buf)
81 })
82 }
83
84 pub fn tick(&mut self) -> Result<AdapterEvent> {
86 let _ = self.receive_available()?;
87 self.poll()
88 }
89}