• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 The Tint Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef SRC_UTILS_DEFER_H_
16 #define SRC_UTILS_DEFER_H_
17 
18 #include <utility>
19 
20 #include "src/utils/concat.h"
21 
22 namespace tint {
23 namespace utils {
24 
25 /// Defer executes a function or function like object when it is destructed.
26 template <typename F>
27 class Defer {
28  public:
29   /// Constructor
30   /// @param f the function to call when the Defer is destructed
Defer(F && f)31   explicit Defer(F&& f) : f_(std::move(f)) {}
32 
33   /// Move constructor
34   Defer(Defer&&) = default;
35 
36   /// Destructor
37   /// Calls the deferred function
~Defer()38   ~Defer() { f_(); }
39 
40  private:
41   Defer(const Defer&) = delete;
42   Defer& operator=(const Defer&) = delete;
43 
44   F f_;
45 };
46 
47 /// Constructor
48 /// @param f the function to call when the Defer is destructed
49 template <typename F>
MakeDefer(F && f)50 inline Defer<F> MakeDefer(F&& f) {
51   return Defer<F>(std::forward<F>(f));
52 }
53 
54 }  // namespace utils
55 }  // namespace tint
56 
57 /// TINT_DEFER(S) executes the statement(s) `S` when exiting the current lexical
58 /// scope.
59 #define TINT_DEFER(S)                          \
60   auto TINT_CONCAT(tint_defer_, __COUNTER__) = \
61       ::tint::utils::MakeDefer([&] { S; })
62 
63 #endif  //  SRC_UTILS_DEFER_H_
64