Pigweed
 
Loading...
Searching...
No Matches
scope_guard.h
1// Copyright 2023 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://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, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <utility>
17
18namespace pw {
19
37template <typename Functor>
39 public:
40 constexpr ScopeGuard(Functor&& functor)
41 : functor_(std::forward<Functor>(functor)), dismissed_(false) {}
42
43 constexpr ScopeGuard(ScopeGuard&& other) noexcept
44 : functor_(std::move(other.functor_)), dismissed_(other.dismissed_) {
45 other.dismissed_ = true;
46 }
47
48 template <typename OtherFunctor>
49 constexpr ScopeGuard(ScopeGuard<OtherFunctor>&& other)
50 : functor_(std::move(other.functor_)), dismissed_(other.dismissed_) {
51 other.dismissed_ = true;
52 }
53
54 ~ScopeGuard() {
55 if (dismissed_) {
56 return;
57 }
58 functor_();
59 }
60
61 ScopeGuard& operator=(ScopeGuard&& other) noexcept {
62 functor_ = std::move(other.functor_);
63 dismissed_ = std::move(other.dismissed_);
64 other.dismissed_ = true;
65 }
66
67 ScopeGuard() = delete;
68 ScopeGuard(const ScopeGuard&) = delete;
69 ScopeGuard& operator=(const ScopeGuard&) = delete;
70
73 void Dismiss() { dismissed_ = true; }
74
75 private:
76 template <typename OtherFunctor>
77 friend class ScopeGuard;
78
79 Functor functor_;
80 bool dismissed_;
81};
82
83// Enable type deduction for a compatible function pointer.
84template <typename Function>
85ScopeGuard(Function()) -> ScopeGuard<Function (*)()>;
86
87} // namespace pw
Definition: scope_guard.h:38
void Dismiss()
Definition: scope_guard.h:73
fit::function_impl< function_internal::config::kInlineCallableSize, !function_internal::config::kEnableDynamicAllocation, FunctionType, PW_FUNCTION_DEFAULT_ALLOCATOR_TYPE > Function
Definition: function.h:74
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27