CringeDB/File-Page Abstraction/cdb_file-page.c
2024-02-18 17:42:05 +01:00

95 lines
2.9 KiB
C

#include "cdb_file-page.h"
#include "../System Abstraction/cdb_sustem.h"
struct fp_File_impl{
sys_File file;
unsigned long pageSize;
};
//Creates a new file, opens it, and resizes it to the specified page size
fp_File fp_fileNew(char * fileName, unsigned long pageSize){ //there shouldn't be a page, longer than 4gb
sys_File currentFile = sys_fileOpenInMem(fileName, SYS_FILE_NEW);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sys_heapAlloc(sizeof(struct fp_File_impl));
returnable->pageSize = pageSize;
returnable->file = currentFile;
//The new File will be initialized with one memory Unit (Byte), so this code resizes it to the pageSize
if(sys_fileResize(returnable->file, pageSize - 1) == NULL){
sys_heapFree(returnable);
return NULL;
}
return returnable;
}
fp_File fp_fileTemp(char * fileName, unsigned long pageSize){
sys_File currentFile = sys_fileOpenInMem(fileName, SYS_FILE_TEMP);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sys_heapAlloc(sizeof(struct fp_File_impl));
returnable->pageSize = pageSize;
returnable->file = currentFile;
//The new File will be initialized with one memory Unit (Byte), so this code resizes it to the pageSize
if(sys_fileResize(returnable->file, pageSize - 1) == NULL){
sys_heapFree(returnable);
return NULL;
}
return returnable;
}
fp_File fp_fileOpen(char * fileName){
sys_File currentFile = sys_fileOpenInMem(fileName, SYS_FILE_NOTHING);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sys_heapAlloc(sizeof(struct fp_File_impl));
//returnable->pageSize = pageSize;
returnable->file = currentFile;
//since this function does not read the header, there is no way of knowing, what the page size is. Somebody else has to call the fp_fileInit function for this
return returnable;
}
//Since someone else has to read the header, this function sets the read page size after fp_fileOpen has been called
void fp_fileInit(fp_File file, unsigned long pageSize){
file->pageSize = pageSize;
}
//negative values indicate the removable of the latest pages; so this library doesn't need more functions
void * fp_fileAppendPages(fp_File file, long numberOfPages){
void *newMem = sys_fileResize(file->file, file->pageSize * numberOfPages);
if(newMem == NULL) {
sys_fileClose(file->file);
file->file = NULL;
file->pageSize = 0;
return NULL;
}
return newMem;
}
void * fp_fileToMemory(fp_File file){
return sys_fileFileToMemory(file->file);
}
void fp_fileFlush(fp_File file) {
sys_fileFlush(file->file);
}
void fp_fileClose(fp_File file){
if(file->file != NULL) {
sys_fileClose(file->file);
}
sys_heapFree(file);
}