Skip to content

Commit

Permalink
Reduce redundant code in disconnect() (#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
uklotzde authored Oct 13, 2024
1 parent 263e32a commit 4823606
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 25 deletions.
20 changes: 20 additions & 0 deletions src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,26 @@ pub(crate) mod rtu;
#[cfg(feature = "tcp")]
pub(crate) mod tcp;

#[cfg(any(feature = "rtu", feature = "tcp"))]
async fn disconnect<T, C>(framed: tokio_util::codec::Framed<T, C>) -> std::io::Result<()>
where
T: tokio::io::AsyncWrite + Unpin,
{
use tokio::io::AsyncWriteExt as _;

framed
.into_inner()
.shutdown()
.await
.or_else(|err| match err.kind() {
std::io::ErrorKind::NotConnected | std::io::ErrorKind::BrokenPipe => {
// Already disconnected.
Ok(())
}
_ => Err(err),
})
}

/// Check that `req_hdr` is the same `Header` as `rsp_hdr`.
///
/// # Errors
Expand Down
16 changes: 3 additions & 13 deletions src/service/rtu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{fmt, io};

use futures_util::{SinkExt as _, StreamExt as _};
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt as _};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::Framed;

use crate::{
Expand All @@ -14,7 +14,7 @@ use crate::{
ProtocolError, Result,
};

use super::verify_response_header;
use super::{disconnect, verify_response_header};

/// Modbus RTU client
#[derive(Debug)]
Expand Down Expand Up @@ -106,17 +106,7 @@ where
// Already disconnected.
return Ok(());
};
framed
.into_inner()
.shutdown()
.await
.or_else(|err| match err.kind() {
io::ErrorKind::NotConnected | io::ErrorKind::BrokenPipe => {
// Already disconnected.
Ok(())
}
_ => Err(err),
})
disconnect(framed).await
}
}

Expand Down
16 changes: 4 additions & 12 deletions src/service/tcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use std::{fmt, io};

use futures_util::{SinkExt as _, StreamExt as _};
use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt as _};
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::codec::Framed;

use crate::{
Expand All @@ -18,6 +18,8 @@ use crate::{
ExceptionResponse, ProtocolError, Request, Response, Result,
};

use super::disconnect;

const INITIAL_TRANSACTION_ID: TransactionId = 0;

#[derive(Debug)]
Expand Down Expand Up @@ -137,17 +139,7 @@ where
// Already disconnected.
return Ok(());
};
framed
.into_inner()
.shutdown()
.await
.or_else(|err| match err.kind() {
io::ErrorKind::NotConnected | io::ErrorKind::BrokenPipe => {
// Already disconnected.
Ok(())
}
_ => Err(err),
})
disconnect(framed).await
}
}

Expand Down

0 comments on commit 4823606

Please sign in to comment.