Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions Sming/Core/Data/Range.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#pragma once

#include <WString.h>
#include <limits>
#include <esp_systemapi.h>

/**
Expand Down Expand Up @@ -80,7 +81,7 @@ template <typename T> struct TRange {
/**
* @brief Determine if range contains a value
*/
bool contains(T value) const
template <typename V> constexpr bool contains(V value) const
{
return (value >= min) && (value <= max);
}
Expand All @@ -96,21 +97,24 @@ template <typename T> struct TRange {
/**
* @brief Clip values to within the range
*/
T clip(T value) const
template <typename V> constexpr T clip(V value) const
{
return (value < min) ? min : (value > max) ? max : value;
return (value < min) ? min : (value > max) ? max : T(value);
}

/**
* @brief Return a random value within the range
*/
T random() const
{
auto n = 1 + max - min;
uint64_t n = 1 + max - min;
if(n == 0) {
return 0;
}
auto value = os_random();
T value = os_random();
if(n > std::numeric_limits<uint32_t>::max()) {
value |= uint64_t(os_random()) << 32;
}
return min + value % n;
}

Expand Down
1 change: 1 addition & 0 deletions tests/HostTests/include/modules.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
XX(Libc) \
XX(PreCache) \
XX(BitSet) \
XX(Range) \
XX(String) \
XX(ArduinoString) \
XX(Wiring) \
Expand Down
56 changes: 56 additions & 0 deletions tests/HostTests/modules/Range.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <HostTests.h>
#include <Data/Range.h>

class RangeTest : public TestGroup
{
public:
RangeTest() : TestGroup(_F("Range"))
{
}

void execute() override
{
TEST_CASE("constexpr")
{
constexpr TRange<int> range(0, 100);
constexpr auto int64 = 120000000000LL;
constexpr auto val = range.clip(int64);
static_assert(val == 100, "Bad clip");

constexpr int64_t tmp = 0x8000000000LL;
static_assert(!range.contains(tmp));

for(unsigned i = 0; i < 10; ++i) {
Serial << range.random() << endl;
}
}

TEST_CASE("truncation")
{
constexpr TRange<int8_t> range(0, 100);
int val = 0x1020;
val = range.clip(val);
REQUIRE_EQ(val, 100);
}

TEST_CASE("Membership")
{
constexpr TRange<int8_t> range(0, 100);
int val = 0x8000;
REQUIRE(!range.contains(val));
}

TEST_CASE("Random")
{
constexpr TRange<int64_t> range(-0x10000000000LL, 0x10000000000LL);
for(unsigned i = 0; i < 10; ++i) {
Serial << range.random() << endl;
}
}
}
};

void REGISTER_TEST(Range)
{
registerGroup<RangeTest>();
}
Loading