~bigbes/tarantool

tarantool-protobuf

ref: ee07048d3ab9678553493c643fb74328e7d5e908 tarantool-protobuf/bench/c_accel/generic_codec.c -rw-r--r-- 10.4 KiB
ee07048d — Eugene Blikh beads: close 74c 2 months ago
                                                                                
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
/*
 * generic_codec.c -- one-C-call generic codec, descriptor-walking.
 *
 * Strategy 3 of tarantool-protobuf-04c.
 *
 * Same boundary as person_codec.c (one C call per top-level
 * encode/decode), but the inner loop walks a `message_desc_t` and
 * dispatches per-field on `kind_t`. This is what `ra6` would ship
 * in production. The gap to person_codec.c (Strategy 4) is the
 * dispatch overhead of being generic.
 *
 * Scope mirrors person_codec.c: only Person fields exercised by
 * bench/bench.lua. The descriptor tables for Person and Address
 * are hand-built; a real implementation would build them at
 * `pb.finalize_message` time from the Lua descriptor.
 */

#include <module.h>
#include <lauxlib.h>

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

/* ---------------------------------------------------------------- *
 *  buf_t (identical to person_codec.c -- duplicated to keep the    *
 *  spike modules independent).                                     *
 * ---------------------------------------------------------------- */

typedef struct {
	uint8_t *data;
	size_t len;
	size_t cap;
	uint8_t stack[4096];
} buf_t;

static inline void
buf_init(buf_t *b)
{
	b->data = b->stack;
	b->len = 0;
	b->cap = sizeof(b->stack);
}

static inline void
buf_free(buf_t *b)
{
	if (b->data != b->stack)
		free(b->data);
}

static void
buf_grow(buf_t *b, size_t need)
{
	size_t nc = b->cap ? b->cap * 2 : 64;
	while (nc < b->len + need)
		nc *= 2;
	uint8_t *nd = (uint8_t *)malloc(nc);
	memcpy(nd, b->data, b->len);
	if (b->data != b->stack)
		free(b->data);
	b->data = nd;
	b->cap = nc;
}

static inline void
buf_reserve(buf_t *b, size_t need)
{
	if (b->len + need > b->cap)
		buf_grow(b, need);
}

static inline void
write_varint(buf_t *b, uint64_t v)
{
	buf_reserve(b, 10);
	while (v >= 0x80) {
		b->data[b->len++] = (uint8_t)(v | 0x80);
		v >>= 7;
	}
	b->data[b->len++] = (uint8_t)v;
}

static inline void
write_bytes(buf_t *b, const void *src, size_t n)
{
	buf_reserve(b, n);
	memcpy(b->data + b->len, src, n);
	b->len += n;
}

static const uint8_t *
read_varint(const uint8_t *p, const uint8_t *end, uint64_t *out)
{
	uint64_t v = 0;
	int shift = 0;
	while (p < end) {
		uint8_t c = *p++;
		v |= (uint64_t)(c & 0x7f) << shift;
		if (!(c & 0x80)) {
			*out = v;
			return p;
		}
		shift += 7;
		if (shift >= 64)
			return NULL;
	}
	return NULL;
}

/* ---------------------------------------------------------------- *
 *  Descriptor model.                                               *
 * ---------------------------------------------------------------- */

typedef enum {
	K_INT32 = 0,
	K_STRING,
	K_MESSAGE,
	K_REPEATED_STRING,
	K_PACKED_INT32,
} kind_t;

struct message_desc;

typedef struct field_desc {
	uint32_t tag;          /* (field_num << 3) | wire_type */
	int      field_num;
	const char *name;
	kind_t   kind;
	const struct message_desc *submsg;
} field_desc_t;

typedef struct message_desc {
	const char *name;
	int n_fields;
	const field_desc_t *fields;
} message_desc_t;

/* Address (sub-message used by Person.address) */
static const field_desc_t address_fields[] = {
	{(1 << 3) | 2, 1, "street", K_STRING, NULL},
	{(2 << 3) | 2, 2, "city",   K_STRING, NULL},
	{(3 << 3) | 0, 3, "zip",    K_INT32,  NULL},
};
static const message_desc_t Address_desc = {
	"Address", 3, address_fields,
};

/* Person (subset exercised by bench payloads) */
static const field_desc_t person_fields[] = {
	{(1 << 3) | 2, 1, "name",          K_STRING,          NULL},
	{(2 << 3) | 0, 2, "age",           K_INT32,           NULL},
	{(3 << 3) | 2, 3, "emails",        K_REPEATED_STRING, NULL},
	{(5 << 3) | 2, 5, "address",       K_MESSAGE,         &Address_desc},
	{(7 << 3) | 2, 7, "lucky_numbers", K_PACKED_INT32,    NULL},
};
static const message_desc_t Person_desc = {
	"Person", 5, person_fields,
};

static int
find_field_idx(const message_desc_t *md, int field_num)
{
	for (int i = 0; i < md->n_fields; i++)
		if (md->fields[i].field_num == field_num)
			return i;
	return -1;
}

/* Max descriptor fields per message in the spike. Bumped above the
 * exercise to keep the stack-allocated index arrays in decode_message
 * safe; a real runtime would size dynamically. */
#define MAX_FIELDS_PER_MSG 16

/* ---------------------------------------------------------------- *
 *  Generic encode.                                                 *
 * ---------------------------------------------------------------- */

static void
encode_message(buf_t *b, lua_State *L, int t,
               const message_desc_t *md)
{
	for (int i = 0; i < md->n_fields; i++) {
		const field_desc_t *fd = &md->fields[i];
		lua_getfield(L, t, fd->name);
		if (lua_isnil(L, -1)) {
			lua_pop(L, 1);
			continue;
		}
		switch (fd->kind) {
		case K_STRING: {
			size_t n;
			const char *s = lua_tolstring(L, -1, &n);
			write_varint(b, fd->tag);
			write_varint(b, (uint64_t)n);
			write_bytes(b, s, n);
			break;
		}
		case K_INT32: {
			write_varint(b, fd->tag);
			write_varint(b,
			    (uint64_t)(int64_t)lua_tointeger(L, -1));
			break;
		}
		case K_REPEATED_STRING: {
			int idx = lua_gettop(L);
			int n = (int)lua_objlen(L, idx);
			for (int j = 1; j <= n; j++) {
				lua_rawgeti(L, idx, j);
				size_t slen;
				const char *s =
				    lua_tolstring(L, -1, &slen);
				write_varint(b, fd->tag);
				write_varint(b, (uint64_t)slen);
				write_bytes(b, s, slen);
				lua_pop(L, 1);
			}
			break;
		}
		case K_MESSAGE: {
			int idx = lua_gettop(L);
			buf_t sub;
			buf_init(&sub);
			encode_message(&sub, L, idx, fd->submsg);
			write_varint(b, fd->tag);
			write_varint(b, (uint64_t)sub.len);
			write_bytes(b, sub.data, sub.len);
			buf_free(&sub);
			break;
		}
		case K_PACKED_INT32: {
			int idx = lua_gettop(L);
			int n = (int)lua_objlen(L, idx);
			buf_t sub;
			buf_init(&sub);
			for (int j = 1; j <= n; j++) {
				lua_rawgeti(L, idx, j);
				write_varint(&sub,
				    (uint64_t)(int64_t)
				        lua_tointeger(L, -1));
				lua_pop(L, 1);
			}
			write_varint(b, fd->tag);
			write_varint(b, (uint64_t)sub.len);
			write_bytes(b, sub.data, sub.len);
			buf_free(&sub);
			break;
		}
		}
		lua_pop(L, 1);
	}
}

/* ---------------------------------------------------------------- *
 *  Generic decode.                                                 *
 * ---------------------------------------------------------------- */

static const uint8_t *
decode_message(lua_State *L, const uint8_t *p, const uint8_t *end,
               const message_desc_t *md);

/* Skip an unknown field given its wire type. Returns new p or NULL. */
static const uint8_t *
skip_field(const uint8_t *p, const uint8_t *end, int wt)
{
	uint64_t v;
	switch (wt) {
	case 0: /* varint */
		return read_varint(p, end, &v);
	case 1: /* 64-bit */
		if (end - p < 8) return NULL;
		return p + 8;
	case 2: { /* LEN */
		p = read_varint(p, end, &v);
		if (!p || (uint64_t)(end - p) < v) return NULL;
		return p + v;
	}
	case 5: /* 32-bit */
		if (end - p < 4) return NULL;
		return p + 4;
	default:
		return NULL;
	}
}

static const uint8_t *
decode_message(lua_State *L, const uint8_t *p, const uint8_t *end,
               const message_desc_t *md)
{
	lua_createtable(L, 0, md->n_fields);
	const int result_idx = lua_gettop(L);

	/* Per-field caches for repeated-array fields. Indexed by field
	 * position in md->fields. arr_stk[i] == 0 means "not yet
	 * created". Setting to result table happens once at the end so
	 * we only pay lua_setfield once per repeated field, not per
	 * element -- matches the hand-written codec's pattern. */
	int arr_stk[MAX_FIELDS_PER_MSG] = {0};
	int arr_n[MAX_FIELDS_PER_MSG] = {0};

	while (p < end) {
		uint64_t tag;
		p = read_varint(p, end, &tag);
		if (!p) break;
		int field_num = (int)(tag >> 3);
		int wt = (int)(tag & 7);
		int fi = find_field_idx(md, field_num);
		if (fi < 0) {
			p = skip_field(p, end, wt);
			if (!p) break;
			continue;
		}
		const field_desc_t *fd = &md->fields[fi];
		switch (fd->kind) {
		case K_STRING: {
			uint64_t slen;
			p = read_varint(p, end, &slen);
			if (!p || (uint64_t)(end - p) < slen) goto done;
			lua_pushlstring(L, (const char *)p, (size_t)slen);
			lua_setfield(L, result_idx, fd->name);
			p += slen;
			break;
		}
		case K_INT32: {
			uint64_t v;
			p = read_varint(p, end, &v);
			if (!p) goto done;
			lua_pushinteger(L, (lua_Integer)(int32_t)v);
			lua_setfield(L, result_idx, fd->name);
			break;
		}
		case K_REPEATED_STRING: {
			uint64_t slen;
			p = read_varint(p, end, &slen);
			if (!p || (uint64_t)(end - p) < slen) goto done;
			if (arr_stk[fi] == 0) {
				lua_createtable(L, 4, 0);
				arr_stk[fi] = lua_gettop(L);
			}
			lua_pushlstring(L, (const char *)p, (size_t)slen);
			lua_rawseti(L, arr_stk[fi], ++arr_n[fi]);
			p += slen;
			break;
		}
		case K_MESSAGE: {
			uint64_t slen;
			p = read_varint(p, end, &slen);
			if (!p || (uint64_t)(end - p) < slen) goto done;
			decode_message(L, p, p + slen, fd->submsg);
			lua_setfield(L, result_idx, fd->name);
			p += slen;
			break;
		}
		case K_PACKED_INT32: {
			uint64_t slen;
			p = read_varint(p, end, &slen);
			if (!p || (uint64_t)(end - p) < slen) goto done;
			const uint8_t *fend = p + slen;
			if (arr_stk[fi] == 0) {
				lua_createtable(L, 8, 0);
				arr_stk[fi] = lua_gettop(L);
			}
			while (p < fend) {
				uint64_t v;
				p = read_varint(p, fend, &v);
				if (!p) break;
				lua_pushinteger(L,
				    (lua_Integer)(int32_t)v);
				lua_rawseti(L, arr_stk[fi], ++arr_n[fi]);
			}
			break;
		}
		}
	}
done:
	/* Attach any deferred repeated arrays to the result table. */
	for (int i = 0; i < md->n_fields; i++) {
		if (arr_stk[i]) {
			lua_pushvalue(L, arr_stk[i]);
			lua_setfield(L, result_idx, md->fields[i].name);
		}
	}
	lua_settop(L, result_idx);
	return p;
}

/* ---------------------------------------------------------------- *
 *  Lua entry points.                                               *
 * ---------------------------------------------------------------- */

static int
Person_encode(lua_State *L)
{
	luaL_checktype(L, 1, LUA_TTABLE);
	buf_t b;
	buf_init(&b);
	encode_message(&b, L, 1, &Person_desc);
	lua_pushlstring(L, (const char *)b.data, b.len);
	buf_free(&b);
	return 1;
}

static int
Person_decode(lua_State *L)
{
	size_t len;
	const char *buf = luaL_checklstring(L, 1, &len);
	decode_message(L, (const uint8_t *)buf,
	               (const uint8_t *)buf + len, &Person_desc);
	return 1;
}

static const struct luaL_Reg lib[] = {
	{"Person_encode", Person_encode},
	{"Person_decode", Person_decode},
	{NULL, NULL},
};

LUA_API int
luaopen_pb_c_generic(lua_State *L)
{
	luaL_register(L, "pb_c_generic", lib);
	return 1;
}