-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(server): add
const_service
and service_fn
helpers
- `const_service` creates a `NewService` that clones references to the wrapped service. - `service_fn` creates a `Service` from a function. Useful with closures.
- Loading branch information
1 parent
68e0df7
commit fe38aa4
Showing
3 changed files
with
78 additions
and
23 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
use std::marker::PhantomData; | ||
use std::sync::Arc; | ||
|
||
use futures::IntoFuture; | ||
use tokio_service::{NewService, Service}; | ||
|
||
/// Create a `Service` from a function. | ||
pub fn service_fn<F, R, S>(f: F) -> ServiceFn<F, R> | ||
where | ||
F: Fn(R) -> S, | ||
S: IntoFuture, | ||
{ | ||
ServiceFn { | ||
f: f, | ||
_req: PhantomData, | ||
} | ||
} | ||
|
||
/// Create a `NewService` by sharing references of `service. | ||
pub fn const_service<S>(service: S) -> ConstService<S> { | ||
ConstService { | ||
svc: Arc::new(service), | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub struct ServiceFn<F, R> { | ||
f: F, | ||
_req: PhantomData<fn() -> R>, | ||
} | ||
|
||
impl<F, R, S> Service for ServiceFn<F, R> | ||
where | ||
F: Fn(R) -> S, | ||
S: IntoFuture, | ||
{ | ||
type Request = R; | ||
type Response = S::Item; | ||
type Error = S::Error; | ||
type Future = S::Future; | ||
|
||
fn call(&self, req: Self::Request) -> Self::Future { | ||
(self.f)(req).into_future() | ||
} | ||
} | ||
|
||
#[derive(Debug)] | ||
pub struct ConstService<S> { | ||
svc: Arc<S>, | ||
} | ||
|
||
impl<S> NewService for ConstService<S> | ||
where | ||
S: Service, | ||
{ | ||
type Request = S::Request; | ||
type Response = S::Response; | ||
type Error = S::Error; | ||
type Instance = Arc<S>; | ||
|
||
fn new_service(&self) -> ::std::io::Result<Self::Instance> { | ||
Ok(self.svc.clone()) | ||
} | ||
} |