ZeroErr
Loading...
Searching...
No Matches
in_range.h
Go to the documentation of this file.
1#pragma once
2
4#include <cmath>
5#include <random>
6#include <stdexcept>
8
10
11namespace zeroerr {
12
30template <typename T>
31class InRange : public DomainConvertable<T> {
32public:
33 using ValueType = T;
34 using CorpusType = T;
35
37
38 InRange(T min, T max) : min(min), max(max) { validate(); }
39
40 CorpusType GetRandomCorpus(Rng& rng) const override {
41 validate();
42 return sample(rng);
43 }
44
45 void Mutate(Rng& rng, CorpusType& v, bool) const override {
46 v = GetRandomCorpus(rng);
47 }
48
49private:
50 void validate() const {
51 if (!(min <= max) || !std::isfinite(static_cast<long double>(min)) ||
52 !std::isfinite(static_cast<long double>(max)))
53 throw std::invalid_argument("InRange requires finite ordered bounds");
54 }
55
56 template <class U = T>
57 typename std::enable_if<std::is_integral<U>::value, T>::type sample(Rng& rng) const {
58 // Promote small integers because standard distributions exclude char and bool.
59 using Int = typename std::conditional<std::is_signed<U>::value, int64_t, uint64_t>::type;
60 std::uniform_int_distribution<Int> distribution(min, max);
61 return static_cast<T>(distribution(rng));
62 }
63
64 template <class U = T>
65 typename std::enable_if<std::is_floating_point<U>::value, T>::type sample(Rng& rng) const {
66 if (min == max) return min;
67 const T fraction = static_cast<T>(rng.uniform01());
68 // Opposite-sign extremes may overflow max - min.
69 T value = min < 0 && max > 0
70 ? min * (T(1) - fraction) + max * fraction
71 : min + (max - min) * fraction;
72 return value < min ? min : value > max ? max : value;
73 }
74};
75
76} // namespace zeroerr
77
DomainConvertable is a base class for domains that can be converted to and from a ValueType.
Definition domain.h:48
ValueType max
Definition in_range.h:36
InRange(T min, T max)
Definition in_range.h:38
ValueType min
Definition in_range.h:36
T CorpusType
Definition in_range.h:34
void Mutate(Rng &rng, CorpusType &v, bool) const override
Definition in_range.h:45
CorpusType GetRandomCorpus(Rng &rng) const override
Definition in_range.h:40
T ValueType
Definition in_range.h:33
Definition rng.h:30
#define ZEROERR_SUPPRESS_COMMON_WARNINGS_POP
Definition config.h:283
#define ZEROERR_SUPPRESS_COMMON_WARNINGS_PUSH
Definition config.h:235
Definition assert_text.cpp:5