gcc/libstdc++-v3/testsuite/26_numerics/valarray/mask.cc
Jonathan Wakely abb958ada1 libstdc++: Add assertions to std::mask_array operations [PR62196]
Add assertions to diagnose incorrect uses of valarray masks.

The assignment operators of std::mask_array do not have any explicit
preconditions in the standard, but the assignment operator
valarray<T>::operator=(const mask_array<T>&) requires the lengths to
match, so it seems consistent to also require that when the operands are
reversed.  In support of that interpretation, libstdc++ has undefined
behaviour if the right-hand operand has more elements than are selected
by the mask, and libc++ has undefined behaviour if it has fewer
elements. Our std::mask_array stores the number of selected elements as
_M_sz so it's easy to add an assertion that checks it.

For the valarray::operator[] that takes a valarray<bool> mask,
[valarray.sub] in the standard says: "In each case the selected
element(s) shall exist." This makes it undefined to have a mask that
refers to out-of-range elements. We can easily check this too.

libstdc++-v3/ChangeLog:

	PR libstdc++/62196
	* include/bits/mask_array.h (mask_array): Add assertions to
	assignment operators.
	* include/std/valarray (valarray::operator[](valarray<bool>)):
	Add assertions.
	* testsuite/26_numerics/valarray/mask-1_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-2_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-3_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-4_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-5_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-6_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-7_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask-8_neg.cc: New test.
	* testsuite/26_numerics/valarray/mask.cc: New test.
2023-03-14 10:28:38 +00:00

47 lines
1 KiB
C++

// { dg-options "-D_GLIBCXX_ASSERTIONS" }
// { dg-do run }
#include <valarray>
#include <testsuite_hooks.h>
using std::valarray;
template<typename T>
bool equal(const valarray<T>& lhs, const valarray<T>& rhs)
{
if (lhs.size() != rhs.size())
return false;
for (unsigned i = 0; i < lhs.size(); ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
// Taken from examples in C++11 [valarray.sub].
void
test01() // valarray<T> operator[](const valarray<bool>& boolarr) const;
{
const valarray<char> v0("abcdefghijklmnop", 16);
const bool vb[] = {false, false, true, true, false, true};
valarray<char> v1 = v0[valarray<bool>(vb, 6)];
VERIFY( equal(v1, valarray<char>("cdf", 3)) );
}
void
test02() // mask_array<T> operator[](const valarray<bool>& boolarr);
{
valarray<char> v0("abcdefghijklmnop", 16);
valarray<char> v1("ABC", 3);
const bool vb[] = {false, false, true, true, false, true};
v0[valarray<bool>(vb, 6)] = v1;
VERIFY( equal(v0, valarray<char>("abABeCghijklmnop", 16)) );
}
int main()
{
test01();
test02();
}