-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryStdIn.h
126 lines (107 loc) · 2.85 KB
/
BinaryStdIn.h
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
#include <bits/stdc++.h>
using namespace std;
#ifndef COMPRESSION_LIBRARY_BINARYSTDIN_H
#define COMPRESSION_LIBRARY_BINARYSTDIN_H
class BinaryStdIn {
private:
string file;
char buffer;
ifstream in;
char n;
bool isInitialized;
void initialize() {
in = ifstream(file, std::ios::binary);
buffer = 0;
n = 0; // remaining bits
fillBuffer();
isInitialized = true;
}
void fillBuffer() {
try {
in.read(reinterpret_cast<char*>(&buffer), sizeof(buffer));
n = 8;
}
catch (exception &e) {
buffer = EOF;
n = -1;
}
}
public:
explicit BinaryStdIn(string && file) : file(std::move(file)) {
initialize();
}
void close() {
if (!isInitialized) initialize();
try {
in.close();
isInitialized = false;
std::cout << "\n";
}
catch (exception& ioe) {
std::cout << "Could not close file";
}
}
bool readBoolean() {
if (isEmpty()) throw std::exception();
n--;
bool bit = ((buffer >> n) & 1) == 1; // take the bit
if (n == 0) fillBuffer();
return bit;
}
unsigned char readChar() {
if(!isInitialized) initialize();
if (isEmpty()) throw exception();
// special case when aligned byte
if (n == 8) {
unsigned char x = buffer;
fillBuffer();
return x;
}
// combine last n bits of current buffer with first 8-n bits of new buffer
unsigned char x = buffer;
x <<= (8 - n);
char oldN = n;
fillBuffer();
if (isEmpty()) throw exception();
n = oldN;
x |= (static_cast<unsigned char>(buffer) >> n);
return x;
// the above code doesn't quite work for the last character if n = 8
// because buffer will be -1, so there is a special case for aligned byte
}
int readInt() {
int x = 0;
for (int i = 0; i < 4; i++) {
unsigned char c = readChar();
x <<= 8;
x |= c;
}
return x;
}
int readInt(int r) {
if (r < 1 || r > 32) throw exception();
// optimize r = 32 case
if (r == 32) return readInt();
int x = 0;
for (int i = 0; i < r; i++) {
x <<= 1;
bool bit = readBoolean();
if (bit) x |= 1;
}
return x;
}
string readString() {
stringstream ss;
if (isEmpty()) throw exception();
while (!isEmpty()) {
unsigned char c = readChar();
ss << c;
}
return ss.str();
}
bool isEmpty() {
if (!isInitialized) initialize();
return in.eof(); // && buffer == EOF;
}
};
#endif //COMPRESSION_LIBRARY_BINARYSTDIN_H