1
0
Fork 0
tsgames/build/assets/stdlib.c

70 lines
1.4 KiB
C

#include <stdlib.h>
#define BLOCK_SIZE (64 * 1024)
#define BLOCK_1MB 16
static uintptr_t bump_pointer = (uintptr_t)&__heap_base;
static uintptr_t heap_end = BLOCK_1MB * BLOCK_SIZE;
IMPORT(grow) void grow(uint32_t blocks);
static void* bump_alloc(uintptr_t n) {
uintptr_t r = bump_pointer;
bump_pointer += n;
while (bump_pointer >= heap_end) {
grow(heap_end / BLOCK_SIZE);
heap_end *= 2;
}
return (void*)r;
}
void* malloc(uintptr_t n) {
return bump_alloc(n);
}
void free(void* p) { (void)p; }
void* memset(void* s, uint8_t c, uint32_t n) {
uint8_t* p = (uint8_t*)s;
while (n--) {
*p++ = c;
}
return s;
}
void* memcpy(void* dest, const void* src, uint32_t n) {
uint8_t* d = (uint8_t*)dest;
const uint8_t* s = (const uint8_t*)src;
while (n--) {
*d++ = *s++;
}
return dest;
}
int memcmp(const void* s1, const void* s2, uint32_t n) {
const uint8_t* p1 = (const uint8_t*)s1;
const uint8_t* p2 = (const uint8_t*)s2;
while (n--) {
if (*p1 != *p2) {
return (*p1 - *p2);
}
p1++;
p2++;
}
return 0; // Memory blocks are equal
}
static uint64_t rand_state;
void srand(uint64_t seed) { rand_state = seed; }
uint64_t rand(void) {
uint64_t z = (rand_state += 0x9e3779b97f4a7c15);
z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
return z ^ (z >> 31);
}