core: add random number generator

This commit is contained in:
2024-10-24 21:33:05 +01:00
parent d0dcee9c6f
commit 44fb8593a5
8 changed files with 505 additions and 3 deletions

View File

@@ -0,0 +1,32 @@
#ifndef BLUELIB_INIT_H_
#define BLUELIB_INIT_H_
#ifdef __cplusplus
#define B_INIT(f) \
static void f(void); \
struct f##_t_ { \
f##_t_(void) \
{ \
f(); \
} \
}; \
static f##_t_ f##_; \
static void f(void)
#elif defined(_MSB_VER)
#pragma section(".CRT$XCU", read)
#define B_INIT2_(f, p) \
static void f(void); \
__declspec(allocate(".CRT$XCU")) void (*f##_)(void) = f; \
__pragma(comment(linker, "/include:" p #f "_")) static void f(void)
#ifdef _WIN64
#define B_INIT(f) B_INIT2_(f, "")
#else
#define B_INIT(f) B_INIT2_(f, "_")
#endif
#else
#define B_INIT(f) \
static void f(void) __attribute__((constructor)); \
static void f(void)
#endif
#endif

View File

@@ -1,5 +1,5 @@
#ifndef BLUELIB_MISC_H_
#define BLUELIB_MISC_H_
#ifndef BLUELIB_MISB_H_
#define BLUELIB_MISB_H_
#define b_unbox(type, box, member) \
((type *_Nonnull)((box) ? (uintptr_t)(box) - (offsetof(type, member)) : 0))
@@ -10,4 +10,4 @@
#define z__b_numargs(arg_type, ...) \
(sizeof((arg_type[]) {__VA_ARGS__}) / sizeof(arg_type))
#endif // C_MISC_H_
#endif // B_MISB_H_

View File

@@ -0,0 +1,37 @@
#ifndef BLUELIB_RANDOM_H_
#define BLUELIB_RANDOM_H_
#include <blue/core/status.h>
#include <stddef.h>
struct b_random_algorithm;
typedef enum b_random_flags {
/* algorithm selection */
B_RANDOM_MT19937 = 0x01u,
/* generation flags */
B_RANDOM_SECURE = 0x100u,
} b_random_flags;
typedef struct b_random_ctx {
b_random_flags __f;
struct b_random_algorithm *__a;
union {
struct {
unsigned long long mt[312];
size_t mti;
} __mt19937;
};
} b_random_ctx;
extern b_random_ctx *b_random_global_ctx(void);
extern b_status b_random_init(b_random_ctx *ctx, b_random_flags flags);
extern unsigned long long b_random_next_int64(b_random_ctx *ctx);
extern double b_random_next_double(b_random_ctx *ctx);
extern void b_random_next_bytes(
b_random_ctx *ctx, unsigned char *out, size_t nbytes);
#endif