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
use crate::tubes::buffer::Buffer;
use crate::tubes::tube::Tube;
use std::io;
use std::io::{Read, Write};
use std::net::{Shutdown, TcpStream};
use std::time::Duration;
pub struct Sock {
sock: TcpStream,
buffer: Buffer,
}
impl Sock {
pub fn new(sock: TcpStream) -> Self {
Self {
sock,
buffer: Buffer::new(),
}
}
}
impl Tube for Sock {
fn get_buffer(&mut self) -> &mut Buffer {
&mut self.buffer
}
fn fill_buffer(&mut self, timeout: Option<Duration>) -> io::Result<usize> {
self.sock.set_read_timeout(timeout)?;
let mut temp_buf: [u8; 1024] = [0; 1024];
let mut total: usize = 0;
loop {
let read = self.sock.read(&mut temp_buf)?;
let buffer = self.get_buffer();
buffer.add(temp_buf[..read].to_vec());
total += read;
if read < 1024 {
break;
}
}
Ok(total)
}
fn send_raw(&mut self, data: Vec<u8>) -> io::Result<()> {
self.sock.write_all(&data)
}
fn close(&mut self) -> io::Result<()> {
self.sock.shutdown(Shutdown::Both)
}
}
impl Clone for Sock {
fn clone(&self) -> Self {
Sock {
sock: self.sock.try_clone().unwrap(),
buffer: self.buffer.clone(),
}
}
}