diff --git a/src/tools/view/IteratorView.hpp b/src/tools/view/IteratorView.hpp index 4cbbce7..2994235 100644 --- a/src/tools/view/IteratorView.hpp +++ b/src/tools/view/IteratorView.hpp @@ -3,6 +3,7 @@ // system includes #include +#include // other includes @@ -109,6 +110,22 @@ class IteratorView { return *( std::next( this->begin(), i ) ); } + /** + * @brief Return an element at a given index with range checking + * + * @param[in] i the index + */ + constexpr decltype(auto) at( size_type i ) const { + + if ( i >= this->size() ) { + + throw std::out_of_range( "Index out of range: " + std::to_string( i ) + + " >= size (" + std::to_string( this->size() ) + + ")" ); + } + return this->operator[]( i ); + } + /** * @brief Verify if the IteratorView is equal to another container * diff --git a/src/tools/view/IteratorView/test/IteratorView.test.cpp b/src/tools/view/IteratorView/test/IteratorView.test.cpp index 005d680..704fc33 100644 --- a/src/tools/view/IteratorView/test/IteratorView.test.cpp +++ b/src/tools/view/IteratorView/test/IteratorView.test.cpp @@ -30,9 +30,24 @@ SCENARIO( "IteratorView" ) { CHECK( 1 == chunk[3] ); CHECK( 2 == chunk[4] ); + CHECK( -2 == chunk.at( 0 ) ); + CHECK( -1 == chunk.at( 1 ) ); + CHECK( 0 == chunk.at( 2 ) ); + CHECK( 1 == chunk.at( 3 ) ); + CHECK( 2 == chunk.at( 4 ) ); + CHECK( -2 == chunk.front() ); CHECK( 2 == chunk.back() ); } // THEN + + THEN( "an exception is thrown when using an index that is too large or " + "too small" ) { + + CHECK_NOTHROW( chunk.at( 0 ) ); + CHECK_NOTHROW( chunk.at( 4 ) ); + CHECK_THROWS( chunk.at( 5 ) ); + CHECK_THROWS( chunk.at( 10 ) ); + } // THEN } // WHEN WHEN( "when make functions are used" ) { @@ -50,9 +65,24 @@ SCENARIO( "IteratorView" ) { CHECK( 1 == chunk[3] ); CHECK( 2 == chunk[4] ); + CHECK( -2 == chunk.at( 0 ) ); + CHECK( -1 == chunk.at( 1 ) ); + CHECK( 0 == chunk.at( 2 ) ); + CHECK( 1 == chunk.at( 3 ) ); + CHECK( 2 == chunk.at( 4 ) ); + CHECK( -2 == chunk.front() ); CHECK( 2 == chunk.back() ); } // THEN + + THEN( "an exception is thrown when using an index that is too large or " + "too small" ) { + + CHECK_NOTHROW( chunk.at( 0 ) ); + CHECK_NOTHROW( chunk.at( 4 ) ); + CHECK_THROWS( chunk.at( 5 ) ); + CHECK_THROWS( chunk.at( 10 ) ); + } // THEN } // WHEN } // GIVEN