]> git.lizzy.rs Git - rust.git/blob - library/core/src/const_closure.rs
23b3f87e72172faf4edf01b173e1ba6b2733a449
[rust.git] / library / core / src / const_closure.rs
1 use crate::marker::Destruct;
2
3 /// Struct representing a closure with mutably borrowed data.
4 ///
5 /// Example:
6 /// ```no_build
7 /// #![feature(const_mut_refs)]
8 /// use crate::const_closure::ConstFnMutClosure;
9 /// const fn imp(state: &mut i32, (arg,): (i32,)) -> i32 {
10 ///   *state += arg;
11 ///   *state
12 /// }
13 /// let mut i = 5;
14 /// let mut cl = ConstFnMutClosure::new(&mut i, imp);
15 ///
16 /// assert!(7 == cl(2));
17 /// assert!(8 == cl(1));
18 /// ```
19 pub(crate) struct ConstFnMutClosure<CapturedData, Function> {
20     /// The Data captured by the Closure.
21     /// Must be either a (mutable) reference or a tuple of (mutable) references.
22     pub data: CapturedData,
23     /// The Function of the Closure, must be: Fn(CapturedData, ClosureArgs) -> ClosureReturn
24     pub func: Function,
25 }
26
27 macro_rules! impl_fn_mut_tuple {
28     ($($var:ident)*) => {
29       #[allow(unused_parens)]
30       impl<'a, $($var,)* ClosureArguments, Function, ClosureReturnValue> const
31         FnOnce<ClosureArguments> for ConstFnMutClosure<($(&'a mut $var),*), Function>
32       where
33         Function: ~const Fn(($(&mut $var),*), ClosureArguments) -> ClosureReturnValue+ ~const Destruct,
34       {
35         type Output = ClosureReturnValue;
36
37         extern "rust-call" fn call_once(mut self, args: ClosureArguments) -> Self::Output {
38           self.call_mut(args)
39         }
40       }
41       #[allow(unused_parens)]
42       impl<'a, $($var,)* ClosureArguments, Function, ClosureReturnValue> const
43         FnMut<ClosureArguments> for ConstFnMutClosure<($(&'a mut $var),*), Function>
44       where
45         Function: ~const Fn(($(&mut $var),*), ClosureArguments)-> ClosureReturnValue,
46       {
47         extern "rust-call" fn call_mut(&mut self, args: ClosureArguments) -> Self::Output {
48           #[allow(non_snake_case)]
49           let ($($var),*) = &mut self.data;
50           (self.func)(($($var),*), args)
51         }
52       }
53
54     };
55   }
56 impl_fn_mut_tuple!(A);
57 impl_fn_mut_tuple!(A B);
58 impl_fn_mut_tuple!(A B C);
59 impl_fn_mut_tuple!(A B C D);
60 impl_fn_mut_tuple!(A B C D E);