-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
util: more general interface for
UdpFramed
Previously `UdpFramed` only accepted smart pointers to `UdpSocket`. This commit changes it to accept anything that has `.poll_recv_from()` and `.poll_send_to()`. It allows for easier testing and more composability.
- Loading branch information
1 parent
37bb47c
commit c6e7472
Showing
2 changed files
with
66 additions
and
13 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,62 @@ | ||
//! UDP framing | ||
|
||
use std::{ | ||
borrow::Borrow, | ||
io, | ||
net::SocketAddr, | ||
task::{Context, Poll}, | ||
}; | ||
use tokio::{io::ReadBuf, net::UdpSocket}; | ||
|
||
mod frame; | ||
pub use frame::UdpFramed; | ||
|
||
/// Types that support receiving datagrams. | ||
/// | ||
/// This trait is implemented for any types that implement [`Borrow`]<[`UdpSocket`]>. | ||
pub trait PollRecvFrom { | ||
/// Attempts to receive a single datagram on the socket. | ||
/// | ||
/// See [`UdpSocket::poll_recv_from()`] for more information. | ||
fn poll_recv_from( | ||
&mut self, | ||
cx: &mut Context<'_>, | ||
buf: &mut ReadBuf<'_>, | ||
) -> Poll<io::Result<SocketAddr>>; | ||
} | ||
|
||
impl<T: Borrow<UdpSocket>> PollRecvFrom for T { | ||
fn poll_recv_from( | ||
&mut self, | ||
cx: &mut Context<'_>, | ||
buf: &mut ReadBuf<'_>, | ||
) -> Poll<io::Result<SocketAddr>> { | ||
(*self).borrow().poll_recv_from(cx, buf) | ||
} | ||
} | ||
|
||
/// Types that support sending datagrams to [`SocketAddr`]s. | ||
/// | ||
/// This trait is implemented for any types that implement [`Borrow`]<[`UdpSocket`]>. | ||
pub trait PollSendTo { | ||
/// Attempts to send data on the socket to a given address. | ||
/// | ||
/// See [`UdpSocket::poll_send_to()`] for more information. | ||
fn poll_send_to( | ||
&mut self, | ||
cx: &mut Context<'_>, | ||
buf: &[u8], | ||
target: SocketAddr, | ||
) -> Poll<io::Result<usize>>; | ||
} | ||
|
||
impl<T: Borrow<UdpSocket>> PollSendTo for T { | ||
fn poll_send_to( | ||
&mut self, | ||
cx: &mut Context<'_>, | ||
buf: &[u8], | ||
target: SocketAddr, | ||
) -> Poll<io::Result<usize>> { | ||
(*self).borrow().poll_send_to(cx, buf, target) | ||
} | ||
} |