[random] introduce template-based NonCrypto random APIs (#13142)

This commit introduces a new set of template-based APIs for
non-cryptographic random number generation in the `Random::NonCrypto`
namespace. These new methods provide a cleaner, type-safe, and more
robust interface compared to the previous methods.

Key additions:
- `Generate<UintType>()`: Returns a random value of the given
  unsigned integer type (`uint8_t`, `uint16_t`, or `uint32_t`).
- `GenerateUpToExcluding<UintType>(aMax)`: Returns a random value in
  the range `[0, aMax)`.
- `GenerateFromMinUpToExcluding<UintType>(aMin, aMax)`: Returns a
  random value in the range `[aMin, aMax)`.
- `GenerateInClosedRange<UintType>(aMin, aMax)`: Returns a random
  value in the closed range `[aMin, aMax]`.

The introduction of `GenerateInClosedRange` is an improvement as it
safely handles ranges up to the maximum value of the integer type
(e.g., `0xffff`) without the risk of overflow.

All call sites across the OpenThread core stack and tests have been
updated to adopt these new APIs. The public `otRandomNonCrypto`
functions are also updated to leverage the new internal methods.

Doxygen documentation is added for all new template methods,
detailing their behavior, including edge cases where the upper bound
is smaller than or equal to the lower bound.
This commit is contained in:
Abtin Keshavarzian
2026-05-25 19:39:59 -07:00
committed by GitHub
parent 9d95a19e52
commit 4de7bc578e
46 changed files with 393 additions and 141 deletions
+2 -2
View File
@@ -125,11 +125,11 @@ OwnedPtr<Message> PrepareMessage(Node &aNode)
VerifyOrQuit(message != nullptr);
length = Random::NonCrypto::GetUint16InRange(1, kMessageSize);
length = Random::NonCrypto::GenerateFromMinUpToExcluding<uint16_t>(1, kMessageSize);
for (uint16_t i = 0; i < length; i++)
{
SuccessOrQuit(message->Append(Random::NonCrypto::GetUint8()));
SuccessOrQuit(message->Append(Random::NonCrypto::Generate<uint8_t>()));
}
return OwnedPtr<Message>(message);
+3 -3
View File
@@ -144,8 +144,8 @@ static void UpdateSrpRegistration(Node &aNode)
service->mSubTypeLabels = nullptr;
service->mTxtEntries = nullptr;
service->mNumTxtEntries = 0;
service->mPort = Random::NonCrypto::GetUint16InRange(0x100, 0xff00);
service->mSubTypeLabels = &info->mSubTypeLabels[Random::NonCrypto::GetUint8InRange(0, 4)];
service->mPort = Random::NonCrypto::GenerateFromMinUpToExcluding<uint16_t>(0x100, 0xff00);
service->mSubTypeLabels = &info->mSubTypeLabels[Random::NonCrypto::GenerateUpToExcluding<uint8_t>(4)];
SuccessOrQuit(aNode.Get<Srp::Client>().AddService(*service));
}
@@ -154,7 +154,7 @@ static bool ShouldPerform(uint16_t aProbability)
{
// Uses the given probability to randomly decide whether a certain action should be performed.
return Random::NonCrypto::GetUint16InRange(0, 1000) < aProbability;
return Random::NonCrypto::GenerateUpToExcluding<uint16_t>(1000) < aProbability;
}
static const Srp::Server::Host *FindHost(Node &aServer, const char *aName)
+1
View File
@@ -250,6 +250,7 @@ ot_unit_test(pool)
ot_unit_test(power_calibration)
ot_unit_test(priority_queue)
ot_unit_test(pskc)
ot_unit_test(random)
ot_unit_test(routing_manager)
ot_unit_test(seeker)
ot_unit_test(serial_number)
+2 -2
View File
@@ -159,11 +159,11 @@ void CorruptMessage(Message &aMessage)
uint8_t bitOffset;
uint8_t byte;
byteOffset = Random::NonCrypto::GetUint16InRange(0, aMessage.GetLength());
byteOffset = Random::NonCrypto::GenerateUpToExcluding<uint16_t>(aMessage.GetLength());
SuccessOrQuit(aMessage.Read(byteOffset, byte));
bitOffset = Random::NonCrypto::GetUint8InRange(0, kBitsPerByte);
bitOffset = Random::NonCrypto::GenerateUpToExcluding<uint8_t>(kBitsPerByte);
byte ^= (1 << bitOffset);
+225
View File
@@ -0,0 +1,225 @@
/*
* Copyright (c) 2026, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
c * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "test_platform.h"
#include <openthread/config.h>
#include "test_util.h"
#include "common/code_utils.hpp"
#include "common/num_utils.hpp"
#include "common/numeric_limits.hpp"
#include "common/random.hpp"
namespace ot {
template <typename UintType> void TestRandomNonCryto(const char *aName)
{
static constexpr uint8_t kMaxIters = 6;
Instance *instance = static_cast<Instance *>(testInitInstance());
UintType value;
UintType max = NumericLimits<UintType>::kMax;
VerifyOrQuit(instance != nullptr);
printf("--------------------------------------------------------------------\n\r");
printf("TestRandomNonCryto<%s>()\r\n", aName);
//--------------------------------------------------------------------------
// GenerateUpToExcluding
value = Random::NonCrypto::GenerateUpToExcluding<UintType>(0);
VerifyOrQuit(value == 0);
printf("\r\nGenerateUpToExcluding(100): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateUpToExcluding<UintType>(100);
printf("%lu, ", ToUlong(value));
VerifyOrQuit(value < 100);
}
printf("\r\nGenerateUpToExcluding(kMax): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateUpToExcluding<UintType>(max);
printf("0x%lx, ", ToUlong(value));
VerifyOrQuit(value < max);
}
//--------------------------------------------------------------------------
// GenerateUpToExcluding
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(12, 12);
VerifyOrQuit(value == 12);
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(12, 11);
VerifyOrQuit(value == 12);
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(12, 0);
VerifyOrQuit(value == 12);
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(max, 0);
VerifyOrQuit(value == max);
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(max, max);
VerifyOrQuit(value == max);
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(iter, iter + 1);
VerifyOrQuit(value == iter);
}
printf("\r\nGenerateFromMinUpToExcluding(100, 105): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(100, 105);
printf("%lu, ", ToUlong(value));
VerifyOrQuit(value >= 100);
VerifyOrQuit(value < 105);
}
printf("\r\nGenerateFromMinUpToExcluding(max - 2, max): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(max - 2, max);
printf("0x%lx, ", ToUlong(value));
VerifyOrQuit(value >= max - 2);
VerifyOrQuit(value < max);
}
printf("\r\nGenerateFromMinUpToExcluding(0, max): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateFromMinUpToExcluding<UintType>(0, max);
printf("0x%lx, ", ToUlong(value));
VerifyOrQuit(value < max);
}
//--------------------------------------------------------------------------
// GenerateInClosedRange
value = Random::NonCrypto::GenerateInClosedRange<UintType>(101, 101);
VerifyOrQuit(value == 101);
value = Random::NonCrypto::GenerateInClosedRange<UintType>(101, 100);
VerifyOrQuit(value == 101);
value = Random::NonCrypto::GenerateInClosedRange<UintType>(101, 0);
VerifyOrQuit(value == 101);
value = Random::NonCrypto::GenerateInClosedRange<UintType>(max, max);
VerifyOrQuit(value == max);
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateInClosedRange<UintType>(iter, iter);
VerifyOrQuit(value == iter);
}
printf("\r\nGenerateInClosedRange(200, 201): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateInClosedRange<UintType>(200, 201);
printf("%lu, ", ToUlong(value));
VerifyOrQuit(value >= 200);
VerifyOrQuit(value <= 201);
}
while (true)
{
// Make sure upper bound can be returned
value = Random::NonCrypto::GenerateInClosedRange<UintType>(100, 101);
VerifyOrQuit(value >= 100);
VerifyOrQuit(value <= 101);
if (value == 101)
{
break;
}
}
printf("\r\nGenerateInClosedRange(0, max): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateInClosedRange<UintType>(0, max);
printf("0x%lx, ", ToUlong(value));
}
printf("\r\nGenerateInClosedRange(max-1, max): ");
for (uint8_t iter = 0; iter < kMaxIters; iter++)
{
value = Random::NonCrypto::GenerateInClosedRange<UintType>(max - 1, max);
printf("0x%lx, ", ToUlong(value));
VerifyOrQuit(value >= max - 1);
}
while (true)
{
// Make sure upper bound can be returned
value = Random::NonCrypto::GenerateInClosedRange<UintType>(max - 1, max);
VerifyOrQuit(value >= max - 1);
if (value == max)
{
break;
}
}
printf("\r\nTest passed\r\n");
}
} // namespace ot
int main(void)
{
ot::TestRandomNonCryto<uint8_t>("uint8_t");
ot::TestRandomNonCryto<uint16_t>("uint16_t");
ot::TestRandomNonCryto<uint32_t>("uint32_t");
printf("\nAll tests passed.\n");
return 0;
}
+1 -1
View File
@@ -887,7 +887,7 @@ uint32_t GetRandom(uint32_t max)
}
else
{
value = Random::NonCrypto::GetUint32();
value = Random::NonCrypto::Generate<uint32_t>();
}
return value % max;