From 1dcf59ea52e5306830d5ef1ff8936e53a3fb32f6 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sun, 12 Apr 2026 19:53:57 -0600 Subject: [PATCH] [internal] Add hb_scope_guard_t + HB_SCOPE_GUARD() macro MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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, 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) --- src/hb-algs.hh | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/hb-algs.hh b/src/hb-algs.hh index f0af8ed19..4c74b802d 100644 --- a/src/hb-algs.hh +++ b/src/hb-algs.hh @@ -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 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 +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 +static inline hb_scope_guard_t hb_make_scope_guard (F &&f) +{ return hb_scope_guard_t (std::forward (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 */