-
Notifications
You must be signed in to change notification settings - Fork 122
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
server: Add DynamicService trait and adapter
- Loading branch information
Showing
3 changed files
with
43 additions
and
2 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 |
---|---|---|
@@ -1,7 +1,7 @@ | ||
// SPDX-FileCopyrightText: Copyright (c) 2017-2024 slowtec GmbH <[email protected]> | ||
// SPDX-License-Identifier: MIT OR Apache-2.0 | ||
|
||
use std::{future::Future, ops::Deref}; | ||
use std::{future::Future, ops::Deref, pin::Pin}; | ||
|
||
/// A Modbus server service. | ||
pub trait Service { | ||
|
@@ -36,3 +36,42 @@ where | |
self.deref().call(req) | ||
} | ||
} | ||
|
||
/// A Modbus server service that uses dynamic dispatch. | ||
pub trait DynamicService { | ||
/// Requests handled by the service. | ||
type Request; | ||
|
||
/// Responses given by the service. | ||
type Response; | ||
|
||
/// Errors produced by the service. | ||
type Error; | ||
|
||
/// Process the request and return the response asynchronously. | ||
#[allow(clippy::type_complexity)] | ||
fn call( | ||
&self, | ||
req: Self::Request, | ||
) -> Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; | ||
} | ||
|
||
/// An adapter that allows to use a [`DynamicService`] as a [`Service`]. | ||
#[derive(Debug, Clone)] | ||
pub struct DynamicServiceAdapter<T> { | ||
delegate: T, | ||
} | ||
|
||
impl<T> Service for DynamicServiceAdapter<T> | ||
where | ||
T: DynamicService, | ||
{ | ||
type Request = T::Request; | ||
type Response = T::Response; | ||
type Error = T::Error; | ||
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>; | ||
|
||
fn call(&self, req: Self::Request) -> Self::Future { | ||
self.delegate.call(req) | ||
} | ||
} |