Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Disposer.hpp
Go to the documentation of this file.
1// The Reactive C++ Toolbox.
2// Copyright (C) 2013-2019 Swirly Cloud Limited
3// Copyright (C) 2021 Reactive Markets Limited
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17#ifndef TOOLBOX_IO_DISPOSER_HPP
18#define TOOLBOX_IO_DISPOSER_HPP
19
20#include <toolbox/sys/Time.hpp>
22
23namespace toolbox {
24inline namespace io {
25
28template <typename DerivedT>
30 public:
32
33 // Copy.
36
37 // Move.
40
43 {
44 if (locks_ == 0) {
45 // Prevent the object from being disposed a second time by holding a lock
46 // indefinitely.
47 locks_ = 1;
48 static_cast<DerivedT*>(this)->dispose_now(now);
49 } else {
50 dispose_ = true;
51 }
52 }
53
54 protected:
55 ~BasicDisposer() = default;
56
58 bool is_locked() const noexcept { return locks_ > 0; }
59
62 bool is_dispose_deferred() const noexcept { return dispose_; }
63
66 [[nodiscard]] auto lock_this(CyclTime now) noexcept
67 {
68 ++locks_;
69 return make_finally([this, now]() noexcept {
70 if (--locks_ == 0 && dispose_) {
71 // Prevent the object from being disposed a second time by holding a lock
72 // indefinitely.
73 locks_ = 1;
74 static_cast<DerivedT*>(this)->dispose_now(now);
75 }
76 });
77 }
78
79 private:
80 short locks_{0};
81 bool dispose_{false};
82};
83
84} // namespace io
85} // namespace toolbox
86
87#endif // TOOLBOX_IO_DISPOSER_HPP
auto lock_this(CyclTime now) noexcept
Definition Disposer.hpp:66
BasicDisposer() noexcept=default
bool is_dispose_deferred() const noexcept
Definition Disposer.hpp:62
bool is_locked() const noexcept
Returns true if the lock is held or the object has been disposed.
Definition Disposer.hpp:58
void dispose(CyclTime now) noexcept
The dispose method may be safely called from callback functions while a lock is held.
Definition Disposer.hpp:42
auto make_finally(FnT fn) noexcept
Definition Finally.hpp:48
constexpr auto bind() noexcept
Definition Slot.hpp:97