forked from Shopify/go-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.go
More file actions
2010 lines (1922 loc) · 47.9 KB
/
string.go
File metadata and controls
2010 lines (1922 loc) · 47.9 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
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
package lua
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"strings"
"unicode"
"unsafe"
)
func relativePosition(pos, length int) int {
if pos >= 0 {
return pos
} else if -pos > length {
return 0
}
return length + pos + 1
}
// Pattern matching constants
const (
patternMaxCaptures = 32
patternSpecials = "^$*+?.([%-"
)
// maxStringSize is the maximum size of strings created by string operations.
// This matches Lua 5.3's MAX_SIZE which is typically limited to ~2GB to match
// 32-bit int limits (even on 64-bit systems) for compatibility.
const maxStringSize = 0x7FFFFFFF // 2^31 - 1
// Capture represents a captured substring
type capture struct {
start int // start position (0-based), -1 for position capture
end int // end position (0-based), -1 for unfinished
}
// matchState holds the state during pattern matching
type matchState struct {
l *State
matchDepth int
src string
srcEnd int
pattern string
captures []capture
numCaptures int
}
const maxMatchDepth = 200
// Check if character c matches character class cl
func matchClass(c byte, cl byte) bool {
var res bool
switch cl | 0x20 { // lowercase
case 'a':
res = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
case 'c':
res = c < 32 || c == 127
case 'd':
res = c >= '0' && c <= '9'
case 'g':
res = c > 32 && c < 127
case 'l':
res = c >= 'a' && c <= 'z'
case 'p':
res = (c >= 33 && c <= 47) || (c >= 58 && c <= 64) ||
(c >= 91 && c <= 96) || (c >= 123 && c <= 126)
case 's':
res = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'
case 'u':
res = c >= 'A' && c <= 'Z'
case 'w':
res = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
case 'x':
res = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')
case 'z':
res = c == 0
default:
return c == cl
}
// Uppercase class = complement
if cl >= 'A' && cl <= 'Z' {
return !res
}
return res
}
// Find end of character class [...], returns index after ]
// Returns -1 if malformed (missing ])
func classEnd(pattern string, p int) int {
p++ // skip '['
if p < len(pattern) && pattern[p] == '^' {
p++
}
// First ] after [ or [^ is literal, not end of class
if p < len(pattern) && pattern[p] == ']' {
p++ // skip literal ]
}
for {
if p >= len(pattern) {
return -1 // malformed: missing ]
}
c := pattern[p]
p++
if c == ']' {
return p
}
if c == '%' {
if p >= len(pattern) {
return -1 // malformed: ends with %
}
p++ // skip escaped char
}
}
}
// Check if character c matches the class at pattern[p]
// Returns (matched, next position in pattern)
func (ms *matchState) singleMatch(c byte, p int) (bool, int) {
if p >= len(ms.pattern) {
return false, p
}
switch ms.pattern[p] {
case '.':
return true, p + 1
case '%':
if p+1 >= len(ms.pattern) {
return false, p + 1
}
return matchClass(c, ms.pattern[p+1]), p + 2
case '[':
end := classEnd(ms.pattern, p)
if end < 0 {
Errorf(ms.l, "malformed pattern (missing ']')")
}
return ms.matchBracketClass(c, p, end), end
default:
return c == ms.pattern[p], p + 1
}
}
// Match character against bracket class [...]
func (ms *matchState) matchBracketClass(c byte, p, end int) bool {
sig := true
p++ // skip '['
if p < end && ms.pattern[p] == '^' {
sig = false
p++
}
// First ] after [ or [^ is literal
if p < end-1 && ms.pattern[p] == ']' {
if c == ']' {
return sig
}
p++
}
for p < end-1 {
if ms.pattern[p] == '%' {
p++
if p < end-1 && matchClass(c, ms.pattern[p]) {
return sig
}
p++
} else if p+2 < end-1 && ms.pattern[p+1] == '-' {
// Range a-z (but not if - is at end before ])
if c >= ms.pattern[p] && c <= ms.pattern[p+2] {
return sig
}
p += 3
} else {
if c == ms.pattern[p] {
return sig
}
p++
}
}
return !sig
}
// Start a new capture
func (ms *matchState) startCapture(s, p int, what int) (int, bool) {
if ms.numCaptures >= patternMaxCaptures {
Errorf(ms.l, "too many captures")
}
ms.captures = append(ms.captures, capture{start: s, end: what})
ms.numCaptures++
res, ok := ms.match(s, p)
if !ok {
ms.numCaptures--
ms.captures = ms.captures[:len(ms.captures)-1]
}
return res, ok
}
// End a capture
func (ms *matchState) endCapture(s, p int) (int, bool) {
// Find the most recent unfinished capture
for i := ms.numCaptures - 1; i >= 0; i-- {
if ms.captures[i].end == -1 {
ms.captures[i].end = s
res, ok := ms.match(s, p)
if !ok {
ms.captures[i].end = -1
}
return res, ok
}
}
Errorf(ms.l, "invalid pattern capture")
return 0, false
}
// Match balanced pair %bxy
func (ms *matchState) matchBalance(s, p int) (int, bool) {
if p+1 >= len(ms.pattern) {
Errorf(ms.l, "malformed pattern (missing arguments to '%%b')")
}
open, close := ms.pattern[p], ms.pattern[p+1]
if s >= ms.srcEnd || ms.src[s] != open {
return 0, false
}
count := 1
s++
for s < ms.srcEnd {
if ms.src[s] == close {
count--
if count == 0 {
return s + 1, true
}
} else if ms.src[s] == open {
count++
}
s++
}
return 0, false
}
// Get capture reference %1-%9
func (ms *matchState) checkCapture(c byte) int {
if c < '1' || c > '9' {
Errorf(ms.l, "invalid capture index %%"+string(c))
}
n := int(c - '1')
// C Lua: all three conditions produce "invalid capture index %N"
if n >= ms.numCaptures || ms.captures[n].end == -1 {
Errorf(ms.l, "invalid capture index %%%d", n+1)
}
return n
}
// Match against captured string %1-%9
func (ms *matchState) matchCapture(s, p int) (int, bool) {
n := ms.checkCapture(ms.pattern[p])
cap := ms.captures[n]
length := cap.end - cap.start
if s+length > ms.srcEnd {
return 0, false
}
if ms.src[s:s+length] != ms.src[cap.start:cap.end] {
return 0, false
}
return s + length, true
}
// Match frontier pattern %f[set]
func (ms *matchState) matchFrontier(s, p int) (int, bool) {
if p >= len(ms.pattern) || ms.pattern[p] != '[' {
Errorf(ms.l, "missing '[' after '%%f' in pattern")
}
end := classEnd(ms.pattern, p)
if end < 0 {
Errorf(ms.l, "malformed pattern (missing ']')")
}
var prev byte = 0
if s > 0 {
prev = ms.src[s-1]
}
var curr byte = 0
if s < ms.srcEnd {
curr = ms.src[s]
}
if ms.matchBracketClass(prev, p, end) || !ms.matchBracketClass(curr, p, end) {
return 0, false
}
return s, true // Return same position (frontier is zero-width)
}
// Match with max expansion (greedy)
func (ms *matchState) maxExpand(s, p, ep int) (int, bool) {
i := 0
for s+i < ms.srcEnd {
matched, _ := ms.singleMatch(ms.src[s+i], p)
if !matched {
break
}
i++
}
// Try to match rest with maximum, then backtrack
for i >= 0 {
res, ok := ms.match(s+i, ep)
if ok {
return res, true
}
i--
}
return 0, false
}
// Match with min expansion (non-greedy)
func (ms *matchState) minExpand(s, p, ep int) (int, bool) {
for {
res, ok := ms.match(s, ep)
if ok {
return res, true
}
if s < ms.srcEnd {
matched, _ := ms.singleMatch(ms.src[s], p)
if matched {
s++
continue
}
}
return 0, false
}
}
// Main matching function
func (ms *matchState) match(s, p int) (int, bool) {
ms.matchDepth++
if ms.matchDepth > maxMatchDepth {
Errorf(ms.l, "pattern too complex")
}
defer func() { ms.matchDepth-- }()
for p < len(ms.pattern) {
switch ms.pattern[p] {
case '(':
if p+1 < len(ms.pattern) && ms.pattern[p+1] == ')' {
// Position capture: use -2 as marker
return ms.startCapture(s, p+2, -2)
}
return ms.startCapture(s, p+1, -1) // -1 = unfinished
case ')':
return ms.endCapture(s, p+1)
case '$':
if p+1 == len(ms.pattern) {
// End anchor
if s == ms.srcEnd {
return s, true
}
return 0, false
}
// $ not at end is literal
goto dflt
case '%':
if p+1 >= len(ms.pattern) {
Errorf(ms.l, "malformed pattern (ends with '%%')")
}
switch ms.pattern[p+1] {
case 'b':
newS, ok := ms.matchBalance(s, p+2)
if !ok {
return 0, false
}
s = newS
p += 4
continue
case 'f':
newS, ok := ms.matchFrontier(s, p+2)
if !ok {
return 0, false
}
s = newS
end := classEnd(ms.pattern, p+2)
if end < 0 {
Errorf(ms.l, "malformed pattern (missing ']')")
}
p = end
continue
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
newS, ok := ms.matchCapture(s, p+1)
if !ok {
return 0, false
}
s = newS
p += 2
continue
default:
goto dflt
}
default:
goto dflt
}
dflt:
// Find end of current pattern item
ep := p
switch ms.pattern[p] {
case '%':
ep = p + 2
case '[':
ep = classEnd(ms.pattern, p)
if ep < 0 {
Errorf(ms.l, "malformed pattern (missing ']')")
}
default:
ep = p + 1
}
// Check for repetition
if ep < len(ms.pattern) {
switch ms.pattern[ep] {
case '*':
return ms.maxExpand(s, p, ep+1)
case '+':
// One or more
if s < ms.srcEnd {
matched, _ := ms.singleMatch(ms.src[s], p)
if matched {
return ms.maxExpand(s+1, p, ep+1)
}
}
return 0, false
case '-':
return ms.minExpand(s, p, ep+1)
case '?':
// Zero or one
if s < ms.srcEnd {
matched, _ := ms.singleMatch(ms.src[s], p)
if matched {
res, ok := ms.match(s+1, ep+1)
if ok {
return res, true
}
}
}
return ms.match(s, ep+1)
}
}
// No repetition, single match
if s >= ms.srcEnd {
return 0, false
}
matched, _ := ms.singleMatch(ms.src[s], p)
if !matched {
return 0, false
}
s++
p = ep
}
return s, true
}
// Push capture results onto stack
func (ms *matchState) pushCaptures(sstart, send int) int {
if ms.numCaptures == 0 {
// No captures, push whole match
ms.l.PushString(ms.src[sstart:send])
return 1
}
for i := 0; i < ms.numCaptures; i++ {
cap := ms.captures[i]
if cap.end == -1 {
Errorf(ms.l, "unfinished capture")
}
if cap.end == -2 {
// Position capture: () returns position as integer
ms.l.PushInteger(cap.start + 1) // 1-based position
} else {
ms.l.PushString(ms.src[cap.start:cap.end])
}
}
return ms.numCaptures
}
// Push one capture for gsub
func (ms *matchState) pushOneCapture(i, sstart, send int) {
if i >= ms.numCaptures {
if i == 0 {
ms.l.PushString(ms.src[sstart:send])
} else {
Errorf(ms.l, "invalid capture index %%%d", i+1)
}
return
}
cap := ms.captures[i]
if cap.end == -1 {
Errorf(ms.l, "unfinished capture")
}
if cap.end == -2 {
// Position capture
ms.l.PushInteger(cap.start + 1)
} else {
ms.l.PushString(ms.src[cap.start:cap.end])
}
}
// Check if pattern has special characters
func noSpecials(pattern string) bool {
return !strings.ContainsAny(pattern, patternSpecials)
}
func findHelper(l *State, isFind bool) int {
s, p := CheckString(l, 1), CheckString(l, 2)
init := relativePosition(OptInteger(l, 3, 1), len(s))
if init < 1 {
init = 1
} else if init > len(s)+1 {
l.PushNil()
return 1
}
// For find with plain=true or no special characters, use simple search
if isFind {
isPlain := l.ToBoolean(4)
if isPlain || noSpecials(p) {
if start := strings.Index(s[init-1:], p); start >= 0 {
l.PushInteger(start + init)
l.PushInteger(start + init + len(p) - 1)
return 2
}
l.PushNil()
return 1
}
}
// Pattern matching
anchor := len(p) > 0 && p[0] == '^'
patStart := 0
if anchor {
patStart = 1
}
ms := &matchState{
l: l,
src: s,
srcEnd: len(s),
pattern: p[patStart:],
}
spos := init - 1 // Convert to 0-based
for {
ms.captures = ms.captures[:0]
ms.numCaptures = 0
ms.matchDepth = 0
if end, ok := ms.match(spos, 0); ok {
if isFind {
l.PushInteger(spos + 1) // 1-based start
l.PushInteger(end) // 1-based end (end is already past-the-end in 0-based)
return 2 + ms.pushCaptures(spos, end)
}
return ms.pushCaptures(spos, end)
}
spos++
if spos > len(s) || anchor {
break
}
}
l.PushNil()
return 1
}
// scanFormat greedily scans a format specifier (like C Lua's getformat).
// It collects flags, digits, dots, and the conversion character.
func scanFormat(l *State, fs string) string {
const allFlags = "-+ #0123456789."
i := 0
for i < len(fs) && strings.ContainsRune(allFlags, rune(fs[i])) {
i++
}
i++ // include the conversion specifier
if i > 22 { // MAX_FORMAT - 10
Errorf(l, "invalid format (too long)")
}
return "%" + fs[:i]
}
// checkFormat validates a format specifier per conversion type (like C Lua's checkformat).
// flags: allowed flags for this conversion type.
// precision: whether precision is allowed.
func checkFormat(l *State, form string, flags string, precision bool) {
spec := form[1:] // skip '%'
// Skip allowed flags
j := 0
for j < len(spec) && strings.ContainsRune(flags, rune(spec[j])) {
j++
}
spec = spec[j:]
if len(spec) > 0 && spec[0] != '0' {
// Skip up to 2 digits (width)
for k := 0; k < 2 && len(spec) > 0 && spec[0] >= '0' && spec[0] <= '9'; k++ {
spec = spec[1:]
}
if len(spec) > 0 && spec[0] == '.' && precision {
spec = spec[1:]
// Skip up to 2 digits (precision)
for k := 0; k < 2 && len(spec) > 0 && spec[0] >= '0' && spec[0] <= '9'; k++ {
spec = spec[1:]
}
}
}
// Must end at the conversion specifier (alpha character)
if len(spec) != 1 || !(spec[0] >= 'A' && spec[0] <= 'Z') && !(spec[0] >= 'a' && spec[0] <= 'z') {
Errorf(l, "invalid conversion specification: '%s'", form)
}
}
func formatHelper(l *State, fs string, argCount int) string {
var b bytes.Buffer
for i, arg := 0, 1; i < len(fs); i++ {
if fs[i] != '%' {
b.WriteByte(fs[i])
} else if i++; fs[i] == '%' {
b.WriteByte(fs[i])
} else {
if arg++; arg > argCount {
ArgumentError(l, arg, "no value")
}
f := scanFormat(l, fs[i:])
switch i += len(f) - 2; fs[i] {
case 'c':
checkFormat(l, f, "-", false)
// Lua's %c produces a single byte (like string.char), not UTF-8
c := CheckInteger(l, arg)
charStr := string([]byte{byte(c)})
fmtStr := f[:len(f)-1] + "s"
fmt.Fprintf(&b, fmtStr, charStr)
case 'i': // The fmt package doesn't support %i.
f = f[:len(f)-1] + "d"
fallthrough
case 'd':
checkFormat(l, f, "-+0 ", true)
// Lua 5.3: handle integers directly to preserve precision
v := l.ToValue(arg)
switch val := v.(type) {
case int64:
fmt.Fprintf(&b, f, val)
case float64:
ArgumentCheck(l, math.Floor(val) == val && -math.Pow(2, 63) <= val && val < math.Pow(2, 63), arg, "number has no integer representation")
fmt.Fprintf(&b, f, int64(val))
default:
Errorf(l, "number expected")
}
case 'u': // The fmt package doesn't support %u.
checkFormat(l, f, "-0", true)
// Lua 5.3: handle integers as unsigned
// Preserve format flags/precision by replacing 'u' with 'd'
fmtStr := f[:len(f)-1] + "d"
v := l.ToValue(arg)
switch val := v.(type) {
case int64:
fmt.Fprintf(&b, fmtStr, uint64(val))
case float64:
ArgumentCheck(l, math.Floor(val) == val && 0.0 <= val && val < math.Pow(2, 64), arg, "not a non-negative number in proper range")
fmt.Fprintf(&b, fmtStr, uint64(val))
default:
Errorf(l, "number expected")
}
case 'o', 'x', 'X':
checkFormat(l, f, "-#0", true)
// Lua 5.3: integers (including negative) are treated as unsigned
v := l.ToValue(arg)
switch val := v.(type) {
case int64:
fmt.Fprintf(&b, f, uint64(val))
case float64:
ArgumentCheck(l, 0.0 <= val && val < math.Pow(2, 64), arg, "not a non-negative number in proper range")
fmt.Fprintf(&b, f, uint64(val))
default:
Errorf(l, "number expected")
}
case 'e', 'E', 'f', 'g', 'G':
checkFormat(l, f, "-+ #0", true)
fmt.Fprintf(&b, f, CheckNumber(l, arg))
case 'a', 'A':
checkFormat(l, f, "-+ #0", true)
// Lua 5.3: hexadecimal floating-point format
// Go uses %x/%X for hex floats, Lua uses %a/%A
n := CheckNumber(l, arg)
if fs[i] == 'a' {
f = f[:len(f)-1] + "x"
} else {
f = f[:len(f)-1] + "X"
}
s := fmt.Sprintf(f, n)
// Normalize exponent: Go uses 2-digit exponent (P+00), Lua uses minimal (P+0)
// Remove leading zeros from exponent
for j := 0; j < len(s); j++ {
if (s[j] == 'p' || s[j] == 'P') && j+2 < len(s) {
// Found exponent, check for sign
expStart := j + 1
if s[expStart] == '+' || s[expStart] == '-' {
expStart++
}
// Remove leading zeros from exponent (but keep at least one digit)
expEnd := len(s)
numStart := expStart
for numStart < expEnd-1 && s[numStart] == '0' {
numStart++
}
if numStart > expStart {
s = s[:expStart] + s[numStart:]
}
break
}
}
b.WriteString(s)
case 'q':
if len(f) > 2 { // has modifiers
Errorf(l, "specifier '%%q' cannot have modifiers")
}
// Lua 5.3: %q handles multiple types
switch v := l.ToValue(arg).(type) {
case nil:
b.WriteString("nil")
case bool:
if v {
b.WriteString("true")
} else {
b.WriteString("false")
}
case int64:
// For mininteger, use hex format since decimal would be parsed as float
if v == math.MinInt64 {
fmt.Fprintf(&b, "0x%x", uint64(v))
} else {
fmt.Fprintf(&b, "%d", v)
}
case float64:
// Use hex float format for precise representation
if math.IsInf(v, 0) || math.IsNaN(v) {
// Special values can't be represented as literals
if math.IsInf(v, 1) {
b.WriteString("1e9999")
} else if math.IsInf(v, -1) {
b.WriteString("-1e9999")
} else {
b.WriteString("(0/0)")
}
} else {
fmt.Fprintf(&b, "%x", v)
}
case string:
b.WriteByte('"')
for i := 0; i < len(v); i++ {
switch v[i] {
case '"', '\\', '\n':
b.WriteByte('\\')
b.WriteByte(v[i])
default:
if 0x20 <= v[i] && v[i] != 0x7f { // ASCII control characters don't correspond to a Unicode range.
b.WriteByte(v[i])
} else if i+1 < len(v) && unicode.IsDigit(rune(v[i+1])) {
fmt.Fprintf(&b, "\\%03d", v[i])
} else {
fmt.Fprintf(&b, "\\%d", v[i])
}
}
}
b.WriteByte('"')
default:
Errorf(l, "no literal")
}
case 'p':
checkFormat(l, f, "-", false)
v := l.indexToValue(l.AbsIndex(arg))
var pstr string
switch val := v.(type) {
case string:
if len(val) > 0 {
pstr = fmt.Sprintf("%p", unsafe.StringData(val))
}
case *table:
pstr = fmt.Sprintf("%p", val)
case *luaClosure:
pstr = fmt.Sprintf("%p", val)
case *goClosure:
pstr = fmt.Sprintf("%p", val)
case *goFunction:
pstr = fmt.Sprintf("%p", val)
case *userData:
pstr = fmt.Sprintf("%p", val)
case *State:
pstr = fmt.Sprintf("%p", val)
}
if pstr == "" {
pstr = "(null)"
}
// Apply width/alignment from format string
if len(f) > 2 {
// Replace %p with %s in format and use the pointer string
fmtStr := f[:len(f)-1] + "s"
fmt.Fprintf(&b, fmtStr, pstr)
} else {
b.WriteString(pstr)
}
case 's':
s, _ := ToStringMeta(l, arg)
if len(f) == 2 { // no modifiers, just "%s"
b.WriteString(s)
} else {
checkFormat(l, f, "-", true)
// Lua 5.3: %s with width/precision must error if string contains zeros
if strings.ContainsRune(s, 0) {
ArgumentCheck(l, false, arg, "string contains zeros")
}
if !strings.ContainsRune(f, '.') && len(s) >= 100 {
b.WriteString(s)
} else {
fmt.Fprintf(&b, f, s)
}
}
default:
Errorf(l, "invalid conversion '%s' to 'format'", f)
}
}
}
return b.String()
}
// Pack/Unpack support for Lua 5.3
// Format options:
// < = little endian, > = big endian, = = native endian
// ![n] = set max alignment to n (1-16, default native)
// b/B = signed/unsigned byte
// h/H = signed/unsigned short (2 bytes)
// l/L = signed/unsigned long (4 bytes)
// j/J = lua_Integer/lua_Unsigned (8 bytes)
// T = size_t (8 bytes)
// i[n]/I[n] = signed/unsigned int with n bytes (default 4)
// f = float (4 bytes), d = double (8 bytes), n = lua_Number (8 bytes)
// cn = fixed string of n bytes
// z = zero-terminated string
// s[n] = string with length prefix of n bytes (default 8)
// x = one byte padding
// Xop = align to option op (no data)
// (space) = ignored
type packState struct {
fmt string
pos int
littleEnd bool
maxAlign int
alignExplicit bool // true if ! was used explicitly
}
func newPackState(fmt string) *packState {
return &packState{
fmt: fmt,
pos: 0,
littleEnd: nativeEndian() == binary.LittleEndian,
maxAlign: 1, // default is 1 (no alignment); ! option changes this
alignExplicit: false,
}
}
func nativeEndian() binary.ByteOrder {
// Check native endianness using unsafe
var x uint16 = 0x0102
b := *(*[2]byte)(unsafe.Pointer(&x))
if b[0] == 0x02 {
return binary.LittleEndian
}
return binary.BigEndian
}
func (ps *packState) byteOrder() binary.ByteOrder {
if ps.littleEnd {
return binary.LittleEndian
}
return binary.BigEndian
}
func (ps *packState) eof() bool {
return ps.pos >= len(ps.fmt)
}
func (ps *packState) peek() byte {
if ps.eof() {
return 0
}
return ps.fmt[ps.pos]
}
func (ps *packState) next() byte {
if ps.eof() {
return 0
}
c := ps.fmt[ps.pos]
ps.pos++
return c
}
func (ps *packState) getNum(def int) int {
if ps.eof() || !isDigit(ps.peek()) {
return def
}
n := 0
// Limit to prevent overflow: stop when n * 10 + 9 would overflow.
// This matches Lua 5.3's behavior which leaves excess digits unconsumed,
// causing them to be treated as invalid format options.
// Lua uses INT_MAX (2^31-1) even on 64-bit systems.
const maxSize = 0x7FFFFFFF // INT_MAX
const limit = (maxSize - 9) / 10
for !ps.eof() && isDigit(ps.peek()) && n <= limit {
n = n*10 + int(ps.next()-'0')
}
return n
}
func isDigit(c byte) bool {
return c >= '0' && c <= '9'
}
func (ps *packState) optSize(def int) int {
return ps.getNum(def)
}
func (ps *packState) align(size int) int {
if size > ps.maxAlign {
size = ps.maxAlign
}
return size
}
// isPowerOf2 returns true if n is a power of 2
func isPowerOf2(n int) bool {
return n > 0 && (n&(n-1)) == 0
}
func addPadding(buf *bytes.Buffer, pos, align int) int {
if align <= 1 {
return 0
}
pad := (align - (pos % align)) % align
for i := 0; i < pad; i++ {
buf.WriteByte(0)
}
return pad
}
func stringPack(l *State) int {
fmtStr := CheckString(l, 1)
ps := newPackState(fmtStr)
var buf bytes.Buffer
arg := 2
totalSize := 0
for !ps.eof() {
opt := ps.next()
switch opt {
case ' ': // ignored
continue
case '<':
ps.littleEnd = true
case '>':
ps.littleEnd = false
case '=':
ps.littleEnd = nativeEndian() == binary.LittleEndian
case '!':
ps.maxAlign = ps.optSize(8)
ps.alignExplicit = true
if ps.maxAlign < 1 || ps.maxAlign > 16 {
Errorf(l, "integral size (%d) out of limits [1,16]", ps.maxAlign)
}
case 'b': // signed byte
n := CheckInteger(l, arg)
arg++
if n < -128 || n > 127 {
ArgumentError(l, arg-1, "integer overflow")
}
buf.WriteByte(byte(int8(n)))
totalSize++
case 'B': // unsigned byte
n := CheckInteger(l, arg)
arg++
if n < 0 || n > 255 {
ArgumentError(l, arg-1, "unsigned overflow")
}
buf.WriteByte(byte(n))
totalSize++
case 'h': // signed short (2 bytes)
n := CheckInteger(l, arg)
arg++
align := ps.align(2)
pad := addPadding(&buf, totalSize, align)
totalSize += pad
b := make([]byte, 2)
ps.byteOrder().PutUint16(b, uint16(int16(n)))
buf.Write(b)
totalSize += 2
case 'H': // unsigned short (2 bytes)
n := CheckInteger(l, arg)
arg++
align := ps.align(2)
pad := addPadding(&buf, totalSize, align)
totalSize += pad