From b7ca7f78c1f2979b54c22ab1dbeecf2b36b7afd9 Mon Sep 17 00:00:00 2001 From: IonutParau Date: Mon, 7 Jul 2025 20:27:29 +0200 Subject: [PATCH] rng --- src/neonucleus.h | 17 +++++++++++++++++ src/utils.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/neonucleus.h b/src/neonucleus.h index 3871342..b86483a 100644 --- a/src/neonucleus.h +++ b/src/neonucleus.h @@ -128,10 +128,25 @@ typedef struct nn_Clock { nn_ClockProc *proc; } nn_Clock; +typedef size_t nn_RngProc(void *userdata); + +typedef struct nn_Rng { + void *userdata; + size_t maximum; + nn_RngProc *proc; +} nn_Rng; + +size_t nn_rand(nn_Rng *rng); +// returns from 0 to 1 (inclusive) +double nn_randf(nn_Rng *rng); +// returns from 0 to 1 (exclusive) +double nn_randfe(nn_Rng *rng); + typedef struct nn_Context { nn_Alloc allocator; nn_LockManager lockManager; nn_Clock clock; + nn_Rng rng; } nn_Context; // TODO: write a bunch of utils so this *can* work on baremetal. @@ -140,6 +155,7 @@ typedef struct nn_Context { nn_Alloc nn_libcAllocator(); nn_Clock nn_libcRealTime(); nn_LockManager nn_libcMutex(); +nn_Rng nn_libcRng(); nn_Context nn_libcContext(); #endif @@ -283,6 +299,7 @@ nn_Context *nn_getContext(nn_universe *universe); nn_Alloc *nn_getAllocator(nn_universe *universe); nn_Clock *nn_getClock(nn_universe *universe); nn_LockManager *nn_getLockManager(nn_universe *universe); +nn_Rng *nn_getRng(nn_universe *universe); void nn_unsafeDeleteUniverse(nn_universe *universe); void *nn_queryUserdata(nn_universe *universe, const char *name); void nn_storeUserdata(nn_universe *universe, const char *name, void *data); diff --git a/src/utils.c b/src/utils.c index 0ce582e..a2c4572 100644 --- a/src/utils.c +++ b/src/utils.c @@ -61,11 +61,25 @@ nn_Alloc nn_libcAllocator() { }; } +static size_t nni_rand(void *userdata) { + return rand(); +} + +nn_Rng nn_libcRng() { + srand(time(NULL)); + return (nn_Rng) { + .userdata = NULL, + .maximum = RAND_MAX, + .proc = nni_rand, + }; +} + nn_Context nn_libcContext() { return (nn_Context) { .allocator = nn_libcAllocator(), .clock = nn_libcRealTime(), .lockManager = nn_libcMutex(), + .rng = nn_libcRng(), }; } #endif @@ -89,6 +103,23 @@ void nn_deallocStr(nn_Alloc *alloc, char *s) { nn_dealloc(alloc, s, strlen(s)+1); } +size_t nn_rand(nn_Rng *rng) { + return rng->proc(rng->userdata); +} + +// returns from 0 to 1 (inclusive) +double nn_randf(nn_Rng *rng) { + double x = nn_rand(rng); + return x / rng->maximum; +} + +// returns from 0 to 1 (exclusive) +double nn_randfe(nn_Rng *rng) { + double x = nn_rand(rng); + if(x >= rng->maximum) return 0; + return x / rng->maximum; +} + #ifndef NN_BAREMETAL #ifdef NN_POSIX