Skip to main content

rl_lang/interpreter/stdlib/net/
tcp_shutdown.rs

1use std::net::Shutdown;
2
3use crate::interpreter::{
4    evaluator::Evaluator,
5    stdlib::{
6        common::{extract_number, extract_string, verr, vnl, vok, vs},
7        net::NetHandle,
8    },
9    values::Value,
10};
11
12pub fn func(eval: &mut Evaluator, id: Value, mode: Value) -> Value {
13    let id = match extract_number(id, "tcp_shutdown") {
14        Ok(a) if a as i64 >= 0 => a as i64,
15        Ok(_) => return verr!(vs!("tcp_shutdown: id handle cannot be negative".to_string())),
16        Err(e) => return verr!(vs!(format!("tcp_shutdown: {}", e))),
17    };
18    let mode = match extract_string(mode, "tcp_shutdown") {
19        Ok(s) => s,
20        Err(e) => return verr!(vs!(format!("tcp_shutdown: {} ", e))),
21    };
22
23    let mode = match mode.as_str() {
24        "read" => Shutdown::Read,
25        "write" => Shutdown::Write,
26        "both" => Shutdown::Both,
27        other => {
28            return verr!(vs!(format!(
29                "tcp_shutdown: expected \"read\", \"write\", or \"both\", got \"{}\"",
30                other
31            )));
32        }
33    };
34    let stream = match eval.net_handles.get(&id) {
35        Some(NetHandle::TcpStream(stream)) => stream,
36        Some(_) => {
37            return verr!(vs!(format!(
38                "tcp_shutdown: handle {} is not a TCP stream",
39                id
40            )));
41        }
42        None => return verr!(vs!(format!("tcp_shutdown: unknown handle {}", id))),
43    };
44    match stream.shutdown(mode) {
45        Ok(()) => vok!(vnl!()),
46        Err(e) => verr!(vs!(format!("tcp_shutdown(): {}", e))),
47    }
48}