1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
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 HDI_DEVICE_INTELL_VOICE_SCOPE_GUARD_H
16#define HDI_DEVICE_INTELL_VOICE_SCOPE_GUARD_H
17
18#include <utility>
19
20namespace OHOS {
21namespace IntelligentVoice {
22namespace Utils {
23template <typename Func>
24class ScopeGuard {
25public:
26    ScopeGuard(Func &&f) : func_(std::forward<Func>(f)), active_(true)
27    {
28    }
29
30    ScopeGuard(ScopeGuard &&rhs) : func_(std::move(rhs.func)), active_(rhs.active_)
31    {
32        rhs.Disable();
33    }
34
35    ~ScopeGuard()
36    {
37        if (active_) {
38            func_();
39        }
40    }
41
42    void Disable()
43    {
44        active_ = false;
45    }
46
47    bool Active() const
48    {
49        return active_;
50    }
51
52    void EarlyExit()
53    {
54        if (active_) {
55            func_();
56        }
57        active_ = false;
58    }
59private:
60    Func func_;
61    bool active_;
62    ScopeGuard() = delete;
63    ScopeGuard(const ScopeGuard &) = delete;
64    ScopeGuard &operator=(const ScopeGuard &) = delete;
65    ScopeGuard &operator=(ScopeGuard &&) = delete;
66};
67
68// tag dispatch
69struct ScopeGuardOnExit {};
70
71template <typename Func>
72inline ScopeGuard<Func> operator+(ScopeGuardOnExit, Func &&fn)
73{
74    return ScopeGuard<Func>(std::forward<Func>(fn));
75}
76}
77}
78}
79
80/*
81 * ScopeGuard ensure the specified function which is created by ON_SCOPE_EXIT is executed no matter how the current
82 * scope exit.
83 * when use ON_SCOPE_EXIT macro, the format is:
84 * ON_SCOPE_EXIT {
85 *     your code
86 * };
87*/
88#define ON_SCOPE_EXIT \
89    auto __onScopeGuardExit__ = OHOS::IntelligentVoice::Utils::ScopeGuardOnExit() + [&]()
90
91#define CANCEL_SCOPE_EXIT \
92    (__onScopeGuardExit__.Disable())
93
94#define EARLY_SCOPE_EXIT \
95    (__onScopeGuardExit__.EarlyExit())
96
97#define ON_SCOPE_EXIT_WITH_NAME(variable_name) \
98    auto variable_name = OHOS::IntelligentVoice::Utils::ScopeGuardOnExit() + [&]()
99
100#endif
101