1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
//! Tapped reader
//!
//! Wraps an existing reader and copies the read bytes into it's own buffer
//!
//! This can be useful for when you are deserializing a stream of bytes, and want to be able to
//! provide the original input for log messages, error messages, etc
//!
//! # Example
//!
//! ```
//! extern crate tap_reader;
//! extern crate serde_json;
//! extern crate serde;
//! #[macro_use] extern crate serde_derive;
//!
//! # use std::error::Error;
//! use std::io::Cursor;
//! use tap_reader::Tap;
//!
//! # fn main() -> Result<(), ()> {
//! #[derive(Debug, Deserialize, PartialEq)]
//! struct Foo {
//!     foo: String,
//!     bar: usize,
//! }
//!
//! let input = r#"{"foo":"hello, world!","bar":42}"#;
//! let bytes = input.as_bytes();
//! let reader = Cursor::new(bytes);
//! let mut reader = Tap::new(reader);

//! let foo: Foo = match serde_json::from_reader(&mut reader) {
//!     Ok(foo) => foo,
//!     Err(e) => {
//!         eprintln!("Error serializing Foo from input: '{}'\n error was: {}",
//!                   String::from_utf8_lossy(&reader.bytes),
//!                   e.description());
//!         return Err(());
//!     }
//! };
//! assert_eq!(foo, Foo { foo: "hello, world!".to_string(), bar: 42 });
//! assert_eq!(reader.bytes, bytes);
//! #   Ok(())
//! # }
//!
//! ```
//!
//! ```
//! extern crate tap_reader;
//!
//! use std::io::{Cursor, Read};
//!
//! use tap_reader::Tap;
//!
//! # fn main() -> ::std::io::Result<()> {
//! let input = "hello, world!".to_string();
//! let bytes = input.as_bytes();
//! let cursor = Cursor::new(bytes);
//! let mut reader = Tap::new(cursor);
//!
//! let mut output = String::new();
//!
//! reader.read_to_string(&mut output)?;
//!
//! assert_eq!(output, input);
//! assert_eq!(bytes, &reader.bytes[..]);
//!
//! #     Ok(())
//! # }
//! ```

#[cfg(test)]
extern crate serde;
#[cfg(test)]
extern crate serde_json;

#[cfg(test)]
#[cfg_attr(test, macro_use)]
extern crate serde_derive;

use std::io::{self, Read};

/// `Read` adaptor
///
/// Takes a `Read` as input and copies all read bytes into it's own buffer
///
/// # Example
///
/// ```
/// # extern crate tap_reader;
/// use tap_reader::Tap;
/// # use std::io;
/// use std::io::{Cursor, Read};
///
/// # fn main() -> io::Result<()> {
/// let input = "hello, world!";
/// let bytes = input.as_bytes();
/// let cursor = Cursor::new(bytes);
/// let mut reader = Tap::new(cursor);
///
/// let mut output = String::new();
/// reader.read_to_string(&mut output)?;
///
/// assert_eq!(output, String::from_utf8_lossy(&reader.bytes));
/// #   Ok(())
/// # }
/// ```
pub struct Tap<R> {
    pub bytes: Vec<u8>,
    reader: R,
}

impl<R: Read> Tap<R> {
    /// Construct a `Tap` reader from an existing reader
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate tap_reader;
    /// use std::io::Cursor;
    /// use tap_reader::Tap;
    /// let input = "hello, world!";
    /// let bytes = input.as_bytes();
    /// let cursor = Cursor::new(bytes);
    /// let mut reader = Tap::new(cursor);
    /// ```
    pub fn new(r: R) -> Tap<R> {
        Tap { bytes: vec![], reader: r }
    }
}

impl<R: Read> Read for Tap<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let num = self.reader.read(buf)?;
        self.bytes.extend_from_slice(&buf[..num]);
        Ok(num)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[derive(Deserialize, Debug, PartialEq)]
    struct Foo {
        foo: String,
        bar: u64,
    }

    #[test]
    fn tap_serde_deser() {
        let input = r#"{"foo":"hello, world!","bar":42}"#;
        let bytes = input.as_bytes();
        let reader = Cursor::new(bytes);
        let mut reader = Tap::new(reader);

        let foo: Foo = serde_json::from_reader(&mut reader).expect("Couldn't deserialize");
        assert_eq!(
            foo,
            Foo {
                foo: "hello, world!".to_string(),
                bar: 42
            }
        );
        assert_eq!(reader.bytes, bytes);
    }

    #[test]
    fn tap_cursor() {
        let s = String::from("foo bar");
        let bytes = s.as_bytes();
        let reader = Cursor::new(bytes);

        let mut reader = Tap::new(reader);

        let mut output = String::new();
        reader.read_to_string(&mut output).expect("Could not read");

        let tapped = reader.bytes;
        assert_eq!(output, String::from_utf8(bytes.to_vec()).expect("Couldn't create string from bytes"));
        assert_eq!(tapped, bytes);
    }

    #[test]
    fn test_large_string() {
        let text = r#"Demicyclic Disease: Because there is no repeating stage in the life cycle of demicyclic
        fungi, removal of the primary or the alternate host will disrupt the disease cycle. This method, however,
        is not highly effective in managing all demicyclic diseases. Cedar-apple rust disease, for example, can
        persist despite removal of one of the hosts since spores can be disseminated from long distances. The 
        severity of Cedar-apple rust disease can be managed by removal of basidiospore producing galls from 
        junipers or the application of protective fungicides to junipers."#;

        let bytes = text.as_bytes();
        let cursor = Cursor::new(bytes);
        let mut reader = Tap::new(cursor);

        let mut output = String::new();
        reader.read_to_string(&mut output).expect("Could not read");

        let tapped = reader.bytes;
        assert_eq!(output, String::from_utf8(bytes.to_vec()).expect("Couldn't create string from bytes"));
        assert_eq!(tapped, bytes);
    }
}