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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use futures::Future;
use futures::future::{Either, ok};
use futures_cpupool::CpuPool;

use std::io::{self, Write};
use std::mem;
use std::ops::Deref;

use common::*;

/// Adds buffering to any writer, similar to the [standard `BufWriter`], but performs non-buffer
/// writes in a thread pool.
///
/// [standard `BufWriter`]: https://doc.rust-lang.org/std/io/struct.BufWriter.html
///
/// All writes are returned as futures.
///
/// This writer is most useful for wrapping writers that never block or cannot return EWOULDBLOCK,
/// but are slow. Notably, this is useful for wrapping `io::File`.
///
/// All writes must take and own the `BufWriter` and the buffer being written for the duration of
/// the write.
///
/// Note that unlike the standard `BufWriter`, this `BufWriter` is _not_ automatically flushed on
/// drop. Users must call [`flush_buf`] and potentially [`flush_inner`] to flush contents before
/// dropping.
///
/// [`flush_buf`]: struct.BufWriter.html#method.flush_buf
/// [`flush_inner`]: struct.BufWriter.html#method.flush_inner
///
/// # Examples
/// ```
/// # extern crate futures_cpupool;
/// # extern crate futures;
/// # extern crate futures_bufio;
/// #
/// # use futures::Future;
/// # use futures_cpupool::CpuPool;
/// # use futures_bufio::BufWriter;
/// # use std::io;
/// # fn main() {
/// let f = io::Cursor::new(vec![]);
/// let pool = CpuPool::new(1);
/// let writer = BufWriter::with_pool_and_capacity(pool, 4096, f);
///
/// let buf = b"many small writes".to_vec();
/// let (writer, buf) = writer.write_all(buf).wait().unwrap_or_else(|(_, _, e)| {
///     // in real usage, we have the option to deconstruct our BufWriter or reuse buf here
///     panic!("unable to read full: {}", e);
/// });
/// assert_eq!(&*buf, b"many small writes"); // we can reuse buf
/// # }
/// ```
pub struct BufWriter<W> {
    inner: W,
    buf: Box<[u8]>,
    pos: usize,
    w_start: usize,
    pool: Option<CpuPool>,
}

/// Wraps `W` with the original buffer being written.
type OkWrite<W, B> = (W, B);
/// Wraps `W` with the original buffer being written and the error encountered while writing.
type ErrWrite<W, B> = (W, B, io::Error);

impl<W: Write + Send + 'static> BufWriter<W> {
    /// Creates and returns a new `BufWriter` with an internal buffer of size `cap`.
    ///
    /// # Examples
    /// ```
    /// # extern crate futures_cpupool;
    /// # extern crate futures_bufio;
    /// #
    /// # use futures_cpupool::CpuPool;
    /// # use futures_bufio::BufWriter;
    /// # use std::io;
    /// # fn main() {
    /// let f = io::Cursor::new(vec![]);
    /// let pool = CpuPool::new(1);
    /// let writer = BufWriter::with_pool_and_capacity(pool, 4<<10, f);
    /// # }
    /// ```
    pub fn with_pool_and_capacity(pool: CpuPool, cap: usize, inner: W) -> BufWriter<W> {
        let mut buf = Vec::with_capacity(cap);
        unsafe {
            buf.set_len(cap);
        }
        BufWriter::with_pool_and_buf(pool, buf.into_boxed_slice(), inner)
    }

    /// Creates and returns a new `BufWriter` with `buf` as the internal buffer.
    ///
    /// # Examples
    /// ```
    /// # extern crate futures_cpupool;
    /// # extern crate futures_bufio;
    /// #
    /// # use futures_cpupool::CpuPool;
    /// # use futures_bufio::BufWriter;
    /// # use std::io;
    /// # fn main() {
    /// let f = io::Cursor::new(vec![]);
    /// let pool = CpuPool::new(1);
    /// let buf = vec![0; 4096].into_boxed_slice();
    /// let writer = BufWriter::with_pool_and_buf(pool, buf, f);
    /// # }
    /// ```
    pub fn with_pool_and_buf(pool: CpuPool, buf: Box<[u8]>, inner: W) -> BufWriter<W> {
        BufWriter {
            inner: inner,
            buf: buf,
            pos: 0,
            w_start: 0,
            pool: Some(pool),
        }
    }

    /// Gets a reference to the underlying writer.
    ///
    /// It is likely invalid to read directly from the underlying writer and then use the
    /// `BufWriter` again.
    pub fn get_ref(&self) -> &W {
        &self.inner
    }

    /// Gets a mutable reference to the underlying writer.
    ///
    /// It is likely invalid to read directly from the underlying writer and then use the
    /// `BufWriter` again.
    pub fn get_mut(&mut self) -> &W {
        &mut self.inner
    }

    /// Returns the internal components of a `BufWriter`, allowing reuse. This
    /// is unsafe because it does not zero the memory of the buffer, meaning
    /// the buffer could countain uninitialized memory.
    ///
    /// # Examples
    /// ```
    /// # extern crate futures_cpupool;
    /// # extern crate futures_bufio;
    /// #
    /// # use futures_cpupool::CpuPool;
    /// # use futures_bufio::BufWriter;
    /// # use std::io;
    /// # fn main() {
    /// let f = io::Cursor::new(b"foo text".to_vec());
    /// let pool = CpuPool::new(1);
    /// let writer = BufWriter::with_pool_and_capacity(pool, 4<<10, f);
    ///
    /// let (f, buf, pool) = unsafe { writer.components() };
    /// assert_eq!(f.get_ref(), b"foo text");
    /// assert_eq!(buf.len(), 4<<10);
    /// # }
    /// ```
    pub unsafe fn components(mut self) -> (W, Box<[u8]>, CpuPool) {
        let w = mem::replace(&mut self.inner, mem::uninitialized());
        let buf = mem::replace(&mut self.buf, mem::uninitialized());
        let mut pool = mem::replace(&mut self.pool, mem::uninitialized());
        let pool = pool.take().expect(EXP_POOL);
        mem::forget(self);
        (w, buf, pool)
    }

    /// Sets the `BufWriter`s internal buffer position to `pos`.
    ///
    ///
    /// This is _highly_ unsafe for the following reasons:
    ///
    ///   - the internal buffer may have uninitialized memory, and advancing the write position
    ///     will mean writing uninitialized memory
    ///
    ///   - the pos is not validated, meaning it is possible to move the pos past the end of the
    ///     internal buffer. This will cause a panic on the next use of `write_all` or
    ///     `flush_buf`.
    ///
    ///   - it is possible to move _before_ the internal beginning write position, meaning a write
    ///     or flush may panic due to the beginning of a write being after the end of a write.
    ///
    /// This function should only be used for setting up a new `BufWriter` with a buffer that
    /// contains known, existing contents.
    ///
    /// # Examples
    /// ```
    /// # extern crate futures_cpupool;
    /// # extern crate futures;
    /// # extern crate futures_bufio;
    /// #
    /// # use futures::Future;
    /// # use futures_cpupool::CpuPool;
    /// # use futures_bufio::BufWriter;
    /// # use std::io;
    /// # fn main() {
    /// let f = io::Cursor::new(vec![]);
    /// let pool = CpuPool::new(1);
    /// let mut buf = vec![0; 4096].into_boxed_slice();
    ///
    /// // copy some known text to uor buffer - note it must be at the beginning
    /// let p = b"pre-existing text";
    /// &mut buf[0..p.len()].copy_from_slice(p);
    ///
    /// let mut writer = BufWriter::with_pool_and_buf(pool, buf, f);
    ///
    /// // unsafely move the writer's position to the end of our known text, and flush the buffer
    /// unsafe { writer.set_pos(p.len()); }
    /// let writer = writer.flush_buf().wait().unwrap_or_else(|(_, e)| {
    ///     panic!("unable to flush_buf: {}", e);
    /// });
    ///
    /// // the underlying writer should be the contents of p
    /// let (f, _, _) = unsafe { writer.components() };
    /// assert_eq!(f.get_ref().as_slice(), p);
    /// # }
    /// ```
    pub unsafe fn set_pos(&mut self, pos: usize) {
        self.pos = pos;
    }

    /// Writes all of `buf` to the `BufWriter`, returning the buffer for potential reuse and any
    /// error that occurs.
    ///
    /// If used on `io::File`'s, `BufWriter` could be valuable for performing page-aligned writes.
    ///
    /// # Examples
    /// ```
    /// # extern crate futures_cpupool;
    /// # extern crate futures;
    /// # extern crate futures_bufio;
    /// #
    /// # use futures::Future;
    /// # use futures_cpupool::CpuPool;
    /// # use futures_bufio::BufWriter;
    /// # use std::io;
    /// # fn main() {
    /// let f = io::Cursor::new(vec![]);
    /// let pool = CpuPool::new(1);
    /// let writer = BufWriter::with_pool_and_capacity(pool, 4096, f);
    ///
    /// let buf = b"many small writes".to_vec();
    /// let (writer, buf) = writer.write_all(buf).wait().unwrap_or_else(|(_, _, e)| {
    ///     // in real usage, we have the option to deconstruct our BufWriter or reuse buf here
    ///     panic!("unable to read full: {}", e);
    /// });
    /// assert_eq!(&*buf, b"many small writes"); // we can reuse buf
    /// # }
    /// ```
    pub fn write_all<B>(
        mut self,
        buf: B,
    ) -> impl Future<Item = OkWrite<Self, B>, Error = ErrWrite<Self, B>>
    where
        B: Deref<Target = [u8]> + Send + 'static,
    {
        let mut rem = buf.len();
        let mut at = 0;
        let mut write_buf = false;

        if self.pos == 0 {
            if buf.len() < self.buf.len() {
                self.pos = copy(&mut self.buf, &*buf);
                return Either::A(ok::<OkWrite<Self, B>, ErrWrite<Self, B>>((self, buf)));
            }
        } else {
            at = copy(&mut self.buf[self.pos..], &*buf);
            self.pos += at;
            rem -= at;

            if self.pos != self.buf.len() {
                return Either::A(ok::<OkWrite<Self, B>, ErrWrite<Self, B>>((self, buf)));
            }
            write_buf = true;
        }

        let pool = self.pool.take().expect(EXP_POOL);
        let fut = pool.spawn_fn(move || {
            if write_buf {
                if let Err(e) = self.inner.write_all(&self.buf[self.w_start..]) {
                    return Err((self, buf, e));
                }
                self.w_start = 0;
            }

            if rem >= self.buf.len() {
                let n_write = rem -
                    if self.buf.len() != 0 {
                        rem % self.buf.len()
                    } else {
                        0
                    };
                if let Err(e) = self.inner.write_all(&buf[at..at + n_write]) {
                    return Err((self, buf, e));
                }
                at += n_write;
                rem -= n_write;
            }

            self.pos = copy(&mut self.buf, &buf[at..]);
            Ok((self, buf))
        });

        Either::B(fut.then(|res| match res {
            Ok(mut x) => {
                x.0.pool = Some(pool);
                Ok(x)
            }
            Err(mut x) => {
                x.0.pool = Some(pool);
                Err(x)
            }
        }))
    }

    /// Flushes currently buffered data to the inner writer.
    ///
    /// Calling `flush_buf` does not empty the current buffer; instead, a future flush triggered
    /// from `write_all` will be shorter. This is done to keep the full-buffered writes aligned.
    ///
    /// # Examples
    /// ```ignore
    /// let future = writer.flush_buf();
    /// ```
    pub fn flush_buf(mut self) -> impl Future<Item = Self, Error = (Self, io::Error)> {
        if self.w_start == self.pos {
            return Either::A(ok::<Self, (Self, io::Error)>(self));
        }

        let pool = self.pool.take().expect(EXP_POOL);
        let fut = pool.spawn_fn(move || {
            if let Err(e) = self.inner.write_all(&self.buf[self.w_start..self.pos]) {
                return Err((self, e));
            }
            self.w_start = self.pos;
            Ok(self)
        });

        Either::B(fut.then(|res| match res {
            Ok(mut me) => {
                me.pool = Some(pool);
                Ok(me)
            }
            Err(mut x) => {
                x.0.pool = Some(pool);
                Err(x)
            }
        }))
    }

    /// Calls [`flush`] on the inner writer.
    ///
    /// [`flush`]: https://doc.rust-lang.org/std/io/trait.Write.html#tymethod.flush
    ///
    /// # Examples
    /// ```ignore
    /// let future = writer.flush_inner();
    /// ```
    pub fn flush_inner(mut self) -> impl Future<Item = Self, Error = (Self, io::Error)> {
        let pool = self.pool.take().expect(EXP_POOL);
        let fut = pool.spawn_fn(move || {
            if let Err(e) = self.inner.flush() {
                return Err((self, e));
            }
            Ok(self)
        });

        fut.then(|res| match res {
            Ok(mut me) => {
                me.pool = Some(pool);
                Ok(me)
            }
            Err(mut x) => {
                x.0.pool = Some(pool);
                Err(x)
            }
        })
    }
}

#[test]
fn test_write() {
    use std::fs;
    use std::io::Read;

    fn assert_foo(exp: &'static str) {
        let mut foo = fs::File::open("foo.txt").expect("re-open");
        let mut contents = String::new();
        foo.read_to_string(&mut contents).expect(
            "unable to read file",
        );
        assert_eq!(contents, exp);
    }

    let f = BufWriter::with_pool_and_capacity(
        CpuPool::new(1),
        10,
        fs::OpenOptions::new()
            .write(true)
            .read(true) // for seek
            .create_new(true)
            .open("foo.txt")
            .expect("foo not exclusively created?"),
    );

    // memory (5)
    let (f, buf) = f.write_all(b"hello".to_vec()).wait().unwrap_or_else(
        |(_, _, e)| {
            panic!("unable to write to file: {}", e)
        },
    );
    assert_eq!(f.pos, 5);
    assert_eq!(f.w_start, 0);
    assert_eq!(&*buf, b"hello");
    assert_foo("");

    let f = f.flush_buf().wait().unwrap_or_else(|(_, e)| {
        panic!("unable to flush buf: {}", e)
    });
    assert_eq!(f.pos, 5);
    assert_eq!(f.w_start, 5);
    assert_foo("hello");

    let f = f.flush_inner().wait().unwrap_or_else(|(_, e)| {
        panic!("unable to flush file: {}", e)
    });
    assert_eq!(f.pos, 5);
    assert_eq!(f.w_start, 5);
    assert_foo("hello");

    // memory (2) with w_start at 5
    let (f, buf) = f.write_all(b"tw".to_vec()).wait().unwrap_or_else(
        |(_, _, e)| {
            panic!("unable to write to file: {}", e)
        },
    );
    assert_eq!(f.pos, 7);
    assert_eq!(f.w_start, 5);
    assert_eq!(&*buf, b"tw");
    assert_foo("hello");

    let f = f.flush_buf().wait().unwrap_or_else(|(_, e)| {
        panic!("unable to flush buf: {}", e)
    });
    assert_eq!(f.pos, 7);
    assert_eq!(f.w_start, 7);
    assert_foo("hellotw");

    // memory (7)
    let (f, buf) = f.write_all(b"goodbye".to_vec()).wait().unwrap_or_else(
        |(_, _, e)| {
            panic!("unable to write to file: {}", e)
        },
    );
    assert_eq!(f.pos, 4);
    assert_eq!(f.w_start, 0);
    assert_eq!(&*buf, b"goodbye");
    assert_foo("hellotwgoo");

    // memory (6) + disk (10)
    let (f, buf) = f.write_all(b"more++andthenten".to_vec())
        .wait()
        .unwrap_or_else(|(_, _, e)| panic!("unable to write to file: {}", e));
    assert_eq!(f.pos, 0);
    assert_eq!(f.w_start, 0);
    assert_eq!(&*buf, b"more++andthenten");
    assert_foo("hellotwgoodbyemore++andthenten");

    // disk (10)
    let (f, buf) = f.write_all(b"andtenmore".to_vec()).wait().unwrap_or_else(
        |(_, _, e)| {
            panic!("unable to write to file: {}", e)
        },
    );
    assert_eq!(f.pos, 0);
    assert_eq!(f.w_start, 0);
    assert_eq!(&*buf, b"andtenmore");
    assert_foo("hellotwgoodbyemore++andthentenandtenmore");

    // disk (10) + mem (5)
    let (f, buf) = f.write_all(b"this is rly old".to_vec())
        .wait()
        .unwrap_or_else(|(_, _, e)| panic!("unable to write to file: {}", e));
    assert_eq!(f.pos, 5);
    assert_eq!(f.w_start, 0);
    assert_eq!(&*buf, b"this is rly old");
    assert_foo("hellotwgoodbyemore++andthentenandtenmorethis is rl");

    let f = f.flush_buf().wait().unwrap_or_else(|(_, e)| {
        panic!("unable to flush buf: {}", e)
    });
    assert_eq!(f.pos, 5);
    assert_eq!(f.w_start, 5);
    assert_foo("hellotwgoodbyemore++andthentenandtenmorethis is rly old");

    fs::remove_file("foo.txt").expect("expected file to be removed");
}