-
Notifications
You must be signed in to change notification settings - Fork 388
/
pb.c
2202 lines (2000 loc) · 69.2 KB
/
pb.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef _MSC_VER
# define _CRT_SECURE_NO_WARNINGS
# define _CRT_NONSTDC_NO_WARNINGS
# pragma warning(disable: 4244) /* int -> char */
# pragma warning(disable: 4706) /* = in if condition */
# pragma warning(disable: 4709) /* comma in array index */
# pragma warning(disable: 4127) /* const in if condition */
#endif
#define PB_STATIC_API
#include "pb.h"
PB_NS_BEGIN
#define LUA_LIB
#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
#include <errno.h>
/* Lua util routines */
#define PB_STATE "pb.State"
#define PB_BUFFER "pb.Buffer"
#define PB_SLICE "pb.Slice"
#define check_buffer(L,idx) ((pb_Buffer*)luaL_checkudata(L,idx,PB_BUFFER))
#define test_buffer(L,idx) ((pb_Buffer*)luaL_testudata(L,idx,PB_BUFFER))
#define check_slice(L,idx) ((pb_Slice*)luaL_checkudata(L,idx,PB_SLICE))
#define test_slice(L,idx) ((pb_Slice*)luaL_testudata(L,idx,PB_SLICE))
#define push_slice(L,s) lua_pushlstring((L), (s).p, pb_len((s)))
#define lpb_returnself(L) { return lua_settop(L, 1), 1; }
static int lpb_relindex(int idx, int offset) {
return idx < 0 && idx > LUA_REGISTRYINDEX ? idx - offset : idx;
}
static size_t lpb_checkmem(lua_State *L, size_t ret)
{ return ret ? ret : (size_t)luaL_error(L, "out of memory"); }
#if LUA_VERSION_NUM < 502
#include <assert.h>
# define LUA_OK 0
# define lua_rawlen lua_objlen
# define luaL_setfuncs(L,l,n) (assert(n==0), luaL_register(L,NULL,l))
# define luaL_setmetatable(L, name) \
(luaL_getmetatable((L), (name)), lua_setmetatable(L, -2))
static void lua_rawgetp(lua_State *L, int idx, const void *p) {
lua_pushlightuserdata(L, (void*)p);
lua_rawget(L, lpb_relindex(idx, 1));
}
static void lua_rawsetp(lua_State *L, int idx, const void *p) {
lua_pushlightuserdata(L, (void*)p);
lua_insert(L, -2);
lua_rawset(L, lpb_relindex(idx, 1));
}
#ifndef LUA_GCISRUNNING /* not LuaJIT 2.1 */
#define luaL_newlib(L,l) (lua_newtable(L), luaL_register(L,NULL,l))
static lua_Integer lua_tointegerx(lua_State *L, int idx, int *isint) {
lua_Integer i = lua_tointeger(L, idx);
if (isint) *isint = (i != 0 || lua_type(L, idx) == LUA_TNUMBER);
return i;
}
static lua_Number lua_tonumberx(lua_State *L, int idx, int *isnum) {
lua_Number i = lua_tonumber(L, idx);
if (isnum) *isnum = (i != 0 || lua_type(L, idx) == LUA_TNUMBER);
return i;
}
static void *luaL_testudata(lua_State *L, int idx, const char *type) {
void *p = lua_touserdata(L, idx);
if (p != NULL && lua_getmetatable(L, idx)) {
lua_getfield(L, LUA_REGISTRYINDEX, type);
if (!lua_rawequal(L, -2, -1))
p = NULL;
lua_pop(L, 2);
return p;
}
return NULL;
}
#endif
#ifdef LUAI_BITSINT /* not LuaJIT */
#include <errno.h>
static int luaL_fileresult(lua_State *L, int stat, const char *fname) {
int en = errno;
if (stat) return lua_pushboolean(L, 1), 1;
lua_pushnil(L);
lua_pushfstring(L, "%s: %s", fname, strerror(en));
/*if (fname) lua_pushfstring(L, "%s: %s", fname, strerror(en));
else lua_pushstring(L, strerror(en));*//* NOT USED */
lua_pushinteger(L, en);
return 3;
}
#endif /* not LuaJIT */
#endif
#if LUA_VERSION_NUM >= 503
# define lua53_getfield lua_getfield
# define lua53_rawgeti lua_rawgeti
# define lua53_rawgetp lua_rawgetp
#else /* not Lua 5.3 */
static int lua53_getfield(lua_State *L, int idx, const char *field)
{ return lua_getfield(L, idx, field), lua_type(L, -1); }
static int lua53_rawgeti(lua_State *L, int idx, lua_Integer i)
{ return lua_rawgeti(L, idx, i), lua_type(L, -1); }
static int lua53_rawgetp(lua_State *L, int idx, const void *p)
{ return lua_rawgetp(L, idx, p), lua_type(L, -1); }
#endif
/* protobuf global state */
#define lpbS_state(LS) ((LS)->state)
#define lpb_name(LS,s) pb_name(lpbS_state(LS), (s), &(LS)->cache)
static const pb_State *global_state = NULL;
static const char state_name[] = PB_STATE;
enum lpb_Int64Mode { LPB_NUMBER, LPB_STRING, LPB_HEXSTRING };
enum lpb_EncodeMode { LPB_DEFDEF, LPB_COPYDEF, LPB_METADEF, LPB_NODEF };
typedef struct lpb_State {
const pb_State *state;
pb_State local;
pb_Cache cache;
pb_Buffer buffer;
pb_Type array_type;
pb_Type map_type;
int defs_index;
int enc_hooks_index;
int dec_hooks_index;
unsigned use_dec_hooks : 1;
unsigned use_enc_hooks : 1;
unsigned enum_as_value : 1;
unsigned encode_mode : 2; /* lpb_EncodeMode */
unsigned int64_mode : 2; /* lpb_Int64Mode */
unsigned encode_default_values : 1;
unsigned decode_default_array : 1;
unsigned decode_default_message : 1;
unsigned encode_order : 1;
} lpb_State;
static int lpb_reftable(lua_State *L, int ref) {
if (ref != LUA_NOREF) {
lua_rawgeti(L, LUA_REGISTRYINDEX, ref);
return ref;
} else {
lua_newtable(L);
lua_pushvalue(L, -1);
return luaL_ref(L, LUA_REGISTRYINDEX);
}
}
static void lpb_pushdeftable(lua_State *L, lpb_State *LS)
{ LS->defs_index = lpb_reftable(L, LS->defs_index); }
static void lpb_pushenchooktable(lua_State *L, lpb_State *LS)
{ LS->enc_hooks_index = lpb_reftable(L, LS->enc_hooks_index); }
static void lpb_pushdechooktable(lua_State *L, lpb_State *LS)
{ LS->dec_hooks_index = lpb_reftable(L, LS->dec_hooks_index); }
static int Lpb_delete(lua_State *L) {
lpb_State *LS = (lpb_State*)luaL_testudata(L, 1, PB_STATE);
if (LS != NULL) {
const pb_State *GS = global_state;
pb_free(&LS->local);
if (&LS->local == GS)
global_state = NULL;
LS->state = NULL;
pb_resetbuffer(&LS->buffer);
luaL_unref(L, LUA_REGISTRYINDEX, LS->defs_index);
luaL_unref(L, LUA_REGISTRYINDEX, LS->enc_hooks_index);
luaL_unref(L, LUA_REGISTRYINDEX, LS->dec_hooks_index);
}
return 0;
}
LUALIB_API lpb_State *lpb_lstate(lua_State *L) {
lpb_State *LS;
if (lua53_rawgetp(L, LUA_REGISTRYINDEX, state_name) == LUA_TUSERDATA) {
LS = (lpb_State*)lua_touserdata(L, -1);
lua_pop(L, 1);
} else {
lua_pop(L, 1);
LS = (lpb_State*)lua_newuserdata(L, sizeof(lpb_State));
memset(LS, 0, sizeof(lpb_State));
LS->array_type.is_dead = LS->map_type.is_dead = 1;
LS->defs_index = LUA_NOREF;
LS->enc_hooks_index = LUA_NOREF;
LS->dec_hooks_index = LUA_NOREF;
LS->state = &LS->local;
pb_init(&LS->local);
pb_initbuffer(&LS->buffer);
luaL_setmetatable(L, PB_STATE);
lua_rawsetp(L, LUA_REGISTRYINDEX, state_name);
}
return LS;
}
static int Lpb_state(lua_State *L) {
int top = lua_gettop(L);
lpb_lstate(L);
lua_rawgetp(L, LUA_REGISTRYINDEX, state_name);
if (top != 0) {
if (lua_isnil(L, 1))
lua_pushnil(L);
else {
luaL_checkudata(L, 1, PB_STATE);
lua_pushvalue(L, 1);
}
lua_rawsetp(L, LUA_REGISTRYINDEX, state_name);
}
return 1;
}
/* protobuf util routines */
static size_t lpb_addlength(lua_State *L, pb_Buffer *b, size_t len, size_t prealloc) {
size_t wlen = pb_addlength(b, len, prealloc);
return wlen ? wlen : (size_t)luaL_error(L, "encode bytes fail");
}
static int lpb_typeerror(lua_State *L, int idx, const char *type) {
lua_pushfstring(L, "%s expected, got %s", type, luaL_typename(L, idx));
return luaL_argerror(L, idx, lua_tostring(L, -1));
}
static lua_Integer lpb_posrelat(lua_Integer pos, size_t len) {
if (pos >= 0) return pos;
else if (0u - (size_t)pos > len) return 0;
else return (lua_Integer)len + pos + 1;
}
static lua_Integer rangerelat(lua_State *L, int idx, lua_Integer r[2], size_t len) {
r[0] = lpb_posrelat(luaL_optinteger(L, idx, 1), len);
r[1] = lpb_posrelat(luaL_optinteger(L, idx+1, len), len);
if (r[0] < 1) r[0] = 1;
if (r[1] > (lua_Integer)len) r[1] = len;
return r[0] <= r[1] ? r[1] - r[0] + 1 : 0;
}
static int argcheck(lua_State *L, int cond, int idx, const char *fmt, ...) {
if (!cond) {
va_list l;
va_start(l, fmt);
lua_pushvfstring(L, fmt, l);
va_end(l);
return luaL_argerror(L, idx, lua_tostring(L, -1));
}
return 1;
}
static pb_Slice lpb_toslice(lua_State *L, int idx) {
int type = lua_type(L, idx);
if (type == LUA_TSTRING) {
size_t len;
const char *s = lua_tolstring(L, idx, &len);
return pb_lslice(s, len);
} else if (type == LUA_TUSERDATA) {
pb_Buffer *buffer;
pb_Slice *s;
if ((buffer = test_buffer(L, idx)) != NULL)
return pb_result(buffer);
else if ((s = test_slice(L, idx)) != NULL)
return *s;
}
return pb_slice(NULL);
}
LUALIB_API pb_Slice lpb_checkslice(lua_State *L, int idx) {
pb_Slice ret = lpb_toslice(L, idx);
if (ret.p == NULL) lpb_typeerror(L, idx, "string/buffer/slice");
return ret;
}
static void lpb_readbytes(lua_State *L, pb_Slice *s, pb_Slice *pv) {
uint64_t len = 0;
if (pb_readvarint64(s, &len) == 0 || len > PB_MAX_SIZET)
luaL_error(L, "invalid bytes length: %d (at offset %d)",
(int)len, pb_pos(*s)+1);
if (pb_readslice(s, (size_t)len, pv) == 0 && len != 0)
luaL_error(L, "unfinished bytes (len %d at offset %d)",
(int)len, pb_pos(*s)+1);
}
static int lpb_hexchar(char ch) {
switch (ch) {
case '0': return 0;
case '1': return 1; case '2': return 2; case '3': return 3;
case '4': return 4; case '5': return 5; case '6': return 6;
case '7': return 7; case '8': return 8; case '9': return 9;
case 'a': case 'A': return 10; case 'b': case 'B': return 11;
case 'c': case 'C': return 12; case 'd': case 'D': return 13;
case 'e': case 'E': return 14; case 'f': case 'F': return 15;
}
return -1;
}
static uint64_t lpb_tointegerx(lua_State *L, int idx, int *isint) {
int neg = 0;
const char *s, *os;
#if LUA_VERSION_NUM >= 503
uint64_t v = (uint64_t)lua_tointegerx(L, idx, isint);
if (*isint) return v;
#else
uint64_t v = 0;
lua_Number nv = lua_tonumberx(L, idx, isint);
if (*isint) {
if (nv < (lua_Number)INT64_MIN || nv > (lua_Number)INT64_MAX)
luaL_error(L, "number has no integer representation");
return (uint64_t)(int64_t)nv;
}
#endif
if ((os = s = lua_tostring(L, idx)) == NULL) return 0;
while (*s == '#' || *s == '+' || *s == '-')
neg = (*s == '-') ^ neg, ++s;
if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
for (s += 2; *s != '\0'; ++s) {
int n = lpb_hexchar(*s);
if (n < 0) break;
v = v << 4 | n;
}
} else {
for (; *s != '\0'; ++s) {
int n = lpb_hexchar(*s);
if (n < 0 || n > 9) break;
v = v * 10 + n;
}
}
if (!(*isint = *s == '\0')) return 0;
return neg ? ~v + 1 : v;
}
static uint64_t lpb_checkinteger(lua_State *L, int idx) {
int isint;
uint64_t v = lpb_tointegerx(L, idx, &isint);
if (!isint) {
if (lua_type(L, idx) == LUA_TSTRING)
luaL_error(L, "integer format error: '%s'", lua_tostring(L, idx));
lpb_typeerror(L, idx, "number/string");
}
return v;
}
static void lpb_pushinteger(lua_State *L, int64_t n, int u, int mode) {
if (mode != LPB_NUMBER && ((u && n < 0) || n < INT_MIN || n > UINT_MAX)) {
char buff[32], *p = buff + sizeof(buff) - 1;
int neg = !u && n < 0;
uint64_t un = !u && neg ? ~(uint64_t)n + 1 : (uint64_t)n;
if (mode == LPB_STRING) {
for (*p = '\0'; un > 0; un /= 10)
*--p = "0123456789"[un % 10];
} else if (mode == LPB_HEXSTRING) {
for (*p = '\0'; un > 0; un >>= 4)
*--p = "0123456789ABCDEF"[un & 0xF];
*--p = 'x', *--p = '0';
}
if (neg) *--p = '-';
*--p = '#';
lua_pushstring(L, p);
} else if (LUA_VERSION_NUM >= 503 && sizeof(lua_Integer) >= 8)
lua_pushinteger(L, (lua_Integer)n);
else
lua_pushnumber(L, (lua_Number)n);
}
typedef union lpb_Value {
pb_Slice s[1];
uint32_t u32;
uint64_t u64;
lua_Integer lint;
lua_Number lnum;
} lpb_Value;
static const char *lpb_expected(int type) {
switch (type) {
case PB_Tbool: case PB_Tdouble: case PB_Tfloat:
case PB_Tfixed32: case PB_Tsfixed32: case PB_Tint32:
case PB_Tuint32: case PB_Tsint32: case PB_Tfixed64:
case PB_Tsfixed64: case PB_Tint64: case PB_Tuint64:
case PB_Tsint64: case PB_Tenum:
return "number/'#number'";
case PB_Tbytes: case PB_Tstring: case PB_Tmessage:
return "string";
}
return "unknown";
}
static size_t lpb_addtype(lua_State *L, pb_Buffer *b, int idx, int type, int *pexist) {
int ret = 0, has_data = 1;
lpb_Value v;
size_t len = 0;
switch (type) {
case PB_Tbool:
v.u32 = lua_toboolean(L, idx);
len = pb_addvarint32(b, v.u32);
ret = 1;
if (v.u32 == 0) has_data = 0;
break;
case PB_Tdouble:
v.lnum = lua_tonumberx(L, idx, &ret);
if (ret) len = pb_addfixed64(b, pb_encode_double((double)v.lnum));
if (v.lnum == 0.0) has_data = 0;
break;
case PB_Tfloat:
v.lnum = lua_tonumberx(L, idx, &ret);
if (ret) len = pb_addfixed32(b, pb_encode_float((float)v.lnum));
if (v.lnum == 0.0) has_data = 0;
break;
case PB_Tfixed32:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addfixed32(b, v.u32);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tsfixed32:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addfixed32(b, v.u32);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tint32:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addvarint64(b, pb_expandsig((uint32_t)v.u64));
if (v.u64 == 0) has_data = 0;
break;
case PB_Tuint32:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addvarint32(b, v.u32);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tsint32:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addvarint32(b, pb_encode_sint32(v.u32));
if (v.u64 == 0) has_data = 0;
break;
case PB_Tfixed64:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addfixed64(b, v.u64);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tsfixed64:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addfixed64(b, v.u64);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tint64: case PB_Tuint64:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addvarint64(b, v.u64);
if (v.u64 == 0) has_data = 0;
break;
case PB_Tsint64:
v.u64 = lpb_tointegerx(L, idx, &ret);
if (ret) len = pb_addvarint64(b, pb_encode_sint64(v.u64));
if (v.u64 == 0) has_data = 0;
break;
case PB_Tbytes: case PB_Tstring:
*v.s = lpb_toslice(L, idx);
if ((ret = (v.s->p != NULL))) len = pb_addbytes(b, *v.s);
if (pb_len(*v.s) == 0) has_data = 0;
break;
default:
lua_pushfstring(L, "unknown type %s", pb_typename(type, "<unknown>"));
if (idx > 0) luaL_argerror(L, idx, lua_tostring(L, -1));
lua_error(L);
}
if (pexist) *pexist = (ret && has_data);
return ret ? lpb_checkmem(L, len) : 0;
}
static void lpb_readtype(lua_State *L, lpb_State *LS, int type, pb_Slice *s) {
lpb_Value v;
switch (type) {
#define pushinteger(n,u) lpb_pushinteger((L), (n), (u), LS->int64_mode)
case PB_Tbool: case PB_Tenum:
case PB_Tint32: case PB_Tuint32: case PB_Tsint32:
case PB_Tint64: case PB_Tuint64: case PB_Tsint64:
if (pb_readvarint64(s, &v.u64) == 0)
luaL_error(L, "invalid varint value at offset %d", pb_pos(*s)+1);
switch (type) {
case PB_Tbool: lua_pushboolean(L, v.u64 != 0); break;
/*case PB_Tenum: pushinteger(v.u64); break; [> NOT REACHED <]*/
case PB_Tint32: pushinteger((int32_t)v.u64, 0); break;
case PB_Tuint32: pushinteger((uint32_t)v.u64, 1); break;
case PB_Tsint32: pushinteger(pb_decode_sint32((uint32_t)v.u64), 0); break;
case PB_Tint64: pushinteger((int64_t)v.u64, 0); break;
case PB_Tuint64: pushinteger((uint64_t)v.u64, 1); break;
case PB_Tsint64: pushinteger(pb_decode_sint64(v.u64), 0); break;
}
break;
case PB_Tfloat:
case PB_Tfixed32:
case PB_Tsfixed32:
if (pb_readfixed32(s, &v.u32) == 0)
luaL_error(L, "invalid fixed32 value at offset %d", pb_pos(*s)+1);
switch (type) {
case PB_Tfloat: lua_pushnumber(L, pb_decode_float(v.u32)); break;
case PB_Tfixed32: pushinteger(v.u32, 1); break;
case PB_Tsfixed32: pushinteger((int32_t)v.u32, 0); break;
}
break;
case PB_Tdouble:
case PB_Tfixed64:
case PB_Tsfixed64:
if (pb_readfixed64(s, &v.u64) == 0)
luaL_error(L, "invalid fixed64 value at offset %d", pb_pos(*s)+1);
switch (type) {
case PB_Tdouble: lua_pushnumber(L, pb_decode_double(v.u64)); break;
case PB_Tfixed64: pushinteger(v.u64, 1); break;
case PB_Tsfixed64: pushinteger((int64_t)v.u64, 0); break;
}
break;
case PB_Tbytes:
case PB_Tstring:
case PB_Tmessage:
lpb_readbytes(L, s, v.s);
push_slice(L, *v.s);
break;
default:
luaL_error(L, "unknown type %s (%d)", pb_typename(type, NULL), type);
}
}
/* io routines */
#ifdef _WIN32
# include <io.h>
# include <fcntl.h>
#else
# define setmode(a,b) ((void)0)
#endif
static int lpbF_read(lua_State *L) {
FILE *fp = (FILE*)lua_touserdata(L, 1);
size_t nr;
luaL_Buffer b;
luaL_buffinit(L, &b);
do { /* read file in chunks of LUAL_BUFFERSIZE bytes */
char *p = luaL_prepbuffer(&b);
nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, fp);
luaL_addsize(&b, nr);
} while (nr == LUAL_BUFFERSIZE);
luaL_pushresult(&b); /* close buffer */
return 1;
}
static int lpbF_write(lua_State *L, FILE *f, int idx) {
int nargs = lua_gettop(L) - idx + 1;
int status = 1;
for (; nargs--; idx++) {
pb_Slice s = lpb_checkslice(L, idx);
size_t l = pb_len(s);
status = status && (fwrite(s.p, sizeof(char), l, f) == l);
}
return status ? 1 : luaL_fileresult(L, 0, NULL);
}
static int Lio_read(lua_State *L) {
const char *fname = luaL_optstring(L, 1, NULL);
FILE *fp = stdin;
int ret;
if (fname == NULL)
(void)setmode(fileno(stdin), O_BINARY);
else if ((fp = fopen(fname, "rb")) == NULL)
return luaL_fileresult(L, 0, fname);
lua_pushcfunction(L, lpbF_read);
lua_pushlightuserdata(L, fp);
ret = lua_pcall(L, 1, 1, 0);
if (fp != stdin) fclose(fp);
else (void)setmode(fileno(stdin), O_TEXT);
if (ret != LUA_OK) { lua_pushnil(L); lua_insert(L, -2); return 2; }
return 1;
}
static int Lio_write(lua_State *L) {
int res;
(void)setmode(fileno(stdout), O_BINARY);
res = lpbF_write(L, stdout, 1);
fflush(stdout);
(void)setmode(fileno(stdout), O_TEXT);
return res;
}
static int Lio_dump(lua_State *L) {
int res;
const char *fname = luaL_checkstring(L, 1);
FILE *fp = fopen(fname, "wb");
if (fp == NULL) return luaL_fileresult(L, 0, fname);
res = lpbF_write(L, fp, 2);
fclose(fp);
return res;
}
LUALIB_API int luaopen_pb_io(lua_State *L) {
luaL_Reg libs[] = {
#define ENTRY(name) { #name, Lio_##name }
ENTRY(read),
ENTRY(write),
ENTRY(dump),
#undef ENTRY
{ NULL, NULL }
};
luaL_newlib(L, libs);
return 1;
}
/* protobuf integer conversion */
static int Lconv_encode_int32(lua_State *L) {
uint64_t v = pb_expandsig((int32_t)lpb_checkinteger(L, 1));
return lpb_pushinteger(L, v, 1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_encode_uint32(lua_State *L) {
return lpb_pushinteger(L, (uint32_t)lpb_checkinteger(L, 1),
1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_encode_sint32(lua_State *L) {
return lpb_pushinteger(L, pb_encode_sint32((int32_t)lpb_checkinteger(L, 1)),
1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_decode_sint32(lua_State *L) {
return lpb_pushinteger(L, pb_decode_sint32((uint32_t)lpb_checkinteger(L, 1)),
0, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_encode_sint64(lua_State *L) {
return lpb_pushinteger(L, pb_encode_sint64(lpb_checkinteger(L, 1)),
1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_decode_sint64(lua_State *L) {
return lpb_pushinteger(L, pb_decode_sint64(lpb_checkinteger(L, 1)),
0, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_encode_float(lua_State *L) {
return lpb_pushinteger(L, pb_encode_float((float)luaL_checknumber(L, 1)),
1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_decode_float(lua_State *L) {
return lua_pushnumber(L,
pb_decode_float((uint32_t)lpb_checkinteger(L, 1))), 1;
}
static int Lconv_encode_double(lua_State *L) {
return lpb_pushinteger(L, pb_encode_double(luaL_checknumber(L, 1)),
1, lpb_lstate(L)->int64_mode), 1;
}
static int Lconv_decode_double(lua_State *L) {
return lua_pushnumber(L, pb_decode_double(lpb_checkinteger(L, 1))), 1;
}
LUALIB_API int luaopen_pb_conv(lua_State *L) {
luaL_Reg libs[] = {
{ "decode_uint32", Lconv_encode_uint32 },
{ "decode_int32", Lconv_encode_int32 },
#define ENTRY(name) { #name, Lconv_##name }
ENTRY(encode_int32),
ENTRY(encode_uint32),
ENTRY(encode_sint32),
ENTRY(encode_sint64),
ENTRY(decode_sint32),
ENTRY(decode_sint64),
ENTRY(decode_float),
ENTRY(decode_double),
ENTRY(encode_float),
ENTRY(encode_double),
#undef ENTRY
{ NULL, NULL }
};
luaL_newlib(L, libs);
return 1;
}
/* protobuf encode routine */
static int lpb_typefmt(int fmt) {
switch (fmt) {
#define X(name,type,fmt) case fmt: return PB_T##name;
PB_TYPES(X)
#undef X
}
return -1;
}
static int lpb_packfmt(lua_State *L, int idx, pb_Buffer *b, const char **pfmt, int level) {
const char *fmt = *pfmt;
size_t len;
int type;
luaL_argcheck(L, level <= 100, 1, "format level overflow");
for (; *fmt != '\0'; ++fmt) {
switch (*fmt) {
case '#':
len = lpb_addlength(L, b, (size_t)lpb_checkinteger(L, idx++), 0);
break;
case 'v':
len = pb_addvarint64(b, (uint64_t)lpb_checkinteger(L, idx++));
break;
case 'd':
len = pb_addfixed32(b, (uint32_t)lpb_checkinteger(L, idx++));
break;
case 'q':
len = pb_addfixed64(b, (uint64_t)lpb_checkinteger(L, idx++));
break;
case 'c': len = pb_addslice(b, lpb_checkslice(L, idx++)); break;
case 's': len = pb_addbytes(b, lpb_checkslice(L, idx++)); break;
case '(':
if ((len = pb_addvarint32(b, 0)) == 0) break;
len = pb_bufflen(b);
++fmt;
idx = lpb_packfmt(L, idx, b, &fmt, level+1);
len = lpb_addlength(L, b, len, 1);
break;
case ')':
if (level == 0) luaL_argerror(L, 1, "unexpected ')' in format");
*pfmt = fmt;
return idx;
case '\0':
default:
argcheck(L, (type = lpb_typefmt(*fmt)) >= 0,
1, "invalid formater: '%c'", *fmt);
len = lpb_addtype(L, b, idx, type, NULL);
argcheck(L, len > 0, idx, "%s expected for type '%s', got %s",
lpb_expected(type), pb_typename(type, "<unknown>"),
luaL_typename(L, idx));
++idx;
continue;
}
lpb_checkmem(L, len);
}
if (level != 0) luaL_argerror(L, 2, "unmatch '(' in format");
*pfmt = fmt;
return idx;
}
static int Lpb_tohex(lua_State *L) {
pb_Slice s = lpb_checkslice(L, 1);
const char *hexa = "0123456789ABCDEF";
char hex[4] = "XX ";
lua_Integer r[2] = { 1, -1 };
luaL_Buffer lb;
rangerelat(L, 2, r, pb_len(s));
luaL_buffinit(L, &lb);
for (; r[0] <= r[1]; ++r[0]) {
unsigned int ch = s.p[r[0]-1];
hex[0] = hexa[(ch>>4)&0xF];
hex[1] = hexa[(ch )&0xF];
if (r[0] == r[1]) hex[2] = '\0';
luaL_addstring(&lb, hex);
}
luaL_pushresult(&lb);
return 1;
}
static int Lpb_fromhex(lua_State *L) {
pb_Slice s = lpb_checkslice(L, 1);
lua_Integer r[2] = { 1, -1 };
luaL_Buffer lb;
int curr = 0, idx = 0, num;
rangerelat(L, 2, r, pb_len(s));
luaL_buffinit(L, &lb);
for (; r[0] <= r[1]; ++r[0]) {
switch (num = s.p[r[0]-1]) {
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
case '8': case '9': num -= '0'; break;
case 'A': case 'a': num = 10; break;
case 'B': case 'b': num = 11; break;
case 'C': case 'c': num = 12; break;
case 'D': case 'd': num = 13; break;
case 'E': case 'e': num = 14; break;
case 'F': case 'f': num = 15; break;
default: continue;
}
curr = curr<<4 | num;
if (++idx % 2 == 0) luaL_addchar(&lb, curr), curr = 0;
}
luaL_pushresult(&lb);
return 1;
}
static int Lpb_result(lua_State *L) {
pb_Slice s = lpb_checkslice(L, 1);
lua_Integer r[2] = {1, -1}, range = rangerelat(L, 2, r, pb_len(s));
lua_pushlstring(L, s.p+r[0]-1, (size_t)range);
return 1;
}
static int Lbuf_new(lua_State *L) {
int i, top = lua_gettop(L);
pb_Buffer *buf = (pb_Buffer*)lua_newuserdata(L, sizeof(pb_Buffer));
pb_initbuffer(buf);
luaL_setmetatable(L, PB_BUFFER);
for (i = 1; i <= top; ++i)
lpb_checkmem(L, pb_addslice(buf, lpb_checkslice(L, i)));
return 1;
}
static int Lbuf_delete(lua_State *L) {
pb_Buffer *buf = test_buffer(L, 1);
if (buf) pb_resetbuffer(buf);
return 0;
}
static int Lbuf_libcall(lua_State *L) {
int i, top = lua_gettop(L);
pb_Buffer *buf = (pb_Buffer*)lua_newuserdata(L, sizeof(pb_Buffer));
pb_initbuffer(buf);
luaL_setmetatable(L, PB_BUFFER);
for (i = 2; i <= top; ++i)
lpb_checkmem(L, pb_addslice(buf, lpb_checkslice(L, i)));
return 1;
}
static int Lbuf_tostring(lua_State *L) {
pb_Buffer *buf = check_buffer(L, 1);
lua_pushfstring(L, "pb.Buffer: %p", buf);
return 1;
}
static int Lbuf_reset(lua_State *L) {
pb_Buffer *buf = check_buffer(L, 1);
int i, top = lua_gettop(L);
pb_bufflen(buf) = 0;
for (i = 2; i <= top; ++i)
lpb_checkmem(L, pb_addslice(buf, lpb_checkslice(L, i)));
lpb_returnself(L);
}
static int Lbuf_len(lua_State *L) {
pb_Buffer *buf = check_buffer(L, 1);
lua_pushinteger(L, (lua_Integer)buf->size);
return 1;
}
static int Lbuf_pack(lua_State *L) {
pb_Buffer b, *pb = test_buffer(L, 1);
int idx = 1 + (pb != NULL);
const char *fmt = luaL_checkstring(L, idx++);
if (pb == NULL) pb_initbuffer(pb = &b);
lpb_packfmt(L, idx, pb, &fmt, 0);
if (pb != &b)
lua_settop(L, 1);
else {
pb_Slice ret = pb_result(pb);
push_slice(L, ret);
pb_resetbuffer(pb);
}
return 1;
}
LUALIB_API int luaopen_pb_buffer(lua_State *L) {
luaL_Reg libs[] = {
{ "__tostring", Lbuf_tostring },
{ "__len", Lbuf_len },
{ "__gc", Lbuf_delete },
{ "delete", Lbuf_delete },
{ "tohex", Lpb_tohex },
{ "fromhex", Lpb_fromhex },
{ "result", Lpb_result },
#define ENTRY(name) { #name, Lbuf_##name }
ENTRY(new),
ENTRY(reset),
ENTRY(pack),
#undef ENTRY
{ NULL, NULL }
};
if (luaL_newmetatable(L, PB_BUFFER)) {
luaL_setfuncs(L, libs, 0);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
lua_createtable(L, 0, 1);
lua_pushcfunction(L, Lbuf_libcall);
lua_setfield(L, -2, "__call");
lua_setmetatable(L, -2);
}
return 1;
}
/* protobuf decode routine */
#define LPB_INITSTACKLEN 2
typedef struct lpb_Slice {
pb_Slice curr;
pb_Slice *buff;
size_t used;
size_t size;
pb_Slice init_buff[LPB_INITSTACKLEN];
} lpb_Slice;
static void lpb_resetslice(lua_State *L, lpb_Slice *s, size_t size) {
if (size == sizeof(lpb_Slice)) {
if (s->buff != s->init_buff) free(s->buff);
memset(s, 0, sizeof(lpb_Slice));
s->buff = s->init_buff;
s->size = LPB_INITSTACKLEN;
}
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, s);
}
static pb_Slice lpb_checkview(lua_State *L, int idx, pb_Slice *ps) {
pb_Slice src = lpb_checkslice(L, idx);
lua_Integer r[2] = {1, -1}, range = rangerelat(L, idx+1, r, pb_len(src));
pb_Slice ret;
if (ps) *ps = src, ps->start = src.p;
ret.p = src.p + r[0] - 1;
ret.end = ret.p + range;
ret.start = src.p;
return ret;
}
static void lpb_enterview(lua_State *L, lpb_Slice *s, pb_Slice view) {
if (s->used >= s->size) {
size_t newsize = s->size * 2;
pb_Slice *oldp = s->buff != s->init_buff ? s->buff : NULL;
pb_Slice *newp = (pb_Slice*)realloc(oldp, newsize*sizeof(pb_Slice));
if (newp == NULL) { luaL_error(L, "out of memory"); return; }
if (oldp == NULL) memcpy(newp, s->buff, s->used*sizeof(pb_Slice));
s->buff = newp;
s->size = newsize;
}
s->buff[s->used++] = s->curr;
s->curr = view;
}
static void lpb_initslice(lua_State *L, int idx, lpb_Slice *s, size_t size) {
if (size == sizeof(lpb_Slice)) {
memset(s, 0, sizeof(lpb_Slice));
s->buff = s->init_buff;
s->size = LPB_INITSTACKLEN;
}
if (!lua_isnoneornil(L, idx)) {
pb_Slice base, view = lpb_checkview(L, idx, &base);
s->curr = base;
if (size == sizeof(lpb_Slice)) lpb_enterview(L, s, view);
lua_pushvalue(L, idx);
lua_rawsetp(L, LUA_REGISTRYINDEX, s);
}
}
static int lpb_unpackscalar(lua_State *L, int *pidx, int top, int fmt, pb_Slice *s) {
unsigned mode = lpb_lstate(L)->int64_mode;
lpb_Value v;
switch (fmt) {
case 'v':
if (pb_readvarint64(s, &v.u64) == 0) return luaL_error(L,
"invalid varint value at offset %d", pb_pos(*s)+1);
lpb_pushinteger(L, v.u64, 1, mode);
break;
case 'd':
if (pb_readfixed32(s, &v.u32) == 0) return luaL_error(L,
"invalid fixed32 value at offset %d", pb_pos(*s)+1);
lpb_pushinteger(L, v.u32, 1, mode);
break;
case 'q':
if (pb_readfixed64(s, &v.u64) == 0) return luaL_error(L,
"invalid fixed64 value at offset %d", pb_pos(*s)+1);
lpb_pushinteger(L, v.u64, 1, mode);
break;
case 's':
if (pb_readbytes(s, v.s) == 0) return luaL_error(L,
"invalid bytes value at offset %d", pb_pos(*s)+1);
push_slice(L, *v.s);
break;
case 'c':
luaL_argcheck(L, *pidx <= top, 1, "format argument exceed");
v.lint = luaL_checkinteger(L, (*pidx)++);
if (pb_readslice(s, (size_t)v.lint, v.s) == 0) return luaL_error(L,
"invalid sub string at offset %d", pb_pos(*s)+1);
push_slice(L, *v.s);
break;
default:
return 0;
}