-
Notifications
You must be signed in to change notification settings - Fork 0
/
io.h
62 lines (53 loc) · 1.46 KB
/
io.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
#pragma once
#include <cstdio>
#include <iostream>
#include <limits>
#include <vector>
#include "error.h"
#include "slice.h"
/**
* These are implicit interfaces that will used in the library
*
* read n-bytes or until EOF. Throws on error.
* std::size_t read(Slice<uint8_t> buf);
*
* read until byte is read or EOF. Throws on error.
* std::size_t read_until(uint8_t byte, std::vector<uint8_t> &buf_);
*
* write n-bytes. Throws on error.
* void write(Slice<uint8_t> buf);
*/
// wrapper around stdin
struct Stdin {
std::size_t read(Slice<uint8_t> buf) {
auto result = fread(buf.begin(), 1, buf.size(), stdin);
if (ferror(stdin)) throw Error{ErrorType::StdIoError};
return result;
}
};
// wrapper around cin
struct Cin {
std::size_t read(Slice<uint8_t> buf) {
if (buf.size() > std::numeric_limits<std::streamsize>::max())
throw Error{ErrorType::SizeTooLarge};
auto result =
std::cin.read(reinterpret_cast<char*>(buf.begin()), buf.size())
.gcount();
return result;
}
};
// wrapper around stdout
struct Stdout {
void write(Slice<uint8_t> buf) {
fwrite(buf.begin(), 1, buf.size(), stdout);
if (ferror(stdout)) throw Error{ErrorType::StdIoError};
}
};
// wrapper around cout
struct Cout {
void write(Slice<uint8_t> buf) {
if (buf.size() > std::numeric_limits<std::streamsize>::max())
throw Error{ErrorType::SizeTooLarge};
std::cout.write(reinterpret_cast<char*>(buf.begin()), buf.size());
}
};