Skip to content

Commit 5852897

Browse files
committed
Refactored tcp module
1 parent 193e2c1 commit 5852897

File tree

9 files changed

+90
-32
lines changed

9 files changed

+90
-32
lines changed

core/src/tcp/client.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,9 @@
2828

2929
//! A basic TCP client implementation designed for long-running connections.
3030
31-
use crate::tcp::buffer::ChannelBuffer;
32-
use crate::tcp::util::{DataMsg, Network, ReadyEvent};
33-
use crate::tcp::{NetReceiver, BYTES_CHANNEL_SIZE};
31+
use crate::tcp::util::buffer::{ChannelBuffer, NetReceiver};
32+
use crate::tcp::util::DataMsg;
33+
use crate::tcp::BYTES_CHANNEL_SIZE;
3434
use bp3d_debug::{error, trace};
3535
use std::future::Future;
3636
use std::sync::Arc;
@@ -39,6 +39,7 @@ use tokio::net::{TcpStream, ToSocketAddrs};
3939
use tokio::select;
4040
use tokio::sync::mpsc::error::{SendError, TrySendError};
4141
use tokio::sync::{mpsc, watch};
42+
use crate::tcp::util::net::{Network, ReadyEvent};
4243
use crate::util::barrier;
4344

4445
/// The reader trait which is supposed to handle the actual data reading loop.
@@ -185,7 +186,7 @@ impl<F: Factory> Builder<F> {
185186
if let Err(e) = reader.recv(&mut net).await {
186187
error!({?net}, "Client error: {}", e);
187188
}
188-
net.channel_buffer.close();
189+
net.close();
189190
});
190191
loop {
191192
select! {

core/src/tcp/mod.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,3 @@ pub mod client;
3838
pub mod server;
3939

4040
pub mod util;
41-
42-
mod buffer;
43-
//TODO: move to util
44-
pub use buffer::NetReceiver;

core/src/tcp/server/client.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,16 @@
2626
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
2727
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828

29-
use crate::tcp::buffer::ChannelBuffer;
30-
use crate::tcp::util::{DataMsg, Network, ReadyEvent};
31-
use crate::tcp::{NetReceiver, BYTES_CHANNEL_SIZE};
29+
use crate::tcp::util::buffer::{ChannelBuffer, NetReceiver};
30+
use crate::tcp::util::DataMsg;
31+
use crate::tcp::BYTES_CHANNEL_SIZE;
3232
use bp3d_debug::{error, trace};
3333
use std::future::Future;
3434
use tokio::io::AsyncWriteExt;
3535
use tokio::select;
3636
use tokio::sync::mpsc;
3737
use tokio::sync::watch;
38+
use crate::tcp::util::net::{Network, ReadyEvent};
3839
use crate::util::barrier;
3940

4041
/// Represents a client event handler.
@@ -77,7 +78,7 @@ impl<H: Handler + Send + 'static> ClientTask<'_, H> {
7778
if let Err(e) = self.handler.recv(&mut net).await {
7879
error!({?net}, "Client error: {}", e);
7980
}
80-
net.channel_buffer.close();
81+
net.close();
8182
self.handler
8283
});
8384
loop {

core/src/tcp/server/server.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828

2929
use crate::tcp::server::client::ClientTask;
30-
use crate::tcp::util::{DataMsg, Network};
30+
use crate::tcp::util::DataMsg;
3131
use bp3d_debug::{debug, trace};
3232
use std::future::Future;
3333
use std::net::Ipv4Addr;
@@ -41,6 +41,7 @@ use tokio::sync::mpsc;
4141
use tokio::sync::mpsc::error::{SendError, TrySendError};
4242
use tokio::sync::watch;
4343
use tokio::task::JoinSet;
44+
use crate::tcp::util::net::Network;
4445
use crate::util::barrier;
4546

4647
/// A factory trait which can be used to create the instance of the main server event handler.

core/src/tcp/buffer.rs renamed to core/src/tcp/util/buffer.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
2727
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828

29+
//! Async buffered receiver based on mpsc channels.
30+
2931
use crate::tcp::BYTES_BUFFER_SIZE;
3032
use std::fmt::{Debug, Formatter};
3133
use std::io::{Error, ErrorKind};
@@ -36,12 +38,21 @@ use std::task::{Context, Poll};
3638
use tokio::io::{AsyncRead, ReadBuf};
3739
use tokio::sync::mpsc;
3840

41+
/// A single buffer of bytes.
3942
pub struct Bytes<const N: usize> {
4043
bytes: [u8; N],
4144
size: usize,
4245
}
4346

4447
impl<const N: usize> Bytes<N> {
48+
/// Creates a new owned byte buffer.
49+
///
50+
/// # Arguments
51+
///
52+
/// * `bytes`: the array of bytes to store.
53+
/// * `size`: the number of valid bytes in the buffer.
54+
///
55+
/// returns: Bytes<{ N }>
4556
pub fn new(bytes: [u8; N], size: usize) -> Self {
4657
Self { bytes, size }
4758
}
@@ -55,15 +66,24 @@ impl<const N: usize> Deref for Bytes<N> {
5566
}
5667
}
5768

69+
/// The main async channel buffer.
5870
pub struct ChannelBuffer<const N: usize> {
5971
receiver: mpsc::Receiver<Bytes<N>>,
6072
}
6173

6274
impl<const N: usize> ChannelBuffer<N> {
75+
/// Creates a new [ChannelBuffer] by wrapping a mpsc channel.
76+
///
77+
/// # Arguments
78+
///
79+
/// * `receiver`: the channel to wrap.
80+
///
81+
/// returns: ChannelBuffer<{ N }>
6382
pub fn new(receiver: mpsc::Receiver<Bytes<N>>) -> Self {
6483
Self { receiver }
6584
}
6685

86+
/// Closes this [ChannelBuffer].
6787
pub fn close(mut self) {
6888
self.receiver.close();
6989
}
@@ -92,9 +112,9 @@ impl<const N: usize> AsyncRead for ChannelBuffer<N> {
92112
}
93113
}
94114

95-
/// Represents a network receiver.
115+
/// Represents a network receiver which wraps a [ChannelBuffer].
96116
pub struct NetReceiver {
97-
pub(super) channel_buffer: ChannelBuffer<BYTES_BUFFER_SIZE>,
117+
channel_buffer: ChannelBuffer<BYTES_BUFFER_SIZE>,
98118
addr: SocketAddr,
99119
id: usize,
100120
}
@@ -140,6 +160,11 @@ impl NetReceiver {
140160
pub fn id(&self) -> usize {
141161
self.id
142162
}
163+
164+
/// Closes this [ChannelBuffer].
165+
pub fn close(self) {
166+
self.channel_buffer.close();
167+
}
143168
}
144169

145170
impl AsyncRead for NetReceiver {

core/src/tcp/util/mod.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Copyright (c) 2025, BlockProject 3D
2+
//
3+
// All rights reserved.
4+
//
5+
// Redistribution and use in source and binary forms, with or without modification,
6+
// are permitted provided that the following conditions are met:
7+
//
8+
// * Redistributions of source code must retain the above copyright notice,
9+
// this list of conditions and the following disclaimer.
10+
// * Redistributions in binary form must reproduce the above copyright notice,
11+
// this list of conditions and the following disclaimer in the documentation
12+
// and/or other materials provided with the distribution.
13+
// * Neither the name of BlockProject 3D nor the names of its contributors
14+
// may be used to endorse or promote products derived from this software
15+
// without specific prior written permission.
16+
//
17+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21+
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22+
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23+
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24+
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25+
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
26+
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27+
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28+
29+
//! Utility module for TCP client or server.
30+
31+
pub mod net;
32+
pub mod buffer;
33+
34+
use std::fmt::Debug;
35+
36+
#[derive(Clone, Debug)]
37+
pub(super) struct DataMsg {
38+
pub(super) buffer: *const u8,
39+
pub(super) buffer_size: usize,
40+
#[allow(dead_code)]
41+
pub(super) net_id: usize,
42+
}
43+
44+
unsafe impl Send for DataMsg {}

core/src/tcp/util.rs renamed to core/src/tcp/util/net.rs

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,19 @@
2626
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
2727
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828

29-
//! Utility module for TCP client or server.
29+
//! TCP network stream async reader/writer tools.
3030
31-
use bp3d_debug::warning;
3231
use std::fmt::{Debug, Formatter};
3332
use std::io::{Error, ErrorKind, IoSlice};
3433
use std::net::SocketAddr;
3534
use std::pin::Pin;
3635
use std::task::{Context, Poll};
36+
use bp3d_debug::warning;
3737
use tokio::io::{AsyncRead, AsyncWrite, Interest, ReadBuf};
3838
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
3939
use tokio::net::TcpStream;
4040
use tokio::sync::mpsc;
41-
use crate::tcp::buffer::Bytes;
42-
43-
#[derive(Clone, Debug)]
44-
pub(super) struct DataMsg {
45-
pub(super) buffer: *const u8,
46-
pub(super) buffer_size: usize,
47-
#[allow(dead_code)]
48-
pub(super) net_id: usize,
49-
}
50-
51-
unsafe impl Send for DataMsg {}
41+
use crate::tcp::util::buffer::Bytes;
5242

5343
/// The event returned by the ready function in [Network].
5444
pub enum ReadyEvent {

testprog/src/client.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@
2727
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2828

2929
use bp3d_net::tcp::client::{Client, Factory, Handler, Reader};
30-
use bp3d_net::tcp::util::Network;
31-
use bp3d_net::tcp::NetReceiver;
3230
use std::sync::Arc;
3331
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
32+
use bp3d_net::tcp::util::buffer::NetReceiver;
33+
use bp3d_net::tcp::util::net::Network;
3434

3535
#[derive(Clone)]
3636
pub struct EchoClient {

testprog/src/server.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@
2828

2929
use bp3d_debug::debug;
3030
use bp3d_net::tcp::server::{ClientHandler, Factory, Handler, Server};
31-
use bp3d_net::tcp::util::Network;
32-
use bp3d_net::tcp::NetReceiver;
3331
use std::sync::Arc;
3432
use tokio::io::{AsyncBufReadExt, BufReader};
33+
use bp3d_net::tcp::util::buffer::NetReceiver;
34+
use bp3d_net::tcp::util::net::Network;
3535

3636
pub struct EchoServer {
3737
server: Arc<Server<EchoServer>>,

0 commit comments

Comments
 (0)