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
use std::io;
use serde::{Deserialize, Serialize};
use super::socket::Socket;
use crate::bencode;
#[derive(Debug)]
pub enum Op {
Clone,
Close,
Eval,
}
impl std::str::FromStr for Op {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"clone" => Ok(Op::Clone),
"close" => Ok(Op::Close),
"eval" => Ok(Op::Eval),
_ => Err("invalid operation"),
}
}
}
impl std::fmt::Display for Op {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
fmt,
"{}",
match *self {
Op::Clone => "clone",
Op::Close => "close",
Op::Eval => "eval",
}
)
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct WireRequest {
pub op: String,
pub id: String,
pub session: Option<String>,
pub ns: Option<String>,
pub code: Option<String>,
pub line: Option<i32>,
pub column: Option<i32>,
pub file: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Response {
pub session: String,
pub id: Option<String>,
pub status: Option<Vec<String>>,
pub new_session: Option<String>,
pub value: Option<String>,
pub ex: Option<String>,
pub root_ex: Option<String>,
pub out: Option<String>,
pub err: Option<String>,
}
impl Response {
pub fn has_status(&self, label: &str) -> bool {
if let Some(ref ss) = self.status {
for s in ss.iter() {
if s == label {
return true;
}
}
}
false
}
}
#[derive(Debug)]
pub struct Connection {
socket: Socket,
buffer: Vec<u8>,
}
impl Connection {
pub fn new(socket: Socket) -> Self {
Self {
socket,
buffer: Default::default(),
}
}
pub fn send(&mut self, request: &WireRequest) -> Result<(), io::Error> {
let payload = serde_bencode::to_bytes(request).unwrap();
let w = self.socket.borrow_mut_write();
w.write_all(&payload)?;
w.flush()
}
pub fn try_recv(&mut self) -> Result<Response, RecvError> {
let mut buffer = [0_u8; 4096];
loop {
match bencode::scan_next(&self.buffer) {
Ok((_, len)) => {
let response = {
let input = &self.buffer[0..len];
let response: Response =
serde_bencode::from_bytes(input).unwrap();
response
};
self.buffer.copy_within(len.., 0);
self.buffer.truncate(self.buffer.len() - len);
return Ok(response);
}
Err(bencode::Error::UnexpectedEnd) => (),
Err(bencode::Error::BadInput) => {
return Err(RecvError::BadInput);
}
}
let bytes_read = self.socket.borrow_mut_read().read(&mut buffer)?;
if bytes_read == 0 {
return Err(RecvError::HostDisconnected);
}
self.buffer.extend_from_slice(&buffer[0..bytes_read]);
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum RecvError {
#[error("IO error")]
Io(#[from] io::Error),
#[error("bad input")]
BadInput,
#[error("unexpected disconnection by host")]
HostDisconnected,
}