Skip to content

Commit ced597e

Browse files
committed
Add TcpListener::into_incoming and IntoIncoming
The `incoming` method is really useful, however for some use cases the borrow this introduces is needlessly restricting. Thus, an owned variant is added.
1 parent a992a11 commit ced597e

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

library/std/src/net/tcp.rs

+51
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,18 @@ pub struct Incoming<'a> {
9696
listener: &'a TcpListener,
9797
}
9898

99+
/// An iterator that infinitely [`accept`]s connections on a [`TcpListener`].
100+
///
101+
/// This `struct` is created by the [`TcpListener::into_incoming`] method.
102+
/// See its documentation for more.
103+
///
104+
/// [`accept`]: TcpListener::accept
105+
#[derive(Debug)]
106+
#[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
107+
pub struct IntoIncoming {
108+
listener: TcpListener,
109+
}
110+
99111
impl TcpStream {
100112
/// Opens a TCP connection to a remote host.
101113
///
@@ -798,6 +810,37 @@ impl TcpListener {
798810
Incoming { listener: self }
799811
}
800812

813+
/// Turn this into an iterator over the connections being received on this
814+
/// listener.
815+
///
816+
/// The returned iterator will never return [`None`] and will also not yield
817+
/// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
818+
/// calling [`TcpListener::accept`] in a loop.
819+
///
820+
/// # Examples
821+
///
822+
/// ```no_run
823+
/// #![feature(tcplistener_into_incoming)]
824+
/// use std::net::{TcpListener, TcpStream};
825+
///
826+
/// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
827+
/// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
828+
/// listener.into_incoming()
829+
/// .filter_map(Result::ok) /* Ignore failed connections */
830+
/// }
831+
///
832+
/// fn main() -> std::io::Result<()> {
833+
/// for stream in listen_on(80) {
834+
/// /* handle the connection here */
835+
/// }
836+
/// Ok(())
837+
/// }
838+
/// ```
839+
#[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
840+
pub fn into_incoming(self) -> IntoIncoming {
841+
IntoIncoming { listener: self }
842+
}
843+
801844
/// Sets the value for the `IP_TTL` option on this socket.
802845
///
803846
/// This value sets the time-to-live field that is used in every packet sent
@@ -935,6 +978,14 @@ impl<'a> Iterator for Incoming<'a> {
935978
}
936979
}
937980

981+
#[unstable(feature = "tcplistener_into_incoming", issue = "88339")]
982+
impl Iterator for IntoIncoming {
983+
type Item = io::Result<TcpStream>;
984+
fn next(&mut self) -> Option<io::Result<TcpStream>> {
985+
Some(self.listener.accept().map(|p| p.0))
986+
}
987+
}
988+
938989
impl AsInner<net_imp::TcpListener> for TcpListener {
939990
fn as_inner(&self) -> &net_imp::TcpListener {
940991
&self.0

0 commit comments

Comments
 (0)