Gobelijn API documentation  - generated for commit a0cbea7
 All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
random-read-file.h
Go to the documentation of this file.
1 #pragma once
2 /*
3  * This file is part of the gobelijn software.
4  * Gobelijn is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU General Public License as published by the
6  * Free Software Foundation, either version 3 of the License, or any later
7  * version. Gobelijn is distributed in the hope that it will be useful, but
8  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
9  * or FITNESS FOR A PARTICULAR PURPOSE.
10  * See the GNU General Public License for details. You should have received
11  * a copy of the GNU General Public License along with the software. If not,
12  * see <http://www.gnu.org/licenses/>.
13  *
14  * Copyright 2016, Jan Broeckhove.
15  */
21 #include "../files/file.h"
22 
23 #include <cstdio>
24 #include <vector>
25 
26 namespace Raii {
27 
37 {
38 public:
42  RandomReadFile(const char* path) : m_file(path, "r"), m_buf() {}
43 
44  /*
45  * Reads the 'char' at the given offset in this file.
46  */
47  char operator[](size_t Offset) const
48  {
49  // Fills the buffer vector with data, until the 'char' at the given
50  // offset becomes available.
51  // Note that this the enclosing method is marked 'const', though
52  // the logic below clearly mutates the object's state.
53  // That's perfectly fine, actually, because those changes to this
54  // object's state are not visible to the outside world. Hence
55  // the name 'logically const'.
56  while (Offset >= m_buf.size()) {
57  int c = m_file.ReadChar();
58  if (c == EOF)
59  // We can't recover from this, because we're being
60  // asked to read beyond the end of the stream. The
61  // only way out is to throw an exception.
62  throw ReadError();
63 
64  // Append the data to the buffer.
65  m_buf.push_back(c);
66  }
67 
68  // Read the character from the buffer.
69  return m_buf.at(Offset);
70  }
71 
72 private:
73  // The file that is currently open. This member is mutable, even
74  // when its enclosing object is (logically) 'const'.
75  mutable File m_file;
76 
77  // A buffer for previously read data. This member is mutable, even
78  // when its enclosing object is (logically) 'const'.
79  mutable std::vector<char> m_buf;
80 };
81 
82 } // namespace Raii
char operator[](size_t Offset) const
A wrapper around the C FILE*-based IO API.
Definition: file.h:47
std::vector< char > m_buf
A file that supports random reads: reads that are based on an offset.
RandomReadFile(const char *path)
Opens a random-read file at the given path.
int ReadChar()
Reads the next input character from this file.
Definition: file.h:101