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
#![cfg_attr(feature = "seek_convenience", feature(seek_convenience))]

extern crate boolinator;
extern crate memmap;
mod backend;

use backend::*;
use memmap::Mmap;
use std::{fs, io};

// public interface

/// buffered or mmapped file contents handle
pub enum FileHandle {
    Mapped(Mmap),
    Buffered(Vec<u8>),
}

use self::FileHandle::*;

impl FileHandle {
    /// This function returns a slice pointing to
    /// the contents of the [`FileHandle`].
    #[inline]
    pub fn as_slice(&self) -> &[u8] {
        match self {
            Mapped(ref dt) => &dt[..],
            Buffered(ref dt) => &dt[..],
        }
    }

    #[deprecated(since = "0.1.2", note = "please use 'as_slice' instead")]
    #[inline]
    pub fn get_slice(&self) -> &[u8] {
        self.as_slice()
    }
}

impl std::ops::Deref for FileHandle {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub struct LengthSpec {
    bound: Option<usize>,
    is_exact: bool,
}

impl LengthSpec {
    /// @param bound
    ///   ? (read at most $n bytes)
    ///   : (read until EOF)
    /// @param is_exact
    ///   ? (request exactly length or fail)
    ///   : (request biggest readable slice with length as upper bound)
    pub fn new(bound: Option<usize>, is_exact: bool) -> Self {
        Self { bound, is_exact }
    }
}

impl std::default::Default for LengthSpec {
    /// read as much as possible
    #[inline]
    fn default() -> Self {
        Self {
            bound: None,
            is_exact: false,
        }
    }
}

/// Returns the length of the file,
/// and is based upon [`memmap::MmapOptions::get_len()`].
/// It doesn't sanitize the fact that mapping a slice greater than isize::MAX
/// has undefined behavoir.
pub fn get_file_len(fh: &fs::File) -> Option<u64> {
    fh.metadata().ok().map(|x| x.len())
}

/// Reads the file contents
pub fn read_from_file(fh: io::Result<fs::File>) -> io::Result<FileHandle> {
    let mut fh = fh?;
    let lns = LengthSpec {
        bound: None,
        is_exact: true,
    };
    read_part_from_file(&mut fh, 0, lns)
}

/// Reads a part of the file contents,
/// use this if the file is too big and needs to be read in parts,
/// starting at offset and until the given LengthSpec is met.
/// if you want a more ergonomic interface, use [`ContinuableFile`] or [`ChunkedFile`].
/// fh is a reference because this function is intended to be called multiple times
#[inline]
pub fn read_part_from_file(
    mut fh: &mut fs::File,
    offset: u64,
    len: LengthSpec,
) -> io::Result<FileHandle> {
    read_part_from_file_intern(&mut fh, offset, len, None)
}

#[must_use]
pub struct ContinuableFile {
    file: fs::File,
    flen: Option<u64>,
    offset: u64,
}

#[must_use]
pub struct ChunkedFile {
    cf: ContinuableFile,
    lns: LengthSpec,
}

impl ContinuableFile {
    pub fn new(file: fs::File) -> Self {
        let mut ret = Self {
            file,
            flen: None,
            offset: 0,
        };
        ret.sync_len();
        return ret;
    }

    pub fn to_chunks(self, lns: LengthSpec) -> ChunkedFile {
        ChunkedFile { cf: self, lns }
    }

    pub fn sync_len(&mut self) {
        self.flen = get_file_len(&self.file);
    }

    /// Tries to read the next part of the file contents
    pub fn next(&mut self, lns: LengthSpec) -> io::Result<FileHandle> {
        let rfh = read_part_from_file_intern(&mut self.file, self.offset, lns, self.flen)?;
        self.offset += rfh.len() as u64;
        Ok(rfh)
    }

    fn get_soor_err() -> io::Error {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "seek out of range",
        )
    }
}

impl io::Seek for ContinuableFile {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        let oore = Err(Self::get_soor_err());
        use io::SeekFrom::*;

        match pos {
            Start(x) => self.offset = x,
            End(x) => {
                let xn: u64 = (-x) as u64;
                if (x > 0) || self.flen.is_none() || (xn > self.flen.unwrap()) {
                    return oore;
                }
                self.offset = self.flen.unwrap() - xn;
            }
            Current(x) => match do_offset_add(self.offset, x) {
                Some(y) => self.offset = y,
                None => return oore,
            },
        }

        Ok(self.offset)
    }

    #[cfg(feature = "seek_convenience")]
    fn stream_len(&mut self) -> io::Result<u64> {
        match self.flen {
            None => Err(Self::get_soor_err()),
            Some(x) => Ok(x),
        }
    }

    #[cfg(feature = "seek_convenience")]
    fn stream_position(&mut self) -> io::Result<u64> {
        Ok(self.offset)
    }
}

// getters
impl ChunkedFile {
    #[inline]
    pub fn inner_mut(&mut self) -> &mut ContinuableFile {
        &mut self.cf
    }

    #[inline]
    #[deprecated(since = "0.1.2", note = "please use 'inner_mut' instead")]
    pub fn get_inner_ref(&mut self) -> &mut ContinuableFile {
        &mut self.cf
    }

    #[inline]
    pub fn into_inner(self) -> ContinuableFile {
        self.cf
    }

    #[inline]
    pub fn to_lns(&self) -> LengthSpec {
        self.lns
    }

    #[inline]
    #[deprecated(since = "0.1.2", note = "please use 'to_lns' instead")]
    pub fn get_lns(&self) -> LengthSpec {
        self.lns
    }
}

impl std::iter::Iterator for ChunkedFile {
    type Item = io::Result<FileHandle>;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.cf.next(self.lns);
        match item {
            Ok(ref x) if x.len() == 0 => None,
            _ => Some(item),
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let flen = self.cf.flen;
        let offset = self.cf.offset;
        (
            flen.and_then(|x| self.lns.bound.map(|y| ((x - offset as u64) as usize) / y)).unwrap_or(0),
            None,
        )
    }
}

impl io::Seek for ChunkedFile {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        self.cf.seek(pos)
    }
}