From 4b12e982e6c622f7e8bb255677f712bf22c3b483 Mon Sep 17 00:00:00 2001 From: mike919192 <91038685+mike919192@users.noreply.github.com> Date: Fri, 16 Feb 2024 04:21:25 -0500 Subject: [PATCH] In subspan function, add static checks on extents (#843) * In subspan function, add static checks on extents * Change to ETL_STATIC_ASSERT. Add static assert for first and last functions * Add static assert to pre c++11 subspan * Change extent to Extent to better match existing code --- include/etl/span.h | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/include/etl/span.h b/include/etl/span.h index 797e35e5e..2caa38975 100644 --- a/include/etl/span.h +++ b/include/etl/span.h @@ -42,6 +42,7 @@ SOFTWARE. #include "memory.h" #include "array.h" #include "byte.h" +#include "static_assert.h" #include "private/dynamic_extent.h" @@ -295,6 +296,9 @@ namespace etl template ETL_NODISCARD ETL_CONSTEXPR etl::span first() const ETL_NOEXCEPT { + //if Extent is static, check that original span contains at least COUNT elements + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) ? COUNT <= Extent : true, "Original span does not contain COUNT elements"); + return etl::span(pbegin, pbegin + COUNT); } @@ -312,6 +316,9 @@ namespace etl template ETL_NODISCARD ETL_CONSTEXPR etl::span last() const ETL_NOEXCEPT { + //if Extent is static, check that original span contains at least COUNT elements + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) ? COUNT <= Extent : true, "Original span does not contain COUNT elements"); + return etl::span(pbegin + Extent - COUNT, (pbegin + Extent)); } @@ -331,6 +338,12 @@ namespace etl ETL_NODISCARD ETL_CONSTEXPR etl::span subspan() const ETL_NOEXCEPT { + //if Extent is static, check that OFFSET is within the original span + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) ? OFFSET <= Extent : true, "OFFSET is not within the original span"); + + //if count is also static, check that OFFSET + COUNT is within the original span + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) && (COUNT != etl::dynamic_extent) ? COUNT <= (Extent - OFFSET) : true, "OFFSET + COUNT is not within the original span"); + return (COUNT == etl::dynamic_extent) ? etl::span(pbegin + OFFSET, (pbegin + Extent)) : etl::span(pbegin + OFFSET, pbegin + OFFSET + COUNT); } @@ -341,6 +354,12 @@ namespace etl template etl::span subspan() const { + //if Extent is static, check that OFFSET is within the original span + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) ? OFFSET <= Extent : true, "OFFSET is not within the original span"); + + //if count is also static, check that OFFSET + COUNT is within the original span + ETL_STATIC_ASSERT((Extent != etl::dynamic_extent) && (COUNT != etl::dynamic_extent) ? COUNT <= (Extent - OFFSET) : true, "OFFSET + COUNT is not within the original span"); + if (COUNT == etl::dynamic_extent) { return etl::span(pbegin + OFFSET, (pbegin + Extent));