1
0
mirror of https://github.com/fafhrd91/actix-net synced 2025-02-26 02:22:50 +01:00
actix-net/actix-service/src/apply_cfg.rs

113 lines
2.5 KiB
Rust
Raw Normal View History

2019-03-09 09:01:02 -08:00
use std::marker::PhantomData;
use crate::{IntoNewService, NewService};
2019-03-12 16:32:10 -07:00
/// Create new ApplyConfig` service factory combinator
pub fn apply_cfg<F, S, C1, C2, U>(f: F, service: U) -> ApplyConfig<F, S, C1, C2>
where
S: NewService<C2>,
F: Fn(&C1) -> C2,
U: IntoNewService<S, C2>,
{
ApplyConfig::new(service.into_new_service(), f)
}
/// `ApplyConfig` service factory combinator
pub struct ApplyConfig<F, S, C1, C2> {
s: S,
2019-03-09 09:01:02 -08:00
f: F,
r: PhantomData<(C1, C2)>,
}
2019-03-12 16:32:10 -07:00
impl<F, S, C1, C2> ApplyConfig<F, S, C1, C2>
2019-03-09 09:01:02 -08:00
where
2019-03-12 16:32:10 -07:00
S: NewService<C2>,
2019-03-09 09:01:02 -08:00
F: Fn(&C1) -> C2,
{
2019-03-12 16:32:10 -07:00
/// Create new ApplyConfig` service factory combinator
pub fn new<U: IntoNewService<S, C2>>(a: U, f: F) -> Self {
2019-03-09 09:01:02 -08:00
Self {
f,
2019-03-12 16:32:10 -07:00
s: a.into_new_service(),
2019-03-09 09:01:02 -08:00
r: PhantomData,
}
}
}
2019-03-12 16:32:10 -07:00
impl<F, S, C1, C2> Clone for ApplyConfig<F, S, C1, C2>
2019-03-09 09:01:02 -08:00
where
2019-03-12 16:32:10 -07:00
S: Clone,
2019-03-09 09:01:02 -08:00
F: Clone,
{
fn clone(&self) -> Self {
Self {
2019-03-12 16:32:10 -07:00
s: self.s.clone(),
2019-03-09 09:01:02 -08:00
f: self.f.clone(),
r: PhantomData,
}
}
}
2019-03-12 16:32:10 -07:00
impl<F, S, C1, C2> NewService<C1> for ApplyConfig<F, S, C1, C2>
2019-03-09 09:01:02 -08:00
where
2019-03-12 16:32:10 -07:00
S: NewService<C2>,
2019-03-09 09:01:02 -08:00
F: Fn(&C1) -> C2,
{
2019-03-12 16:32:10 -07:00
type Request = S::Request;
type Response = S::Response;
type Error = S::Error;
type Service = S::Service;
2019-03-09 09:01:02 -08:00
2019-03-12 16:32:10 -07:00
type InitError = S::InitError;
type Future = S::Future;
2019-03-09 09:01:02 -08:00
fn new_service(&self, cfg: &C1) -> Self::Future {
let cfg2 = (self.f)(cfg);
2019-03-12 16:32:10 -07:00
self.s.new_service(&cfg2)
2019-03-09 09:01:02 -08:00
}
}
#[cfg(test)]
mod tests {
use futures::future::{ok, FutureResult};
use futures::{Async, Future, Poll};
use crate::{fn_cfg_factory, NewService, Service};
#[derive(Clone)]
struct Srv;
impl Service for Srv {
type Request = ();
type Response = ();
type Error = ();
type Future = FutureResult<(), ()>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> {
Ok(Async::Ready(()))
}
fn call(&mut self, _: ()) -> Self::Future {
ok(())
}
}
#[test]
fn test_new_service() {
let new_srv = fn_cfg_factory(|_: &usize| Ok::<_, ()>(Srv)).apply_cfg(
fn_cfg_factory(|s: &String| {
assert_eq!(s, "test");
Ok::<_, ()>(Srv)
}),
|cfg: &usize| {
assert_eq!(*cfg, 1);
"test".to_string()
},
);
if let Async::Ready(mut srv) = new_srv.new_service(&1).poll().unwrap() {
assert!(srv.poll_ready().is_ok());
}
}
}