Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 429b663c authored by Frederick Mayle's avatar Frederick Mayle Committed by Gerrit Code Review
Browse files

Merge "libbinder: simpler scope_guard implementation" into main

parents 5e1cbe06 ba5fda62
Loading
Loading
Loading
Loading
+28 −7
Original line number Diff line number Diff line
@@ -17,10 +17,37 @@
#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
@@ -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: