]> git.lizzy.rs Git - rust.git/blob - src/libstd/thunk.rs
rollup merge of #21702: nikomatsakis/issue-21636
[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 #![unstable(feature = "std_misc")]
14
15 use alloc::boxed::Box;
16 use core::marker::Send;
17 use core::ops::FnOnce;
18
19 pub struct Thunk<A=(),R=()> {
20     invoke: Box<Invoke<A,R>+Send>
21 }
22
23 impl<R> Thunk<(),R> {
24     pub fn new<F>(func: F) -> Thunk<(),R>
25         where F : FnOnce() -> R, F : Send
26     {
27         Thunk::with_arg(move|: ()| func())
28     }
29 }
30
31 impl<A,R> Thunk<A,R> {
32     pub fn with_arg<F>(func: F) -> Thunk<A,R>
33         where F : FnOnce(A) -> R, F : Send
34     {
35         Thunk {
36             invoke: box func
37         }
38     }
39
40     pub fn invoke(self, arg: A) -> R {
41         self.invoke.invoke(arg)
42     }
43 }
44
45 pub trait Invoke<A=(),R=()> {
46     fn invoke(self: Box<Self>, arg: A) -> R;
47 }
48
49 impl<A,R,F> Invoke<A,R> for F
50     where F : FnOnce(A) -> R
51 {
52     fn invoke(self: Box<F>, arg: A) -> R {
53         let f = *self;
54         f(arg)
55     }
56 }