10 #include "common_types.hh"
12 static inline int getOne(FILE *file, std::pair<Alphabet, double> &p) {
13 return fscanf(file,
" %c %lf\n", &p.first, &p.second);
16 static inline int getOneBinary(FILE *file, std::pair<Alphabet, double> &p) {
17 if (fread(&p.first,
sizeof(
char), 1, file)) {
18 if (fread(&p.second,
sizeof(
double), 1, file)) {
19 return sizeof(char) +
sizeof(
double);
29 class LazyDeque :
public std::deque<std::pair<Alphabet, double>> {
31 std::size_t front = 0;
34 int (*getElem)(FILE *, std::pair<Alphabet, double> &);
43 : N(std::numeric_limits<std::size_t>::max()), file(file) {
44 assert(file !=
nullptr);
45 getElem = isBinary ? getOneBinary : getOne;
47 std::pair<Alphabet, double> operator[](std::size_t n) {
48 const std::size_t indInDeque = n - front;
49 if (n < front || n >= N ||
50 indInDeque >= std::deque<std::pair<Alphabet, double>>::size()) {
51 throw std::out_of_range(
"thrown at LazyDeque::operator[] ");
53 return std::deque<std::pair<Alphabet, double>>::at(indInDeque);
55 std::pair<Alphabet, double> at(std::size_t n) {
return (*
this)[n]; }
56 std::size_t size()
const {
return N; }
60 if (newFront < front) {
61 throw std::out_of_range(
"thrown at LazyDeque::setFront ");
63 const std::size_t eraseSize = std::min(
64 newFront - front, std::deque<std::pair<Alphabet, double>>::size());
65 const int readTimes = (newFront - front) - eraseSize;
67 this->erase(this->begin(), this->begin() + eraseSize);
68 for (
int i = 0; i < readTimes; i++) {
69 std::pair<Alphabet, double> elem;
73 bool fetch(std::size_t n) noexcept {
74 if (n < front || n >= N) {
77 const std::size_t indInDeque = n - front;
78 const int allocTimes =
79 indInDeque - std::deque<std::pair<Alphabet, double>>::size() + 1;
80 for (
int i = 0; i < allocTimes; i++) {
81 std::pair<Alphabet, double> elem;
82 if (getElem(file, elem) == EOF) {
83 N = front + std::deque<std::pair<Alphabet, double>>::size();
86 this->push_back(elem);
A Wrapper of FILE Reading. This class is given to WordContainer class as its template argument.
Definition: lazy_deque.hh:29
void setFront(std::size_t newFront)
Update the internal front. The elements before the front are removed.
Definition: lazy_deque.hh:59
LazyDeque(FILE *file, bool isBinary=false)
Definition: lazy_deque.hh:42