-
Notifications
You must be signed in to change notification settings - Fork 4
/
StandardIO.py
59 lines (46 loc) · 2.07 KB
/
StandardIO.py
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
from sys import stdin, stdout
from flipjump.interpretter.io_devices.IODevice import IODevice
from flipjump.utils.exceptions import IOReadOnEOF, IncompleteOutput
from flipjump.utils.constants import IO_BYTES_ENCODING
class StandardIO(IODevice):
"""
read from stdin, write to stdout
"""
def __init__(self, output_verbose: bool):
"""
@param output_verbose: if true print program's output
"""
self.output_verbose = output_verbose
self._output = b''
self.current_input_byte = 0
self.bits_to_read_in_input_byte = 0
self.current_output_byte = 0
self.bits_to_write_in_output_byte = 0
def read_bit(self) -> bool:
if 0 == self.bits_to_read_in_input_byte:
read_bytes = stdin.read(1).encode(encoding=IO_BYTES_ENCODING)
if 0 == len(read_bytes):
raise IOReadOnEOF("Read an empty input on standard IO (EOF)")
self.current_input_byte = read_bytes[0]
self.bits_to_read_in_input_byte = 8
bit = (self.current_input_byte & 1) == 1
self.current_input_byte >>= 1
self.bits_to_read_in_input_byte -= 1
return bit
def write_bit(self, bit: bool) -> None:
self.current_output_byte |= bit << self.bits_to_write_in_output_byte
self.bits_to_write_in_output_byte += 1
if 8 == self.bits_to_write_in_output_byte:
curr_output: bytes = self.current_output_byte.to_bytes(1, 'little')
if self.output_verbose:
stdout.write(curr_output.decode(encoding=IO_BYTES_ENCODING))
stdout.flush()
self._output += curr_output
self.current_output_byte = 0
self.bits_to_write_in_output_byte = 0
def get_output(self, *, allow_incomplete_output: bool = False) -> bytes:
if not allow_incomplete_output and 0 != self.bits_to_write_in_output_byte:
raise IncompleteOutput(
"tries to get output when an unaligned number of bits was outputted " "(doesn't divide 8)"
)
return self._output