[internal] Add hb_scope_guard_t + HB_SCOPE_GUARD() macro

Generic RAII cleanup helper for the long tail of non-HB-type
resources — raw malloc'd buffers, paired init/end calls like
inflateInit/inflateEnd, FT_Done_* handles, third-party opaque
state, etc.  For HB-typed resources prefer hb_unique_ptr_t<T>,
which already uses the type's hb_*_destroy() via vtable.

Usage:
  void *buf = hb_malloc (len);
  if (!buf) return false;
  HB_SCOPE_GUARD (hb_free (buf));
  ... multiple fallible operations ...
  return true;  // buf freed automatically on any return path

The guard also supports explicit release() for cases where
ownership is transferred out on success.

Uses __LINE__ for unique naming (standard; consistent with other
line-indexed macros in this codebase).  One guard per line is the
convention; putting two on the same line would collide.

Follow-up commits sweep existing manual-cleanup sites to use
hb_unique_ptr_t / HB_SCOPE_GUARD where they fit.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Behdad Esfahbod committed 2026-04-12 19:53:57 -06:00
1 parent c3b32f59fc
commit 1dcf59ea52
1 file changed
+44
+44
View File
@@ -1673,4 +1673,48 @@ double solve_itp (func_t f,
}
/*
* Scope guard: runs a callable at scope exit (RAII cleanup for
* non-HB-type resources — raw malloc'd buffers, paired init/end
* calls like inflateInit/inflateEnd, FT_Done_* handles, etc.).
*
* Prefer hb_unique_ptr_t<hb_blob_t> etc. for HB types; this is
* for the long tail of cleanup that those wrappers don't cover.
*
* Usage:
* void *buf = hb_malloc (len);
* if (!buf) return false;
* HB_SCOPE_GUARD (hb_free (buf));
* ... multiple fallible operations ...
* return true; // buf freed automatically on any return path
*/
template <typename F>
struct hb_scope_guard_t
{
explicit hb_scope_guard_t (F &&f) : f (std::move (f)), active (true) {}
hb_scope_guard_t (const hb_scope_guard_t &) = delete;
hb_scope_guard_t &operator= (const hb_scope_guard_t &) = delete;
~hb_scope_guard_t () { if (active) f (); }
/* Release: dismiss the guard so the cleanup does NOT run. Use
* when transferring ownership out of the scope. */
void release () { active = false; }
private:
F f;
bool active;
};
template <typename F>
static inline hb_scope_guard_t<F> hb_make_scope_guard (F &&f)
{ return hb_scope_guard_t<F> (std::forward<F> (f)); }
#define HB_SCOPE_GUARD_NAME_(line) hb_scope_guard_##line
#define HB_SCOPE_GUARD_NAME(line) HB_SCOPE_GUARD_NAME_(line)
#define HB_SCOPE_GUARD(stmt) \
auto HB_SCOPE_GUARD_NAME(__LINE__) = \
hb_make_scope_guard ([&]() { stmt; }); \
(void) HB_SCOPE_GUARD_NAME(__LINE__)
#endif /* HB_ALGS_HH */