use crate::event_loop::{Ctx, UdpCtx};
use simoom_sys::udp::RecvMeta;
use std::any::Any;
use std::io;
use std::net::SocketAddr;
pub type Message = Box<dyn Any + Send>;
#[derive(Clone, Debug)]
pub struct ConnInfo {
pub listener: usize,
pub peer: Option<SocketAddr>,
pub loop_index: usize,
}
#[derive(Debug)]
pub enum CloseReason {
Closed,
Aborted,
Error(io::Error),
InputLimit,
Stopped,
}
pub trait Acceptor: Send + Sync + 'static {
fn accept(&self, info: &ConnInfo) -> Option<Box<dyn Connection>>;
}
impl<F> Acceptor for F
where
F: Fn(&ConnInfo) -> Option<Box<dyn Connection>> + Send + Sync + 'static,
{
fn accept(&self, info: &ConnInfo) -> Option<Box<dyn Connection>> {
self(info)
}
}
pub trait Connection: 'static {
fn on_open(&mut self, cx: &mut Ctx<'_>) {
let _ = cx;
}
fn on_data(&mut self, cx: &mut Ctx<'_>, data: &[u8]) -> usize;
fn on_eof(&mut self, cx: &mut Ctx<'_>) {
cx.close();
}
fn on_drain(&mut self, cx: &mut Ctx<'_>) {
let _ = cx;
}
fn on_timer(&mut self, cx: &mut Ctx<'_>, token: u64) {
let _ = (cx, token);
}
fn on_message(&mut self, cx: &mut Ctx<'_>, msg: Message) {
let _ = (cx, msg);
}
fn on_stop(&mut self, cx: &mut Ctx<'_>) {
cx.close();
}
fn on_close(&mut self, reason: CloseReason) {
let _ = reason;
}
}
#[derive(Clone, Debug)]
pub struct UdpInfo {
pub binding: usize,
pub loop_index: usize,
pub local_addr: SocketAddr,
}
pub trait UdpService: Send + Sync + 'static {
fn endpoint(&self, info: &UdpInfo) -> Box<dyn Endpoint>;
}
impl<F> UdpService for F
where
F: Fn(&UdpInfo) -> Box<dyn Endpoint> + Send + Sync + 'static,
{
fn endpoint(&self, info: &UdpInfo) -> Box<dyn Endpoint> {
self(info)
}
}
pub trait Endpoint: 'static {
fn on_datagram(&mut self, cx: &mut UdpCtx<'_>, data: &[u8], meta: &RecvMeta);
fn on_timer(&mut self, cx: &mut UdpCtx<'_>, token: u64) {
let _ = (cx, token);
}
fn on_message(&mut self, cx: &mut UdpCtx<'_>, msg: Message) {
let _ = (cx, msg);
}
fn on_stop(&mut self, cx: &mut UdpCtx<'_>) {
let _ = cx;
}
fn is_busy(&self) -> bool {
false
}
fn on_abort(&mut self, cx: &mut UdpCtx<'_>) {
let _ = cx;
}
}