CringeDB/File-Page Abstraction/cdb_file-page.c
2022-08-29 17:29:21 +02:00

95 lines
2.9 KiB
C

#include "cdb_file-page.h"
#include "../System Abstraction/cdb_sustem.h"
struct fp_File_impl{
sus_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
sus_File currentFile = sus_fileOpenInMem(fileName, SUS_FILE_NEW);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sus_heapAlloc(sizeof(struct fp_File_impl));
returnable->pageSize = pageSize;
returnable->file = currentFile;
//The new File will be initialized with one memroy Unit (Byte), so this code resizes it to the pageSize
if(sus_fileResize(returnable->file, pageSize - 1) == NULL){
sus_heapFree(returnable);
return NULL;
}
return returnable;
}
fp_File fp_fileTemp(char * fileName, unsigned long pageSize){
sus_File currentFile = sus_fileOpenInMem(fileName, SUS_FILE_TEMP);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sus_heapAlloc(sizeof(struct fp_File_impl));
returnable->pageSize = pageSize;
returnable->file = currentFile;
//The new File will be initialized with one memroy Unit (Byte), so this code resizes it to the pageSize
if(sus_fileResize(returnable->file, pageSize - 1) == NULL){
sus_heapFree(returnable);
return NULL;
}
return returnable;
}
fp_File fp_fileOpen(char * fileName){
sus_File currentFile = sus_fileOpenInMem(fileName, SUS_FILE_NOTHING);
if(currentFile == NULL){
return NULL;
}
fp_File returnable = sus_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 = sus_fileResize(file->file, file->pageSize * numberOfPages);
if(newMem == NULL) {
sus_fileClose(file->file);
file->file = NULL;
file->pageSize = 0;
return NULL;
}
return newMem;
}
void * fp_fileToMemroy(fp_File file){
return sus_fileFileToMemroy(file->file);
}
void fp_fileFlush(fp_File file) {
sus_fileFlush(file->file);
}
void fp_fileClose(fp_File file){
if(file->file != NULL) {
sus_fileClose(file->file);
}
sus_heapFree(file);
}