Add DEFER macro, similar to go's defer

DEFER macro lets you run a block of code when exit from current scope.
Example use case:
    1. Close a file descriptor when function returns
    2. Call fclose()/lz4stream_close() routines before return

While these cases can be covered with unique ptr or custom RAII object,
inventing a new type for each usecase is somewhat cumbersome. So added
this macro to help.

Test: th
Bug: 206729162

Change-Id: I05d3b5df1bc31a451ef9f6328633acc06d547e6e
diff --git a/common/utils.cc b/common/utils.cc
index e47b70b..8b57075 100644
--- a/common/utils.cc
+++ b/common/utils.cc
@@ -63,7 +63,6 @@
 using base::TimeDelta;
 using std::min;
 using std::numeric_limits;
-using std::pair;
 using std::string;
 using std::vector;
 
diff --git a/common/utils.h b/common/utils.h
index 4ff4050..a0a466d 100644
--- a/common/utils.h
+++ b/common/utils.h
@@ -38,6 +38,7 @@
 #include <brillo/secure_blob.h>
 
 #include "android-base/mapped_file.h"
+#include "android-base/scopeguard.h"
 #include "google/protobuf/repeated_field.h"
 #include "update_engine/common/action.h"
 #include "update_engine/common/action_processor.h"
@@ -584,4 +585,25 @@
 #define TEST_LT(_x, _y) TEST_OP(_x, _y, <)
 #define TEST_GT(_x, _y) TEST_OP(_x, _y, >)
 
+// Macro for running a block of code before function exits.
+// Example:
+// DEFER {
+//     fclose(hc);
+//     hc = nullptr;
+//   };
+// It works by creating a new local variable struct holding the lambda, the
+// destructor of that struct will invoke the lambda.
+
+constexpr struct {
+  template <typename F>
+  constexpr auto operator<<(F&& f) const noexcept {
+    return android::base::make_scope_guard(std::forward<F>(f));
+  }
+} deferrer;
+
+#define TOKENPASTE(x, y) x##y
+#define DEFER                                                    \
+  auto TOKENPASTE(_deferred_lambda_call, __COUNTER__) = deferrer \
+                                                        << [&]() mutable
+
 #endif  // UPDATE_ENGINE_COMMON_UTILS_H_