fix range check, add some tests

This commit is contained in:
Christopher Lackner 2019-08-05 12:48:08 +02:00
parent 73fe929811
commit 9f32a5c3ad
3 changed files with 45 additions and 8 deletions

View File

@ -475,7 +475,7 @@ namespace ngcore
/// Access array. range check by macro NETGEN_CHECK_RANGE
NETGEN_INLINE T & operator[] (size_t i) const
{
NETGEN_CHECK_RANGE(i,0,size-1);
NETGEN_CHECK_RANGE(i,0,size);
return data[i];
}
@ -496,7 +496,7 @@ namespace ngcore
/// access last element. check by macro NETGEN_CHECK_RANGE
T & Last () const
{
NETGEN_CHECK_RANGE(0,size-1,size-1);
NETGEN_CHECK_RANGE(size-1,0,size);
return data[size-1];
}
@ -838,7 +838,7 @@ namespace ngcore
/// Delete element i. Move last element to position i.
NETGEN_INLINE void DeleteElement (size_t i)
{
NETGEN_CHECK_RANGE(i,0,size-1);
NETGEN_CHECK_RANGE(i,0,size);
data[i] = std::move(data[size-1]);
size--;
}
@ -856,7 +856,7 @@ namespace ngcore
/// Delete last element.
NETGEN_INLINE void DeleteLast ()
{
NETGEN_CHECK_RANGE(0,size-1,size-1);
NETGEN_CHECK_RANGE(size-1,0,size);
size--;
}

View File

@ -55,7 +55,7 @@ namespace ngcore
int ind, int imin, int imax) : Exception("")
{
std::stringstream str;
str << where << ": index " << ind << " out of range [" << imin << "," << imax << "]\n";
str << where << ": index " << ind << " out of range [" << imin << "," << imax << ")\n";
Append (str.str());
}
@ -80,9 +80,9 @@ namespace ngcore
#define NG_EXCEPTION(s) ngcore::Exception(__FILE__ ":" NETGEN_CORE_NGEXEPTION_STR(__LINE__) "\t"+std::string(s))
#ifdef NETGEN_ENABLE_CHECK_RANGE
#define NETGEN_CHECK_RANGE(value, min, max) \
{ if ((value)<(min) || (value)>=(max)) \
throw ngcore::RangeException(__FILE__ ":" NETGEN_CORE_NGEXEPTION_STR(__LINE__) "\t", (value), (min), (max)); }
#define NETGEN_CHECK_RANGE(value, min, max_plus_one) \
{ if ((value)<(min) || (value)>=(max_plus_one)) \
throw ngcore::RangeException(__FILE__ ":" NETGEN_CORE_NGEXEPTION_STR(__LINE__) "\t", (value), (min), (max_plus_one)); }
#else // NETGEN_ENABLE_CHECK_RANGE
#define NETGEN_CHECK_RANGE(value, min, max)
#endif // NETGEN_ENABLE_CHECK_RANGE

37
tests/catch/array.cpp Normal file
View File

@ -0,0 +1,37 @@
#include "catch.hpp"
#include <array.hpp>
using namespace ngcore;
using namespace std;
TEST_CASE("Array")
{
Array<int> array;
#ifdef DEBUG
CHECK_THROWS_AS(array[0], RangeException);
CHECK_THROWS_AS(array.DeleteLast(), RangeException);
CHECK_THROWS_AS(array.Last(), RangeException);
#endif // DEBUG
Array<double> a_initlst = { 1., 2., 3.};
CHECK(a_initlst[1] == 2.);
CHECK(a_initlst.size() == 3);
FlatArray fa_a = a_initlst;
CHECK(typeid(fa_a) == typeid(FlatArray<double>));
CHECK(fa_a.size() == 3);
CHECK(a.Last() == 3.);
a.DeleteLast();
CHECK(a.Last() == 2. && a.Size() == 2);
#ifdef DEBUG
CHECK_THROWS_AS(fa_a[5], RangeException);
#endif // DEBUG
Array b = Array<int>(4);
b = 2;
int count = 0;
for(auto val : b)
{
count++;
CHECK(val == 2);
}
CHECK(count == 4);
}