blob: 5d372bba06ce7b15d3351439cc70682d4a5a5661 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
// Copyright (c) 2026 Progmasoft.
// SPDX-License-Identifier: MPL-2.0 WITH AdditionRef-Progmasoft-Exception-2.0
#pragma once
#include <Progmasoft/Catch3/Detail/TypeTraits.hpp>
#include <Progmasoft/Catch3/Generator.hpp>
#include <algorithm>
#include <cstddef>
#include <initializer_list>
#include <iterator>
#include <memory>
#include <utility>
#include <vector>
namespace Progmasoft::Catch3
{
/// Picks uniformly from a fixed, non-empty list of values.
///
/// The list order is the simplicity order: a value shrinks to the values
/// listed before it, earliest first, so place the simplest case first.
/// A value that is not in the list has no candidates.
template<typename ValueType,
std::enable_if_t<Detail::kIsEqualityComparable<ValueType>, int>
= 0>
[[nodiscard]] Generator<ValueType>
Element(std::vector<ValueType> values)
{
if (values.empty())
{
Detail::RejectInvalidArgument(
"Element requires at least one value");
}
// Both callbacks share one immutable copy of the list.
const auto shared
= std::make_shared<const std::vector<ValueType>>(std::move(values));
return MakeGenerator<ValueType>(
[shared](Random &random) {
const std::size_t index
= random.Between(std::size_t{ 0 }, shared->size() - 1);
return static_cast<ValueType>((*shared)[index]);
},
[shared](const ValueType &value) {
const auto found
= std::find(shared->begin(), shared->end(), value);
if (found == shared->end())
{
return std::vector<ValueType>{};
}
return std::vector<ValueType>(shared->begin(), found);
});
}
/// Convenience overload for a literal list of values.
template<typename ValueType,
std::enable_if_t<Detail::kIsEqualityComparable<ValueType>, int>
= 0>
[[nodiscard]] Generator<ValueType>
Element(std::initializer_list<ValueType> values)
{
return Element(std::vector<ValueType>(values));
}
} // namespace Progmasoft::Catch3
|