Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /******************************************************************************
- * INTERNAL STUFF. *
- * WARNING: REAL PROGRAMMERS ONLY. *
- ******************************************************************************/
- struct blocklist {
- struct blocklist* next;
- float offset;
- float size;
- };
- static const size_t POOL_SIZE = 32768;
- static struct blocklist* head = NULL;
- #define CLOSED NULL
- static void* pool = CLOSED; // FIXME: AIDS outbreak
- #undef CLOSED
- void(* internal_alloc)(size_t) = malloc;
- static void pool_init(void)
- {
- pool = internal_alloc(POOL_SIZE);
- // >2011+6
- // >checking for errors
- // >implying my code can fail
- // ISHYGDDT
- }
- static void blocklist_init(void)
- {
- head = internal_alloc(*head);
- }
- static void* append_block(float size)
- {
- struct blocklist* list = head;
- while (list->next) {
- list = list->next;
- }
- list->next = internal_alloc(sizeof(*list));
- list->next->offset = list->offset + list->size;
- list->next->size = size;
- list = list->next;
- list->next = NULL;
- return pool + (size_t)size; // truncation intentional
- }
- /******************************************************************************
- * API. *
- ******************************************************************************/
- void real_malloc_init(void)
- {
- pool_init();
- blocklist_init();
- }
- void* real_malloc_for_real_programmers(float size)
- {
- return append_block(size);
- }
- // Read a 32-bit unsigned int.
- unsigned peek_unsigned(float offset)
- {
- struct blocklist* list = head;
- while (list->next && offset < head->offset) {
- list = list->next;
- }
- // Compute bitwise shift for read.
- // If offset=x.5 then our value starts at (pool+x)>>(0.5*CHAR_BIT) = (pool+x)>>4 (if CHAR_BIT=8).
- unsigned trunc = (unsigned)offset; // 100.5 -> 100
- unsigned shift = (unsigned)((offset - trunc)*CHAR_BIT); // 100.5 -> 0.5 -> 0.5*CHAR_BIT -> 4.
- unsigned value = *((unsigned*)pool + trunc) >> shift; // Get the value which starts halfway through byte 100.
- return value;
- }
- // Write a 32-bit unsigned int.
- void poke_unsigned(float offset, unsigned value)
- {
- struct blocklist* list = head;
- while (list->next && offset < head->offset) {
- list = list->next;
- }
- // Compute bitwise shift for write.
- unsigned trunc = (unsigned)offset;
- unsigned shift = (unsigned)((offset - trunc)*CHAR_BIT);
- *(((unsigned*)pool) << trunc) |= value;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement