From 6382d2b7302b1318d3180fe47b7e84bb1b02a9b2 Mon Sep 17 00:00:00 2001 From: Will Miles Date: Sat, 6 Jan 2024 10:05:18 -0500 Subject: [PATCH] Add C++-style guard class for JSON Buffer lock Add JSONBufferGuard, an RAII lock guard class for JSONBufferLock analogous to std::lock_guard. This permits binding the guard to a scope, such as an object life cycle or function body, guaranteeing that the lock will be released when the scope exits. --- wled00/fcn_declare.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/wled00/fcn_declare.h b/wled00/fcn_declare.h index ec7527269..e256ceb5f 100644 --- a/wled00/fcn_declare.h +++ b/wled00/fcn_declare.h @@ -360,6 +360,22 @@ um_data_t* simulateSound(uint8_t simulationId); void enumerateLedmaps(); uint8_t get_random_wheel_index(uint8_t pos); +// RAII guard class for the JSON Buffer lock +// Modeled after std::lock_guard +class JSONBufferGuard { + bool holding_lock; + public: + inline JSONBufferGuard(uint8_t module=255) : holding_lock(requestJSONBufferLock(module)) {}; + inline ~JSONBufferGuard() { if (holding_lock) releaseJSONBufferLock(); }; + inline JSONBufferGuard(const JSONBufferGuard&) = delete; // Noncopyable + inline JSONBufferGuard& operator=(const JSONBufferGuard&) = delete; + inline JSONBufferGuard(JSONBufferGuard&& r) : holding_lock(r.holding_lock) { r.holding_lock = false; }; // but movable + inline JSONBufferGuard& operator=(JSONBufferGuard&& r) { holding_lock |= r.holding_lock; r.holding_lock = false; return *this; }; + inline bool owns_lock() const { return holding_lock; } + explicit inline operator bool() const { return owns_lock(); }; + inline void release() { if (holding_lock) releaseJSONBufferLock(); holding_lock = false; } +}; + #ifdef WLED_ADD_EEPROM_SUPPORT //wled_eeprom.cpp void applyMacro(byte index);