-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
#pragma once | ||
|
||
#include <optional> | ||
|
||
namespace fpindex { | ||
namespace util { | ||
|
||
template <typename Callback = void()> | ||
class Cleanup { | ||
public: | ||
Cleanup(Callback callback) : callback_(std::move(callback)) {} | ||
~Cleanup() { Invoke(); } | ||
|
||
void Cancel() { callback_.reset(); } | ||
void Invoke() { | ||
if (callback_) { | ||
auto cb = std::move(*callback_); | ||
callback_.reset(); | ||
cb(); | ||
} | ||
} | ||
|
||
private: | ||
std::optional<Callback> callback_; | ||
}; | ||
|
||
template <typename Callback> | ||
Cleanup<Callback> MakeCleanup(Callback callback) { | ||
return {std::move(callback)}; | ||
} | ||
|
||
} // namespace util | ||
} // namespace fpindex |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
#include "fpindex/util/cleanup.h" | ||
|
||
#include <gtest/gtest.h> | ||
|
||
using namespace fpindex; | ||
|
||
TEST(CleanupTest, Cleanup) { | ||
std::string s = "initial"; | ||
{ | ||
auto cleanup = util::MakeCleanup([&s]() { | ||
s = "cleaned"; | ||
}); | ||
EXPECT_EQ(s, "initial"); | ||
} | ||
EXPECT_EQ(s, "cleaned"); | ||
} | ||
|
||
TEST(CleanupTest, Invoke) { | ||
std::string s = "initial"; | ||
{ | ||
auto cleanup = util::MakeCleanup([&s]() { | ||
s = "cleaned"; | ||
}); | ||
EXPECT_EQ(s, "initial"); | ||
cleanup.Invoke(); | ||
EXPECT_EQ(s, "cleaned"); | ||
s = "updated"; | ||
} | ||
EXPECT_EQ(s, "updated"); | ||
} | ||
|
||
TEST(CleanupTest, Cancel) { | ||
std::string s = "initial"; | ||
{ | ||
auto cleanup = util::MakeCleanup([&s]() { | ||
s = "cleaned"; | ||
}); | ||
cleanup.Cancel(); | ||
EXPECT_EQ(s, "initial"); | ||
} | ||
EXPECT_EQ(s, "initial"); | ||
} |