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
use tokio::net::TcpStream;
use std::error::Error;
use std::io;
pub struct Connection(TcpStream);
impl Connection{
pub fn new(stream: TcpStream) -> Self{
Connection(stream)
}
pub async fn read_to_string(&self) -> String{
let mut string = String::from_utf8(self.read_to_vec().await.expect("Error reading vec from stream")).expect("Error decoding stream to utf-8");
trim_newline(&mut string);
string
}
pub async fn read_to_vec(&self) -> Result<Vec::<u8>, Box<dyn Error>>{
let mut buffer = [0; 4096];
let stream: &TcpStream = &self.0;
loop{
stream.readable().await?;
match stream.try_read(&mut buffer) {
Ok(0) => break,
Ok(_) => {
break
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
return Err(e.into());
}
}
}
let buffer: Vec::<u8> = buffer.to_vec().iter().filter(|x| **x != 0x0u8).map(|x| *x).collect();
Ok(buffer)
}
pub async fn write_string(&mut self, data: String) -> Result<(), Box<dyn Error>>{
let stream: &mut TcpStream = &mut self.0;
loop{
stream.writable().await?;
match stream.try_write(data.as_bytes()) {
Ok(_) => {
break;
}
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
continue;
}
Err(e) => {
return Err(e.into());
}
}
}
Ok(())
}
}
fn trim_newline(s: &mut String) {
if s.ends_with('\n') {
s.pop();
if s.ends_with('\r') {
s.pop();
}
}
}