]> git.lizzy.rs Git - rust.git/blob - src/libstd/thunk.rs
rollup merge of #20353: alexcrichton/snapshots
[rust.git] / src / libstd / thunk.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Because this module is temporary...
12 #![allow(missing_docs)]
13
14 use alloc::boxed::Box;
15 use core::kinds::Send;
16 use core::ops::FnOnce;
17
18 pub struct Thunk<A=(),R=()> {
19     invoke: Box<Invoke<A,R>+Send>
20 }
21
22 impl<R> Thunk<(),R> {
23     pub fn new<F>(func: F) -> Thunk<(),R>
24         where F : FnOnce() -> R, F : Send
25     {
26         Thunk::with_arg(move|: ()| func())
27     }
28 }
29
30 impl<A,R> Thunk<A,R> {
31     pub fn with_arg<F>(func: F) -> Thunk<A,R>
32         where F : FnOnce(A) -> R, F : Send
33     {
34         Thunk {
35             invoke: box func
36         }
37     }
38
39     pub fn invoke(self, arg: A) -> R {
40         self.invoke.invoke(arg)
41     }
42 }
43
44 pub trait Invoke<A=(),R=()> {
45     fn invoke(self: Box<Self>, arg: A) -> R;
46 }
47
48 impl<A,R,F> Invoke<A,R> for F
49     where F : FnOnce(A) -> R
50 {
51     fn invoke(self: Box<F>, arg: A) -> R {
52         let f = *self;
53         f(arg)
54     }
55 }