xref: /llvm-project/llvm/unittests/ADT/ScopeExitTest.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
164afe235STim Shen //===- llvm/unittest/ADT/ScopeExit.cpp - Scope exit unit tests --*- C++ -*-===//
264afe235STim Shen //
3*2946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*2946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
5*2946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
664afe235STim Shen //
764afe235STim Shen //===----------------------------------------------------------------------===//
864afe235STim Shen 
964afe235STim Shen #include "llvm/ADT/ScopeExit.h"
1064afe235STim Shen #include "gtest/gtest.h"
1164afe235STim Shen 
1264afe235STim Shen using namespace llvm;
1364afe235STim Shen 
1464afe235STim Shen namespace {
1564afe235STim Shen 
TEST(ScopeExitTest,Basic)1664afe235STim Shen TEST(ScopeExitTest, Basic) {
1764afe235STim Shen   struct Callable {
1864afe235STim Shen     bool &Called;
1964afe235STim Shen     Callable(bool &Called) : Called(Called) {}
2064afe235STim Shen     Callable(Callable &&RHS) : Called(RHS.Called) {}
2164afe235STim Shen     void operator()() { Called = true; }
2264afe235STim Shen   };
2364afe235STim Shen   bool Called = false;
2464afe235STim Shen   {
2564afe235STim Shen     auto g = make_scope_exit(Callable(Called));
2664afe235STim Shen     EXPECT_FALSE(Called);
2764afe235STim Shen   }
2864afe235STim Shen   EXPECT_TRUE(Called);
2964afe235STim Shen }
3064afe235STim Shen 
TEST(ScopeExitTest,Release)317e6d0255SSam McCall TEST(ScopeExitTest, Release) {
327e6d0255SSam McCall   int Count = 0;
337e6d0255SSam McCall   auto Increment = [&] { ++Count; };
347e6d0255SSam McCall   {
357e6d0255SSam McCall     auto G = make_scope_exit(Increment);
367e6d0255SSam McCall     auto H = std::move(G);
377e6d0255SSam McCall     auto I = std::move(G);
387e6d0255SSam McCall     EXPECT_EQ(0, Count);
397e6d0255SSam McCall   }
407e6d0255SSam McCall   EXPECT_EQ(1, Count);
417e6d0255SSam McCall   {
427e6d0255SSam McCall     auto G = make_scope_exit(Increment);
437e6d0255SSam McCall     G.release();
447e6d0255SSam McCall   }
457e6d0255SSam McCall   EXPECT_EQ(1, Count);
467e6d0255SSam McCall }
477e6d0255SSam McCall 
4864afe235STim Shen } // end anonymous namespace
49