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
#[cfg(test)]
extern crate tempfile;

pub use std::io::Result;

use std::ops::{Deref, DerefMut};
use std::convert::From;
use std::sync::Mutex;
use std::io::{SeekFrom, Seek, Read, Write};

/**
 * Read data at an offset
 *
 * Note that compared to Read::read, ReadAt::read_at does not borrow T mutably as it does not need
 * to modify an internal cursor.
 */
pub trait ReadAt {
    fn read_at(&self, buf: &mut[u8], offs: u64) -> Result<usize>;
}

/**
 * Write data at an offset
 */
pub trait WriteAt {
    fn write_at(&mut self, buf: &[u8], offs: u64) -> Result<usize>;

    /* XXX: this impl is very similar to Write::write_all, is there some way to generalize? */
    fn write_all_at(&mut self, mut buf: &[u8], mut offs: u64) -> Result<()> {
        use std::io::{Error, ErrorKind};
        while !buf.is_empty() {
            match self.write_at(buf, offs) {
                Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
                                               "failed to write whole buffer")),
                Ok(n) => {
                    buf = &buf[n..];
                    offs += n as u64;
                },
                Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }
}


/*
 * Adaptors:
 */
/*
pub struct<T: WriteAt> RateLimitWrite<T> {
    ts : u64;
    bytes_per_sec : u64;
    inner: T;
}
*/

/**
 * Adapt a WriteAt and/or ReadAt to a Write and/or Read by tracking a single internal offset and
 * modifying it.
 */
#[derive(Debug, Eq, PartialEq)]
pub struct Cursor<T> {
    offs: u64,
    inner: T,
}

impl<T> Cursor<T> {
    pub fn new(v: T, first_offs: u64) -> Self {
        Cursor { inner: v, offs: first_offs }
    }
}

impl<T: WriteAt> Write for Cursor<T> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let r = self.inner.write_at(buf, self.offs);
        if let Ok(v) = r {
            self.offs += v as u64;
        }
        r
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }
}

impl<T: ReadAt> Read for Cursor<T> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let r = self.inner.read_at(buf, self.offs);
        if let Ok(v) = r {
            self.offs += v as u64;
        }
        r
    }
}

#[test]
fn do_t_cursor() {
    use tempfile;
    let f = tempfile::tempfile().unwrap();
    let _at = Cursor::new(LockedSeek::from(f), 5);

    /* TODO: test it */
}

/**
 * Limit the maximum offset of a WriteAt and/or ReadAt.
 *
 * This can be useful when trying to simulate a fixed size item (like a block device) with a normal
 * file.
 */
#[derive(Debug, Eq, PartialEq)]
pub struct Take<T> {
    max_offs: u64,
    inner: T,
}

impl<T> Take<T> {
    pub fn new(v: T, max_offs: u64) -> Self {
        Take { max_offs : max_offs, inner: v }
    }

    pub fn len(&self) -> u64 {
        self.max_offs
    }
}

impl<T: ReadAt> ReadAt for Take<T> {
    fn read_at(&self, buf: &mut[u8], offs: u64) -> Result<usize> {
        let last = std::cmp::min(buf.len() as u64 + offs, self.max_offs);
        if offs > last {
            Ok(0)
        } else {
            self.inner.read_at(&mut buf[..(last - offs) as usize], offs)
        }
    }
}

impl<T: WriteAt> WriteAt for Take<T> {
    fn write_at(&mut self, buf: &[u8], offs: u64) -> Result<usize> {
        let last = std::cmp::min(buf.len() as u64 + offs, self.max_offs);
        if offs > last {
            Ok(0)
        } else {
            self.inner.write_at(&buf[..(last - offs) as usize], offs)
        }
    }
}

impl<T> Deref for Take<T> {
    type Target = T;
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut for Take<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

#[test]
fn take_test_impl() {
    let f = vec![];
    let at = Take::new(f, 100);
    test_impl(at);
}

#[test]
fn take_test_specifics() {
    /* Partial write */
    let mut at = Take::new(vec![], 5);
    assert_eq!(at.write_at(&[11u8, 2, 3, 4], 4).unwrap(), 1);

    /* Partial read */
    let mut res = [0u8; 4];
    assert_eq!(at.read_at(&mut res, 4).unwrap(), 1);
    assert_eq!(&res[..1], &[11]);

    /* At the end none write */
    assert_eq!(at.write_at(&[12u8, 13], 5).unwrap(), 0);

    /* At the end none read */
    assert_eq!(at.read_at(&mut res, 5).unwrap(), 0);

    /* Past the end none write */
    assert_eq!(at.write_at(&[12u8, 13], 6).unwrap(), 0);

    /* Past the end none read */
    assert_eq!(at.read_at(&mut res, 6).unwrap(), 0);
}

/**
 * Limit the amount of data accepted in a single call to WriteAt (ReadAt is unaffected)
 *
 * This is primarily useful for testing that handling of incomplete writes work properly.
 */
#[derive(Debug, Eq, PartialEq)]
pub struct BlockLimitWrite<T: WriteAt> {
    max_per_block: usize,
    inner: T,
}

impl<T: WriteAt> BlockLimitWrite<T> {
    pub fn new(v: T, max_per_block: usize) -> Self {
        BlockLimitWrite { max_per_block: max_per_block, inner: v }
    }
}

impl<T: WriteAt + ReadAt> ReadAt for BlockLimitWrite<T> {
    fn read_at(&self, buf: &mut[u8], offs: u64) -> Result<usize> {
        self.inner.read_at(buf, offs)
    }
}

impl<T: WriteAt> WriteAt for BlockLimitWrite<T> {
    fn write_at(&mut self, buf: &[u8], offs: u64) -> Result<usize> {
        self.inner.write_at(&buf[..std::cmp::min(buf.len(), self.max_per_block)], offs)
    }
}

impl<T: WriteAt> Deref for BlockLimitWrite<T> {
    type Target = T;
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T: WriteAt> DerefMut for BlockLimitWrite<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

#[test]
fn do_t_block_limit() {
    use tempfile;
    let f = tempfile::tempfile().unwrap();
    let at = BlockLimitWrite::new(LockedSeek::from(f), 2);
    test_impl(at);

    let f = tempfile::tempfile().unwrap();
    let mut at = BlockLimitWrite::new(LockedSeek::from(f), 2);
    assert_eq!(at.write_at(&[1u8, 2, 3], 0).unwrap(), 2);
}

/**
 * Allow a Seek + (Read and/or Write) to impliment WriteAt and/or ReadAt
 *
 * While in most cases more specific adaptations will be more efficient, this allows any Seek to
 * impliment WriteAt or ReadAt with not additional restrictions.
 */
pub struct LockedSeek<T: Seek> {
    inner: Mutex<T>,
}

/* FIXME: only allow for if T is also Read || Write */
impl<T: Seek> From<T> for LockedSeek<T> {
    fn from(v: T) -> Self {
        LockedSeek { inner: Mutex::new(v) }
    }
}

impl<T: Seek + Read> ReadAt for LockedSeek<T> {
    fn read_at(&self, buf: &mut[u8], offs: u64) -> Result<usize> {
        let mut f = self.inner.lock().unwrap();
        try!(f.seek(SeekFrom::Start(offs)));
        f.read(buf)
    }
}

impl<T: Seek + Write> WriteAt for LockedSeek<T> {
    fn write_at(&mut self, buf: &[u8], offs: u64) -> Result<usize> {
        let mut f = self.inner.lock().unwrap();
        try!(f.seek(SeekFrom::Start(offs)));
        f.write(buf)
    }
}

#[test]
fn do_t_locked_seek() {
    use tempfile;
    let f = tempfile::tempfile().unwrap();
    let at = LockedSeek::from(f);
    test_impl(at);
}

/// Use an offset as the base for all ReadAt and WriteAt accesses. Where `Take` modifies then end,
/// `At` modifies the start.
#[derive(Debug, Eq, PartialEq)]
pub struct At<T> {
    offs: u64,
    inner: T,
}

impl<T> At<T> {
    pub fn new(v: T, offs: u64) -> Self {
        At { offs : offs, inner: v }
    }
}

impl<T: ReadAt> ReadAt for At<T> {
    fn read_at(&self, buf: &mut[u8], offs: u64) -> Result<usize> {
        self.inner.read_at(buf, offs + self.offs)
    }
}

impl<T: WriteAt> WriteAt for At<T> {
    fn write_at(&mut self, buf: &[u8], offs: u64) -> Result<usize> {
        self.inner.write_at(buf, offs + self.offs)
    }
}

impl<T> Deref for At<T> {
    type Target = T;
    fn deref<'a>(&'a self) -> &'a T {
        &self.inner
    }
}

impl<T> DerefMut for At<T> {
    fn deref_mut<'a>(&'a mut self) -> &'a mut T {
        &mut self.inner
    }
}

#[test]
fn at_test_impl() {
    let mut f = vec![1u8, 1];
    {
        let mut at = At::new(&mut f, 1);
        test_impl(&mut at);
    }

    f[0] = 1;
    f[1] = 1;

    {
        let mut at = At::new(&mut f, 1);
        at.write_at(&[5], 0).unwrap();
    }

    assert_eq!(f[0], 1);
    assert_eq!(f[1], 5);
}

#[cfg(test)]
fn test_impl<T: ReadAt + WriteAt>(mut at: T) {
    let x = [1u8, 4, 9, 5];

    /* write at start */
    at.write_all_at(&x, 0).unwrap();
    let mut res = [0u8; 4];

    /* read at start */
    assert_eq!(at.read_at(&mut res, 0).unwrap(), 4);
    assert_eq!(&res, &x);

    /* read at middle */
    assert_eq!(at.read_at(&mut res[0..3], 1).unwrap(), 3);
    assert_eq!(&res[..3], &x[1..]);

    /* write at middle */
    at.write_all_at(&x, 1).unwrap();

    assert_eq!(at.read_at(&mut res, 0).unwrap(), 4);
    assert_eq!(&res, &[1u8, 1, 4, 9]);

    assert_eq!(at.read_at(&mut res[0..1], 4).unwrap(), 1);
    assert_eq!(&res[..1], &[5u8]);

    at.write_all_at(&x, 10).unwrap();
    assert_eq!(at.read_at(&mut res, 10).unwrap(), 4);
    assert_eq!(&res, &[1u8, 4, 9, 5]);

    at.write_all_at(&x, 9).unwrap();
    assert_eq!(at.read_at(&mut res, 9).unwrap(), 4);
    assert_eq!(&res, &[1u8, 4, 9, 5]);

}

/**
 * OS specific implimentations of WriteAt and/or ReadAt
 */
#[cfg(any(unix, windows))]
pub mod os;

mod slice;
mod vec;
mod refs;