use crate::{Conn, Handler, Info};
use std::{future::Future, mem};
#[derive(Debug)]
pub struct Init<F>(Option<F>);
impl<F, Fut> Init<F>
where
F: FnOnce(Info) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Info> + Send + 'static,
{
#[must_use]
pub const fn new(init: F) -> Self {
Self(Some(init))
}
}
impl<F, Fut> Handler for Init<F>
where
F: FnOnce(Info) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Info> + Send + 'static,
{
async fn run(&self, conn: Conn) -> Conn {
conn
}
async fn init(&mut self, info: &mut Info) {
match self.0.take() {
Some(init) => {
*info = init(mem::take(info)).await;
}
_ => {
log::warn!("called init more than once");
}
}
}
}
pub const fn init<F, Fut>(init: F) -> Init<F>
where
F: FnOnce(Info) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Info> + Send + 'static,
{
Init::new(init)
}