Skip to content

Commit eb188ee

Browse files
committed
bugfix: call lua_tolstring for bson dict key
1 parent 2166ce3 commit eb188ee

File tree

1 file changed

+31
-17
lines changed

1 file changed

+31
-17
lines changed

lualib-src/lua-bson.c

+31-17
Original file line numberDiff line numberDiff line change
@@ -404,40 +404,54 @@ append_one(struct bson *bs, lua_State *L, const char *key, size_t sz) {
404404
}
405405

406406
static inline int
407-
bson_numstr( char *str, int i ) {
407+
bson_numstr( char *str, unsigned int i ) {
408408
if ( i < MAX_NUMBER) {
409409
memcpy( str, bson_numstrs[i], 4 );
410410
return bson_numstr_len[i];
411411
} else {
412-
return sprintf( str,"%d", i );
412+
return sprintf( str,"%u", i );
413413
}
414414
}
415415

416416
static void
417417
pack_dict(lua_State *L, struct bson *b, bool isarray) {
418-
int arraydec = isarray ? 1 : 0;
419418
int length = reserve_length(b);
420419
lua_pushnil(L);
421420
while(lua_next(L,-2) != 0) {
422421
int kt = lua_type(L, -2);
423422
char numberkey[8];
424423
const char * key = NULL;
425424
size_t sz;
426-
switch(kt) {
427-
case LUA_TNUMBER:
428-
sz = bson_numstr(numberkey, lua_tointeger(L,-2)-arraydec);
429-
key = numberkey;
430-
break;
431-
case LUA_TSTRING:
432-
key = lua_tolstring(L,-2,&sz);
433-
break;
434-
default:
435-
luaL_error(L, "Invalid key type : %s", lua_typename(L, kt));
436-
return;
437-
}
425+
if (isarray) {
426+
if (kt != LUA_TNUMBER) {
427+
luaL_error(L, "Invalid array key type : %s", lua_typename(L, kt));
428+
return;
429+
}
430+
sz = bson_numstr(numberkey, lua_tounsigned(L,-2)-1);
431+
key = numberkey;
438432

439-
append_one(b, L, key, sz);
440-
lua_pop(L,1);
433+
append_one(b, L, key, sz);
434+
lua_pop(L,1);
435+
} else {
436+
switch(kt) {
437+
case LUA_TNUMBER:
438+
// copy key, don't change key type
439+
lua_pushvalue(L,-2);
440+
lua_insert(L,-2);
441+
key = lua_tolstring(L,-2,&sz);
442+
append_one(b, L, key, sz);
443+
lua_pop(L,2);
444+
break;
445+
case LUA_TSTRING:
446+
key = lua_tolstring(L,-2,&sz);
447+
append_one(b, L, key, sz);
448+
lua_pop(L,1);
449+
break;
450+
default:
451+
luaL_error(L, "Invalid key type : %s", lua_typename(L, kt));
452+
return;
453+
}
454+
}
441455
}
442456
write_byte(b,0);
443457
write_length(b, b->size - length, length);

0 commit comments

Comments
 (0)