diff --git a/esprandom.h b/esprandom.h new file mode 100644 index 0000000..c5830be --- /dev/null +++ b/esprandom.h @@ -0,0 +1,42 @@ +#pragma once + +// system includes +#include +#include + +// esp-idf includes +#include + +namespace espcpputils { +namespace { + +class esp_random_device +{ +public: + using result_type = decltype(esp_random()); // should be uint32_t + + result_type operator()() const { return esp_random(); } + + double entropy() const { return 1.; } + result_type min() const { return std::numeric_limits::min(); } + result_type max() const { return std::numeric_limits::max(); } +}; + +std::string randomString(std::size_t length) +{ + static constexpr auto chars = + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + + auto rng = esp_random_device{}; + + auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1}; + + auto result = std::string(length, '\0'); + std::generate_n(std::begin(result), length, [&]() { return chars[dist(rng)]; }); + return result; +} + +} // namespace +} // namespace espcpputils diff --git a/esputils.h b/esputils.h index f7a29c4..ede3b7b 100644 --- a/esputils.h +++ b/esputils.h @@ -8,7 +8,6 @@ #include #include #include -#include /* Avoid "unused parameter" warnings @@ -229,18 +228,5 @@ bool is_in(First &&first, T && ... t) return ((first == t) || ...); } -std::string randomString(std::size_t length) -{ - static constexpr auto chars = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - thread_local auto rng = std::default_random_engine(); - auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1}; - auto result = std::string(length, '\0'); - std::generate_n(std::begin(result), length, [&]() { return chars[dist(rng)]; }); - return result; -} - } // namespace } // namespace espcpputils