From acbe4446771f9f1bcbe364b5697792fd341dfd37 Mon Sep 17 00:00:00 2001 From: Dhaval Gujar Date: Tue, 22 Apr 2025 22:17:28 +0530 Subject: [PATCH] components/esp_matter: Add template specialization for nullable --- .../esp_matter/esp_matter_attribute_utils.h | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/components/esp_matter/esp_matter_attribute_utils.h b/components/esp_matter/esp_matter_attribute_utils.h index c04304b6d..51c5b9d9c 100644 --- a/components/esp_matter/esp_matter_attribute_utils.h +++ b/components/esp_matter/esp_matter_attribute_utils.h @@ -236,6 +236,52 @@ private: T val; }; +/** Template specialization for bool */ +template <> +class nullable +{ + using Traits = chip::app::NumericAttributeTraits; + using StorageType = typename Traits::StorageType; // Resolves to uint8_t + + static_assert(std::is_same_v, + "nullable specialization assumes bool StorageType is uint8_t. Revisit if this changes."); + +public: + /** Constructors */ + nullable() { Traits::SetNull(storage); } + nullable(std::nullptr_t) { Traits::SetNull(storage); } + constexpr nullable(bool v) : storage(static_cast(v)) {} + + /** Observers */ + constexpr bool is_null() const { return Traits::IsNullValue(storage); } + + /** + * @brief Gets the stored bool value. + * + * Returns the boolean interpretation of the internal storage. + * @warning Returns `true` when `is_null()` is true. Check `is_null()` first + * if the distinction between null and `true` is important. + * + * Example: + * ``` + * nullable v_true(true); // v_true.value() == true + * nullable v_false(false); // v_false.value() == false + * nullable v_null; // v_null.value() == true (because internal null 0xFF is non-zero) + * ``` + * @return `true` if storage is non-zero (includes null state), `false` if storage is zero. + */ + constexpr bool value() const { return static_cast(storage); } + + constexpr bool value_or(bool d) const { return is_null() ? d : static_cast(storage); } + + /** Modifiers */ + void operator=(std::nullptr_t) { Traits::SetNull(storage); } + void operator=(bool v) { storage = static_cast(v); } + +private: + StorageType storage; // 1‑byte payload holding 0 / 1 / 0xFF +}; + /*** Attribute val APIs ***/ /** Invalid */ esp_matter_attr_val_t esp_matter_invalid(void *val);