2
2
// onto the JavaScript event loop. This implementation assumes there is a
3
3
// single thread and is *not* compatible with multiple WebAssembly workers sharing
4
4
// the same address space.
5
+ //
6
+ // TODO: Implement support for multiple threads. This will require a mechanism to
7
+ // wake up another thread, such as the `postMessage` API.
5
8
6
9
use futures:: future:: { Future , ExecuteError , Executor } ;
7
10
use futures:: executor:: { self , Notify , Spawn } ;
@@ -14,6 +17,7 @@ use webcore::try_from::TryInto;
14
17
use webcore:: value:: Reference ;
15
18
16
19
20
+ // TODO: Determine optimal values for these constants
17
21
// Initial capacity of the event queue
18
22
const INITIAL_QUEUE_CAPACITY : usize = 10 ;
19
23
// Iterations to wait before allowing the queue to shrink
@@ -117,6 +121,7 @@ impl EventLoopInner {
117
121
var wrapper = function( ) {
118
122
if ( !callback. dropped) { callback( ) }
119
123
} ;
124
+ var nextTick;
120
125
121
126
// Modern browsers can use `MutationObserver` which allows
122
127
// us to schedule a micro-task without allocating a promise.
@@ -127,7 +132,7 @@ impl EventLoopInner {
127
132
128
133
new MutationObserver ( wrapper ) . observe( node, { characterData: true } ) ;
129
134
130
- function nextTick( ) {
135
+ nextTick = function ( ) {
131
136
state = !state;
132
137
node. data = ( state ? "1" : "0" ) ;
133
138
}
@@ -136,7 +141,7 @@ impl EventLoopInner {
136
141
} else {
137
142
var promise = Promise . resolve( null ) ;
138
143
139
- function nextTick( ) {
144
+ nextTick = function ( ) {
140
145
promise. then( wrapper ) ;
141
146
}
142
147
}
@@ -170,6 +175,7 @@ impl EventLoopInner {
170
175
fn pop_task ( & self ) -> Option < Rc < SpawnedTask > > {
171
176
self . microtask_queue . borrow_mut ( ) . pop_front ( )
172
177
}
178
+ // Reclaim space from the queue if it's going to waste
173
179
fn shrink_if_necessary ( & self ) {
174
180
let mut queue = self . microtask_queue . borrow_mut ( ) ;
175
181
// We consider shrinking the queue if it is less than
@@ -179,7 +185,7 @@ impl EventLoopInner {
179
185
// `QUEUE_SHRINK_DELAY` iterations.
180
186
let shrink_counter = self . shrink_counter . get ( ) ;
181
187
if shrink_counter < QUEUE_SHRINK_DELAY {
182
- self . shrink_counter . set ( shrink_counter+ 1 ) ;
188
+ self . shrink_counter . set ( shrink_counter + 1 ) ;
183
189
} else {
184
190
queue. shrink_to_fit ( ) ;
185
191
self . shrink_counter . set ( 0 ) ;
@@ -190,10 +196,10 @@ impl EventLoopInner {
190
196
}
191
197
// Poll the queue until it is empty
192
198
fn drain ( & self ) {
199
+ self . shrink_if_necessary ( ) ;
193
200
while let Some ( task) = self . pop_task ( ) {
194
201
task. poll ( ) ;
195
202
}
196
- self . shrink_if_necessary ( ) ;
197
203
}
198
204
}
199
205
0 commit comments