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
//!A simple library to index and read large files by its lines using a pregenerated index

/// Generic implementation to use various types as reader
pub mod any;
/// Basic implementation for std::io::BufReader
pub mod bufreader;
pub mod error;
/// A wrapper around std::fs::File which implements ReadByLine
pub mod file;
/// The index of files
pub mod index;
/// An indexed string reader
pub mod string;

pub use file::File;
pub use string::IndexedString;

use std::{cmp::Ordering, io::Write};

use index::Index;
pub type Result<T> = std::result::Result<T, error::Error>;

pub trait Indexable {
    /// Returns a reference to the files index.
    fn get_index(&self) -> &Index;

    /// Returns the total amount of lines in the file without the lines used by the index.
    #[inline]
    fn total_lines(&self) -> usize {
        self.get_index().len()
    }

    #[inline]
    fn get_index_byte_len(&self) -> usize {
        self.get_index().len_bytes()
    }
}

pub trait IndexableFile: Indexable {
    /// Should read from the current position until the end of the line, omitting the \n
    fn read_current_line(&mut self, buf: &mut Vec<u8>) -> Result<usize>;

    /// Should seek the file to the given line `line`
    fn seek_line(&mut self, line: usize) -> Result<()>;

    /// Write the index, followed by the files contents into `writer`. A file generated using this
    /// function will always be parsable by `File::open`.
    fn write_to<W: Write + Unpin + Send>(&mut self, writer: &mut W) -> Result<usize>;

    /// Should return the offset to seek to given the line-index
    #[inline(always)]
    fn get_offset(&self, line: usize) -> Result<u64> {
        self.get_index().get(line)
    }
}

/// A trait defining behavior for reading certain lines directly from indexed files.
pub trait ReadByLine: IndexableFile {
    /// Reads the given line
    fn read_line(&mut self, line: usize) -> Result<String> {
        self.seek_line(line)?;

        let mut read_data = Vec::new();
        self.read_current_line(&mut read_data)?;
        Ok(String::from_utf8(read_data)?)
    }

    /// Reads the given line and stores into `buf`
    fn read_line_raw(&mut self, line: usize, buf: &mut Vec<u8>) -> Result<usize> {
        self.seek_line(line)?;
        Ok(self.read_current_line(buf)?)
    }

    /// Do a binary search on `ReadByLine` implementing Types, since it provides everything required
    /// for binary search. Only works with sorted files
    #[inline]
    fn binary_search(&mut self, x: &str) -> Result<usize> {
        self.binary_search_by(|p| p.cmp(x))
    }

    /// Do a binary search by on `ReadByLine` implementing Types, since it provides everything required
    /// for binary search. Only works with sorted files
    fn binary_search_by<F>(&mut self, mut f: F) -> Result<usize>
    where
        F: FnMut(&str) -> std::cmp::Ordering,
    {
        let mut size = self.total_lines();
        let mut left = 0;
        let mut right = size;

        while left < right {
            let mid = left + size / 2;

            let cmp = f(&self.read_line(mid)?);

            if cmp == Ordering::Less {
                left = mid + 1;
            } else if cmp == Ordering::Greater {
                right = mid;
            } else {
                return Ok(mid);
            }

            size = right - left;
        }

        Err(error::Error::NotFound)
    }
}

#[cfg(test)]
mod tests {
    use rand::{distributions::Uniform, Rng};

    use crate::string::IndexedString;

    use super::*;
    use std::{
        convert::TryInto,
        fs::read_to_string,
        io::{prelude::*, BufReader},
    };

    #[test]
    fn test_empty() {
        let indexed_file = File::open("./testfiles/empty");
        assert!(indexed_file.is_err());
    }

    #[test]
    fn test() {
        let input_files = &["input1", "LICENSE"];

        for input_file in input_files {
            let file = format!("./testfiles/{}", input_file);

            // Test File
            let mut indexed_file = File::open_raw(&file).expect("failed opening indexed file");
            test_reader(&mut indexed_file, &file);
            assert_eq!(
                indexed_file.read_all().unwrap(),
                read_to_string(&file).unwrap()
            );

            // Test IndexedString
            let file_content = read_to_string(&file).unwrap();
            let mut indexed_string = IndexedString::new_raw(file_content).unwrap();
            test_reader(&mut indexed_string, &file);

            // Test File to indexed string
            let indexed_file = File::open_raw(&file).expect("failed opening indexed file");
            let indexed_str_file: Result<IndexedString> = indexed_file.try_into();
            assert!(indexed_str_file.is_ok());
            test_reader(&mut indexed_str_file.unwrap(), &file);
        }
    }

    fn test_reader<L: ReadByLine>(reader: &mut L, original_file: &str) {
        test_sequencially(reader, &original_file);
        test_random(reader, &original_file);
    }

    fn test_sequencially<L: ReadByLine>(reader: &mut L, original_file: &str) {
        let original = BufReader::new(std::fs::File::open(&original_file).unwrap());

        for (line, original) in original.lines().enumerate() {
            let original = original.unwrap();

            let read = reader.read_line(line);

            assert!(read.is_ok());
            assert_eq!(original, read.unwrap());

            let mut buf = Vec::new();
            let res = reader.read_line_raw(line, &mut buf);
            assert!(res.is_ok());
            assert_eq!(original, String::from_utf8(buf).unwrap());
        }
    }

    fn test_random<L: ReadByLine>(reader: &mut L, original_file: &str) {
        let original = BufReader::new(std::fs::File::open(&original_file).unwrap());
        let orig_content: Vec<_> = original.lines().map(|i| i.unwrap()).collect();

        let lines: Vec<_> = rand::thread_rng()
            .sample_iter(Uniform::new(0, reader.total_lines() - 1))
            .take(reader.total_lines() * 3)
            .collect();

        for line in lines {
            let original = orig_content.get(line).unwrap();
            let read = reader.read_line(line);

            assert!(read.is_ok());
            assert_eq!(*original, read.unwrap());

            let mut buf = Vec::new();
            let res = reader.read_line_raw(line, &mut buf);
            assert!(res.is_ok());
            assert_eq!(*original, String::from_utf8(buf).unwrap());
        }
    }
}