Skip to content

Commit cb70bcc

Browse files
committed
read code
1 parent 465c362 commit cb70bcc

File tree

6 files changed

+28
-38
lines changed

6 files changed

+28
-38
lines changed

Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ edition = '2021'
55
repository = 'https://github.com/narrowlink/udp-stream'
66
license = 'MIT'
77
name = 'udp-stream'
8-
version = '0.0.12'
8+
version = '0.1.0'
99
keywords = ["stream", "udp", "dtls", "tokio"]
1010

1111
[dependencies]
@@ -14,7 +14,7 @@ log = "0.4"
1414
tokio = { version = "1", features = ["rt", "sync", "net", "macros", "io-util"] }
1515

1616
[dev-dependencies]
17-
env_logger = "0.10"
17+
env_logger = "0.11"
1818
openssl = { version = "0.10", features = ["vendored"] }
1919
tokio = { version = "1", features = ["time", "rt-multi-thread"] }
2020
tokio-openssl = '0.6'

README.md

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,20 @@
1616

1717
To use `udp-stream` in your Rust project, simply add it as a dependency in your `Cargo.toml` file:
1818

19-
toml
20-
21-
```[dependencies]
22-
udp-stream = "0.0.12"
19+
```toml
20+
[dependencies]
21+
udp-stream = "0.1"
2322
```
2423

2524
Then, you can import and use the library in your Rust code:
2625

27-
rust
28-
29-
```
26+
```rust,no_run
3027
use std::{net::SocketAddr, str::FromStr};
31-
3228
use tokio::io::{AsyncReadExt, AsyncWriteExt};
33-
3429
use udp_stream::UdpStream;
3530
3631
#[tokio::main]
37-
async fn main() -> Result<(), Box<dyn Error>> {
32+
async fn main() -> Result<(), Box<dyn std::error::Error>> {
3833
let mut stream = UdpStream::connect(SocketAddr::from_str("127.0.0.1:8080")?).await?;
3934
println!("Ready to Connected to {}", &stream.peer_addr()?);
4035
let mut buffer = String::new();

examples/echo-dtls.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
3333
let listener = UdpListener::bind(SocketAddr::from_str("127.0.0.1:8080")?).await?;
3434
let acceptor = ssl_acceptor(SERVER_CERT, SERVER_KEY)?;
3535
loop {
36-
let (socket, _) = listener.accept().await?;
36+
let socket = listener.accept().await?;
3737
let acceptor = acceptor.clone();
3838
tokio::spawn(async move {
3939
let ssl = Ssl::new(&acceptor).unwrap();

examples/echo-udp.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
1414

1515
let listener = udp_stream::UdpListener::bind(SocketAddr::from_str("127.0.0.1:8080")?).await?;
1616
loop {
17-
let (mut stream, _) = listener.accept().await?;
17+
let mut stream = listener.accept().await?;
1818
tokio::spawn(async move {
1919
let id = std::thread::current().id();
2020
let block = async move {

rustfmt.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
max_width = 140

src/lib.rs

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
#![doc = include_str!("../README.md")]
2+
13
use bytes::{Buf, Bytes, BytesMut};
24
use std::{
35
collections::HashMap,
46
future::Future,
5-
io,
67
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
78
pin::Pin,
89
sync::Arc,
@@ -36,14 +37,14 @@ const CHANNEL_LEN: usize = 100;
3637
/// let mut listener = UdpListener::bind(SocketAddr::from_str("127.0.0.1:8080")?).await?;
3738
///
3839
/// loop {
39-
/// let (socket, _) = listener.accept().await?;
40+
/// let socket = listener.accept().await?;
4041
/// process_socket(socket).await;
4142
/// }
4243
/// }
4344
/// ```
4445
pub struct UdpListener {
4546
handler: tokio::task::JoinHandle<()>,
46-
receiver: Arc<Mutex<mpsc::Receiver<(UdpStream, SocketAddr)>>>,
47+
receiver: Arc<Mutex<mpsc::Receiver<UdpStream>>>,
4748
local_addr: SocketAddr,
4849
}
4950

@@ -55,12 +56,13 @@ impl Drop for UdpListener {
5556

5657
impl UdpListener {
5758
/// Binds the `UdpListener` to the given local address.
58-
pub async fn bind(local_addr: SocketAddr) -> io::Result<Self> {
59+
pub async fn bind(local_addr: SocketAddr) -> std::io::Result<Self> {
5960
let udp_socket = UdpSocket::bind(local_addr).await?;
6061
Self::from_tokio(udp_socket).await
6162
}
63+
6264
/// Creates a `UdpListener` from an existing `tokio::net::UdpSocket`.
63-
pub async fn from_tokio(udp_socket: UdpSocket) -> io::Result<Self> {
65+
pub async fn from_tokio(udp_socket: UdpSocket) -> std::io::Result<Self> {
6466
let (tx, rx) = mpsc::channel(CHANNEL_LEN);
6567
let local_addr = udp_socket.local_addr()?;
6668

@@ -103,7 +105,7 @@ impl UdpListener {
103105
drop: Some(drop_tx.clone()),
104106
remaining: None,
105107
};
106-
if let Err(err) = tx.send((udp_stream, peer_addr)).await {
108+
if let Err(err) = tx.send(udp_stream).await {
107109
log::error!("tx.send {:?}", err);
108110
continue;
109111
}
@@ -122,18 +124,18 @@ impl UdpListener {
122124
}
123125

124126
///Returns the local address that this socket is bound to.
125-
pub fn local_addr(&self) -> io::Result<SocketAddr> {
127+
pub fn local_addr(&self) -> std::io::Result<SocketAddr> {
126128
Ok(self.local_addr)
127129
}
128130

129131
/// Accepts a new incoming UDP connection.
130-
pub async fn accept(&self) -> io::Result<(UdpStream, SocketAddr)> {
132+
pub async fn accept(&self) -> std::io::Result<UdpStream> {
131133
self.receiver
132134
.lock()
133135
.await
134136
.recv()
135137
.await
136-
.ok_or(io::Error::from(io::ErrorKind::BrokenPipe))
138+
.ok_or(std::io::Error::from(std::io::ErrorKind::BrokenPipe))
137139
}
138140
}
139141

@@ -187,10 +189,7 @@ impl UdpStream {
187189
/// Creates a new UdpStream from a tokio::net::UdpSocket.
188190
/// This function is intended to be used to wrap a UDP socket from the tokio library.
189191
/// Note: The UdpSocket must have the UdpSocket::connect method called before invoking this function.
190-
pub async fn from_tokio(
191-
socket: UdpSocket,
192-
peer_addr: SocketAddr,
193-
) -> Result<Self, tokio::io::Error> {
192+
pub async fn from_tokio(socket: UdpSocket, peer_addr: SocketAddr) -> Result<Self, tokio::io::Error> {
194193
let socket = Arc::new(socket);
195194

196195
let local_addr = socket.local_addr()?;
@@ -201,8 +200,7 @@ impl UdpStream {
201200

202201
let handler = tokio::spawn(async move {
203202
let mut buf = BytesMut::with_capacity(UDP_BUFFER_SIZE);
204-
while let Ok((len, received_addr)) = socket_inner.clone().recv_buf_from(&mut buf).await
205-
{
203+
while let Ok((len, received_addr)) = socket_inner.clone().recv_buf_from(&mut buf).await {
206204
if received_addr != peer_addr {
207205
continue;
208206
}
@@ -242,11 +240,7 @@ impl UdpStream {
242240
}
243241

244242
impl AsyncRead for UdpStream {
245-
fn poll_read(
246-
mut self: Pin<&mut Self>,
247-
cx: &mut Context,
248-
buf: &mut ReadBuf,
249-
) -> Poll<io::Result<()>> {
243+
fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut ReadBuf) -> Poll<std::io::Result<()>> {
250244
if let Some(remaining) = self.remaining.as_mut() {
251245
if buf.remaining() < remaining.len() {
252246
buf.put_slice(&remaining.split_to(buf.remaining())[..]);
@@ -271,14 +265,14 @@ impl AsyncRead for UdpStream {
271265
buf.put_slice(&inner_buf[..]);
272266
Poll::Ready(Ok(()))
273267
}
274-
Poll::Ready(None) => Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe))),
268+
Poll::Ready(None) => Poll::Ready(Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe))),
275269
Poll::Pending => Poll::Pending,
276270
}
277271
}
278272
}
279273

280274
impl AsyncWrite for UdpStream {
281-
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<io::Result<usize>> {
275+
fn poll_write(self: Pin<&mut Self>, cx: &mut Context, buf: &[u8]) -> Poll<std::io::Result<usize>> {
282276
match self.socket.poll_send_to(cx, buf, self.peer_addr) {
283277
Poll::Ready(Ok(r)) => Poll::Ready(Ok(r)),
284278
Poll::Ready(Err(e)) => {
@@ -290,10 +284,10 @@ impl AsyncWrite for UdpStream {
290284
Poll::Pending => Poll::Pending,
291285
}
292286
}
293-
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> {
287+
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<std::io::Result<()>> {
294288
Poll::Ready(Ok(()))
295289
}
296-
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<io::Result<()>> {
290+
fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context) -> Poll<std::io::Result<()>> {
297291
Poll::Ready(Ok(()))
298292
}
299293
}

0 commit comments

Comments
 (0)