From 3a5aba3ee193cdc1f607977533c04aa9a800936e Mon Sep 17 00:00:00 2001 From: andrisak Date: Thu, 31 Oct 2019 10:20:23 +0100 Subject: [PATCH] Fix for Document how to deserialize from a prefix of an io::Read without blocking until EOF #522 --- src/de.rs | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/de.rs b/src/de.rs index 1aaab321d..2719b5ed3 100644 --- a/src/de.rs +++ b/src/de.rs @@ -2193,6 +2193,11 @@ where /// as a [`File`], you will want to apply your own buffering because serde_json /// will not buffer the input. See [`std::io::BufReader`]. /// +/// It is expected that the input stream ends after the deserialized object. +/// If the stream does not end, such as in the case of a persistent socket connection, +/// this function will not return. It is possible instead to deserialize from a prefix of an input +/// stream without looking for EOF by managing your own [`Deserializer`]. +/// /// Note that counter to intuition, this function is usually slower than /// reading a file completely into memory and then applying [`from_str`] /// or [`from_slice`] on it. See [issue #160]. @@ -2205,6 +2210,8 @@ where /// /// # Example /// +/// Reading the contents of a file. +/// /// ```edition2018 /// use serde::Deserialize; /// @@ -2239,6 +2246,36 @@ where /// } /// ``` /// +/// Reading from a persistent socket connection. +/// +/// ```edition2018 +/// use serde::Deserialize; +/// +/// use std::error::Error; +/// use std::net::{TcpListener, TcpStream}; +/// +/// #[derive(Deserialize, Debug)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn read_user_from_stream(tcp_stream: TcpStream) -> Result> { +/// let mut de = serde_json::Deserializer::from_reader(tcp_stream); +/// let u = User::deserialize(&mut de)?; +/// +/// Ok(u) +/// } +/// +/// fn main() { +/// let listener = TcpListener::bind("127.0.0.1:4000").unwrap(); +/// +/// for stream in listener.incoming() { +/// println!("{:#?}", read_user_from_stream(stream.unwrap())); +/// } +/// } +/// ``` +/// /// # Errors /// /// This conversion can fail if the structure of the input does not match the