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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use core::usize;
use {fmt, str};
use string::String;
use vec::{IntoIter, Vec};
use syscall::{sys_read, sys_write};
pub struct Error;
pub trait Read {
fn read(&mut self, buf: &mut [u8]) -> Option<usize>;
fn read_to_end(&mut self, vec: &mut Vec<u8>) -> Option<usize> {
let mut read = 0;
loop {
let mut bytes = [0; 4096];
match self.read(&mut bytes) {
Some(0) => return Some(read),
None => return None,
Some(count) => {
vec.push_all(&bytes[0..count]);
read += count;
}
}
}
}
fn read_to_string(&mut self, string: &mut String) -> Option<usize> {
let mut read = 0;
loop {
let mut bytes = [0; 4096];
match self.read(&mut bytes) {
Some(0) => return Some(read),
None => return None,
Some(count) => {
string.push_str(unsafe { &str::from_utf8_unchecked(&bytes[0..count]) });
read += count;
}
}
}
}
fn bytes(&mut self) -> IntoIter<u8> {
let mut buf = Vec::new();
self.read_to_end(&mut buf);
buf.into_iter()
}
}
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Option<usize>;
fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), Error> {
match self.write(fmt::format(args).as_bytes()) {
Some(_) => Ok(()),
None => Err(Error)
}
}
}
pub enum SeekFrom {
Start(usize),
Current(isize),
End(isize),
}
pub trait Seek {
fn seek(&mut self, pos: SeekFrom) -> Option<usize>;
}
pub struct Stdin;
pub fn stdin() -> Stdin {
Stdin
}
impl Stdin {
pub fn read_line(&mut self, string: &mut String) -> Result<usize, Error> {
let mut bytes = [0; 1024];
match self.read(&mut bytes) {
None => return Err(Error),
Some(count) => {
for i in 0..count {
string.push(bytes[i] as char);
}
return Ok(count);
}
}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
unsafe {
let count = sys_read(0, buf.as_mut_ptr(), buf.len());
if count == usize::MAX {
None
} else {
Some(count)
}
}
}
}
pub struct Stdout;
pub fn stdout() -> Stdout {
Stdout
}
impl Write for Stdout {
fn write(&mut self, buf: &[u8]) -> Option<usize> {
unsafe {
let count = sys_write(1, buf.as_ptr(), buf.len());
if count == usize::MAX {
None
} else {
Some(count)
}
}
}
}
pub struct Stderr;
pub fn stderr() -> Stderr {
Stderr
}
impl Write for Stderr {
fn write(&mut self, buf: &[u8]) -> Option<usize> {
unsafe {
let count = sys_write(2, buf.as_ptr(), buf.len());
if count == usize::MAX {
None
} else {
Some(count)
}
}
}
}
#[allow(unused_must_use)]
pub fn _print(args: fmt::Arguments) {
stdout().write_fmt(args);
}