Files
quantum-utils/quantum/src/memory/zone.c
Wesley Irvin 75b5767e36 Log Colors
Added colored output to the logs. Also added the logs to zone for
outputting errors using our logger instead of printf().
2024-02-10 11:24:10 -05:00

87 lines
2.4 KiB
C

#include <stdio.h> // printf()
#include <stdlib.h> // malloc() free()
#include <string.h> // memset()
#include "../defines.h"
#include "../logger/logger.h"
#include "zone.h"
typedef struct ZoneHeader {
u64 capacity;
u64 cur_size;
} ZoneHeader;
Zone *zoneCreate(size_t sizeBytes) {
// First we need to get a block of memory from the OS
// This block needs to include the size of what we want to store
// plus the size of our ZoneHeader
void *mem_block = malloc(sizeBytes + sizeof(ZoneHeader));
// Now that we have the block let's get the addresses
// for where the header is, and the offset where the data starts
ZoneHeader *zone_header = (ZoneHeader *)mem_block;
Zone *zone_addr = (Zone *)(zone_header + sizeof(ZoneHeader));
// Initialize the values of the header
zone_header->capacity = sizeBytes;
zone_header->cur_size = 0;
return zone_addr;
}
void *zoneAlloc(Zone *zone, size_t sizeBytes) {
ZoneHeader *zone_header = (ZoneHeader *)zone - sizeof(ZoneHeader);
if (zone_header->cur_size + sizeBytes > zone_header->capacity) {
QERROR("Could not allocate, not enough space.");
return NULL;
}
void *new_mem = (char *)zone + zone_header->cur_size;
zone_header->cur_size += sizeBytes;
printf("Zone Header Information:\n");
printf("Current Size: %" PRIu64 "\n", zone_header->cur_size);
printf("Total Capacity: %" PRIu64 "\n", zone_header->capacity);
return new_mem;
}
void zoneFree(void *data, size_t dataSize) {
// TODO: We want to eventually pass in a pointer to the zone so we can track
// our free blocks
// Lets first check to make sure we weren't given a NULL pointer
if (data == NULL)
return;
// First we need to set the memory starting at `data` and going to `dataSize`
// to 0
memset(data, 0, dataSize);
// Now we need to null the pointer
data = NULL;
// TODO: Add logic to alert that this space can now be used
}
void zoneClear(Zone *zone) {
ZoneHeader *zone_header = (ZoneHeader *)zone - sizeof(ZoneHeader);
zone_header->cur_size = 0;
printf("Zone Header Information:\n");
printf("Current Size: %" PRIu64 "\n", zone_header->cur_size);
printf("Total Capacity: %" PRIu64 "\n", zone_header->capacity);
}
void zoneDestroy(Zone *zone) {
// First we need to go back to the beginning of the header as we returned
// an offset for the user to use
void *del_mem = (ZoneHeader *)zone - sizeof(ZoneHeader);
// Free the memory
free(del_mem);
}