Badrand pseudo random number generator, emphasis on pseudo

This commit is contained in:
Imbus 2025-09-02 01:59:24 +02:00
parent edc082adcb
commit 4c96aac02c
4 changed files with 95 additions and 1 deletions

View file

@ -59,7 +59,8 @@ KERNEL_OBJ := \
kern/libkern/memory.o \
kern/libkern/spinlock.o \
kern/libkern/mini-printf.o \
kern/libkern/stdio.o
kern/libkern/stdio.o \
kern/libkern/badrand.o
kern/kernel.elf: $(KERNEL_OBJ)
@echo LD $@

35
kern/libkern/badrand.c Normal file
View file

@ -0,0 +1,35 @@
#include "badrand.h"
#include <stdint.h>
#define PRAND_BUILD_SEED \
((uint64_t)(__TIME__[0]) * (uint64_t)(__TIME__[1]) * (uint64_t)(__TIME__[3]) * (uint64_t)(__TIME__[4]) * \
(uint64_t)(__TIME__[6]) * (uint64_t)(__TIME__[7]))
static uint64_t seed = PRAND_BUILD_SEED * 6364136223846793005ULL + 1;
uint64_t badrand() {
seed = seed * 6364136223846793005ULL + 1;
return seed;
}
uint64_t badrand_range(uint64_t min, uint64_t max) {
uint64_t range = max - min + 1;
uint64_t x;
uint64_t limit = UINT64_MAX - (UINT64_MAX % range);
do {
x = badrand();
} while (x > limit);
return min + (x % range);
}
void sbadprand(uint64_t s) {
if (s) {
seed ^= (s * 0x9e3779b97f4a7c15ULL) + (seed << 6) + (seed >> 2);
} else {
seed ^= PRAND_BUILD_SEED;
}
}
#undef PRAND_BUILD_SEED

43
kern/libkern/badrand.h Normal file
View file

@ -0,0 +1,43 @@
#ifndef BADRAND_H
#define BADRAND_H
#include <stdint.h>
/*
* This is a PRNG for non-cryptographic use.
*
* See:
* https://en.wikipedia.org/wiki/Linear_congruential_generator
*/
/**
* @brief Sets the seed for the PRNG.
*
* @param s The specific seed value or zero. If zero is passed, it will call
* rand_reseed().
*/
void sbadrand(uint64_t s);
/**
* @brief Generates a pseudo-random 64-bit number.
*
* Uses a simple Linear Congruential Generator (LCG) to produce
* a sequence of pseudo-random numbers.
*
* @return A pseudo-random 64-bit unsigned integer.
*/
uint64_t badrand();
/**
* @brief Generates a random number within a specified range.
*
* Produces a random number in the inclusive range [min, max].
* Ensures uniform distribution by applying a modulo operation.
*
* @param min The lower bound of the range (inclusive).
* @param max The upper bound of the range (inclusive).
* @return A random number between min and max.
*/
uint64_t badrand_range(uint64_t min, uint64_t max);
#endif // BADRAND_H

View file

@ -12,3 +12,18 @@ typedef unsigned long uint64_t;
typedef uint64_t size_t;
typedef uint64_t uintptr_t;
#define INT8_MIN (-128)
#define INT16_MIN (-32767 - 1)
#define INT32_MIN (-2147483647 - 1)
#define INT64_MIN (-__INT64_C(9223372036854775807) - 1)
#define INT8_MAX (127)
#define INT16_MAX (32767)
#define INT32_MAX (2147483647)
#define INT64_MAX (__INT64_C(9223372036854775807))
#define UINT8_MAX (255)
#define UINT16_MAX (65535)
#define UINT32_MAX (4294967295U)
#define UINT64_MAX (__UINT64_C(18446744073709551615))