aboutsummaryrefslogtreecommitdiff
path: root/src/LargeFileStream.cpp
blob: 95e7c1cdfd8dcd19282a7281d4b3c7d35f0d59ad (plain)
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
#include "LargeFileStream.hpp"

namespace pgnp {
using namespace std;

LargeFileStream::LargeFileStream()
    : chuck_count(-1), last_read_size(0), last_loc(0), use_string(false),
      eof(false) {}

void LargeFileStream::FromFile(std::string filepath) {
  file.open(filepath);
  ReadNextChunk();
}

void LargeFileStream::FromString(std::string content) {
  use_string = true;
  this->content = content;
}

void LargeFileStream::ReadNextChunk() {
  chuck_count++;
  file.read(buffer, BUFFER_SIZE);
  last_read_size = file.gcount();
}

char LargeFileStream::operator[](ull loc) {
  // Perform various checks
  if (eof) {
    throw ReadToFar();
  }
  if (loc < last_loc) {
    throw BackwardRead();
  }
  last_loc = loc; // Keep track

  // Shortcut the operator for string content
  if (use_string) {
    if (loc >= content.size()) {
      eof = true;
    }
    return ('?');
  }

  // Goto the right memory chuck
  ull loc_chunk_count = loc / BUFFER_SIZE;
  while (chuck_count < loc_chunk_count) {
    ReadNextChunk();
  }
  ull offset = loc - (loc_chunk_count * BUFFER_SIZE);
  
  // Ensure for EOF
  if (!file && offset >= last_read_size) {
    eof = true;
    return ('?');
  }

  // Return character
  return buffer[offset];
}

bool LargeFileStream::IsEOF() { return (eof); }

} // namespace pgnp