@@ -96,6 +96,18 @@ pub struct Incoming<'a> {
96
96
listener : & ' a TcpListener ,
97
97
}
98
98
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
+
99
111
impl TcpStream {
100
112
/// Opens a TCP connection to a remote host.
101
113
///
@@ -798,6 +810,37 @@ impl TcpListener {
798
810
Incoming { listener : self }
799
811
}
800
812
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
+
801
844
/// Sets the value for the `IP_TTL` option on this socket.
802
845
///
803
846
/// 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> {
935
978
}
936
979
}
937
980
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
+
938
989
impl AsInner < net_imp:: TcpListener > for TcpListener {
939
990
fn as_inner ( & self ) -> & net_imp:: TcpListener {
940
991
& self . 0
0 commit comments