-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.rs
More file actions
103 lines (99 loc) · 3.98 KB
/
Copy pathsocket.rs
File metadata and controls
103 lines (99 loc) · 3.98 KB
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
use crate::{StdFunction, StdlibModule, StdlibRegistry};
use std::collections::HashMap;
use std::net::TcpStream;
use std::rc::Rc;
use techscript_runtime::{error::RuntimeError, value::RuntimeValue};
impl StdlibRegistry {
pub fn register_socket(&mut self) {
let mut exports: HashMap<String, Rc<dyn techscript_runtime::function::Callable>> =
HashMap::new();
exports.insert(
"connect".to_string(),
Rc::new(StdFunction {
name: "connect".to_string(),
arity: 2,
callback: |_ctx, args| {
let host = match &args[0] {
RuntimeValue::Str(s) => s.clone(),
_ => {
return Err(RuntimeError::new(
techscript_runtime::error::RuntimeErrorKind::TypeMismatch {
expected: "string".to_string(),
found: "other".to_string(),
},
None,
None,
))
}
};
let port = match &args[1] {
RuntimeValue::Int(n) => *n as u16,
_ => {
return Err(RuntimeError::new(
techscript_runtime::error::RuntimeErrorKind::TypeMismatch {
expected: "int".to_string(),
found: "other".to_string(),
},
None,
None,
))
}
};
let addr = format!("{}:{}", host, port);
TcpStream::connect(&addr).map_err(|e| {
RuntimeError::new(
techscript_runtime::error::RuntimeErrorKind::InvalidOperation(
e.to_string(),
),
None,
None,
)
})?;
Ok(RuntimeValue::Str(format!("Connected to {}", addr)))
},
}),
);
exports.insert(
"listen".to_string(),
Rc::new(StdFunction {
name: "listen".to_string(),
arity: 1,
callback: |_ctx, args| {
let port = match &args[0] {
RuntimeValue::Int(n) => *n as u16,
_ => {
return Err(RuntimeError::new(
techscript_runtime::error::RuntimeErrorKind::TypeMismatch {
expected: "int".to_string(),
found: "other".to_string(),
},
None,
None,
))
}
};
let addr = format!("0.0.0.0:{}", port);
let _listener = std::net::TcpListener::bind(&addr).map_err(|e| {
RuntimeError::new(
techscript_runtime::error::RuntimeErrorKind::InvalidOperation(
e.to_string(),
),
None,
None,
)
})?;
Ok(RuntimeValue::Str(format!("Listening on {}", addr)))
},
}),
);
self.register_module(
"std.socket",
StdlibModule {
name: "std.socket".to_string(),
version: "1.0.0".to_string(),
exports,
required_capabilities: Vec::new(),
},
);
}
}