From ba5fda62ea1a01dbf388dda63f9fcf2c4ea448bd Mon Sep 17 00:00:00 2001 From: Frederick Mayle Date: Fri, 3 May 2024 16:04:56 -0700 Subject: libbinder: simpler scope_guard implementation libbinder_on_trusty_mock size: 289,374 -> 286,533 bytes Bug: 338458975 Test: TH Change-Id: I9fc817ba09c8697fb8b5f566cec28f15b6e7ea5d --- libs/binder/include/binder/Functional.h | 35 ++++++++++++++++++++++++++------- 1 file 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,10 +17,37 @@ #pragma once #include -#include +#include namespace android::binder::impl { +template +class scope_guard; + +template +scope_guard make_scope_guard(F f); + +template +class scope_guard { +public: + inline ~scope_guard() { + if (f_.has_value()) std::move(f_.value())(); + } + inline void release() { f_.reset(); } + +private: + friend scope_guard android::binder::impl::make_scope_guard(F); + + inline scope_guard(F&& f) : f_(std::move(f)) {} + + std::optional f_; +}; + +template +inline scope_guard make_scope_guard(F f) { + return scope_guard(std::move(f)); +} + template constexpr void assert_small_callable() { // While this buffer (std::function::__func::__buf_) is an implementation detail generally not @@ -32,12 +59,6 @@ constexpr void assert_small_callable() { "Try using std::ref, but make sure lambda lives long enough to be called."); } -template -std::unique_ptr> make_scope_guard(F&& f) { - assert_small_callable(); - return {reinterpret_cast(true), std::bind(f)}; -} - template class SmallFunction : public std::function { public: -- cgit v1.2.3-59-g8ed1b