Skip to content

Commit

Permalink
Add blanket impl for Deref where target is Service (slowtec#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
Halkcyon authored May 23, 2023
1 parent 824143a commit 0b70a27
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/server/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::future::Future;
use std::ops::Deref;

/// A Modbus server service.
pub trait Service {
Expand All @@ -20,3 +21,19 @@ pub trait Service {
/// Process the request and return the response asynchronously.
fn call(&self, req: Self::Request) -> Self::Future;
}

impl<D> Service for D
where
D: Deref,
D::Target: Service,
{
type Request = <D::Target as Service>::Request;
type Response = <D::Target as Service>::Response;
type Error = <D::Target as Service>::Error;
type Future = <D::Target as Service>::Future;

/// A forwarding blanket impl to support smart pointers around [`Service`].
fn call(&self, req: Self::Request) -> Self::Future {
self.deref().call(req)
}
}
37 changes: 37 additions & 0 deletions src/server/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,45 @@ mod tests {

use crate::{prelude::*, server::Service};

use std::sync::Arc;

use futures::future;

#[tokio::test]
async fn delegate_service_through_deref_for_server() {
#[derive(Clone)]
struct DummyService {
response: Response,
}

impl Service for DummyService {
type Request = Request;
type Response = Response;
type Error = io::Error;
type Future = future::Ready<Result<Self::Response, Self::Error>>;

fn call(&self, _: Self::Request) -> Self::Future {
future::ready(Ok(self.response.clone()))
}
}

let service = Arc::new(DummyService {
response: Response::ReadInputRegisters(vec![0x33]),
});
let svc = |_socket_addr| Ok(Some(Arc::clone(&service)));
let on_connected =
|stream, socket_addr| async move { accept_tcp_connection(stream, socket_addr, svc) };

// bind 0 to let the OS pick a random port
let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
let listener = TcpListener::bind(addr).await.unwrap();
let server = Server::new(listener);

// passes type-check is the goal here
// added `mem::drop` to satisfy `must_use` compiler warnings
std::mem::drop(server.serve(&on_connected, |_err| {}));
}

#[tokio::test]
async fn service_wrapper() {
#[derive(Clone)]
Expand Down

0 comments on commit 0b70a27

Please sign in to comment.