1use std::{future::Future, pin::Pin};
2
3use crate::Svc;
4
5pub struct FnSvc<F> {
6 f: F,
7}
8
9impl<F> FnSvc<F> {
10 pub fn new(f: F) -> Self {
11 Self { f }
12 }
13}
14
15impl<F, Req, Fut, Res> Svc<Req> for FnSvc<F>
16where
17 F: FnMut(Req) -> Fut + Unpin,
18 Fut: Future<Output = Res>,
19{
20 type Res = Res;
21 type Fut = Fut;
22
23 fn exec(mut self: Pin<&mut Self>, req: Req) -> Self::Fut {
24 (self.f)(req)
25 }
26}
27
28#[cfg(test)]
29mod tests {
30 use futures_util::pin_mut;
31
32 use super::*;
33
34 #[tokio::test]
35 async fn test_fn_service() {
36 async fn doubler(n: u64) -> u64 {
37 n * 2
38 }
39
40 let svc = FnSvc::new(doubler);
41 pin_mut!(svc);
42
43 let res = svc.exec(42).await;
44 assert_eq!(res, 84);
45 }
46}