Coverage Report

Created: 2023-11-12 09:30

/proc/self/cwd/source/common/common/interval_value.h
Line
Count
Source (jump to first uncovered line)
1
#pragma once
2
3
#include <algorithm>
4
5
namespace Envoy {
6
7
// Template helper type that represents a closed interval with the given minimum and maximum values.
8
template <typename T, T MinValue, T MaxValue> struct Interval {
9
  static_assert(MinValue <= MaxValue, "min must be <= max");
10
  static constexpr T min_value = MinValue;
11
  static constexpr T max_value = MaxValue;
12
};
13
14
// Utility type that represents a value of type T in the given interval.
15
template <typename T, typename Interval> class ClosedIntervalValue {
16
public:
17
268k
  static constexpr ClosedIntervalValue min() { return ClosedIntervalValue(Interval::min_value); }
18
5.46k
  static constexpr ClosedIntervalValue max() { return ClosedIntervalValue(Interval::max_value); }
19
20
  constexpr explicit ClosedIntervalValue(T value)
21
315k
      : value_(std::max<T>(Interval::min_value, std::min<T>(Interval::max_value, value))) {}
22
23
207k
  T value() const { return value_; }
24
25
  // Returns a value that is as far from max as the original value is from min.
26
  // This guarantees that max().invert() == min() and min().invert() == max().
27
0
  ClosedIntervalValue invert() const {
28
0
    return ClosedIntervalValue(value_ == Interval::max_value ? Interval::min_value
29
0
                               : value_ == Interval::min_value
30
0
                                   ? Interval::max_value
31
0
                                   : Interval::max_value - (value_ - Interval::min_value));
32
0
  }
33
34
  // Comparisons are performed using the same operators on the underlying value
35
  // type, with the same exactness guarantees.
36
37
190k
  bool operator==(ClosedIntervalValue<T, Interval> other) const { return value_ == other.value(); }
38
0
  bool operator!=(ClosedIntervalValue<T, Interval> other) const { return value_ != other.value(); }
39
  bool operator<(ClosedIntervalValue<T, Interval> other) const { return value_ < other.value(); }
40
  bool operator<=(ClosedIntervalValue<T, Interval> other) const { return value_ <= other.value(); }
41
  bool operator>=(ClosedIntervalValue<T, Interval> other) const { return value_ >= other.value(); }
42
0
  bool operator>(ClosedIntervalValue<T, Interval> other) const { return value_ > other.value(); }
43
44
private:
45
  T value_;
46
};
47
48
// C++17 doesn't allow templating on floating point values, otherwise that's
49
// what we should do here instead of relying on a int => float implicit
50
// conversion. TODO(akonradi): when Envoy is using C++20, switch these template
51
// parameters to floats.
52
53
// Floating point value in the range [0, 1].
54
using UnitFloat = ClosedIntervalValue<float, Interval<int, 0, 1>>;
55
56
} // namespace Envoy