2020-05-27 06:25:46 -04:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 04:24:48 -04:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-05-27 06:25:46 -04:00
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <AK/Platform.h>
|
|
|
|
#include <AK/Types.h>
|
|
|
|
|
2022-07-11 03:04:39 -04:00
|
|
|
#if defined(__serenity__) || defined(AK_OS_ANDROID)
|
2020-05-27 06:25:46 -04:00
|
|
|
# include <stdlib.h>
|
|
|
|
#endif
|
|
|
|
|
2020-10-17 16:25:13 -04:00
|
|
|
#if defined(__unix__)
|
2020-05-27 06:25:46 -04:00
|
|
|
# include <unistd.h>
|
|
|
|
#endif
|
|
|
|
|
2021-09-12 12:06:33 -04:00
|
|
|
#if defined(AK_OS_MACOS)
|
2020-05-29 16:22:01 -04:00
|
|
|
# include <sys/random.h>
|
|
|
|
#endif
|
|
|
|
|
2022-09-20 03:15:12 -04:00
|
|
|
#if defined(AK_OS_WINDOWS)
|
|
|
|
# include <random>
|
|
|
|
# include <unistd.h>
|
|
|
|
#endif
|
|
|
|
|
2020-05-27 06:25:46 -04:00
|
|
|
namespace AK {
|
|
|
|
|
2020-12-20 18:09:48 -05:00
|
|
|
inline void fill_with_random([[maybe_unused]] void* buffer, [[maybe_unused]] size_t length)
|
2020-05-27 06:25:46 -04:00
|
|
|
{
|
2022-07-11 03:04:39 -04:00
|
|
|
#if defined(__serenity__) || defined(AK_OS_ANDROID)
|
2020-05-27 06:25:46 -04:00
|
|
|
arc4random_buf(buffer, length);
|
2020-11-27 17:57:02 -05:00
|
|
|
#elif defined(OSS_FUZZ)
|
2021-09-12 12:06:33 -04:00
|
|
|
#elif defined(__unix__) or defined(AK_OS_MACOS)
|
2020-12-20 18:09:48 -05:00
|
|
|
[[maybe_unused]] int rc = getentropy(buffer, length);
|
2022-09-20 03:15:12 -04:00
|
|
|
#else
|
|
|
|
char* char_buffer = static_cast<char*>(buffer);
|
|
|
|
for (size_t i = 0; i < length; i++) {
|
|
|
|
char_buffer[i] = std::rand();
|
|
|
|
}
|
2020-05-27 06:25:46 -04:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
inline T get_random()
|
|
|
|
{
|
|
|
|
T t;
|
|
|
|
fill_with_random(&t, sizeof(T));
|
|
|
|
return t;
|
|
|
|
}
|
|
|
|
|
2021-05-14 11:16:06 -04:00
|
|
|
u32 get_random_uniform(u32 max_bounds);
|
|
|
|
|
2020-05-27 06:25:46 -04:00
|
|
|
}
|
2020-10-16 15:59:53 -04:00
|
|
|
|
|
|
|
using AK::fill_with_random;
|
|
|
|
using AK::get_random;
|
2021-05-14 11:16:06 -04:00
|
|
|
using AK::get_random_uniform;
|