]> git.lizzy.rs Git - rust.git/blob - library/core/src/const_closure.rs
Auto merge of #101833 - jyn514:cross-compile-compiler-builtins, r=Mark-Simulacrum
[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<'a, CapturedData: ?Sized, Function> {
20     data: &'a mut CapturedData,
21     func: Function,
22 }
23
24 impl<'a, CapturedData: ?Sized, Function> ConstFnMutClosure<'a, CapturedData, Function> {
25     /// Function for creating a new closure.
26     ///
27     /// `data` is the a mutable borrow of data that is captured from the environment.
28     ///
29     /// `func` is the function of the closure, it gets the data and a tuple of the arguments closure
30     ///   and return the return value of the closure.
31     pub(crate) const fn new<ClosureArguments, ClosureReturnValue>(
32         data: &'a mut CapturedData,
33         func: Function,
34     ) -> Self
35     where
36         Function: ~const Fn(&mut CapturedData, ClosureArguments) -> ClosureReturnValue,
37     {
38         Self { data, func }
39     }
40 }
41
42 impl<'a, CapturedData: ?Sized, ClosureArguments, Function, ClosureReturnValue> const
43     FnOnce<ClosureArguments> for ConstFnMutClosure<'a, CapturedData, Function>
44 where
45     Function:
46         ~const Fn(&mut CapturedData, ClosureArguments) -> ClosureReturnValue + ~const Destruct,
47 {
48     type Output = ClosureReturnValue;
49
50     extern "rust-call" fn call_once(mut self, args: ClosureArguments) -> Self::Output {
51         self.call_mut(args)
52     }
53 }
54
55 impl<'a, CapturedData: ?Sized, ClosureArguments, Function, ClosureReturnValue> const
56     FnMut<ClosureArguments> for ConstFnMutClosure<'a, CapturedData, Function>
57 where
58     Function: ~const Fn(&mut CapturedData, ClosureArguments) -> ClosureReturnValue,
59 {
60     extern "rust-call" fn call_mut(&mut self, args: ClosureArguments) -> Self::Output {
61         (self.func)(self.data, args)
62     }
63 }