record_query/value/
raw.rs

1use crate::error;
2use crate::value;
3use std::io;
4
5#[derive(Debug)]
6pub struct Source<R>(io::Lines<io::BufReader<R>>)
7where
8    R: io::Read;
9
10#[derive(Debug)]
11pub struct Sink<W>(io::LineWriter<W>)
12where
13    W: io::Write;
14
15#[inline]
16pub fn source<R>(r: R) -> Source<R>
17where
18    R: io::Read,
19{
20    use std::io::BufRead;
21    Source(io::BufReader::new(r).lines())
22}
23
24#[inline]
25pub fn sink<W>(w: W) -> Sink<W>
26where
27    W: io::Write,
28{
29    Sink(io::LineWriter::new(w))
30}
31
32impl<R> value::Source for Source<R>
33where
34    R: io::Read,
35{
36    #[inline]
37    fn read(&mut self) -> error::Result<Option<value::Value>> {
38        match self.0.next() {
39            Some(Ok(v)) => Ok(Some(value::Value::String(v))),
40            Some(Err(e)) => Err(error::Error::from(e)),
41            None => Ok(None),
42        }
43    }
44}
45
46impl<W> value::Sink for Sink<W>
47where
48    W: io::Write,
49{
50    #[inline]
51    fn write(&mut self, value: value::Value) -> error::Result<()> {
52        use std::io::Write;
53        match value {
54            value::Value::String(s) => {
55                self.0.write_all(s.as_bytes())?;
56                self.0.write_all(b"\n")?;
57                Ok(())
58            }
59            value::Value::Bytes(b) => {
60                self.0.write_all(&b)?;
61                self.0.write_all(b"\n")?;
62                Ok(())
63            }
64            value::Value::Char(c) => {
65                writeln!(self.0, "{}", c)?;
66                Ok(())
67            }
68            x => Err(error::Error::Format {
69                msg: format!("raw can only output strings, bytes and chars, got: {:?}", x),
70            }),
71        }
72    }
73}