-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.rs
More file actions
116 lines (107 loc) · 3.7 KB
/
Copy pathsync.rs
File metadata and controls
116 lines (107 loc) · 3.7 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
104
105
106
107
108
109
110
111
112
113
114
115
116
use crate::{StdFunction, StdlibModule, StdlibRegistry};
use indexmap::IndexMap;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::{Condvar, Mutex};
use techscript_runtime::{error::RuntimeError, value::RuntimeValue};
pub struct ScriptMutex {
locked: Mutex<bool>,
condvar: Condvar,
}
impl ScriptMutex {
pub fn new() -> Self {
Self {
locked: Mutex::new(false),
condvar: Condvar::new(),
}
}
pub fn lock(&self) {
let mut guard = self.locked.lock().unwrap();
while *guard {
guard = self.condvar.wait(guard).unwrap();
}
*guard = true;
}
pub fn unlock(&self) {
let mut guard = self.locked.lock().unwrap();
*guard = false;
self.condvar.notify_one();
}
}
impl StdlibRegistry {
pub fn register_sync(&mut self) {
let mut exports: HashMap<String, Rc<dyn techscript_runtime::function::Callable>> =
HashMap::new();
exports.insert(
"make_mutex".to_string(),
Rc::new(StdFunction {
name: "make_mutex".to_string(),
arity: 0,
callback: |ctx, _args| {
let mutex = ScriptMutex::new();
let handle_id = ctx.resources.borrow_mut().insert(mutex);
let mut map = IndexMap::new();
map.insert("_handle".to_string(), RuntimeValue::Int(handle_id as i64));
Ok(RuntimeValue::Map {
entries: Rc::new(RefCell::new(map)),
is_const: false,
})
},
}),
);
exports.insert(
"mutex_lock".to_string(),
Rc::new(StdFunction {
name: "mutex_lock".to_string(),
arity: 1,
callback: |ctx, args| {
if let RuntimeValue::Map { entries, .. } = &args[0] {
let handle_id = entries
.borrow()
.get("_handle")
.cloned()
.unwrap_or(RuntimeValue::Null)
.try_into_int()? as u32;
let resources = ctx.resources.borrow();
if let Some(mutex) = resources.get::<ScriptMutex>(handle_id) {
mutex.lock();
}
}
Ok(RuntimeValue::Null)
},
}),
);
exports.insert(
"mutex_unlock".to_string(),
Rc::new(StdFunction {
name: "mutex_unlock".to_string(),
arity: 1,
callback: |ctx, args| {
if let RuntimeValue::Map { entries, .. } = &args[0] {
let handle_id = entries
.borrow()
.get("_handle")
.cloned()
.unwrap_or(RuntimeValue::Null)
.try_into_int()? as u32;
let resources = ctx.resources.borrow();
if let Some(mutex) = resources.get::<ScriptMutex>(handle_id) {
mutex.unlock();
}
}
Ok(RuntimeValue::Null)
},
}),
);
self.register_module(
"std.sync",
StdlibModule {
name: "std.sync".to_string(),
version: "1.0.0".to_string(),
exports,
required_capabilities: Vec::new(),
},
);
}
}