@@ -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
///
@@ -845,6 +857,37 @@ impl TcpListener {
845
857
Incoming { listener : self }
846
858
}
847
859
860
+ /// Turn this into an iterator over the connections being received on this
861
+ /// listener.
862
+ ///
863
+ /// The returned iterator will never return [`None`] and will also not yield
864
+ /// the peer's [`SocketAddr`] structure. Iterating over it is equivalent to
865
+ /// calling [`TcpListener::accept`] in a loop.
866
+ ///
867
+ /// # Examples
868
+ ///
869
+ /// ```no_run
870
+ /// #![feature(tcplistener_into_incoming)]
871
+ /// use std::net::{TcpListener, TcpStream};
872
+ ///
873
+ /// fn listen_on(port: u16) -> impl Iterator<Item = TcpStream> {
874
+ /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
875
+ /// listener.into_incoming()
876
+ /// .filter_map(Result::ok) /* Ignore failed connections */
877
+ /// }
878
+ ///
879
+ /// fn main() -> std::io::Result<()> {
880
+ /// for stream in listen_on(80) {
881
+ /// /* handle the connection here */
882
+ /// }
883
+ /// Ok(())
884
+ /// }
885
+ /// ```
886
+ #[ unstable( feature = "tcplistener_into_incoming" , issue = "88339" ) ]
887
+ pub fn into_incoming ( self ) -> IntoIncoming {
888
+ IntoIncoming { listener : self }
889
+ }
890
+
848
891
/// Sets the value for the `IP_TTL` option on this socket.
849
892
///
850
893
/// This value sets the time-to-live field that is used in every packet sent
@@ -982,6 +1025,14 @@ impl<'a> Iterator for Incoming<'a> {
982
1025
}
983
1026
}
984
1027
1028
+ #[ unstable( feature = "tcplistener_into_incoming" , issue = "88339" ) ]
1029
+ impl Iterator for IntoIncoming {
1030
+ type Item = io:: Result < TcpStream > ;
1031
+ fn next ( & mut self ) -> Option < io:: Result < TcpStream > > {
1032
+ Some ( self . listener . accept ( ) . map ( |p| p. 0 ) )
1033
+ }
1034
+ }
1035
+
985
1036
impl AsInner < net_imp:: TcpListener > for TcpListener {
986
1037
fn as_inner ( & self ) -> & net_imp:: TcpListener {
987
1038
& self . 0
0 commit comments