Skip to content

Commit

Permalink
file: remove use of luaM_free
Browse files Browse the repository at this point in the history
  • Loading branch information
jpeletier committed Jan 28, 2019
1 parent e38fc7a commit d2106b7
Showing 1 changed file with 9 additions and 18 deletions.
27 changes: 9 additions & 18 deletions components/modules/file.c
Original file line number Diff line number Diff line change
Expand Up @@ -383,32 +383,27 @@ static int file_stat( lua_State* L )
// g_read()
static int file_g_read( lua_State* L, int n, int16_t end_char, int fd )
{
static char *heap_mem = NULL;
// free leftover memory
if (heap_mem) {
luaM_free(L, heap_mem);
heap_mem = NULL;
}
char *heap_mem = NULL;

if(n <= 0)
n = FILE_READ_CHUNK;

if(end_char < 0 || end_char >255)
end_char = EOF;


if(!fd)
return luaL_error(L, "open a file first");

char *p;
int i;
size_t alloc_size = n;

if (n > LUAL_BUFFERSIZE) {
// get buffer from heap
p = heap_mem = luaM_malloc(L, n);
p = heap_mem = luaM_malloc(L, alloc_size);
} else {
// small chunks go onto the stack
p = alloca(n);
p = alloca(alloc_size);
}

n = vfs_read(fd, p, n);
Expand All @@ -425,20 +420,16 @@ static int file_g_read( lua_State* L, int n, int16_t end_char, int fd )
}

if (i == 0 || n == VFS_RES_ERR) {
if (heap_mem) {
luaM_free(L, heap_mem);
heap_mem = NULL;
}
lua_pushnil(L);
return 1;
} else {
vfs_lseek(fd, -(n - i), VFS_SEEK_CUR);
lua_pushlstring(L, p, i);
}

vfs_lseek(fd, -(n - i), VFS_SEEK_CUR);
lua_pushlstring(L, p, i);
if (heap_mem) {
luaM_free(L, heap_mem);
heap_mem = NULL;
luaM_freearray(L, heap_mem, alloc_size, char);
}

return 1;
}

Expand Down

0 comments on commit d2106b7

Please sign in to comment.