@@ -20,6 +20,7 @@ use web_sys::{Event, Worker};
20
20
pub struct WorkerPool {
21
21
state : Rc < PoolState > ,
22
22
script_src : String ,
23
+ worker_js_preamble : String ,
23
24
}
24
25
25
26
struct PoolState {
@@ -29,6 +30,18 @@ struct PoolState {
29
30
30
31
#[ wasm_bindgen]
31
32
impl WorkerPool {
33
+ pub fn new (
34
+ initial : Option < usize > ,
35
+ script_src : Option < String > ,
36
+ worker_js_preamble : Option < String > ,
37
+ ) -> Result < WorkerPool , JsValue > {
38
+ Self :: new_raw (
39
+ initial. unwrap_or_else ( get_wasm_hardware_concurrency) ,
40
+ script_src. unwrap_or_else ( || script_path ( ) . expect ( "fail to get script path" ) ) ,
41
+ worker_js_preamble. unwrap_or_default ( ) ,
42
+ )
43
+ }
44
+
32
45
/// Creates a new `WorkerPool` which immediately creates `initial` workers.
33
46
///
34
47
/// The pool created here can be used over a long period of time, and it
@@ -40,7 +53,11 @@ impl WorkerPool {
40
53
/// Returns any error that may happen while a JS web worker is created and a
41
54
/// message is sent to it.
42
55
#[ wasm_bindgen( constructor) ]
43
- pub fn new ( initial : usize , script_src : String ) -> Result < WorkerPool , JsValue > {
56
+ pub fn new_raw (
57
+ initial : usize ,
58
+ script_src : String ,
59
+ worker_js_preamble : String ,
60
+ ) -> Result < WorkerPool , JsValue > {
44
61
let pool = WorkerPool {
45
62
script_src,
46
63
state : Rc :: new ( PoolState {
@@ -53,6 +70,7 @@ impl WorkerPool {
53
70
}
54
71
} ) ,
55
72
} ) ,
73
+ worker_js_preamble,
56
74
} ;
57
75
for _ in 0 ..initial {
58
76
let worker = pool. spawn ( ) ?;
@@ -72,9 +90,11 @@ impl WorkerPool {
72
90
/// Returns any error that may happen while a JS web worker is created and a
73
91
/// message is sent to it.
74
92
fn spawn ( & self ) -> Result < Worker , JsValue > {
75
- let src = & self . script_src ;
93
+ let worker_js_preamble = & self . worker_js_preamble ;
94
+ let script_src = & self . script_src ;
76
95
let script = format ! (
77
- "importScripts('{}');
96
+ "{worker_js_preamble}
97
+ importScripts('{script_src}');
78
98
const FRB_ACTION_PANIC = 3;
79
99
onmessage = event => {{
80
100
let init = wasm_bindgen(...event.data).catch(err => {{
@@ -97,7 +117,6 @@ impl WorkerPool {
97
117
}}
98
118
}}
99
119
}}" ,
100
- src
101
120
) ;
102
121
let blob = Blob :: new_with_blob_sequence_and_options (
103
122
& Array :: from_iter ( [ JsValue :: from ( script) ] ) . into ( ) ,
@@ -225,11 +244,7 @@ impl PoolState {
225
244
226
245
impl Default for WorkerPool {
227
246
fn default ( ) -> Self {
228
- Self :: new (
229
- get_wasm_hardware_concurrency ( ) ,
230
- script_path ( ) . expect ( "fail to get script path" ) ,
231
- )
232
- . expect ( "fail to create WorkerPool" )
247
+ Self :: new ( None , None , None ) . expect ( "fail to create WorkerPool" )
233
248
}
234
249
}
235
250
0 commit comments