From 2d0ff9774dd47eb827db16fb7cef8eb7c222f707 Mon Sep 17 00:00:00 2001 From: Lukas Tenbrink Date: Thu, 12 Jun 2025 11:45:50 +0200 Subject: [PATCH] Add a smoke test to `Span` in debug builds to recover from non-empty `nullptr` `Span`. --- core/templates/span.h | 13 +++++++++++-- tests/core/templates/test_span.h | 8 ++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/core/templates/span.h b/core/templates/span.h index 7d6ed50588c..d6d63641d15 100644 --- a/core/templates/span.h +++ b/core/templates/span.h @@ -51,8 +51,17 @@ public: std::is_same>; _FORCE_INLINE_ constexpr Span() = default; - _FORCE_INLINE_ constexpr Span(const T *p_ptr, uint64_t p_len) : - _ptr(p_ptr), _len(p_len) {} + + _FORCE_INLINE_ Span(const T *p_ptr, uint64_t p_len) : + _ptr(p_ptr), _len(p_len) { +#ifdef DEBUG_ENABLED + // TODO In c++20, make this check run only in non-consteval, and make this constructor constexpr. + if (_ptr == nullptr && _len > 0) { + ERR_PRINT("Internal bug, please report: Span was created from nullptr with size > 0. Recovering by using size = 0."); + _len = 0; + } +#endif + } // Allows creating Span directly from C arrays and string literals. template diff --git a/tests/core/templates/test_span.h b/tests/core/templates/test_span.h index 9fe0b03058e..0059d8d4f34 100644 --- a/tests/core/templates/test_span.h +++ b/tests/core/templates/test_span.h @@ -43,10 +43,10 @@ TEST_CASE("[Span] Constexpr Validators") { static_assert(span_empty.is_empty()); constexpr static uint16_t value = 5; - constexpr Span span_value(&value, 1); - static_assert(span_value.ptr() == &value); - static_assert(span_value.size() == 1); - static_assert(!span_value.is_empty()); + Span span_value(&value, 1); + CHECK(span_value.ptr() == &value); + CHECK(span_value.size() == 1); + CHECK(!span_value.is_empty()); static constexpr int ints[] = { 0, 1, 2, 3, 4, 5 }; constexpr Span span_array = ints;