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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
use std::borrow::Cow;
use std::io::{self, Write};

const BUFFER_SIZE: usize = 65_536;

use ser;
use serde::ser::Serialize;
use {FixedWidth, LineBreak, Result};

/// A trait to ease converting byte like data into a byte slice. This allows handling these types
/// with one generic function.
pub trait AsByteSlice {
    /// Borrows self as a slice of bytes.
    fn as_byte_slice(&self) -> &[u8];
}

impl AsByteSlice for String {
    /// Borrow a `String` as `&[u8]`
    fn as_byte_slice(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsByteSlice for str {
    /// Borrow a `str` as `&[u8]`
    fn as_byte_slice(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsByteSlice for [u8] {
    /// Borrow a `[u8]` as `&[u8]`
    fn as_byte_slice(&self) -> &[u8] {
        self
    }
}

impl AsByteSlice for Vec<u8> {
    /// Borrow a `Vec<u8>` as `&[u8]`
    fn as_byte_slice(&self) -> &[u8] {
        &self
    }
}

impl<'a, T: ?Sized> AsByteSlice for Cow<'a, T>
where
    T: AsByteSlice + ToOwned,
    <T as ToOwned>::Owned: AsByteSlice,
{
    /// Borrow a `Cow` type as `&[u8]`
    fn as_byte_slice(&self) -> &[u8] {
        match *self {
            Cow::Borrowed(v) => v.as_byte_slice(),
            Cow::Owned(ref v) => v.as_byte_slice(),
        }
    }
}

impl<'a, T: ?Sized + AsByteSlice> AsByteSlice for &'a T {
    fn as_byte_slice(&self) -> &[u8] {
        (*self).as_byte_slice()
    }
}

/// A fixed width data writer. It writes data provided in iterators to any type that implements
/// io::Write.
///
/// ### Example
///
/// Writing a `Vec<String>` to a file:
///
/// ```rust
/// extern crate fixed_width;
/// use std::io::Write;
/// use fixed_width::Writer;
///
/// let data = vec![
///     "1234".to_string(),
///     "5678".to_string(),
/// ];
///
/// let mut wrtr = Writer::from_memory();
/// wrtr.write_iter(data.iter());
/// wrtr.flush();
/// ```
pub struct Writer<W: Write> {
    wrtr: io::BufWriter<W>,
    linebreak: LineBreak,
}

impl<W> Writer<W>
where
    W: Write,
{
    /// Creates a new writer from any type that implements io::Write
    pub fn from_writer(wrtr: W) -> Self {
        Self::from_buffer(io::BufWriter::with_capacity(BUFFER_SIZE, wrtr))
    }

    /// Creates a new writer from a io::BufWriter that wraps a type that implements io::Write
    pub fn from_buffer(buf: io::BufWriter<W>) -> Self {
        Self {
            wrtr: buf,
            linebreak: LineBreak::None,
        }
    }

    /// Writes the given iterator of `FixedWidth + Serialize` types to the underlying writer,
    /// optionally inserting linebreaks if specified.
    pub fn write_serialized<T: FixedWidth + Serialize>(
        &mut self,
        records: impl Iterator<Item = T>,
    ) -> Result<()> {
        let mut first_record = true;

        for record in records {
            if !first_record {
                self.write_linebreak()?;
            } else {
                first_record = false;
            }

            ser::to_writer(self, &record)?;
        }

        Ok(())
    }

    /// Writes the given iterator of types that implement AsByteSlice to the underlying writer,
    /// optionally inserting linebreaks if specified.
    pub fn write_iter<T: AsByteSlice>(&mut self, records: impl Iterator<Item = T>) -> Result<()> {
        let mut first_record = true;

        for record in records {
            if !first_record {
                self.write_linebreak()?;
            } else {
                first_record = false;
            }

            self.write_all(record.as_byte_slice())?;
        }

        Ok(())
    }

    /// Writes the linebreak specified to the underlying writer. Does nothing if there is no
    /// linebreak.
    #[inline]
    pub fn write_linebreak(&mut self) -> Result<()> {
        match self.linebreak {
            LineBreak::Newline => {
                self.write_all(b"\n")?;
            }
            LineBreak::CRLF => {
                self.write_all(b"\r\n")?;
            }
            LineBreak::None => {}
        }

        Ok(())
    }

    /// Sets the linebreak desired for this data. Defaults to `LineBreak::None`.
    pub fn linebreak(mut self, linebreak: LineBreak) -> Self {
        self.linebreak = linebreak;
        self
    }
}

impl<W> Write for Writer<W>
where
    W: Write,
{
    /// Writes a buffer into the underlying writer.
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.wrtr.write(buf)
    }

    /// flushes the underlying writer.
    fn flush(&mut self) -> io::Result<()> {
        self.wrtr.flush()?;
        Ok(())
    }
}

impl Writer<Vec<u8>> {
    /// Creates a new writer in memory from a `Vec<u8>`.
    pub fn from_memory() -> Self {
        Self::from_writer(Vec::with_capacity(BUFFER_SIZE))
    }
}

impl Into<Vec<u8>> for Writer<Vec<u8>> {
    /// Converts the writer into a `Vec<u8>`, but panics if unable to flush to the underlying
    /// writer.
    fn into(mut self) -> Vec<u8> {
        match self.wrtr.flush() {
            Err(e) => panic!("could not flush bytes: {}", e),
            Ok(()) => self.wrtr.into_inner().unwrap(),
        }
    }
}

impl Into<String> for Writer<Vec<u8>> {
    /// Converts the writer into a `String`, but panics if unable to flush to the underlying
    fn into(mut self) -> String {
        match self.wrtr.flush() {
            Err(e) => panic!("could not flush bytes: {}", e),
            Ok(()) => String::from_utf8(self.into()).unwrap(),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use {Field, FixedWidth};

    #[test]
    fn write_to_memory() {
        let records = vec![
            "1111222233334444".to_string(),
            "1111222233334444".to_string(),
            "1111222233334444".to_string(),
        ];

        let mut wrtr = Writer::from_memory();

        wrtr.write_iter(records.iter()).unwrap();

        let mut expected = b"1111222233334444".to_vec();
        expected.append(&mut b"1111222233334444".to_vec());
        expected.append(&mut b"1111222233334444".to_vec());

        assert_eq!(expected, Into::<Vec<u8>>::into(wrtr));
    }

    #[test]
    fn write_to_writer() {
        let v = vec![16; 0];
        let records = vec![
            "1111222233334444".to_string(),
            "1111222233334444".to_string(),
            "1111222233334444".to_string(),
        ];

        let mut wrtr = Writer::from_writer(v);

        wrtr.write_iter(records.iter()).unwrap();

        let mut expected = b"1111222233334444".to_vec();
        expected.append(&mut b"1111222233334444".to_vec());
        expected.append(&mut b"1111222233334444".to_vec());

        assert_eq!(expected, Into::<Vec<u8>>::into(wrtr));
    }

    #[derive(Debug, Serialize)]
    struct Test2 {
        a: usize,
        b: String,
    }

    impl FixedWidth for Test2 {
        fn fields() -> Vec<Field> {
            vec![Field::default().range(0..3), Field::default().range(3..6)]
        }
    }

    #[test]
    fn serialized_write() {
        let tests = vec![
            Test2 {
                a: 1234,
                b: "foobar".to_string(),
            },
            Test2 {
                a: 12,
                b: "fb".to_string(),
            },
            Test2 {
                a: 123,
                b: "foo".to_string(),
            },
        ];

        let mut w = Writer::from_memory().linebreak(LineBreak::Newline);
        w.write_serialized(tests.into_iter()).unwrap();
        let s: String = w.into();

        assert_eq!(s, "123foo\n12 fb \n123foo");
    }

    #[test]
    fn test_write() {
        let bytes = b"abcd1234";
        let mut w = Writer::from_memory();
        w.write(bytes).unwrap();
        let s: String = w.into();

        assert_eq!(s, "abcd1234");
    }
}