Skip to main content

rl_lang/interpreter/stdlib/net/
tcp_read.rs

1use std::io::Read;
2
3use crate::interpreter::{
4    evaluator::Evaluator,
5    stdlib::{
6        common::{extract_number, verr, vok, vs},
7        net::NetHandle,
8    },
9    values::Value,
10};
11
12pub fn func(eval: &mut Evaluator, id: Value, max_bytes: Value) -> Value {
13    let id = match extract_number(id, "tcp_read") {
14        Ok(a) if a as i64 >= 0 => a as i64,
15        Ok(_) => return verr!(vs!("tcp_read: id handle cannot be negative".to_string())),
16        Err(e) => return verr!(vs!(format!("tcp_accept: {}", e))),
17    };
18    let max_bytes = match extract_number(max_bytes, "tcp_read") {
19        Ok(a) => a as usize,
20        Err(e) => return verr!(vs!(format!("tcp_read: {}", e))),
21    };
22
23    let stream = match eval.net_handles.get_mut(&id) {
24        Some(NetHandle::TcpStream(stream)) => stream,
25        Some(_) => {
26            return verr!(vs!(format!("tcp_read: handle {} is not a TCP stream", id)));
27        }
28        None => return verr!(vs!(format!("tcp_read: unknown handle {}", id))),
29    };
30
31    let mut buf = vec![0u8; max_bytes];
32    match stream.read(&mut buf) {
33        Ok(n) => {
34            buf.truncate(n);
35            vok!(vs!(String::from_utf8_lossy(&buf).into_owned()))
36        }
37        Err(e) => verr!(vs!(format!("tcp_read: {}", e))),
38    }
39}