json_streaming/blocking/io.rs
1use core::error::Error;
2
3
4/// [BlockingWrite] is the library's abstraction for blocking write I/O.
5///
6/// It is similar to `std::io::Write`, and there is a blanket implementation of [BlockingWrite] for
7/// any implementation of `Write`. The reason for introducing [BlockingWrite] is that it allows
8/// json-streaming to be used in a `no-std` environment.
9///
10/// Note that json-streaming writes data to a [BlockingWrite] in many small chunks without any I/O
11/// buffering. It is the client's responsibility to use `std::io::BufWriter` or similar for
12/// improved performance where desired.
13pub trait BlockingWrite {
14 type Error: Error;
15
16 fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error>;
17}
18
19#[cfg(feature = "std")]
20/// Blanket implementation that allows any [std::io::Write] implementation to be used seamlessly as
21/// [BlockingWrite].
22impl <W: std::io::Write> BlockingWrite for W {
23 type Error = std::io::Error;
24
25 fn write_all(&mut self, buf: &[u8]) -> Result<(), Self::Error> {
26 W::write_all(self, buf)
27 }
28}
29
30/// [BlockingRead] is the library's abstraction for blocking read I/O.
31///
32/// It is similar to `std:io::Read`, and there is a blanket implementation of [BlockingRead] for
33/// any implementation of `Read`. The reason for introducing [BlockingRead] is that it allows
34/// json-streaming in a `no-std` environment.
35///
36/// Note that json-streaming reads data from a [BlockingRead] in many small chunks without any I/O
37/// buffering. It is the client's responsibility to use `std::io::BufRead` or similar for
38/// improved performance where desired.
39pub trait BlockingRead {
40 type Error: Error;
41
42 fn read(&mut self) -> Result<Option<u8>, Self::Error>;
43}
44
45#[cfg(feature = "std")]
46/// Blanket implementation that allows any [std::io::Read] implementation to be used seamlessly as
47/// [BlockingRead].
48impl <R: std::io::Read> BlockingRead for R {
49 type Error = std::io::Error;
50
51 fn read(&mut self) -> Result<Option<u8>, Self::Error> {
52 let mut result = [0u8; 1];
53 let num_read = R::read(self, &mut result)?;
54 if num_read == 1 {
55 Ok(Some(result[0]))
56 }
57 else {
58 Ok(None)
59 }
60 }
61}