@@ -404,40 +404,54 @@ append_one(struct bson *bs, lua_State *L, const char *key, size_t sz) {
404
404
}
405
405
406
406
static inline int
407
- bson_numstr ( char * str , int i ) {
407
+ bson_numstr ( char * str , unsigned int i ) {
408
408
if ( i < MAX_NUMBER ) {
409
409
memcpy ( str , bson_numstrs [i ], 4 );
410
410
return bson_numstr_len [i ];
411
411
} else {
412
- return sprintf ( str ,"%d " , i );
412
+ return sprintf ( str ,"%u " , i );
413
413
}
414
414
}
415
415
416
416
static void
417
417
pack_dict (lua_State * L , struct bson * b , bool isarray ) {
418
- int arraydec = isarray ? 1 : 0 ;
419
418
int length = reserve_length (b );
420
419
lua_pushnil (L );
421
420
while (lua_next (L ,-2 ) != 0 ) {
422
421
int kt = lua_type (L , -2 );
423
422
char numberkey [8 ];
424
423
const char * key = NULL ;
425
424
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 ;
438
432
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
+ }
441
455
}
442
456
write_byte (b ,0 );
443
457
write_length (b , b -> size - length , length );
0 commit comments