-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrpack.c
More file actions
909 lines (793 loc) · 33.3 KB
/
Copy pathstrpack.c
File metadata and controls
909 lines (793 loc) · 33.3 KB
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
/*
** strpack.c — Lua 5.4-compatible string.pack / string.unpack / string.packsize
** for LuaJIT 2.1+
**
** Implements the full Lua 5.4 format specification:
** < > = !n — endianness / alignment control
** b B h H i I l L j J T n f d — numeric types
** c s z — string types
** x X — padding
** (space) — ignored
**
** License: MIT
** Author: CandyMi (adapted from Lua 5.4 reference design)
*/
// #include "common.h"
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
/* ═══════════════════════════════════════════════════════════════
* Endianness detection (compile-time, with runtime sentinel)
* ═══════════════════════════════════════════════════════════════ */
#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define NATIVE_BIG 1
#elif defined(__BIG_ENDIAN__) || defined(__ARMEB__) || defined(__THUMBEB__)
#define NATIVE_BIG 1
#else
/* x86, x64, ARM (default), RISC-V — all little-endian in practice */
#define NATIVE_LE 1
#endif
/* ═══════════════════════════════════════════════════════════════
* Byte-swap helpers (no external dependency)
* ═══════════════════════════════════════════════════════════════ */
static inline uint16_t swab16(uint16_t x) {
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap16(x);
#elif defined(_MSC_VER)
return _byteswap_ushort(x);
#else
return (uint16_t)((x << 8) | (x >> 8));
#endif
}
static inline uint32_t swab32(uint32_t x) {
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap32(x);
#elif defined(_MSC_VER)
return _byteswap_ulong(x);
#else
return ((x & 0x000000FFU) << 24) |
((x & 0x0000FF00U) << 8) |
((x & 0x00FF0000U) >> 8) |
((x & 0xFF000000U) >> 24);
#endif
}
static inline uint64_t swab64(uint64_t x) {
#if defined(__GNUC__) || defined(__clang__)
return __builtin_bswap64(x);
#elif defined(_MSC_VER)
return _byteswap_uint64(x);
#else
return ((x & UINT64_C(0x00000000000000FF)) << 56) |
((x & UINT64_C(0x000000000000FF00)) << 40) |
((x & UINT64_C(0x0000000000FF0000)) << 24) |
((x & UINT64_C(0x00000000FF000000)) << 8) |
((x & UINT64_C(0x000000FF00000000)) >> 8) |
((x & UINT64_C(0x0000FF0000000000)) >> 24) |
((x & UINT64_C(0x00FF000000000000)) >> 40) |
((x & UINT64_C(0xFF00000000000000)) >> 56);
#endif
}
/* ═══════════════════════════════════════════════════════════════
* Platform size queries
* ═══════════════════════════════════════════════════════════════ */
/* size_t width — 4 on ILP32, 8 on LP64 */
#if INTPTR_MAX == INT64_MAX
#define SIZEOF_SIZE_T 8
#else
#define SIZEOF_SIZE_T 4
#endif
/* long width — 4 on Windows/iOS/32-bit, 8 on most 64-bit Unix */
#define SIZEOF_LONG ((int)sizeof(long))
/* int width */
#define SIZEOF_INT ((int)sizeof(int))
/* int16_t / int32_t / int64_t widths */
#define SIZEOF_I16 ((int)sizeof(int16_t))
#define SIZEOF_I32 ((int)sizeof(int32_t))
#define SIZEOF_I64 ((int)sizeof(int64_t))
/* float / double */
#define SIZEOF_FLOAT ((int)sizeof(float))
#define SIZEOF_DOUBLE ((int)sizeof(double))
/* lua_Integer / lua_Number (always 8 bytes in LuaJIT) */
#define SIZEOF_LUA_INTEGER ((int)sizeof(lua_Integer))
#define SIZEOF_LUA_NUMBER ((int)sizeof(lua_Number))
/* ═══════════════════════════════════════════════════════════════
* Format state machine
* ═══════════════════════════════════════════════════════════════ */
typedef enum { ENDIAN_NATIVE, ENDIAN_LITTLE, ENDIAN_BIG } endian_t;
typedef struct {
const char *pos; /* current position in format string */
endian_t endian; /* current endianness */
int maxalign; /* max alignment from !n (default 1) */
int len; /* remaining length of format string */
} fmt_state_t;
/* ═══════════════════════════════════════════════════════════════
* Option descriptor — returned by parse_option
* ═══════════════════════════════════════════════════════════════ */
typedef enum {
OPT_b, OPT_B, /* signed/unsigned byte (1) */
OPT_h, OPT_H, /* signed/unsigned short (2) */
OPT_i, OPT_I, /* signed/unsigned int (default 4, or iN/IN) */
OPT_l, OPT_L, /* signed/unsigned long */
OPT_j, OPT_J, /* lua_Integer / lua_Unsigned */
OPT_T, /* size_t */
OPT_n, /* lua_Number */
OPT_f, OPT_d, /* float / double */
OPT_c, /* fixed-length string (cN) */
OPT_s, /* counted string (sN — N-byte length prefix) */
OPT_z, /* zero-terminated string */
OPT_x, /* one-byte pad */
OPT_X, /* alignment pad (XN — align to N) */
OPT_END, /* end of format */
OPT_ERROR /* invalid option */
} opt_t;
typedef struct {
opt_t type;
int size; /* byte count for fixed-size types; for c/s: field value */
int nat_align; /* natural alignment for this type */
bool is_signed; /* signed integer? */
} pack_opt_t;
/* ═══════════════════════════════════════════════════════════════
* Integer range helpers
* ═══════════════════════════════════════════════════════════════ */
static bool int_fits_signed(int64_t v, int bytes) {
if (bytes <= 0 || bytes > 8) return false;
int bits = bytes * 8;
int64_t lo = -(int64_t)1 << (bits - 1);
int64_t hi = ((int64_t)1 << (bits - 1)) - 1;
return lo <= v && v <= hi;
}
static bool int_fits_unsigned(uint64_t v, int bytes) {
if (bytes <= 0 || bytes > 8) return false;
if (bytes == 8) return true; /* any uint64_t fits in 8 bytes */
uint64_t max = ((uint64_t)1 << (bytes * 8)) - 1;
return v <= max;
}
/* ═══════════════════════════════════════════════════════════════
* Endian-aware integer read/write
* ═══════════════════════════════════════════════════════════════ */
/* Write 'len' bytes of 'val' at 'dst' in current endian order.
Supports any len 1–8. */
static void write_int(unsigned char *dst, uint64_t val, int len, endian_t e) {
int i;
bool be = (e == ENDIAN_BIG);
#if defined(NATIVE_BIG)
if (e == ENDIAN_NATIVE) be = true;
#endif
if (be) {
/* MSB first: byte 0 = byte (len-1) */
for (i = 0; i < len; i++)
dst[i] = (unsigned char)((val >> ((len - 1 - i) * 8)) & 0xFF);
} else {
/* LSB first */
for (i = 0; i < len; i++)
dst[i] = (unsigned char)((val >> (i * 8)) & 0xFF);
}
}
/* Read 'len' bytes from 'src' in current endian order, sign-extend if signed.
Supports any len 1–8. */
static int64_t read_int(const unsigned char *src, int len, endian_t e, bool is_signed) {
uint64_t val = 0;
int i;
bool be = (e == ENDIAN_BIG);
#if defined(NATIVE_BIG)
if (e == ENDIAN_NATIVE) be = true;
#endif
if (be) {
/* MSB first: src[0] is the most significant byte */
for (i = 0; i < len; i++)
val |= (uint64_t)src[i] << ((len - 1 - i) * 8);
} else {
/* LSB first */
for (i = 0; i < len; i++)
val |= (uint64_t)src[i] << (i * 8);
}
/* Sign-extend if needed */
if (is_signed && len < 8) {
int bits = len * 8;
uint64_t sign_bit = (uint64_t)1 << (bits - 1);
if (val & sign_bit) {
val |= (~(uint64_t)0) << bits;
}
}
return (int64_t)val;
}
/* ═══════════════════════════════════════════════════════════════
* Format option parser
* ═══════════════════════════════════════════════════════════════ */
/* Parse an optional numeric suffix, returning 'def' if none. */
static int getnum(fmt_state_t *fs, int def) {
if (fs->len > 0 && isdigit((unsigned char)*fs->pos)) {
int val = 0;
while (fs->len > 0 && isdigit((unsigned char)*fs->pos)) {
val = val * 10 + (*fs->pos - '0');
fs->pos++;
fs->len--;
}
return val;
}
return def;
}
static pack_opt_t parse_option(fmt_state_t *fs) {
pack_opt_t opt;
memset(&opt, 0, sizeof(opt));
while (fs->len > 0) {
char c = *fs->pos;
/* Space — ignored */
if (c == ' ') {
fs->pos++;
fs->len--;
continue;
}
/* Endianness / alignment control */
if (c == '<') {
fs->endian = ENDIAN_LITTLE;
fs->pos++; fs->len--;
continue;
}
if (c == '>') {
fs->endian = ENDIAN_BIG;
fs->pos++; fs->len--;
continue;
}
if (c == '=') {
fs->endian = ENDIAN_NATIVE;
fs->pos++; fs->len--;
continue;
}
if (c == '!') {
fs->pos++; fs->len--;
fs->maxalign = getnum(fs, 1);
/* Must be power of 2 */
if (fs->maxalign < 1 || (fs->maxalign & (fs->maxalign - 1)) != 0) {
opt.type = OPT_ERROR;
return opt;
}
continue;
}
/* Move past the option character */
fs->pos++;
fs->len--;
opt.size = 0;
switch (c) {
/* ── Bytes ── */
case 'b': opt.type = OPT_b; opt.size = 1; opt.nat_align = 1; opt.is_signed = true; return opt;
case 'B': opt.type = OPT_B; opt.size = 1; opt.nat_align = 1; opt.is_signed = false; return opt;
/* ── Shorts ── */
case 'h': opt.type = OPT_h; opt.size = SIZEOF_I16; opt.nat_align = 2; opt.is_signed = true; return opt;
case 'H': opt.type = OPT_H; opt.size = SIZEOF_I16; opt.nat_align = 2; opt.is_signed = false; return opt;
/* ── Ints (with optional width) ── */
case 'i': {
opt.type = OPT_i;
int n = getnum(fs, 0);
opt.size = (n > 0) ? n : SIZEOF_INT;
opt.nat_align = (n > 0) ? n : SIZEOF_INT;
opt.is_signed = true;
return opt;
}
case 'I': {
opt.type = OPT_I;
int n = getnum(fs, 0);
opt.size = (n > 0) ? n : SIZEOF_INT;
opt.nat_align = (n > 0) ? n : SIZEOF_INT;
opt.is_signed = false;
return opt;
}
/* ── Longs ── */
case 'l': opt.type = OPT_l; opt.size = SIZEOF_LONG; opt.nat_align = SIZEOF_LONG; opt.is_signed = true; return opt;
case 'L': opt.type = OPT_L; opt.size = SIZEOF_LONG; opt.nat_align = SIZEOF_LONG; opt.is_signed = false; return opt;
/* ── lua_Integer / lua_Unsigned ── */
case 'j': opt.type = OPT_j; opt.size = SIZEOF_LUA_INTEGER; opt.nat_align = SIZEOF_LUA_INTEGER; opt.is_signed = true; return opt;
case 'J': opt.type = OPT_J; opt.size = SIZEOF_LUA_INTEGER; opt.nat_align = SIZEOF_LUA_INTEGER; opt.is_signed = false; return opt;
/* ── size_t ── */
case 'T': opt.type = OPT_T; opt.size = SIZEOF_SIZE_T; opt.nat_align = SIZEOF_SIZE_T; opt.is_signed = false; return opt;
/* ── lua_Number ── */
case 'n': opt.type = OPT_n; opt.size = SIZEOF_LUA_NUMBER; opt.nat_align = SIZEOF_LUA_NUMBER; opt.is_signed = false; return opt;
/* ── Float / Double ── */
case 'f': opt.type = OPT_f; opt.size = SIZEOF_FLOAT; opt.nat_align = SIZEOF_FLOAT; return opt;
case 'd': opt.type = OPT_d; opt.size = SIZEOF_DOUBLE; opt.nat_align = SIZEOF_DOUBLE; return opt;
/* ── Strings ── */
case 'c': {
int n = getnum(fs, 1);
opt.type = OPT_c;
opt.size = n; /* fixed byte count */
opt.nat_align = 1;
return opt;
}
case 's': {
int n = getnum(fs, 1); /* length prefix byte count */
opt.type = OPT_s;
opt.size = n; /* n bytes for the length prefix */
opt.nat_align = 1;
return opt;
}
case 'z':
opt.type = OPT_z;
opt.size = 0;
opt.nat_align = 1;
return opt;
/* ── Padding ── */
case 'x':
opt.type = OPT_x;
opt.size = 1;
opt.nat_align = 1;
return opt;
case 'X': {
int n = getnum(fs, 0);
opt.type = OPT_X;
opt.size = (n > 0) ? n : fs->maxalign; /* X alone → maxalign; Xn → n */
opt.nat_align = 1;
if (opt.size < 1 || (opt.size & (opt.size - 1)) != 0) {
opt.type = OPT_ERROR;
return opt;
}
return opt;
}
default:
opt.type = OPT_ERROR;
return opt;
}
}
opt.type = OPT_END;
return opt;
}
/* ═══════════════════════════════════════════════════════════════
* Pack helper — append bytes to luaL_Buffer
* ═══════════════════════════════════════════════════════════════ */
/* 64-byte zero buffer for batch padding — avoids per-byte luaL_addchar. */
static const char pack_zeros[64] = {0};
/* Helper: write N zero bytes to buffer in 64-byte batches. */
static void pack_pad(luaL_Buffer *buf, int n) {
while (n > 0) {
int chunk = n > 64 ? 64 : n;
luaL_addlstring(buf, pack_zeros, chunk);
n -= chunk;
}
}
/* Align 'cur' to next multiple of 'align' (must be power of 2). */
static int align_offset(int cur, int align) {
int mask = align - 1;
if (cur & mask)
return cur + (align - (cur & mask));
return cur;
}
static void pack_value(lua_State *L, luaL_Buffer *buf, fmt_state_t *fs,
pack_opt_t *opt, int *offset, int arg_idx) {
int size = opt->size;
int align = opt->nat_align;
/* Apply max alignment cap */
if (align > fs->maxalign)
align = fs->maxalign;
/* Alignment padding before this field */
if (align > 1) {
int aligned = align_offset(*offset, align);
int pad = aligned - *offset;
if (pad > 0) pack_pad(buf, pad);
*offset = aligned;
}
switch (opt->type) {
/* ── Integer types ── */
case OPT_b: case OPT_B:
case OPT_h: case OPT_H:
case OPT_i: case OPT_I:
case OPT_l: case OPT_L:
case OPT_j: case OPT_J:
case OPT_T: {
/* Read value from Lua stack */
lua_Integer v;
if (lua_type(L, arg_idx) == LUA_TNUMBER) {
v = lua_tointeger(L, arg_idx);
} else if (lua_type(L, arg_idx) == LUA_TSTRING) {
/* Parse via strtoll/strtoull to preserve full 64-bit precision
(lua_tointegerx goes through double and loses bits > 2^53) */
size_t slen;
const char *s = lua_tolstring(L, arg_idx, &slen);
char *end;
/* Try signed first */
errno = 0;
int64_t sv = strtoll(s, &end, 0);
if (end != s && *end == '\0' && errno != ERANGE) {
v = (lua_Integer)sv;
} else {
/* Try unsigned */
errno = 0;
uint64_t uv = strtoull(s, &end, 0);
if (end == s || *end != '\0' || errno == ERANGE) {
luaL_argerror(L, arg_idx, lua_pushfstring(L,
"bad argument #%d to 'pack' (cannot parse string as integer: '%s')",
arg_idx, s));
return;
}
v = (lua_Integer)uv;
}
} else {
luaL_argerror(L, arg_idx, lua_pushfstring(L,
"bad argument #%d to 'pack' (number or numeric string expected, got %s)",
arg_idx, lua_typename(L, lua_type(L, arg_idx))));
return;
}
/* Range check */
if (opt->is_signed) {
if (!int_fits_signed(v, size)) {
luaL_error(L, "bad argument #%d to 'pack' (%s overflow)",
arg_idx, opt->type == OPT_b ? "'b' format" :
opt->type == OPT_h ? "'h' format" :
opt->type == OPT_i ? "'i' format" :
opt->type == OPT_l ? "'l' format" : "'j' format");
}
} else {
if (!int_fits_unsigned((uint64_t)v, size)) {
luaL_error(L, "bad argument #%d to 'pack' (%s overflow)",
arg_idx, opt->type == OPT_B ? "'B' format" :
opt->type == OPT_H ? "'H' format" :
opt->type == OPT_I ? "'I' format" :
opt->type == OPT_L ? "'L' format" :
opt->type == OPT_J ? "'J' format" : "'T' format");
}
}
/* Write bytes */
unsigned char tmp[8];
write_int(tmp, (uint64_t)v, size, fs->endian);
luaL_addlstring(buf, (const char *)tmp, size);
*offset += size;
break;
}
/* ── Float / Double / lua_Number ── */
case OPT_f: {
float v = (float)luaL_checknumber(L, arg_idx);
unsigned char tmp[4];
uint32_t raw;
memcpy(&raw, &v, 4);
write_int(tmp, raw, 4, fs->endian);
luaL_addlstring(buf, (const char *)tmp, 4);
*offset += 4;
break;
}
case OPT_d: case OPT_n: {
lua_Number v = luaL_checknumber(L, arg_idx);
unsigned char tmp[8];
uint64_t raw;
memcpy(&raw, &v, 8);
write_int(tmp, raw, 8, fs->endian);
luaL_addlstring(buf, (const char *)tmp, 8);
*offset += 8;
break;
}
/* ── Fixed-length string ── */
case OPT_c: {
size_t slen;
const char *s = luaL_checklstring(L, arg_idx, &slen);
int n = size; /* fixed length from cN */
if (slen >= (size_t)n) {
luaL_addlstring(buf, s, n);
} else {
luaL_addlstring(buf, s, slen);
/* pad with zeros */
if (slen < (size_t)n)
pack_pad(buf, n - (int)slen);
}
*offset += n;
break;
}
/* ── Counted string ── */
case OPT_s: {
size_t slen;
const char *s = luaL_checklstring(L, arg_idx, &slen);
int len_bytes = size; /* N-byte length prefix */
/* Check string length fits in N bytes */
if (!int_fits_unsigned(slen, len_bytes)) {
luaL_error(L, "bad argument #%d to 'pack' (string too long for 's%d')",
arg_idx, len_bytes);
}
/* Write length prefix */
unsigned char tmp[8];
write_int(tmp, (uint64_t)slen, len_bytes, fs->endian);
luaL_addlstring(buf, (const char *)tmp, len_bytes);
*offset += len_bytes;
/* Write string data */
luaL_addlstring(buf, s, slen);
*offset += (int)slen;
break;
}
/* ── Zero-terminated string ── */
case OPT_z: {
size_t slen;
const char *s = luaL_checklstring(L, arg_idx, &slen);
luaL_addlstring(buf, s, slen);
luaL_addchar(buf, '\0');
*offset += (int)slen + 1;
break;
}
/* ── Padding ── */
case OPT_x:
luaL_addchar(buf, '\0');
*offset += 1;
break;
case OPT_X: {
int target = align_offset(*offset, size);
int pad = target - *offset;
if (pad > 0) pack_pad(buf, pad);
*offset = target;
break;
}
default:
break;
}
}
/* ═══════════════════════════════════════════════════════════════
* Unpack helper — read from input buffer, push to Lua stack
* ═══════════════════════════════════════════════════════════════ */
static int unpack_value(lua_State *L, const unsigned char *data, int data_len,
fmt_state_t *fs, pack_opt_t *opt, int *offset) {
int size = opt->size;
int align = opt->nat_align;
/* Apply max alignment cap */
if (align > fs->maxalign)
align = fs->maxalign;
/* Alignment padding — skip bytes */
if (align > 1) {
int aligned = align_offset(*offset, align);
*offset = aligned;
}
/* Bounds check */
if (*offset < 0 || *offset >= data_len) {
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
}
switch (opt->type) {
/* ── Integer types ── */
case OPT_b: case OPT_B:
case OPT_h: case OPT_H:
case OPT_i: case OPT_I:
case OPT_l: case OPT_L:
case OPT_j: case OPT_J:
case OPT_T: {
if (*offset + size > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
int64_t v = read_int(data + *offset, size, fs->endian, opt->is_signed);
lua_pushinteger(L, (lua_Integer)v);
*offset += size;
return 1;
}
/* ── Float ── */
case OPT_f: {
if (*offset + 4 > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
uint64_t raw = read_int(data + *offset, 4, fs->endian, false);
float v;
uint32_t raw32 = (uint32_t)(raw & 0xFFFFFFFFU);
memcpy(&v, &raw32, 4);
lua_pushnumber(L, (lua_Number)v);
*offset += 4;
return 1;
}
/* ── Double / lua_Number ── */
case OPT_d: case OPT_n: {
if (*offset + 8 > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
uint64_t raw = read_int(data + *offset, 8, fs->endian, false);
lua_Number v;
memcpy(&v, &raw, 8);
lua_pushnumber(L, v);
*offset += 8;
return 1;
}
/* ── Fixed-length string ── */
case OPT_c: {
int n = size;
if (*offset + n > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
lua_pushlstring(L, (const char *)(data + *offset), n);
*offset += n;
return 1;
}
/* ── Counted string ── */
case OPT_s: {
int len_bytes = size;
if (*offset + len_bytes > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
uint64_t slen = (uint64_t)read_int(data + *offset, len_bytes, fs->endian, false);
*offset += len_bytes;
if (*offset + (int)slen > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
lua_pushlstring(L, (const char *)(data + *offset), (size_t)slen);
*offset += (int)slen;
return 1;
}
/* ── Zero-terminated string ── */
case OPT_z: {
int end = *offset;
while (end < data_len && data[end] != '\0')
end++;
if (end >= data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
int slen = end - *offset;
lua_pushlstring(L, (const char *)(data + *offset), slen);
*offset = end + 1; /* skip the null */
return 1;
}
/* ── Padding — skip, nothing pushed ── */
case OPT_x:
if (*offset + 1 > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
*offset += 1;
return 0;
case OPT_X: {
int target = align_offset(*offset, size);
if (target > data_len)
luaL_error(L, "bad argument #2 to 'unpack' (data too short)");
*offset = target;
return 0;
}
default:
return 0;
}
}
/* ═══════════════════════════════════════════════════════════════
* strpack — string.pack(fmt, v1, v2, ...)
* ═══════════════════════════════════════════════════════════════ */
int strpack(lua_State *L) {
/* Argument 1: format string */
size_t fmt_len;
const char *fmt_str = luaL_checklstring(L, 1, &fmt_len);
fmt_state_t fs;
fs.pos = fmt_str;
fs.len = (int)fmt_len;
fs.endian = ENDIAN_NATIVE;
fs.maxalign = 1;
luaL_Buffer buf;
luaL_buffinit(L, &buf);
int offset = 0;
int arg_idx = 2; /* values start at arg 2 */
while (fs.len > 0) {
pack_opt_t opt = parse_option(&fs);
if (opt.type == OPT_END)
break;
if (opt.type == OPT_ERROR) {
luaL_error(L, "bad argument #1 to 'pack' (invalid format option '%c')",
fs.pos[-1]); /* pos[-1] is the offending char */
}
if (opt.type == OPT_z || opt.type == OPT_s || opt.type == OPT_c) {
/* String types consume one Lua argument */
if (lua_gettop(L) < arg_idx) {
luaL_argerror(L, arg_idx,
lua_pushfstring(L, "bad argument #%d to 'pack' (no value)", arg_idx));
}
} else if (opt.type != OPT_x && opt.type != OPT_X) {
/* Data types consume one Lua argument */
if (lua_gettop(L) < arg_idx) {
luaL_argerror(L, arg_idx,
lua_pushfstring(L, "bad argument #%d to 'pack' (no value)", arg_idx));
}
}
pack_value(L, &buf, &fs, &opt, &offset, arg_idx);
/* Consume argument for data types and string types */
if (opt.type != OPT_x && opt.type != OPT_X) {
arg_idx++;
}
}
luaL_pushresult(&buf);
return 1;
}
/* ═══════════════════════════════════════════════════════════════
* strunpack — string.unpack(fmt, s [, init])
* Returns: v1, v2, ..., next_position
* (position is 1-indexed, like Lua 5.4)
* ═══════════════════════════════════════════════════════════════ */
int strunpack(lua_State *L) {
/* Argument 1: format string */
size_t fmt_len;
const char *fmt_str = luaL_checklstring(L, 1, &fmt_len);
/* Argument 2: data string */
size_t data_len;
const char *data = luaL_checklstring(L, 2, &data_len);
/* Track whether user passed explicit init position (for stack cleanup) */
int has_init = (lua_gettop(L) >= 3 && !lua_isnil(L, 3));
/* Argument 3: initial position (optional, default 1) */
int init = 1;
if (has_init) {
init = (int)luaL_checkinteger(L, 3);
if (init < 1 || init > (int)data_len + 1) {
luaL_argerror(L, 3, "position out of range");
}
}
fmt_state_t fs;
fs.pos = fmt_str;
fs.len = (int)fmt_len;
fs.endian = ENDIAN_NATIVE;
fs.maxalign = 1;
int offset = init - 1; /* 0-indexed internal offset */
int nresults = 0;
/* Unpack values — they go on the stack after function arguments */
while (fs.len > 0) {
pack_opt_t opt = parse_option(&fs);
if (opt.type == OPT_END)
break;
if (opt.type == OPT_ERROR) {
luaL_error(L, "bad argument #1 to 'unpack' (invalid format option '%c')",
fs.pos[-1]);
}
int pushed = unpack_value(L, (const unsigned char *)data, (int)data_len,
&fs, &opt, &offset);
nresults += pushed;
}
/* Remove function arguments from the bottom of the stack.
After unpack, stack is: [fmt, data, init?, v1, v2, ..., vN] */
lua_remove(L, 1); /* remove fmt */
lua_remove(L, 1); /* remove data */
if (has_init) {
lua_remove(L, 1); /* remove init */
}
/* Stack now: [v1, v2, ..., vN] */
/* Push the next position: [v1, v2, ..., vN, pos] (Lua 5.4 convention) */
lua_pushinteger(L, offset + 1);
return nresults + 1;
}
/* ═══════════════════════════════════════════════════════════════
* strpacksize — string.packsize(fmt)
* Returns: number of bytes the format would pack (known fixed-size only)
* Errors on 'z' and 's' (variable-size formats)
* ═══════════════════════════════════════════════════════════════ */
int strpacksize(lua_State *L) {
size_t fmt_len;
const char *fmt_str = luaL_checklstring(L, 1, &fmt_len);
fmt_state_t fs;
fs.pos = fmt_str;
fs.len = (int)fmt_len;
fs.endian = ENDIAN_NATIVE;
fs.maxalign = 1;
int offset = 0;
while (fs.len > 0) {
pack_opt_t opt = parse_option(&fs);
if (opt.type == OPT_END)
break;
if (opt.type == OPT_ERROR) {
luaL_error(L, "bad argument #1 to 'packsize' (invalid format option '%c')",
fs.pos[-1]);
}
int align = opt.nat_align;
if (align > fs.maxalign) align = fs.maxalign;
if (align > 1) {
offset = align_offset(offset, align);
}
switch (opt.type) {
case OPT_z:
luaL_error(L, "packsize cannot compute size for 'z' format");
return 0;
case OPT_s:
luaL_error(L, "packsize cannot compute size for 's' format");
return 0;
case OPT_X: {
int target = align_offset(offset, opt.size);
offset = target;
break;
}
case OPT_x:
offset += 1;
break;
default:
offset += opt.size;
break;
}
}
lua_pushinteger(L, offset);
return 1;
}
#if __cplusplus
extern "C"
#else
extern
#endif
int luaopen_strpack(lua_State *L) {
lua_getglobal(L, "string");
lua_pushcfunction(L, strpack); lua_setfield(L, -2, "pack");
lua_pushcfunction(L, strunpack); lua_setfield(L, -2, "unpack");
lua_pushcfunction(L, strpacksize); lua_setfield(L, -2, "packsize");
lua_pop(L, 1);
return 0;
}