From beb1f3c207bcf1ebc6ca1e83f1940bd91c867d9a Mon Sep 17 00:00:00 2001 From: Martin Braun Date: Wed, 27 Mar 2019 17:32:09 -0700 Subject: utils: Add scope_exit object This is a utility for RAII-style operations. An object that will run code when a scope is left. Also includes unit tests. --- host/tests/CMakeLists.txt | 1 + host/tests/scope_exit_test.cpp | 45 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 host/tests/scope_exit_test.cpp (limited to 'host/tests') diff --git a/host/tests/CMakeLists.txt b/host/tests/CMakeLists.txt index 8a67e3f85..33fbcdbf9 100644 --- a/host/tests/CMakeLists.txt +++ b/host/tests/CMakeLists.txt @@ -39,6 +39,7 @@ set(test_sources narrow_cast_test.cpp property_test.cpp ranges_test.cpp + scope_exit_test.cpp sid_t_test.cpp sensors_test.cpp soft_reg_test.cpp diff --git a/host/tests/scope_exit_test.cpp b/host/tests/scope_exit_test.cpp new file mode 100644 index 000000000..7c05613a8 --- /dev/null +++ b/host/tests/scope_exit_test.cpp @@ -0,0 +1,45 @@ +// +// Copyright 2019 Ettus Research, a National Instruments Brand +// +// SPDX-License-Identifier: GPL-3.0-or-later +// + +#include +#include +#include + +BOOST_AUTO_TEST_CASE(test_scope_exit) +{ + bool flag = false; + { + auto flag_setter = uhd::utils::scope_exit::make([&flag]() { flag = true; }); + BOOST_CHECK(!flag); + } + BOOST_CHECK(flag); +} + +BOOST_AUTO_TEST_CASE(test_scope_exit_function_object) +{ + bool flag = false; + std::function resetter = [&flag]() { flag = true; }; + + { + auto flag_setter = uhd::utils::scope_exit::make(std::move(resetter)); + BOOST_CHECK(!flag); + } + BOOST_CHECK(flag); +} + +BOOST_AUTO_TEST_CASE(test_scope_exit_function_named_lambda) +{ + bool flag = false; + auto resetter = [&flag]() { flag = true; }; + + { + // Note: Does not require std::move() + auto flag_setter = uhd::utils::scope_exit::make(resetter); + BOOST_CHECK(!flag); + } + BOOST_CHECK(flag); +} + -- cgit v1.2.3