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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
//! Files that can be read concurrently.
//!
//! [`std::fs::File`] is `Sync` but reading concurrently from it results in race
//! conditions, because the OS has a single cursor which is advanced and used
//! by several threads.
//!
//! [`SyncFile`] solves this problem by using platform-specific extensions to
//! do positional I/O, so the cursor of the file is not shared. Note that
//! writing concurrently at the same position in a file can still result in race
//! conditions, but only on the content, not the position.
//!
//! This library also exposes platform-independant fonctions for positional I/O.
//!
//! # Example
//!
//! ```
//! use std::io::Read;
//! use sync_file::SyncFile;
//! # use std::io::Write;
//! # let mut f = SyncFile::create("hello.txt")?;
//! # f.write_all(b"Hello World!\n")?;
//! # drop(f);
//!
//! /// Reads a file byte by byte.
//! /// Don't do this in real code !
//! fn read_all<R: Read>(mut file: R) -> std::io::Result<Vec<u8>> {
//!     let mut result = Vec::new();
//!     let mut buf = [0];
//!
//!     while file.read(&mut buf)? != 0 {
//!         result.extend(&buf);
//!     }
//!
//!     Ok(result)
//! }
//!
//! // Open a file
//! let f = SyncFile::open("hello.txt")?;
//! let f_clone = f.clone();
//!
//! // Read it concurrently
//! let thread = std::thread::spawn(move || read_all(f_clone));
//! let res1 = read_all(f)?;
//! let res2 = thread.join().unwrap()?;
//!
//! // Both clones read the whole content
//! // This would not work with `std::fs::File`
//! assert_eq!(res1, b"Hello World!\n");
//! assert_eq!(res2, b"Hello World!\n");
//!
//! # std::fs::remove_file("hello.txt")?;
//! # Ok::<_, std::io::Error>(())
//! ```
//!
//! # OS support
//!
//! Windows and Unix targets provide extensions for positional I/O, so on these
//! targets `SyncFile` is zero-cost. Wasi also provide these but only with a
//! nightly compiler.
//!
//! If platform-specific extensions are not available, `SyncFile` fallbacks to a
//! mutex.

#![warn(missing_docs)]

mod adapter;
mod file;

pub use adapter::Adapter;
pub use file::{RandomAccessFile, SyncFile};

use std::{cmp::min, convert::TryInto, io};

/// The `ReadAt` trait allows for reading bytes from a source at a given offset.
///
/// Additionally, the methods of this trait only require a shared reference,
/// which makes it ideal for parallel use.
pub trait ReadAt {
    /// Reads a number of bytes starting from a given offset.
    ///
    /// Returns the number of bytes read.
    ///
    /// Note that similar to [`io::Read::read`], it is not an error to return with
    /// a short read.
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize>;

    /// Reads the exact number of byte required to fill buf from the given
    /// offset.
    ///
    /// # Errors
    ///
    /// If this function encounters an error of the kind
    /// [`io::ErrorKind::Interrupted`] then the error is ignored and the
    /// operation will continue.
    ///
    /// If this function encounters an “end of file” before completely filling
    /// the buffer, it returns an error of the kind
    /// [`io::ErrorKind::UnexpectedEof`]. The contents of buf are unspecified
    /// in this case.
    ///
    /// If any other read error is encountered then this function immediately
    /// returns. The contents of buf are unspecified in this case.
    fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
        while !buf.is_empty() {
            match self.read_at(buf, offset) {
                Ok(0) => break,
                Ok(n) => {
                    buf = &mut buf[n..];
                    offset += n as u64;
                }
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        if buf.is_empty() {
            Ok(())
        } else {
            Err(fill_buffer_error())
        }
    }

    /// Like `read_at`, except that it reads into a slice of buffers.
    ///
    /// Data is copied to fill each buffer in order, with the final buffer
    /// written to possibly being only partially filled. This method must behave
    /// equivalently to a single call to read with concatenated buffers.
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        let buf = bufs
            .iter_mut()
            .find(|b| !b.is_empty())
            .map_or(&mut [][..], |b| &mut **b);
        self.read_at(buf, offset)
    }
}

impl ReadAt for [u8] {
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        let read = (|| {
            let offset = offset.try_into().ok()?;
            let this = self.get(offset..)?;
            let len = min(this.len(), buf.len());

            buf[..len].copy_from_slice(&this[..len]);
            Some(len)
        })();

        Ok(read.unwrap_or(0))
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (|| {
            let offset = offset.try_into().ok()?;
            let this = self.get(offset..)?;
            let len = buf.len();
            (this.len() >= len).then(|| buf.copy_from_slice(&this[..len]))
        })()
        .ok_or_else(fill_buffer_error)
    }
}

impl<const N: usize> ReadAt for [u8; N] {
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        self.as_ref().read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.as_ref().read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        self.as_ref().read_vectored_at(bufs, offset)
    }
}

impl ReadAt for Vec<u8> {
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl ReadAt for std::borrow::Cow<'_, [u8]> {
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl<R> ReadAt for &R
where
    R: ReadAt + ?Sized,
{
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl<R> ReadAt for Box<R>
where
    R: ReadAt + ?Sized,
{
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl<R> ReadAt for std::sync::Arc<R>
where
    R: ReadAt + ?Sized,
{
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl<R> ReadAt for std::rc::Rc<R>
where
    R: ReadAt + ?Sized,
{
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        (**self).read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        (**self).read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        (**self).read_vectored_at(bufs, offset)
    }
}

impl<T> ReadAt for io::Cursor<T>
where
    T: AsRef<[u8]>,
{
    #[inline]
    fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
        self.get_ref().as_ref().read_at(buf, offset)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], offset: u64) -> io::Result<()> {
        self.get_ref().as_ref().read_exact_at(buf, offset)
    }

    #[inline]
    fn read_vectored_at(&self, bufs: &mut [io::IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
        self.get_ref().as_ref().read_vectored_at(bufs, offset)
    }
}

impl ReadAt for io::Empty {
    #[inline]
    fn read_at(&self, _buf: &mut [u8], _offset: u64) -> io::Result<usize> {
        Ok(0)
    }

    #[inline]
    fn read_exact_at(&self, buf: &mut [u8], _offset: u64) -> io::Result<()> {
        if buf.is_empty() {
            Ok(())
        } else {
            Err(fill_buffer_error())
        }
    }

    #[inline]
    fn read_vectored_at(&self, _: &mut [io::IoSliceMut<'_>], _: u64) -> io::Result<usize> {
        Ok(0)
    }
}

/// The `WriteAt` trait allows for writing bytes to a source at a given offset.
///
/// Additionally, the methods of this trait only require a shared reference,
/// which makes it ideal for parallel use.
pub trait WriteAt {
    /// Writes a number of bytes starting from a given offset.
    ///
    /// Returns the number of bytes written.
    ///
    /// Note that similar to [`io::Write::write`], it is not an error to return a
    /// short write.
    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize>;

    /// Attempts to write an entire buffer starting from a given offset.
    ///
    /// # Errors
    ///
    /// This function will return the first error of
    /// non-[`io::ErrorKind::Interrupted`] kind that `write_at` returns.
    fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
        while !buf.is_empty() {
            match self.write_at(buf, offset) {
                Ok(0) => {
                    return Err(write_buffer_error());
                }
                Ok(n) => {
                    buf = &buf[n..];
                    offset += n as u64;
                }
                Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(e) => return Err(e),
            }
        }
        Ok(())
    }

    /// Like `write_at`, except that it writes from a slice of buffers.
    ///
    /// Data is copied from each buffer in order, with the final buffer read
    /// from possibly being only partially consumed. This method must behave as
    /// a call to `write_at` with the buffers concatenated would.
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize> {
        let buf = bufs
            .iter()
            .find(|b| !b.is_empty())
            .map_or(&[][..], |b| &**b);
        self.write_at(buf, offset)
    }

    /// Flush this output stream, ensuring that all intermediately buffered
    /// contents reach their destination.
    ///
    /// # Errors
    ///
    /// It is considered an error if not all bytes could be written due to I/O
    /// errors or EOF being reached.
    #[inline]
    fn flush(&self) -> io::Result<()> {
        Ok(())
    }
}

impl<W> WriteAt for &W
where
    W: WriteAt + ?Sized,
{
    #[inline]
    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        (**self).write_at(buf, offset)
    }

    #[inline]
    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
        (**self).write_all_at(buf, offset)
    }

    #[inline]
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize> {
        (**self).write_vectored_at(bufs, offset)
    }

    #[inline]
    fn flush(&self) -> io::Result<()> {
        (**self).flush()
    }
}

impl<W> WriteAt for Box<W>
where
    W: WriteAt + ?Sized,
{
    #[inline]
    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        (**self).write_at(buf, offset)
    }

    #[inline]
    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
        (**self).write_all_at(buf, offset)
    }

    #[inline]
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize> {
        (**self).write_vectored_at(bufs, offset)
    }

    #[inline]
    fn flush(&self) -> io::Result<()> {
        (**self).flush()
    }
}

impl<W> WriteAt for std::sync::Arc<W>
where
    W: WriteAt + ?Sized,
{
    #[inline]
    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        (**self).write_at(buf, offset)
    }

    #[inline]
    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
        (**self).write_all_at(buf, offset)
    }

    #[inline]
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize> {
        (**self).write_vectored_at(bufs, offset)
    }

    #[inline]
    fn flush(&self) -> io::Result<()> {
        (**self).flush()
    }
}

impl<W> WriteAt for std::rc::Rc<W>
where
    W: WriteAt + ?Sized,
{
    #[inline]
    fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
        (**self).write_at(buf, offset)
    }

    #[inline]
    fn write_all_at(&self, buf: &[u8], offset: u64) -> io::Result<()> {
        (**self).write_all_at(buf, offset)
    }

    #[inline]
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], offset: u64) -> io::Result<usize> {
        (**self).write_vectored_at(bufs, offset)
    }

    #[inline]
    fn flush(&self) -> io::Result<()> {
        (**self).flush()
    }
}

impl WriteAt for io::Sink {
    #[inline]
    fn write_at(&self, buf: &[u8], _offset: u64) -> io::Result<usize> {
        Ok(buf.len())
    }

    #[inline]
    fn write_all_at(&self, _buf: &[u8], _offset: u64) -> io::Result<()> {
        Ok(())
    }

    #[inline]
    fn write_vectored_at(&self, bufs: &[io::IoSlice<'_>], _offset: u64) -> io::Result<usize> {
        Ok(bufs.iter().map(|b| b.len()).sum())
    }
}

#[cold]
fn fill_buffer_error() -> io::Error {
    io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")
}

#[cold]
fn write_buffer_error() -> io::Error {
    io::Error::new(io::ErrorKind::WriteZero, "failed to write whole buffer")
}

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

    #[test]
    fn smoke_test() {
        let mut f = SyncFile::open("LICENSE-APACHE").unwrap();
        let mut buf = [0; 9];
        f.read_exact(&mut buf).unwrap();
        assert_eq!(&buf, b"Copyright");
        assert_eq!(f.stream_position().unwrap(), 9);
        assert_eq!(f.seek(io::SeekFrom::Current(-2)).unwrap(), 7);
        f.read_exact(&mut buf[..2]).unwrap();
        assert_eq!(&buf[..2], b"ht");
        assert!(f.seek(io::SeekFrom::Current(-10)).is_err());
    }
}