Toolbox snapshot
The Reactive C++ Toolbox
Loading...
Searching...
No Matches
Hook.ut.cpp
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#include "Hook.hpp"
18
19#include <boost/test/unit_test.hpp>
20
21using namespace std;
22using namespace toolbox;
23
24namespace {
25
26// This class template implements a hook that will call a function object before unhooking itself.
27template <typename FnT>
28struct Test {
29 explicit Test(FnT fn)
30 : fn_{fn}
31 , hook{bind<&Test::call_then_delete>(this)}
32 {
33 }
34 void call_then_delete(CyclTime /*now*/)
35 {
36 fn_();
37 delete this;
38 }
39 FnT fn_;
40 Hook hook;
41};
42
43template <typename FnT>
44auto make_test(FnT fn)
45{
46 return new Test{fn};
47}
48
49} // namespace
50
52
54{
55 HookList l;
56 BOOST_CHECK(l.empty());
57 {
58 Hook h;
59 BOOST_CHECK(!h.is_linked());
60 l.push_back(h);
61 BOOST_CHECK(h.is_linked());
62 BOOST_CHECK(!l.empty());
63 }
64 BOOST_CHECK(l.empty());
65}
66
68{
69 int i{0};
70 auto fn = [&i](CyclTime) { ++i; };
71
72 HookList l;
73 {
74 Hook h1{bind(&fn)};
75 l.push_back(h1);
76
77 dispatch(CyclTime::now(), l);
79
80 dispatch(CyclTime::now(), l);
82 {
83 Hook h2{bind(&fn)};
84 l.push_back(h2);
85
86 dispatch(CyclTime::now(), l);
88 }
89 }
90}
91
93{
94 int i{0};
95 auto fn = [&i](CyclTime) { ++i; };
96
97 HookList l;
98
99 Hook h1{bind(&fn)};
100 l.push_back(make_test([&l, &h1]() { l.push_back(h1); })->hook);
101
102 Hook h2{bind(&fn)};
103 l.push_back(make_test([&l, &h2]() { l.push_back(h2); })->hook);
104
105 BOOST_CHECK_EQUAL(l.size(), 2);
106 BOOST_CHECK(!h1.is_linked());
107 BOOST_CHECK(!h2.is_linked());
108
109 dispatch(CyclTime::now(), l);
111
112 BOOST_CHECK_EQUAL(l.size(), 2);
113 BOOST_CHECK(h1.is_linked());
114 BOOST_CHECK(h2.is_linked());
115
116 dispatch(CyclTime::now(), l);
118}
119
BOOST_AUTO_TEST_CASE(HookAutoUnlinkCase)
Definition Hook.ut.cpp:53
BOOST_CHECK_EQUAL(v.size(), 10U)
STL namespace.
void dispatch(CyclTime now, const HookList &l) noexcept
Definition Hook.cpp:24
boost::intrusive::list< Hook, boost::intrusive::constant_time_size< false > > HookList
Definition Hook.hpp:39
constexpr auto bind() noexcept
Definition Slot.hpp:92
BOOST_CHECK(isnan(stod(""sv, numeric_limits< double >::quiet_NaN())))