Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds an ability to use preallocated memory instead of file #28

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions gifdec.c
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,79 @@
#include <unistd.h>
#endif

#ifdef USE_ALLOCATED_SPACE
uint8_t *emu_memory;
size_t emu_offset;
size_t emu_size;

int emu_open(const char *path, int) {
emu_memory = NULL;
emu_offset = 0;
emu_size = 0;

FILE *f = fopen(path, "rb");
fseek(f, 0, SEEK_END);
emu_size = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */

emu_memory = (uint8_t *)malloc(emu_size + 1);
if(!emu_memory) {
return -1;
}

fread(emu_memory, emu_size, 1, f);
fclose(f);

return 1;
}

int emu_close(int) {
if(emu_memory) {
free(emu_memory);
}
return 0;
}

int emu_read(int, void *buffer, size_t len) {
if(!emu_memory) {
return -1;
}

size_t read_length = ((emu_size - 1) < emu_offset + len) ? emu_size - emu_offset : len;
memcpy(buffer, emu_memory + emu_offset, read_length);
emu_offset += read_length;
return read_length;
}

int emu_lseek(int, size_t value, int type) {
size_t last_offset = emu_offset;

switch(type) {
case SEEK_SET:
emu_offset = value;
break;
case SEEK_CUR:
emu_offset += value;
break;
case SEEK_END:
emu_offset = emu_size - 1;
break;
}

if(emu_offset >= emu_size) {
emu_offset = last_offset;
return -1;
}

return emu_offset;
}

#define read emu_read
#define lseek emu_lseek
#define open emu_open
#define close emu_close
#endif

#define MIN(A, B) ((A) < (B) ? (A) : (B))
#define MAX(A, B) ((A) > (B) ? (A) : (B))

Expand Down