Skip to content

Commit 3a5aba3

Browse files
committed
Fix for Document how to deserialize from a prefix of an io::Read without blocking until EOF #522
1 parent 0c72820 commit 3a5aba3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/de.rs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2193,6 +2193,11 @@ where
21932193
/// as a [`File`], you will want to apply your own buffering because serde_json
21942194
/// will not buffer the input. See [`std::io::BufReader`].
21952195
///
2196+
/// It is expected that the input stream ends after the deserialized object.
2197+
/// If the stream does not end, such as in the case of a persistent socket connection,
2198+
/// this function will not return. It is possible instead to deserialize from a prefix of an input
2199+
/// stream without looking for EOF by managing your own [`Deserializer`].
2200+
///
21962201
/// Note that counter to intuition, this function is usually slower than
21972202
/// reading a file completely into memory and then applying [`from_str`]
21982203
/// or [`from_slice`] on it. See [issue #160].
@@ -2205,6 +2210,8 @@ where
22052210
///
22062211
/// # Example
22072212
///
2213+
/// Reading the contents of a file.
2214+
///
22082215
/// ```edition2018
22092216
/// use serde::Deserialize;
22102217
///
@@ -2239,6 +2246,36 @@ where
22392246
/// }
22402247
/// ```
22412248
///
2249+
/// Reading from a persistent socket connection.
2250+
///
2251+
/// ```edition2018
2252+
/// use serde::Deserialize;
2253+
///
2254+
/// use std::error::Error;
2255+
/// use std::net::{TcpListener, TcpStream};
2256+
///
2257+
/// #[derive(Deserialize, Debug)]
2258+
/// struct User {
2259+
/// fingerprint: String,
2260+
/// location: String,
2261+
/// }
2262+
///
2263+
/// fn read_user_from_stream(tcp_stream: TcpStream) -> Result<User, Box<dyn Error>> {
2264+
/// let mut de = serde_json::Deserializer::from_reader(tcp_stream);
2265+
/// let u = User::deserialize(&mut de)?;
2266+
///
2267+
/// Ok(u)
2268+
/// }
2269+
///
2270+
/// fn main() {
2271+
/// let listener = TcpListener::bind("127.0.0.1:4000").unwrap();
2272+
///
2273+
/// for stream in listener.incoming() {
2274+
/// println!("{:#?}", read_user_from_stream(stream.unwrap()));
2275+
/// }
2276+
/// }
2277+
/// ```
2278+
///
22422279
/// # Errors
22432280
///
22442281
/// This conversion can fail if the structure of the input does not match the

0 commit comments

Comments
 (0)