Files
aho_corasick
ansi_term
arrayvec
atty
backtrace
backtrace_sys
base64
bincode
bitflags
byteorder
bytes
c2_chacha
capnp
capnp_futures
capnp_rpc
cfg_if
chrono
clap
crossbeam_deque
crossbeam_epoch
crossbeam_queue
crossbeam_utils
ctrlc
daemon
failure
failure_derive
flexi_logger
fnv
futures
getrandom
glob
hid_io
api
device
module
protocol
hidapi
install_service
iovec
lazy_static
libc
lock_api
log
memchr
memoffset
mio
mio_uds
nanoid
net2
nix
nodrop
num_cpus
num_integer
num_traits
open
parking_lot
parking_lot_core
pem
ppv_lite86
proc_macro2
quote
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
rcgen
regex
regex_syntax
remove_dir_all
ring
rustc_demangle
rustls
scoped_tls
scopeguard
sct
serde
slab
smallvec
spin
stream_cancel
strsim
syn
synstructure
tempfile
textwrap
thread_local
time
tokio
tokio_codec
tokio_core
tokio_current_thread
tokio_executor
tokio_fs
tokio_io
tokio_reactor
tokio_rustls
tokio_sync
tokio_tcp
tokio_threadpool
tokio_timer
tokio_udp
tokio_uds
unicode_width
unicode_xid
untrusted
vec_map
void
webpki
windows_service
x11
xcb
xkbcommon
yasna
  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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright (c) 2013-2017 Sandstorm Development Group, Inc. and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

use futures::{executor, task, Async, Future};
use futures::executor::Notify;

use std::cell::{Cell, RefCell};
use std::rc::{Rc};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::collections::HashMap;

struct Unparker {
    original_needs_poll: AtomicBool,

    // It's sad that we need a mutex here, even though we know that the RPC
    // system is restricted to a single thread.
    tasks: Mutex<HashMap<u64, task::Task>>,
}

impl Unparker {
    fn new(original_needs_poll: AtomicBool) -> Unparker {
        Unparker {
            original_needs_poll: original_needs_poll,
            tasks: Mutex::new(HashMap::new()),
        }
    }

    fn insert(&self, idx: u64, task: task::Task) {
        self.tasks.lock().unwrap().insert(idx, task);
    }

    fn remove(&self, idx: u64) {
        self.tasks.lock().unwrap().remove(&idx);
    }
}

impl executor::Notify for Unparker {
    fn notify(&self, _id: usize) {
        self.original_needs_poll.store(true, Ordering::SeqCst);
        let tasks = ::std::mem::replace(&mut *self.tasks.lock().unwrap(), HashMap::new());
        for (_, task) in tasks {
            task.notify();
        }
    }
}

struct ForkedPromiseInner<F> where F: Future {
    next_clone_id: Cell<u64>,
    state: RefCell<State<F>>,
}

enum State<F> where F: Future{
    Waiting(Arc<Unparker>, executor::Spawn<F>),
    Polling(Arc<Unparker>),
    Done(Result<F::Item, F::Error>),
}

pub struct ForkedPromise<F> where F: Future {
    id: u64,
    inner: Rc<ForkedPromiseInner<F>>,
}

impl <F> Clone for ForkedPromise<F> where F: Future {
    fn clone(&self) -> ForkedPromise<F> {
        let clone_id = self.inner.next_clone_id.get();
        self.inner.next_clone_id.set(clone_id + 1);
        ForkedPromise {
            id: clone_id,
            inner: self.inner.clone(),
        }
    }
}

impl <F> ForkedPromise<F> where F: Future {
    pub fn new(f: F) -> ForkedPromise<F> {
        ForkedPromise {
            id: 0,
            inner: Rc::new(ForkedPromiseInner {
                next_clone_id: Cell::new(1),
                state: RefCell::new(State::Waiting(
                    Arc::new(Unparker::new(AtomicBool::new(true))), executor::spawn(f))),
            })
        }
    }
}

impl<F> Drop for ForkedPromise<F> where F: Future {
    fn drop(&mut self) {
        match *self.inner.state.borrow() {
            State::Waiting(ref unparker, _) | State::Polling(ref unparker) => {
                unparker.remove(self.id);
            }
            State::Done(_) => (),
        }
    }
}

impl <F> Future for ForkedPromise<F>
    where F: Future, F::Item: Clone, F::Error: Clone,
{
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self) -> ::futures::Poll<Self::Item, Self::Error> {
        let unparker = match *self.inner.state.borrow() {
            State::Waiting(ref unparker, _) => {
                unparker.insert(self.id, task::current());
                if unparker.original_needs_poll.swap(false, Ordering::SeqCst) {
                    unparker.clone()
                } else {
                    return Ok(Async::NotReady)
                }
            }
            State::Polling(ref unparker) => {
                if unparker.original_needs_poll.load(Ordering::SeqCst) {
                    task::current().notify();
                } else {
                    unparker.insert(self.id, task::current());
                }
                return Ok(Async::NotReady)
            }
            State::Done(Ok(ref v)) => return Ok(Async::Ready(v.clone())),
            State::Done(Err(ref e)) => return Err(e.clone()),
        };
        let (unparker, mut original_future) = match ::std::mem::replace(
            &mut *self.inner.state.borrow_mut(), State::Polling(unparker)) {
            State::Waiting(unparker, original_future) => (unparker, original_future),
            _ => unreachable!(),
        };

        let done_val = match original_future.poll_future_notify(&unparker, 0) {
            Ok(Async::NotReady) => {
                *self.inner.state.borrow_mut() =
                    State::Waiting(unparker.clone(), original_future);
                return Ok(Async::NotReady)
            }
            Ok(Async::Ready(v)) => Ok(v),
            Err(e) => Err(e),
        };

        match ::std::mem::replace(
            &mut *self.inner.state.borrow_mut(),
            State::Done(done_val.clone()))
        {
            State::Polling(ref unparker) => unparker.notify(0),
            _ => unreachable!(),
        }

        match done_val {
            Ok(v) => Ok(Async::Ready(v)),
            Err(e) => Err(e),
        }
    }
}

#[cfg(test)]
mod test {
    use futures::{Future, Poll};
    use futures::sync::oneshot;
    use std::rc::Rc;
    use std::sync::Arc;
    use std::cell::RefCell;
    use super::ForkedPromise;


    // This test was pilfered from a futures::future::Shared test.
    #[test]
    fn drop_in_poll() {
        let slot = Rc::new(RefCell::new(None));
        let slot2 = slot.clone();
        let future = ForkedPromise::new(::futures::future::poll_fn(move || {
            drop(slot2.borrow_mut().take().unwrap());
            Ok::<_, ()>(1.into())
        }));
        let future2 = Box::new(future.clone()) as Box<dyn Future<Item=_, Error=_>>;
        *slot.borrow_mut() = Some(future2);
        assert_eq!(future.wait().unwrap(), 1);
    }

    enum Mode { Left, Right }

    struct ModedFutureInner<F> where F: Future {
        mode: Mode,
        left: F,
        right: F,
        task: Option<::futures::task::Task>,
    }

    struct ModedFuture<F> where F: Future {
        inner: Rc<RefCell<ModedFutureInner<F>>>,
    }

    struct ModedFutureHandle<F> where F: Future {
        inner: Rc<RefCell<ModedFutureInner<F>>>,
    }

    impl <F> ModedFuture<F> where F: Future {
        pub fn new(left: F, right: F, mode: Mode) -> (ModedFutureHandle<F>, ModedFuture<F>) {
            let inner = Rc::new(RefCell::new(ModedFutureInner {
                left: left, right: right, mode: mode, task: None,
            }));
            (ModedFutureHandle { inner: inner.clone() }, ModedFuture { inner: inner })
        }
    }

    impl <F> ModedFutureHandle<F> where F: Future {
        pub fn switch_mode(&mut self, mode: Mode) {
            self.inner.borrow_mut().mode = mode;
            if let Some(t) = self.inner.borrow_mut().task.take() {
                // The other future may have become ready while we were ignoring it.
                t.notify();
            }
        }
    }

    impl <F> Future for ModedFuture<F> where F: Future {
        type Item = F::Item;
        type Error = F::Error;
        fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
            let ModedFutureInner { ref mut mode, ref mut left, ref mut right, ref mut task } =
                *self.inner.borrow_mut();
            *task = Some(::futures::task::current());
            match *mode {
                Mode::Left => left.poll(),
                Mode::Right => right.poll(),
            }
        }
    }

    struct Reaper;
    impl crate::task_set::TaskReaper<(), ()> for Reaper {
        fn task_failed(&mut self, _err: ()) {}
    }

    struct Unpark;
    impl ::futures::executor::Notify for Unpark {
        fn notify(&self, _id: usize) {}
    }

    fn forked_propagates_unpark_helper(spawn_moded_first: bool) {
        let (handle, tasks) = crate::task_set::TaskSet::<(), ()>::new(Box::new(Reaper));

        let mut spawn = ::futures::executor::spawn(tasks);
        let unpark = Arc::new(Unpark);

        let (tx, rx) = oneshot::channel::<u32>();
        let f1 = ForkedPromise::new(rx);
        let f2 = f1.clone();

        let (mut mfh, mf) = ModedFuture::new(
            Box::new(f1.map_err(|_| ())) as Box<dyn Future<Item=u32, Error=()>>,
            Box::new(::futures::future::empty()) as Box<dyn Future<Item=u32, Error=()>>,
            Mode::Left);


        let mut handle0 = handle.clone();
        let spawn_mf = move || {
            handle0.add(mf.map(|_| ()));
        };

        let mut handle0 = handle.clone();
        let spawn_f2 = move || {
            let mut handle1 = handle0.clone();
            handle0.add(f2.map(move |_| handle1.terminate(Ok(()))).map_err(|_|()));

        };

        if spawn_moded_first {
            (spawn_mf)();
            match spawn.poll_future_notify(&unpark, 0) {
                Ok(::futures::Async::NotReady) => (),
                _ => panic!("should not be ready yet."),
            }
            (spawn_f2)();
        } else {
            (spawn_f2)();
            match spawn.poll_future_notify(&unpark, 0) {
                Ok(::futures::Async::NotReady) => (),
                _ => panic!("should not be ready yet."),
            }
            (spawn_mf)();
        }

        match spawn.poll_future_notify(&unpark, 0) {
            Ok(::futures::Async::NotReady) => (),
            _ => panic!("should not be ready yet."),
        }

        mfh.switch_mode(Mode::Right);

        tx.send(11).unwrap(); // This should cause `f2` and then eventually `spawn` to resolve.

        loop {
            match spawn.poll_future_notify(&unpark, 0) {
                Ok(::futures::Async::NotReady) => (),
                Ok(::futures::Async::Ready(_)) => break,
                Err(e) => panic!("error: {:?}", e),
            }
        }
    }

    #[test]
    fn forked_propagates_unpark() {
        forked_propagates_unpark_helper(true);
        forked_propagates_unpark_helper(false);
    }

    #[test]
    fn recursive_poll() {
        use futures::sync::mpsc;
        use futures::{Stream, future, task};

        let mut core = local_executor::Core::new();
        let (tx0, rx0) = mpsc::unbounded::<Box<dyn Future<Item=(),Error=()>>>();
        let run_stream = rx0.for_each(|f| f);

        let (tx1, rx1) = oneshot::channel::<()>();

        let f1 = ForkedPromise::new(run_stream);
        let f2 = f1.clone();
        let f3 = f1.clone();
        tx0.unbounded_send(Box::new(future::lazy(move || {
            task::current().notify();
            f1.map(|_|()).map_err(|_|())
                .select(rx1.map_err(|_|()))
                .map(|_| ()).map_err(|_|())
        }))).unwrap();

        core.spawn(f2.map(|_|()).map_err(|_|()));

        // Call poll() on the spawned future. We want to be sure that this does not trigger a
        // deadlock or panic due to a recursive lock() on a mutex.
        core.run(future::ok::<(),()>(())).unwrap();

        tx1.send(()).unwrap(); // Break the cycle.
        drop(tx0);
        core.run(f3).unwrap();
    }


    mod local_executor {
        //! (This module is borrowed from futures-rs/tests/support)
        //!
        //! Execution of futures on a single thread
        //!
        //! This module has no special handling of any blocking operations other than
        //! futures-aware inter-thread communications, and should therefore probably not
        //! be used to manage IO.

        use std::sync::{Arc, Mutex, mpsc};
        use std::collections::HashMap;
        use std::collections::hash_map;
        use std::boxed::Box;
        use std::rc::Rc;
        use std::cell::RefCell;

        use futures::{Future, Async};

        use futures::executor::{self, Spawn};

        /// Main loop object
        pub struct Core {
            unpark_send: mpsc::Sender<u64>,
            unpark: mpsc::Receiver<u64>,
            live: HashMap<u64, Spawn<Box<dyn Future<Item=(), Error=()>>>>,
            next_id: u64,
        }

        impl Core {
            /// Create a new `Core`.
            pub fn new() -> Self {
                let (send, recv) = mpsc::channel();
                Core {
                    unpark_send: send,
                    unpark: recv,
                    live: HashMap::new(),
                    next_id: 0,
                }
            }

            /// Spawn a future to be executed by a future call to `run`.
            pub fn spawn<F>(&mut self, f: F)
                where F: Future<Item=(), Error=()> + 'static
            {
                self.live.insert(self.next_id, executor::spawn(Box::new(f)));
                self.unpark_send.send(self.next_id).unwrap();
                self.next_id += 1;
            }

            /// Run the loop until all futures previously passed to `spawn` complete.
            pub fn _wait(&mut self) {
                while !self.live.is_empty() {
                    self.turn();
                }
            }

            /// Run the loop until the future `f` completes.
            pub fn run<F>(&mut self, f: F) -> Result<F::Item, F::Error>
                where F: Future + 'static,
                      F::Item: 'static,
                      F::Error: 'static,
            {
                let out = Rc::new(RefCell::new(None));
                let out2 = out.clone();
                self.spawn(f.then(move |x| { *out.borrow_mut() = Some(x); Ok(()) }));
                loop {
                    self.turn();
                    if let Some(x) = out2.borrow_mut().take() {
                        return x;
                    }
                }
            }

            fn turn(&mut self) {
                let task = self.unpark.recv().unwrap(); // Safe to unwrap because self.unpark_send keeps the channel alive
                let unpark = Arc::new(Unpark { task: task, send: Mutex::new(self.unpark_send.clone()), });
                let mut task = if let hash_map::Entry::Occupied(x) = self.live.entry(task) { x } else { return };
                let result = task.get_mut().poll_future_notify(&unpark, 0);
                match result {
                    Ok(Async::Ready(())) => { task.remove(); }
                    Err(()) => { task.remove(); }
                    Ok(Async::NotReady) => {}
                }
            }
        }

        struct Unpark {
            task: u64,
            send: Mutex<mpsc::Sender<u64>>,
        }

        impl executor::Notify for Unpark {
            fn notify(&self, _id: usize) {
                let _ = self.send.lock().unwrap().send(self.task);
            }
        }
    }
}