/
StringLib.java
1506 lines (1352 loc) · 42.3 KB
/
StringLib.java
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
/*
Copyright (c) 2007-2009 Kristofer Karlsson <kristofer.karlsson@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package se.krka.kahlua.stdlib;
import se.krka.kahlua.vm.*;
public final class StringLib implements JavaFunction {
private static final int SUB = 0;
private static final int CHAR = 1;
private static final int BYTE = 2;
private static final int LOWER = 3;
private static final int UPPER = 4;
private static final int REVERSE = 5;
private static final int FORMAT = 6;
private static final int FIND = 7;
private static final int MATCH = 8;
private static final int GSUB = 9;
private static final int NUM_FUNCTIONS = 10;
private static final boolean[] SPECIALS = new boolean[256];
static {
String s = "^$*+?.([%-";
for (int i = 0; i < s.length(); i++) {
SPECIALS[(int) s.charAt(i)] = true;
}
}
private static final int LUA_MAXCAPTURES = 32;
private static final char L_ESC = '%';
private static final int CAP_UNFINISHED = ( -1 );
private static final int CAP_POSITION = ( -2 );
private static final String[] names;
private static final StringLib[] functions;
// NOTE: String.class won't work in J2ME - so this is used as a workaround
private static final Class STRING_CLASS = "".getClass();
static {
names = new String[NUM_FUNCTIONS];
names[SUB] = "sub";
names[CHAR] = "char";
names[BYTE] = "byte";
names[LOWER] = "lower";
names[UPPER] = "upper";
names[REVERSE] = "reverse";
names[FORMAT] = "format";
names[FIND] = "find";
names[MATCH] = "match";
names[GSUB] = "gsub";
functions = new StringLib[NUM_FUNCTIONS];
for (int i = 0; i < NUM_FUNCTIONS; i++) {
functions[i] = new StringLib(i);
}
}
/** @exclude */
private final int methodId;
public StringLib(int index) {
this.methodId = index;
}
public static void register(Platform platform, KahluaTable env) {
KahluaTable string = platform.newTable();
for (int i = 0; i < NUM_FUNCTIONS; i++) {
string.rawset(names[i], functions[i]);
}
string.rawset("__index", string);
KahluaTable metatables = KahluaUtil.getClassMetatables(platform, env);
metatables.rawset(STRING_CLASS, string);
env.rawset("string", string);
}
public String toString() {
return names[methodId];
}
public int call(LuaCallFrame callFrame, int nArguments) {
switch (methodId) {
case SUB: return sub(callFrame, nArguments);
case CHAR: return stringChar(callFrame, nArguments);
case BYTE: return stringByte(callFrame, nArguments);
case LOWER: return lower(callFrame, nArguments);
case UPPER: return upper(callFrame, nArguments);
case REVERSE: return reverse(callFrame, nArguments);
case FORMAT: return format(callFrame, nArguments);
case FIND: return findAux(callFrame, true);
case MATCH: return findAux(callFrame, false);
case GSUB: return gsub(callFrame, nArguments);
default: return 0; // Should never happen.
}
}
private long unsigned(long v) {
if (v < 0L) {
v += (1L << 32);
}
return v;
}
private int format(LuaCallFrame callFrame, int nArguments) {
String f = KahluaUtil.getStringArg(callFrame, 1, names[FORMAT]);
int len = f.length();
int argc = 2;
StringBuffer result = new StringBuffer();
for (int i = 0; i < len; i++) {
char c = f.charAt(i);
if (c == '%') {
i++;
KahluaUtil.luaAssert(i < len, "incomplete option to 'format'");
c = f.charAt(i);
if (c == '%') {
result.append('%');
} else {
// Detect flags
boolean repr = false;
boolean zeroPadding = false;
boolean leftJustify = false;
boolean showPlus = false;
boolean spaceForSign = false;
flagLoop: while (true) {
switch (c) {
case '-':
leftJustify = true;
break;
case '+':
showPlus = true;
break;
case ' ':
spaceForSign = true;
break;
case '#':
repr = true;
break;
case '0':
zeroPadding = true;
break;
default:
break flagLoop;
}
i++;
KahluaUtil.luaAssert(i < len, "incomplete option to 'format'");
c = f.charAt(i);
}
// Detect width
int width = 0;
while (c >= '0' && c <= '9') {
width = 10 * width + c - '0';
i++;
KahluaUtil.luaAssert(i < len, "incomplete option to 'format'");
c = f.charAt(i);
}
// Detect precision
int precision = 0;
boolean hasPrecision = false;
if (c == '.') {
hasPrecision = true;
i++;
KahluaUtil.luaAssert(i < len, "incomplete option to 'format'");
c = f.charAt(i);
while (c >= '0' && c <= '9') {
precision = 10 * precision + c - '0';
i++;
KahluaUtil.luaAssert(i < len, "incomplete option to 'format'");
c = f.charAt(i);
}
}
if (leftJustify) {
zeroPadding = false;
}
// This will be overriden to space for the appropiate specifiers
// Pass 1: set up various variables needed for each specifier
// This simplifies the second pass by being able to combine several specifiers.
int base = 10;
boolean upperCase = false;
int defaultPrecision = 6; // This is the default for all float numerics
String basePrepend = "";
switch (c) {
// Simple character
case 'c':
zeroPadding = false;
break;
// change base
case 'o':
base = 8;
defaultPrecision = 1;
basePrepend = "0";
break;
case 'x':
base = 16;
defaultPrecision = 1;
basePrepend = "0x";
break;
case 'X':
base = 16;
defaultPrecision = 1;
upperCase = true;
basePrepend = "0X";
break;
// unsigned integer and signed integer
case 'u':
defaultPrecision = 1;
break;
case 'd':
case 'i':
defaultPrecision = 1;
break;
case 'e':
break;
case 'E':
upperCase = true;
break;
case 'g':
break;
case 'G':
upperCase = true;
break;
case 'f':
break;
case 's':
zeroPadding = false;
break;
case 'q':
// %q neither needs nor supports width
width = 0;
break;
default:
throw new RuntimeException("invalid option '%" + c +
"' to 'format'");
}
// Set precision
if (!hasPrecision) {
precision = defaultPrecision;
}
if (hasPrecision && base != 10) {
zeroPadding = false;
}
char padCharacter = zeroPadding ? '0' : ' ';
// extend the string by "width" characters, and delete a subsection of them later to get the correct padding width
int resultStartLength = result.length();
if (!leftJustify) {
extend(result, width, padCharacter);
}
// Detect specifier and compute result
switch (c) {
case 'c':
result.append((char)(getDoubleArg(callFrame, argc)).shortValue());
break;
case 'o':
case 'x':
case 'X':
case 'u': {
long vLong = getDoubleArg(callFrame, argc).longValue();
vLong = unsigned(vLong);
if (repr) {
if (base == 8) {
int digits = 0;
long vLong2 = vLong;
while (vLong2 > 0) {
vLong2 /= 8;
digits++;
}
if (precision <= digits) {
result.append(basePrepend);
}
} else if (base == 16) {
if (vLong != 0) {
result.append(basePrepend);
}
}
}
if (vLong != 0 || precision > 0) {
stringBufferAppend(result, vLong, base, false, precision);
}
break;
}
case 'd':
case 'i': {
Double v = getDoubleArg(callFrame, argc);
long vLong = v.longValue();
if (vLong < 0) {
result.append('-');
vLong = -vLong;
} else if (showPlus) {
result.append('+');
} else if (spaceForSign) {
result.append(' ');
}
if (vLong != 0 || precision > 0) {
stringBufferAppend(result, vLong, base, false, precision);
}
break;
}
case 'e':
case 'E':
case 'f': {
Double v = getDoubleArg(callFrame, argc);
boolean isNaN = v.isInfinite() || v.isNaN();
double vDouble = v.doubleValue();
if (KahluaUtil.isNegative(vDouble)) {
if (!isNaN) {
result.append('-');
}
vDouble = -vDouble;
} else if (showPlus) {
result.append('+');
} else if (spaceForSign) {
result.append(' ');
}
if (isNaN) {
result.append(KahluaUtil.numberToString(v));
} else {
if (c == 'f') {
appendPrecisionNumber(result, vDouble, precision, repr);
} else {
appendScientificNumber(result, vDouble, precision, repr, false);
}
}
break;
}
case 'g':
case 'G':
{
// Precision is significant digits for %g
if (precision <= 0) {
precision = 1;
}
// first round to correct significant digits (precision),
// then check which formatting to be used.
Double v = getDoubleArg(callFrame, argc);
boolean isNaN = v.isInfinite() || v.isNaN();
double vDouble = v.doubleValue();
if (KahluaUtil.isNegative(vDouble)) {
if (!isNaN) {
result.append('-');
}
vDouble = -vDouble;
} else if (showPlus) {
result.append('+');
} else if (spaceForSign) {
result.append(' ');
}
if (isNaN) {
result.append(KahluaUtil.numberToString(v));
} else {
double x = roundToSignificantNumbers(vDouble, precision);
/*
* Choose %f version if:
* |v| >= 10^(-4)
* AND
* |v| < 10^(precision)
*
* otherwise, choose %e
*/
if (x == 0 || (x >= 1e-4 && x < (double) KahluaUtil.ipow(10, precision))) {
int iPartSize;
if (x == 0) {
iPartSize = 1;
} else if (Math.floor(x) == 0) {
iPartSize = 0;
} else {
double longValue = x;
iPartSize = 1;
while (longValue >= 10.0) {
longValue /= 10.0;
iPartSize++;
}
}
// format with %f, with precision significant numbers
appendSignificantNumber(result, x, precision - iPartSize, repr);
} else {
// format with %e, with precision significant numbers, i.e. precision -1 digits
// but skip trailing zeros unless repr
appendScientificNumber(result, x, precision - 1, repr, true);
}
}
break;
}
case 's': {
String s = getStringArg(callFrame, argc);
int n = s.length();
if (hasPrecision) {
n = Math.min(precision, s.length());
}
append(result, s, 0, n);
break;
}
case 'q':
String q = getStringArg(callFrame, argc);
result.append('"');
for (int j = 0; j < q.length(); j++) {
char d = q.charAt(j);
switch (d) {
case '\\': result.append("\\"); break;
case '\n': result.append("\\\n"); break;
case '\r': result.append("\\r"); break;
case '"': result.append("\\\""); break;
default: result.append(d);
}
}
result.append('"');
break;
default:
throw new RuntimeException("Internal error");
}
if (leftJustify) {
int currentResultLength = result.length();
int d = width - (currentResultLength - resultStartLength);
if (d > 0) {
extend(result, d, ' ');
}
} else {
int currentResultLength = result.length();
int d = currentResultLength - resultStartLength - width;
d = Math.min(d, width);
if (d > 0) {
result.delete(resultStartLength, resultStartLength + d);
}
if (zeroPadding) {
int signPos = resultStartLength + (width - d);
char ch = result.charAt(signPos);
if (ch == '+' || ch == '-' || ch == ' ') {
result.setCharAt(signPos, '0');
result.setCharAt(resultStartLength, ch);
}
}
}
if (upperCase) {
stringBufferUpperCase(result, resultStartLength);
}
argc++;
}
} else {
result.append(c);
}
}
callFrame.push(result.toString());
return 1;
}
private void append(StringBuffer buffer, String s, int start, int end) {
for (int i = start; i < end; i++) {
buffer.append(s.charAt(i));
}
}
private void extend(StringBuffer buffer, int extraWidth, char padCharacter) {
int preLength = buffer.length();
buffer.setLength(preLength + extraWidth);
for (int i = extraWidth - 1; i >= 0; i--) {
buffer.setCharAt(preLength + i, padCharacter);
}
}
private void stringBufferUpperCase(StringBuffer buffer, int start) {
int length = buffer.length();
for (int i = start; i < length; i++) {
char c = buffer.charAt(i);
if (c >= 'a' && c <= 'z') {
buffer.setCharAt(i, (char) (c - 32));
}
}
}
private static final char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Precondition: value >= 0
* Precondition: 2 <= base <= 16
* @param sb the stringbuffer to append to
* @param value the value to append
* @param base the base to use when formatting (typically 8, 10 or 16)
* @param printZero
* @param minDigits
*/
private static void stringBufferAppend(StringBuffer sb, double value, int base, boolean printZero, int minDigits) {
int startPos = sb.length();
while (value > 0 || minDigits > 0) {
double newValue = Math.floor(value / base);
sb.append(digits[(int) (value - (newValue * base))]);
value = newValue;
minDigits--;
}
int endPos = sb.length() - 1;
if (startPos > endPos && printZero) {
sb.append('0');
} else {
// Note that the digits are in reverse order now, so we need to correct it.
// We can't use StringBuffer.reverse because that reverses the entire string
int swapCount = (1 + endPos - startPos) / 2;
for (int i = swapCount - 1; i >= 0; i--) {
int leftPos = startPos + i;
int rightPos = endPos - i;
char left = sb.charAt(leftPos);
char right = sb.charAt(rightPos);
sb.setCharAt(leftPos, right);
sb.setCharAt(rightPos, left);
}
}
}
/**
* Only works with non-negative numbers
* @param buffer
* @param number
* @param precision
* @param requirePeriod
*/
private void appendPrecisionNumber(StringBuffer buffer, double number, int precision, boolean requirePeriod) {
number = roundToPrecision(number, precision);
double iPart = Math.floor(number);
double fPart = number - iPart;
for (int i = 0; i < precision; i++) {
fPart *= 10.0;
}
fPart = KahluaUtil.round(iPart + fPart) - iPart;
stringBufferAppend(buffer, iPart, 10, true, 0);
if (requirePeriod || precision > 0) {
buffer.append('.');
}
stringBufferAppend(buffer, fPart, 10, false, precision);
}
/**
* Only works with non-negative numbers
* @param buffer
* @param number
* @param significantDecimals
* @param includeTrailingZeros
*/
private void appendSignificantNumber(StringBuffer buffer, double number, int significantDecimals, boolean includeTrailingZeros) {
double iPart = Math.floor(number);
stringBufferAppend(buffer, iPart, 10, true, 0);
double fPart = roundToSignificantNumbers(number - iPart, significantDecimals);
boolean hasNotStarted = iPart == 0 && fPart != 0;
int zeroPaddingBefore = 0;
int scanLength = significantDecimals;
for (int i = 0; i < scanLength; i++) {
fPart *= 10.0;
if (Math.floor(fPart) == 0 && fPart != 0) {
zeroPaddingBefore++;
if (hasNotStarted) {
scanLength++;
}
}
}
fPart = KahluaUtil.round(fPart);
if (!includeTrailingZeros) {
while (fPart > 0 && (fPart % 10) == 0) {
fPart /= 10;
significantDecimals--;
}
}
buffer.append('.');
int periodPos = buffer.length();
extend(buffer, zeroPaddingBefore, '0');
int prePos = buffer.length();
stringBufferAppend(buffer, fPart, 10, false, 0);
int postPos = buffer.length();
int len = postPos - prePos;
if (includeTrailingZeros && len < significantDecimals) {
int padRightSize = significantDecimals - len - zeroPaddingBefore;
extend(buffer, padRightSize, '0');
}
if (!includeTrailingZeros && periodPos == buffer.length()) {
buffer.delete(periodPos - 1, buffer.length());
}
}
private void appendScientificNumber(StringBuffer buffer, double x, int precision, boolean repr, boolean useSignificantNumbers) {
int exponent = 0;
// Run two passes to handle cases such as %.2e with the value 95.
for (int i = 0; i < 2; i++) {
if (x >= 1.0) {
while (x >= 10.0) {
x /= 10.0;
exponent++;
}
} else {
while (x > 0 && x < 1.0) {
x *= 10.0;
exponent--;
}
}
x = roundToPrecision(x, precision);
}
int absExponent = Math.abs(exponent);
char expSign;
if (exponent >= 0) {
expSign = '+';
} else {
expSign = '-';
}
if (useSignificantNumbers) {
appendSignificantNumber(buffer, x, precision, repr);
} else {
appendPrecisionNumber(buffer, x, precision, repr);
}
buffer.append('e');
buffer.append(expSign);
stringBufferAppend(buffer, absExponent, 10, true, 2);
}
private String getStringArg(LuaCallFrame callFrame, int argc) {
return getStringArg(callFrame, argc, names[FORMAT]);
}
private String getStringArg(LuaCallFrame callFrame, int argc, String funcname) {
return KahluaUtil.getStringArg(callFrame, argc, funcname);
}
private Double getDoubleArg(LuaCallFrame callFrame, int argc) {
return getDoubleArg(callFrame, argc, names[FORMAT]);
}
private Double getDoubleArg(LuaCallFrame callFrame, int argc, String name) {
return KahluaUtil.getNumberArg(callFrame, argc, name);
}
private int lower(LuaCallFrame callFrame, int nArguments) {
KahluaUtil.luaAssert(nArguments >= 1, "not enough arguments");
String s = getStringArg(callFrame,1,names[LOWER]);
callFrame.push(s.toLowerCase());
return 1;
}
private int upper(LuaCallFrame callFrame, int nArguments) {
KahluaUtil.luaAssert(nArguments >= 1, "not enough arguments");
String s = getStringArg(callFrame,1,names[UPPER]);
callFrame.push(s.toUpperCase());
return 1;
}
private int reverse(LuaCallFrame callFrame, int nArguments) {
KahluaUtil.luaAssert(nArguments >= 1, "not enough arguments");
String s = getStringArg(callFrame, 1, names[REVERSE]);
s = new StringBuffer(s).reverse().toString();
callFrame.push(s);
return 1;
}
private int stringByte(LuaCallFrame callFrame, int nArguments) {
KahluaUtil.luaAssert(nArguments >= 1, "not enough arguments");
String s = getStringArg(callFrame, 1, names[BYTE]);
int i = nullDefault(1, KahluaUtil.getOptionalNumberArg(callFrame, 2));
int j = nullDefault(i, KahluaUtil.getOptionalNumberArg(callFrame, 3));
int len = s.length();
if (i < 0) {
i += len + 1;
}
if (i <= 0) {
i = 1;
}
if (j < 0) {
j += len + 1;
} else if (j > len) {
j = len;
}
int nReturns = 1 +j - i;
if (nReturns <= 0) {
return 0;
}
callFrame.setTop(nReturns);
int offset = i - 1;
for (int i2 = 0; i2 < nReturns; i2++) {
char c = s.charAt(offset + i2);
callFrame.set(i2, KahluaUtil.toDouble(c));
}
return nReturns;
}
private int nullDefault(int defaultValue, Double val) {
if (val == null) {
return defaultValue;
}
return val.intValue();
}
private int stringChar(LuaCallFrame callFrame, int nArguments) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < nArguments; i++) {
int num = getDoubleArg(callFrame, i + 1, names[CHAR]).intValue();
sb.append((char) num);
}
return callFrame.push(sb.toString());
}
private int sub(LuaCallFrame callFrame, int nArguments) {
String s = getStringArg(callFrame, 1, names[SUB]);
double start = getDoubleArg(callFrame, 2, names[SUB]).doubleValue();
double end = -1;
if (nArguments >= 3) {
end = getDoubleArg(callFrame, 3, names[SUB]).doubleValue();
}
String res;
int istart = (int) start;
int iend = (int) end;
int len = s.length();
if (istart < 0) {
istart = Math.max(len + istart + 1, 1);
} else if (istart == 0) {
istart = 1;
}
if (iend < 0) {
iend = Math.max(0, iend + len + 1);
} else if (iend > len) {
iend = len;
}
if (istart > iend) {
return callFrame.push("");
}
res = s.substring(istart - 1, iend);
return callFrame.push(res);
}
/**
* Rounds to keep <em>precision</em> decimals. Rounds towards even numbers.
* @param x the number to round
* @param precision the precision to round to. A precision of 3 will for instance round 1.65432 to 1.654
* @return the rounded number
*/
public static double roundToPrecision(double x, int precision) {
double roundingOffset = KahluaUtil.ipow(10, precision);
return KahluaUtil.round(x * roundingOffset) / roundingOffset;
}
public static double roundToSignificantNumbers(double x, int precision) {
if (x == 0) {
return 0;
}
if (x < 0) {
return -roundToSignificantNumbers(-x, precision);
}
double lowerLimit = KahluaUtil.ipow(10, precision - 1);
double upperLimit = lowerLimit * 10.0;
double multiplier = 1.0;
while (multiplier * x < lowerLimit) {
multiplier *= 10.0;
}
while (multiplier * x >= upperLimit) {
multiplier /= 10.0;
}
return KahluaUtil.round(x * multiplier) / multiplier;
}
/* Pattern Matching
* Original code that this was adapted from is copyright (c) 2008 groundspeak, inc.
*/
/** @exclude */
public static class MatchState {
public final LuaCallFrame callFrame;
public final StringPointer src_init; /* init of source string */
public final int endIndex; /* end (`\0') of source string */
public final Capture[] capture;
public MatchState(LuaCallFrame callFrame, StringPointer srcInit, int endIndex) {
this.callFrame = callFrame;
this.src_init = srcInit;
this.endIndex = endIndex;
capture = new Capture[LUA_MAXCAPTURES];
for (int i = 0; i < LUA_MAXCAPTURES; i++) {
capture[i] = new Capture();
}
}
public int level; /* total number of captures (finished or unfinished) */
/** @exclude */
public static class Capture {
public StringPointer init;
public int len;
}
public Object getCapture(int i) {
if (i >= level) {
return null;
}
if (capture[i].len == CAP_POSITION) {
return new Double(src_init.length() - capture[i].init.length() + 1);
} else {
return capture[i].init.getStringSubString(capture[i].len);
}
}
}
/** @exclude */
public static class StringPointer {
private final String string;
private int index = 0;
public StringPointer(String original) {
this.string = original;
}
public StringPointer(String original, int index) {
this.string = original;
this.index = index;
}
public StringPointer getClone() {
return new StringPointer(string, index);
}
public int getIndex () {
return index;
}
public void setIndex (int ind) {
index = ind;
}
public String getString() {
if (index == 0) {
return string;
}
return string.substring(index);
}
public int getStringLength() {
return getStringLength(0);
}
public int getStringLength(int i) {
return string.length() - (index + i);
}
public String getStringSubString(int len) {
return string.substring(index, index + len);
}
public char getChar() {
return getChar(0);
}
public char getChar(int strIndex) {
int i = index + strIndex;
if (i >= string.length()) {
return '\0';
} else {
return string.charAt(i);
}
}
public int length() {
return string.length () - index;
}
public int postIncrStringI(int num) {
int oldIndex = index;
index += num;
return oldIndex;
}
public int preIncrStringI(int num) {
index += num;
return index;
}
public char postIncrString (int num) {
char c = getChar();
index += num;
return c;
}
public int compareTo(StringPointer cmp, int len) {
for (int i = 0; i < len; i++) {
int val = getChar(i) - cmp.getChar(i);
if (val != 0) {
return val;
}
}
return 0;
}
}
private static Object push_onecapture ( MatchState ms, int i, StringPointer s, StringPointer e ) {
if (i >= ms.level) {
if ( i == 0 ) { // ms->level == 0, too
String res = s.string.substring(s.index, e.index);
ms.callFrame.push(res);
return res;
} else {
throw new RuntimeException("invalid capture index");
}
} else {
int l = ms.capture[i].len;
if (l == CAP_UNFINISHED) {
throw new RuntimeException("unfinished capture");
} else if (l == CAP_POSITION) {
Double res = new Double(ms.src_init.length() - ms.capture[i].init.length() + 1);
ms.callFrame.push(res);
return res;
} else {
int index = ms.capture[i].init.index;
String res = ms.capture[i].init.string.substring(index, index+l);
ms.callFrame.push(res);
return res;
}
}
}
private static int push_captures ( MatchState ms, StringPointer s, StringPointer e ) {
int nlevels = ( ms.level == 0 && s != null ) ? 1 : ms.level;
KahluaUtil.luaAssert(nlevels <= LUA_MAXCAPTURES, "too many captures");
for (int i = 0; i < nlevels; i++) {
push_onecapture (ms, i, s, e);
}
return nlevels; // number of strings pushed
}
private static boolean noSpecialChars(String pattern) {
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (c < 256 && SPECIALS[c]) {
return false;
}
}
return true;
}
private static int findAux (LuaCallFrame callFrame, boolean find ) {
String f = find ? names[FIND] : names[MATCH];
String source = KahluaUtil.getStringArg(callFrame, 1, f);
String pattern = KahluaUtil.getStringArg(callFrame, 2, f);
Double i = KahluaUtil.getOptionalNumberArg(callFrame, 3);
boolean plain = KahluaUtil.boolEval(KahluaUtil.getOptionalArg(callFrame, 4));
int init = (i == null ? 0 : i.intValue() - 1);
if ( init < 0 ) {
// negative numbers count back from the end of the string.
init += source.length();
if ( init < 0 ) {
init = 0; // if we are still negative, just start at the beginning.
}
} else if ( init > source.length() ) {
init = source.length();