use crate::error::{Error, Result};
use futures_core::Stream;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
pub type Psm = u16;
const L2CAP_BACKLOG: usize = 2048;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Closed {
ByPeer,
Locally,
Error(String),
}
pub trait ChannelSink: Send + Sync {
fn on_bytes(&self, bytes: Vec<u8>);
fn on_closed(&self, reason: Closed);
}
pub trait PlatformChannel: Send + Sync + 'static {
fn psm(&self) -> Psm;
fn peer_id(&self) -> &str;
fn send(&self, bytes: &[u8]) -> std::result::Result<(), Closed>;
fn pending_bytes(&self) -> usize;
fn closed(&self) -> Option<Closed>;
fn close(&self);
}
pub struct Sink {
bytes: crate::backlog::Sender<Vec<u8>>,
closed: Mutex<Vec<futures_channel::oneshot::Sender<Closed>>>,
}
impl ChannelSink for Sink {
fn on_bytes(&self, bytes: Vec<u8>) {
let _ = self.bytes.send(bytes);
}
fn on_closed(&self, reason: Closed) {
self.bytes.close();
for tx in self.closed.lock().unwrap().drain(..) {
let _ = tx.send(reason.clone());
}
}
}
pub fn sink() -> (Arc<dyn ChannelSink>, Arc<Sink>, Incoming) {
let (tx, rx) = crate::backlog::bounded(L2CAP_BACKLOG, crate::backlog::Overflow::KeepOldest);
let sink = Arc::new(Sink {
bytes: tx,
closed: Mutex::new(Vec::new()),
});
(sink.clone(), sink, Incoming { rx })
}
pub struct L2capChannel<C: PlatformChannel> {
channel: C,
incoming: Mutex<Option<Incoming>>,
sink: Arc<Sink>,
}
impl<C: PlatformChannel> L2capChannel<C> {
pub fn new(channel: C, sink: Arc<Sink>, incoming: Incoming) -> Self {
Self {
channel,
incoming: Mutex::new(Some(incoming)),
sink,
}
}
pub fn psm(&self) -> Psm {
self.channel.psm()
}
pub fn peer_id(&self) -> &str {
self.channel.peer_id()
}
pub fn take_incoming(&self) -> Option<Incoming> {
self.incoming.lock().unwrap().take()
}
pub fn send(&self, bytes: &[u8]) -> Result<()> {
self.channel.send(bytes).map_err(closed_error)
}
pub fn pending_bytes(&self) -> usize {
self.channel.pending_bytes()
}
pub async fn flushed(&self) -> Result<()> {
while self.pending_bytes() > 0 {
if let Some(reason) = self.closed() {
return Err(match reason {
Closed::ByPeer => Error::Network("the peer closed mid-write".into()),
Closed::Locally => Error::InvalidState("the channel was closed".into()),
Closed::Error(m) => Error::Network(format!("L2CAP channel failed: {m}")),
});
}
crate::timer::sleep(std::time::Duration::from_millis(5)).await;
}
Ok(())
}
pub fn closed(&self) -> Option<Closed> {
self.channel.closed()
}
pub async fn on_close(&self) -> Closed {
if let Some(reason) = self.closed() {
return reason;
}
let rx = {
let (tx, rx) = futures_channel::oneshot::channel();
if let Some(reason) = self.closed() {
return reason;
}
self.sink.closed.lock().unwrap().push(tx);
rx
};
rx.await.unwrap_or(Closed::Locally)
}
pub fn close(&self) {
self.channel.close()
}
}
fn closed_error(reason: Closed) -> Error {
match reason {
Closed::ByPeer => Error::Network("the peer closed the L2CAP channel".into()),
Closed::Locally => Error::InvalidState("the L2CAP channel is closed".into()),
Closed::Error(m) => Error::Network(format!("L2CAP channel failed: {m}")),
}
}
impl<C: PlatformChannel> std::fmt::Debug for L2capChannel<C> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("L2capChannel")
.field("psm", &self.psm())
.field("peer_id", &self.peer_id())
.field("closed", &self.closed())
.finish()
}
}
pub struct Incoming {
rx: crate::backlog::Receiver<Vec<u8>>,
}
impl Stream for Incoming {
type Item = Vec<u8>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
Pin::new(&mut self.rx).poll_next(cx)
}
}