Skip to content

Commit

Permalink
Adding a range checked at() to the iterator view
Browse files Browse the repository at this point in the history
  • Loading branch information
whaeck committed Oct 12, 2023
1 parent 0ab5a13 commit 39d7d60
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/tools/view/IteratorView.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

// system includes
#include <iterator>
#include <stdexcept>

// other includes

Expand Down Expand Up @@ -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
*
Expand Down
30 changes: 30 additions & 0 deletions src/tools/view/IteratorView/test/IteratorView.test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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" ) {
Expand All @@ -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

Expand Down

0 comments on commit 39d7d60

Please sign in to comment.