104 lines
2.5 KiB
C
104 lines
2.5 KiB
C
/**
|
|
* Copyright (c) 2021 Dominic Msters
|
|
*
|
|
* This software is released under the MIT License.
|
|
* https://opensource.org/licenses/MIT
|
|
*/
|
|
|
|
#include "asset.h"
|
|
|
|
size_t assetRawLoad(char *assetName, uint8_t *buffer) {
|
|
assetbuffer_t *asset;
|
|
size_t length, read;
|
|
|
|
// Open a buffer.
|
|
asset = assetBufferOpen(assetName);
|
|
if(asset == NULL) return 0;
|
|
|
|
// Read the count of bytes in the file
|
|
assetBufferEnd(asset);
|
|
length = assetBufferGetCurrentPosition(asset);// Get our current position (the end)
|
|
|
|
// Are we only reading the size?
|
|
if(buffer == NULL) {
|
|
assetBufferClose(asset);
|
|
return length;
|
|
}
|
|
|
|
// Reset to start
|
|
assetBufferStart(asset);
|
|
|
|
// Read and seal the string.
|
|
read = assetBufferRead(asset, buffer, length);
|
|
assetBufferClose(asset); // Close the buffer.
|
|
|
|
// Did we read successfully?
|
|
if(read < length) return 0;
|
|
return read;
|
|
}
|
|
|
|
char * assetStringLoad(char *assetName) {
|
|
size_t length;
|
|
char *string;
|
|
|
|
length = assetRawLoad(assetName, NULL);
|
|
if(length == 0) return NULL;
|
|
|
|
string = malloc(length + 1);// +1 for null terminator
|
|
if(string == NULL) return NULL;
|
|
|
|
length = assetRawLoad(assetName, string);
|
|
if(length == 0) {
|
|
free(string);
|
|
return NULL;
|
|
}
|
|
|
|
string[length] = '\0';// Null terminate
|
|
return string;
|
|
}
|
|
|
|
assetbuffer_t * assetBufferOpen(char *assetName) {
|
|
// Get the directory based on the raw input by creating a new string.
|
|
FILE *fptr;
|
|
char filename[512];
|
|
|
|
// Prep filename
|
|
filename[0] = '\0';//Start at null
|
|
strcat(filename, ASSET_PREFIX);//Add prefix
|
|
strcat(filename, assetName);//Add body
|
|
|
|
printf("Opening up %s\n", filename);
|
|
|
|
// Open the file pointer now.
|
|
fptr = fopen(filename, "rb");
|
|
if(fptr == NULL) {
|
|
printf("Error opening %s: %s\n", filename, strerror(errno));
|
|
return NULL;// File available?
|
|
}
|
|
return (assetbuffer_t *)fptr;
|
|
}
|
|
|
|
bool assetBufferClose(assetbuffer_t *buffer) {
|
|
return fclose((FILE *)buffer);
|
|
}
|
|
|
|
int32_t assetBufferRead(assetbuffer_t *buffer, char *data, size_t size) {
|
|
return (int32_t)fread(data, 1, size, (FILE *)buffer);
|
|
}
|
|
|
|
int32_t assetBufferEnd(assetbuffer_t *buffer) {
|
|
// return feof((FILE *)buffer);
|
|
return fseek((FILE *)buffer, 0, SEEK_END);// Seek to the end
|
|
}
|
|
|
|
int32_t assetBufferStart(assetbuffer_t *buffer) {
|
|
return fseek((FILE *)buffer, 0, SEEK_SET);
|
|
}
|
|
|
|
int32_t assetBufferSkip(assetbuffer_t *buffer, long n) {
|
|
return fseek((FILE *)buffer, n, SEEK_CUR);
|
|
}
|
|
|
|
size_t assetBufferGetCurrentPosition(assetbuffer_t *buffer) {
|
|
return ftell((FILE *)buffer);
|
|
} |