Hegel 0.18.3
Property-based testing for C++
Loading...
Searching...
No Matches
numeric.h
1#pragma once
2
3#include <array>
4#include <cmath>
5#include <cstddef>
6#include <cstdint>
7#include <limits>
8#include <type_traits>
9
10#include "hegel/config.h"
11#include "hegel/core.h"
12
13namespace hegel::generators {
14
15 // =============================================================================
16 // Parameter structs
17 // =============================================================================
18
23 template <typename T> struct IntegersParams {
24 std::optional<T>
26 std::optional<T>
28 };
29
34 template <typename T> struct FloatsParams {
35 std::optional<T> min_value;
36 std::optional<T> max_value;
37 std::optional<T>
40 std::optional<T>
43 std::optional<bool>
45 std::optional<bool>
47 std::optional<bool>
50 };
51
53 namespace detail {
54
55 // Draws an integer of a type wider than 64 bits through the engine's
56 // big-integer draw. The buffers have one byte more than T, so the
57 // sign of an unsigned bound is always clear.
58 template <typename T>
59 T draw_wide_integer(const TestCase& tc, T min_value, T max_value) {
60 using U = std::make_unsigned_t<T>;
61 constexpr std::size_t len = sizeof(T) + 1;
62 auto encode = [](T value) {
63 std::array<uint8_t, len> bytes{};
64 auto bits = static_cast<U>(value);
65 for (std::size_t i = 0; i < sizeof(T); ++i) {
66 bytes[i] = static_cast<uint8_t>(bits >> (8 * i));
67 }
68 if constexpr (std::is_signed_v<T>) {
69 bytes[sizeof(T)] = value < 0 ? 0xFF : 0;
70 }
71 return bytes;
72 };
73 std::array<uint8_t, len> min_bytes = encode(min_value);
74 std::array<uint8_t, len> max_bytes = encode(max_value);
75 std::array<uint8_t, len> out{};
76 hegel::internal::draw_integer_bytes(
77 tc, min_bytes.data(), max_bytes.data(), len, out.data());
78 U bits = 0;
79 for (std::size_t i = 0; i < sizeof(T); ++i) {
80 bits |= static_cast<U>(out[i]) << (8 * i);
81 }
82 return static_cast<T>(bits);
83 }
84
85 template <typename To, typename From> To narrow_up(From value) {
86 if (value > static_cast<From>(std::numeric_limits<To>::max())) {
87 return std::numeric_limits<To>::infinity();
88 }
89 if (value < static_cast<From>(std::numeric_limits<To>::lowest())) {
90 return std::numeric_limits<To>::lowest();
91 }
92 auto narrowed = static_cast<To>(value);
93 if (static_cast<From>(narrowed) < value) {
94 narrowed = std::nextafter(narrowed,
95 std::numeric_limits<To>::infinity());
96 }
97 return narrowed;
98 }
99
100 template <typename To, typename From> To narrow_down(From value) {
101 return -narrow_up<To>(-value);
102 }
103
104 } // namespace detail
105
106 // Concrete IGenerator<T> subclass produced by integers().
107 template <typename T>
108 HEGEL_REQUIRES(std::is_integral_v<T>)
109 class IntegerGenerator : public detail::ValuePrinted<T> {
110 static_assert(std::is_integral_v<T>,
111 "integers<T> requires an integral type T");
112
113 public:
114 explicit IntegerGenerator(const IntegersParams<T>& params = {})
115 : min_(params.min_value.value_or(std::numeric_limits<T>::min())),
116 max_(params.max_value.value_or(std::numeric_limits<T>::max())) {
117 if (min_ > max_) {
118 throw std::invalid_argument(
119 "Cannot have max_value < min_value");
120 }
121 }
122
123 T do_draw(const TestCase& tc) const override {
124 if constexpr (sizeof(T) > sizeof(int64_t)) {
125 return detail::draw_wide_integer<T>(tc, min_, max_);
126 } else if constexpr (std::is_signed_v<T>) {
127 return static_cast<T>(hegel::internal::draw_integer(
128 tc, static_cast<int64_t>(min_),
129 static_cast<int64_t>(max_)));
130 } else {
131 return static_cast<T>(hegel::internal::draw_integer_unsigned(
132 tc, static_cast<uint64_t>(min_),
133 static_cast<uint64_t>(max_)));
134 }
135 }
136
137 uint64_t label() const override {
138 return hegel::internal::label(hegel::internal::LabelName::Integers);
139 }
140
141 private:
142 T min_;
143 T max_;
144 };
145
146 // Concrete IGenerator<T> subclass produced by floats(). Resolves the
147 // engine draw parameters once at construction.
148 template <typename T>
149 HEGEL_REQUIRES(std::is_floating_point_v<T>)
150 class FloatGenerator : public detail::ValuePrinted<T> {
151 static_assert(std::is_floating_point_v<T>,
152 "floats<T> requires a floating-point type T");
153
154 // The engine draws 32-bit and 64-bit floats. A float is drawn at 32
155 // bits, and every other type at 64.
156 using Drawn =
157 std::conditional_t<std::is_same_v<T, float>, float, double>;
158
159 public:
160 explicit FloatGenerator(const FloatsParams<T>& params = {}) {
161 if (params.min_value && params.min_value_exclusive) {
162 throw std::invalid_argument(
163 "Cannot give both min_value and min_value_exclusive");
164 }
165 if (params.max_value && params.max_value_exclusive) {
166 throw std::invalid_argument(
167 "Cannot give both max_value and max_value_exclusive");
168 }
169 bool exclude_min = params.min_value_exclusive.has_value();
170 bool exclude_max = params.max_value_exclusive.has_value();
171 std::optional<T> min_value =
172 exclude_min ? params.min_value_exclusive : params.min_value;
173 std::optional<T> max_value =
174 exclude_max ? params.max_value_exclusive : params.max_value;
175 bool has_min = min_value.has_value();
176 bool has_max = max_value.has_value();
177 allow_nan_ = params.allow_nan.value_or(!has_min && !has_max);
178 allow_infinity_ =
179 params.allow_infinity.value_or(!has_min || !has_max);
180 if (allow_nan_ && (has_min || has_max)) {
181 throw std::invalid_argument(
182 "Cannot have allow_nan=true with min_value or max_value");
183 }
184 if (has_min && has_max && *min_value > *max_value) {
185 throw std::invalid_argument(
186 "Cannot have max_value < min_value");
187 }
188 if (allow_infinity_ && has_min && has_max) {
189 throw std::invalid_argument(
190 "Cannot have allow_infinity=true with both min_value and "
191 "max_value");
192 }
193
194 // An unset bound is the widest the draw allows: infinite when
195 // infinities may be drawn, else the finite extreme of the width
196 // drawn at.
197 min_ =
198 has_min ? detail::narrow_up<double>(*min_value)
199 : allow_infinity_
200 ? -std::numeric_limits<double>::infinity()
201 : static_cast<double>(std::numeric_limits<Drawn>::lowest());
202 max_ = has_max ? detail::narrow_down<double>(*max_value)
203 : allow_infinity_
204 ? std::numeric_limits<double>::infinity()
205 : static_cast<double>(std::numeric_limits<Drawn>::max());
206 exclude_min_ = exclude_min && static_cast<T>(min_) == *min_value;
207 exclude_max_ = exclude_max && static_cast<T>(max_) == *max_value;
208
209 const auto smallest_normal =
210 static_cast<double>(std::numeric_limits<Drawn>::min());
211 bool allow_subnormal = params.allow_subnormal.value_or(
212 subnormal_default(has_min, has_max, smallest_normal));
213 if (allow_subnormal) {
214 if (has_min && min_ >= smallest_normal) {
215 throw std::invalid_argument(
216 "allow_subnormal=true, but min_value excludes all "
217 "values below the smallest positive normal");
218 }
219 if (has_max && max_ <= -smallest_normal) {
220 throw std::invalid_argument(
221 "allow_subnormal=true, but max_value excludes all "
222 "values above the smallest negative normal");
223 }
224 } else if (has_min && has_max) {
225 bool contains_zero = min_ <= 0.0 && max_ >= 0.0;
226 if (!contains_zero && max_ < smallest_normal &&
227 min_ > -smallest_normal) {
228 throw std::invalid_argument(
229 "allow_subnormal=false leaves no floating-point "
230 "values between min_value and max_value");
231 }
232 }
233 smallest_nonzero_magnitude_ =
234 allow_subnormal ? static_cast<double>(
235 std::numeric_limits<Drawn>::denorm_min())
236 : smallest_normal;
237 }
238
239 T do_draw(const TestCase& tc) const override {
240 constexpr uint32_t width = std::is_same_v<T, float> ? 32 : 64;
241 return static_cast<T>(hegel::internal::draw_float(
242 tc, width, min_, max_, allow_nan_, allow_infinity_,
243 exclude_min_, exclude_max_, smallest_nonzero_magnitude_));
244 }
245
246 uint64_t label() const override {
247 return hegel::internal::label(hegel::internal::LabelName::Floats);
248 }
249
250 private:
251 bool subnormal_default(bool has_min, bool has_max,
252 double smallest_normal) const {
253 if (has_min && has_max) {
254 if (min_ == max_) {
255 return -smallest_normal < min_ && min_ < smallest_normal;
256 }
257 return min_ < smallest_normal && max_ > -smallest_normal;
258 }
259 if (has_min) {
260 return min_ < smallest_normal;
261 }
262 if (has_max) {
263 return max_ > -smallest_normal;
264 }
265 return true;
266 }
267
268 double min_;
269 double max_;
270 bool allow_nan_;
271 bool allow_infinity_;
272 bool exclude_min_;
273 bool exclude_max_;
274 double smallest_nonzero_magnitude_;
275 };
277
280
299 template <typename T = int64_t>
300 HEGEL_REQUIRES(std::is_integral_v<T>)
301 Generator<T> integers(IntegersParams<T> params = {}) {
302 return Generator<T>(new IntegerGenerator<T>(std::move(params)));
303 }
304
335 template <typename T = double>
336 HEGEL_REQUIRES(std::is_floating_point_v<T>)
337 Generator<T> floats(FloatsParams<T> params = {}) {
338 return Generator<T>(new FloatGenerator<T>(std::move(params)));
339 }
340
342
343} // namespace hegel::generators
Handle to the currently-executing test case.
Definition test_case.h:46
A printable generator: TestCase::draw() accepts it.
Definition core.h:470
Hegel generators.
Definition core.h:25
Generator< T > integers(IntegersParams< T > params={})
Generate random integers. For a given integral type T, produces values in the range [std::numeric_lim...
Definition numeric.h:301
Generator< T > floats(FloatsParams< T > params={})
Generate random floating point numbers.
Definition numeric.h:337
Parameters for floats() generator.
Definition numeric.h:34
std::optional< T > max_value_exclusive
Definition numeric.h:41
std::optional< bool > allow_subnormal
Definition numeric.h:48
std::optional< T > min_value_exclusive
Definition numeric.h:38
std::optional< T > min_value
Inclusive minimum. Default: no minimum.
Definition numeric.h:35
std::optional< T > max_value
Inclusive maximum. Default: no maximum.
Definition numeric.h:36
std::optional< bool > allow_nan
Allow NaN. Default: true if unbounded.
Definition numeric.h:44
std::optional< bool > allow_infinity
Allow infinity. Default: true if unbounded.
Definition numeric.h:46
Parameters for integers() generator.
Definition numeric.h:23
std::optional< T > max_value
Maximum value (inclusive). Default: type maximum.
Definition numeric.h:27
std::optional< T > min_value
Minimum value (inclusive). Default: type minimum.
Definition numeric.h:25