diff --git a/docs/containers/queues & stacks/circular-buffer.md b/docs/containers/queues & stacks/circular-buffer.md index 3c3faf2a..66aecc90 100644 --- a/docs/containers/queues & stacks/circular-buffer.md +++ b/docs/containers/queues & stacks/circular-buffer.md @@ -123,6 +123,7 @@ const_reference operator[](size_t i) const ``` **Description** Returns a reference or const reference to the indexed element. +Emits an `etl::circular_buffer_out_of_bounds` if ETL_CHECK_INDEX_OPERATOR is defined and the index is out of range of the deque. Undefined behaviour if asserts or exceptions are not enabled. --- diff --git a/include/etl/circular_buffer.h b/include/etl/circular_buffer.h index b0586cfb..c820e09f 100644 --- a/include/etl/circular_buffer.h +++ b/include/etl/circular_buffer.h @@ -83,6 +83,19 @@ namespace etl } }; + //*************************************************************************** + /// circular_buffer out of bounds exception. + //*************************************************************************** + class circular_buffer_out_of_bounds : public etl::circular_buffer_exception + { + public: + + circular_buffer_out_of_bounds(string_type file_name_, numeric_type line_number_) + : etl::circular_buffer_exception(ETL_ERROR_TEXT("circular_buffer:bounds", ETL_CIRCULAR_BUFFER_FILE_ID"C"), file_name_, line_number_) + { + } + }; + //*************************************************************************** /// //*************************************************************************** @@ -888,6 +901,8 @@ namespace etl //************************************************************************* reference operator[](size_t index) { + ETL_ASSERT_CHECK_INDEX_OPERATOR(index < size(), ETL_ERROR(circular_buffer_out_of_bounds)); + return pbuffer[(out + index) % buffer_size]; } @@ -897,6 +912,8 @@ namespace etl //************************************************************************* const_reference operator[](size_t index) const { + ETL_ASSERT_CHECK_INDEX_OPERATOR(index < size(), ETL_ERROR(circular_buffer_out_of_bounds)); + return pbuffer[(out + index) % buffer_size]; } diff --git a/test/test_circular_buffer.cpp b/test/test_circular_buffer.cpp index cdbd162d..bb48c636 100644 --- a/test/test_circular_buffer.cpp +++ b/test/test_circular_buffer.cpp @@ -647,6 +647,8 @@ namespace { CHECK_EQUAL(input2[i], data[i]); } + + CHECK_THROW(data[data.size()], etl::circular_buffer_out_of_bounds); } //************************************************************************* @@ -662,6 +664,8 @@ namespace { CHECK_EQUAL(input[i + 3], data[i]); } + + CHECK_THROW(data[data.size()], etl::circular_buffer_out_of_bounds); } //*************************************************************************