-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathBinaryStdIO.cpp
102 lines (88 loc) · 2.63 KB
/
BinaryStdIO.cpp
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
#include "BinaryStdIO.h"
#include <iostream>
void BinaryStdIO::writeBit(std::byte bit) {
outBuffer = (outBuffer << 1) | bit; // Add bit to buffer.
if (++outN == 8) {
std::cout.put(std::to_integer<char>(outBuffer));
outBuffer = std::byte();
outN = 0;
} // If buffer is full (8 bits), write out as a single byte.
}
void BinaryStdIO::writeByte(std::byte byte) {
if (outN == 0) {
std::cout.put(std::to_integer<char>(byte));
return;
} // optimized if byte-aligned
for (int i = 0; i < 8; ++i) writeBit(byte >> (8 - i - 1) & std::byte{1}); // Otherwise write one bit at a time.
}
void BinaryStdIO::fillInBuffer() {
inBuffer = static_cast<std::byte>(std::cin.get());
if (std::cin.eof()) inN = -1;
else if (inN == 0) inN = 8;
}
void BinaryStdIO::write(int x) {
for (int i = 0; i < sizeof(int); ++i)
writeByte(static_cast<std::byte>(x >> (sizeof(int) - i - 1) * 8 & 0xFF));
}
void BinaryStdIO::write(int x, int r) {
if (r == sizeof(int)) {
write(x);
return;
}
for (int i = 0; i < r; ++i)
writeBit(static_cast<std::byte>(x >> (r - i - 1) & 1));
}
void BinaryStdIO::write(const std::string &s) {
for (int i = 0; i < s.length(); ++i) write(s[i]);
}
bool BinaryStdIO::readBool() {
if (inN == 0) fillInBuffer();
bool bit = std::to_integer<bool>((inBuffer >> --inN) & std::byte{1});
if (inN == 0) fillInBuffer();
return bit;
}
char BinaryStdIO::readChar() {
if (inN == 0) fillInBuffer();
auto x = inBuffer;
if (inN == 8) fillInBuffer(); // special case when aligned byte
else {
x <<= 8 - inN;
fillInBuffer();
x |= inBuffer >> inN;
} // Combine last n bits of current buffer with first 8-n bits of new buffer.
return std::to_integer<char>(x);
}
int BinaryStdIO::readInt() {
int x = 0;
for (int i = 0; i < sizeof(int); ++i) {
x <<= 8;
x |= readChar() & 0xFF;
}
return x;
}
int BinaryStdIO::readInt(int r) {
if (r == sizeof(int)) readInt();
int x = 0;
for (int i = 0; i < r; ++i) {
x <<= 1;
x |= readBool();
}
return x;
}
std::string BinaryStdIO::readString() {
std::string s;
while (!isEmpty()) s += readChar();
return s;
}
void BinaryStdIO::closeOut() {
if (outN > 0) {
outBuffer <<= 8 - outN; // Pad 0s if number of bits written so far is not a multiple of 8.
std::cout.put(std::to_integer<char>(outBuffer));
}
outN = 0;
outBuffer = std::byte();
}
void BinaryStdIO::closeIn() {
inN = 0;
inBuffer = std::byte();
}