Skip to content

Commit 06bf998

Browse files
author
Evan Klitzke
committed
properly check if the file is closed when calling the read method
1 parent 3d14be5 commit 06bf998

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

lbz.c

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,13 @@
55
#include <lauxlib.h>
66
#include <lualib.h>
77

8+
#define LBZ_EOS 0x01 /* end of stream */
9+
#define LBZ_CLOSED 0x02 /* the file is closed */
10+
811
typedef struct {
912
BZFILE *bz_stream;
1013
FILE *f;
11-
int end_of_stream;
14+
int flags;
1215
} lbz_state;
1316

1417
/* Binding to libbzip2's BZ2_bzReadOpen method */
@@ -23,7 +26,7 @@ int lbz_read_open(lua_State *L) {
2326
lbz_state *state = (lbz_state *) lua_newuserdata(L, sizeof(lbz_state));
2427
state->bz_stream = BZ2_bzReadOpen(&bzerror, f, 0, 0, NULL, 0);
2528
state->f = f;
26-
state->end_of_stream = 0;
29+
state->flags = 0;
2730

2831
if (bzerror != BZ_OK)
2932
lua_pushnil(L);
@@ -37,7 +40,7 @@ int lbz_read(lua_State *L) {
3740
lbz_state *state = (lbz_state *) lua_touserdata(L, 1);
3841
len = luaL_checkint(L, 2);
3942

40-
if (state->end_of_stream) {
43+
if (state->flags & (LBZ_EOS | LBZ_CLOSED)) {
4144
/* The logical end of file has been reached -- there's no more data to
4245
* return, and the user should call the read_close method. */
4346
lua_pushnil(L);
@@ -56,7 +59,7 @@ int lbz_read(lua_State *L) {
5659
}
5760

5861
if (bzerror == BZ_STREAM_END)
59-
state->end_of_stream = 1;
62+
state->flags |= LBZ_EOS;
6063

6164
luaL_addlstring(&b, buf, ret);
6265
luaL_pushresult(&b);
@@ -69,6 +72,7 @@ static int lbz_read_close(lua_State *L) {
6972
lbz_state *state = (lbz_state *) lua_touserdata(L, 1);
7073
BZ2_bzReadClose(&bzerror, state->bz_stream);
7174
fclose(state->f);
75+
state->flags |= LBZ_CLOSED;
7276
lua_pushnil(L);
7377
return 1;
7478
}

test.lua

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ require("bz2")
33
-- read in a file and display the uncompressed data to stdout (i.e. this
44
-- behaves identically to bzcat)
55
b = bz2.read_open("access_log.bz2")
6-
text = bz2.read(b, 1024)
6+
function read_chunk() return bz2.read(b, 1024) end
7+
text = read_chunk()
78
while text ~= nil do
89
io.write(text)
9-
text = bz2.read(b, 1024)
10+
text = read_chunk()
1011
end
1112
bz2.read_close(b)

0 commit comments

Comments
 (0)