diff options
| author | 2024-05-03 16:04:56 -0700 | |
|---|---|---|
| committer | 2024-06-26 10:49:05 -0700 | |
| commit | ba5fda62ea1a01dbf388dda63f9fcf2c4ea448bd (patch) | |
| tree | 82e82d3a4a35ac46bd8fb4438a5ec2c000ba62ca | |
| parent | f8ec3975ab092b828e1b7c71ec504a7415c29203 (diff) | |
libbinder: simpler scope_guard implementation
libbinder_on_trusty_mock size: 289,374 -> 286,533 bytes
Bug: 338458975
Test: TH
Change-Id: I9fc817ba09c8697fb8b5f566cec28f15b6e7ea5d
| -rw-r--r-- | libs/binder/include/binder/Functional.h | 35 |
1 files changed, 28 insertions, 7 deletions
diff --git a/libs/binder/include/binder/Functional.h b/libs/binder/include/binder/Functional.h index 08e3b214da..bb0e5f4115 100644 --- a/libs/binder/include/binder/Functional.h +++ b/libs/binder/include/binder/Functional.h @@ -17,11 +17,38 @@ #pragma once #include <functional> -#include <memory> +#include <optional> namespace android::binder::impl { template <typename F> +class scope_guard; + +template <typename F> +scope_guard<F> make_scope_guard(F f); + +template <typename F> +class scope_guard { +public: + inline ~scope_guard() { + if (f_.has_value()) std::move(f_.value())(); + } + inline void release() { f_.reset(); } + +private: + friend scope_guard<F> android::binder::impl::make_scope_guard(F); + + inline scope_guard(F&& f) : f_(std::move(f)) {} + + std::optional<F> f_; +}; + +template <typename F> +inline scope_guard<F> make_scope_guard(F f) { + return scope_guard<F>(std::move(f)); +} + +template <typename F> constexpr void assert_small_callable() { // While this buffer (std::function::__func::__buf_) is an implementation detail generally not // accessible to users, it's a good bet to assume its size to be around 3 pointers. @@ -32,12 +59,6 @@ constexpr void assert_small_callable() { "Try using std::ref, but make sure lambda lives long enough to be called."); } -template <typename F> -std::unique_ptr<void, std::function<void(void*)>> make_scope_guard(F&& f) { - assert_small_callable<decltype(std::bind(f))>(); - return {reinterpret_cast<void*>(true), std::bind(f)}; -} - template <typename T> class SmallFunction : public std::function<T> { public: |