-
Notifications
You must be signed in to change notification settings - Fork 178
/
StringSupport.java
1876 lines (1678 loc) · 68.9 KB
/
StringSupport.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
/*
***** BEGIN LICENSE BLOCK *****
* Version: EPL 2.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Eclipse Public
* License Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/epl-v20.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the EPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the EPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.truffleruby.core.string;
import static com.oracle.truffle.api.strings.TruffleString.CodeRange.ASCII;
import static com.oracle.truffle.api.strings.TruffleString.CodeRange.VALID;
import java.util.Arrays;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.nodes.Node;
import com.oracle.truffle.api.strings.AbstractTruffleString;
import com.oracle.truffle.api.strings.InternalByteArray;
import com.oracle.truffle.api.strings.TruffleString;
import com.oracle.truffle.api.strings.TruffleString.CreateCodePointIteratorNode;
import com.oracle.truffle.api.strings.TruffleString.ErrorHandling;
import com.oracle.truffle.api.strings.TruffleString.FromByteArrayNode;
import org.graalvm.collections.Pair;
import org.graalvm.shadowed.org.jcodings.Config;
import org.graalvm.shadowed.org.jcodings.Encoding;
import org.graalvm.shadowed.org.jcodings.IntHolder;
import org.graalvm.shadowed.org.jcodings.ascii.AsciiTables;
import org.graalvm.shadowed.org.jcodings.constants.CharacterType;
import org.graalvm.shadowed.org.jcodings.specific.ASCIIEncoding;
import org.graalvm.shadowed.org.jcodings.specific.UTF8Encoding;
import org.graalvm.shadowed.org.jcodings.util.IntHash;
import org.truffleruby.RubyContext;
import org.truffleruby.collections.ByteArrayBuilder;
import org.truffleruby.collections.IntHashMap;
import org.truffleruby.core.array.ArrayUtils;
import org.truffleruby.core.encoding.Encodings;
import org.truffleruby.core.encoding.RubyEncoding;
import org.truffleruby.core.encoding.TStringUtils;
import org.truffleruby.language.control.RaiseException;
import org.truffleruby.utils.Utils;
public final class StringSupport {
public static final int TRANS_SIZE = 256;
// We don't know how many characters the case map operation will produce and it requires a non-exposed
// minimum buffer size for its internal operations. We create a buffer larger than expected to avoid
// exceeding the buffer size.
private static final int CASE_MAP_BUFFER_SIZE = 32;
/** codeRange==null means unknown. recoverIfBroken=false so can return negative values. */
private static int characterLength(Encoding encoding, TruffleString.CodeRange codeRange, byte[] bytes,
int byteOffset, int byteEnd) {
assert byteOffset >= 0 && byteOffset < byteEnd && byteEnd <= bytes.length;
if (codeRange == null) {
return preciseLength(encoding, bytes, byteOffset, byteEnd);
}
switch (codeRange) {
case ASCII:
return 1;
case VALID:
return characterLengthValid(encoding, bytes, byteOffset, byteEnd);
case BROKEN:
return preciseLength(encoding, bytes, byteOffset, byteEnd);
default:
throw Utils.unsupportedOperation("unknown code range value: ", codeRange);
}
}
/** recoverIfBroken=false so can return negative values */
public static int characterLength(RubyEncoding encoding, byte[] bytes, int byteOffset, int byteEnd) {
assert byteOffset >= 0 && byteOffset < byteEnd && byteEnd <= bytes.length;
return preciseLength(encoding.jcoding, bytes, byteOffset, byteEnd);
}
private static int characterLengthValid(Encoding encoding, byte[] bytes, int byteOffset, int byteEnd) {
if (encoding.isUTF8()) {
return utf8CharWidth(bytes[byteOffset]);
} else if (encoding.isAsciiCompatible()) {
if (bytes[byteOffset] >= 0) {
return 1;
} else {
return encLength(encoding, bytes, byteOffset, byteEnd);
}
} else if (encoding.isFixedWidth()) {
final int width = encoding.minLength();
assert (byteEnd - byteOffset) >= width;
return width;
} else {
return encLength(encoding, bytes, byteOffset, byteEnd);
}
}
public static int utf8CharWidth(byte b) {
if (b >= 0) {
return 1;
} else {
switch (b & 0xf0) {
case 0xe0:
return 3;
case 0xf0:
return 4;
default:
return 2;
}
}
}
/** This method returns the byte length of the first encountered character in `bytes`, starting at offset `p` and
* ending at byte position `e`. The `Encoding` implementation will perform character validation and return a
* negative number if the byte sequence does not correspond to a valid character. Otherwise, the byte length of the
* character is returned. See the docs for `Encoding#length` for more details.
*
* It is up to the caller to check if the return value is negative. In practice, it is expected this method is only
* called when the caller knows the code range of the byte sequence is either `CR_7BIT` or `CR_VALID`, in which case
* no check on the return values is necessary -- it will always be positive.
*
* Corresponding MRI method: rb_enc_fast_mbclen */
@TruffleBoundary
private static int encLength(Encoding enc, byte[] bytes, int p, int e) {
return enc.length(bytes, p, e);
}
/** This method functions like `StringSupport.encLength`, but differs when an invalid character is encountered
* (i.e., a negative byte length). In such cases, it attempts to perform a limited form of error recovery. It checks
* the `Encoding`'s minimum length to see if it's small enough to fit within the range [end - p]. If it is, the
* method pretends a character with a byte length equal to the `Encoding`'s minimum length was discovered and that
* byte length is returned. If the minimum character length can't fit in the range, this method pretends a character
* with a byte length corresponding to the size of the range was encountered and the range size is returned. If a
* valid character was encountered, its byte length is returned just as would be the case with
* `StringSupport.encLength`. Consequently, this method never returns a negative value.
*
* Ruby allows Strings with a `CR_BROKEN` code range to propagate through to an end user, who may call methods on
* that String. This variant of getting a character's length is designed is intended to be used in such cases. E.g.,
* if calling `String#each_char` on a String that is `CR_BROKEN`, returning negative values for the character length
* would break iteration. In such cases, Ruby just pretends broken byte sequences have some arbitrary, but
* deterministic, positive byte length.
*
* Corresponding MRI method: rb_enc_mbclen */
public static int length(Encoding enc, byte[] bytes, int p, int end) {
int n = encLength(enc, bytes, p, end);
if (MBCLEN_CHARFOUND_P(n) && MBCLEN_CHARFOUND_LEN(n) <= end - p) {
return MBCLEN_CHARFOUND_LEN(n);
}
int min = enc.minLength();
return min <= end - p ? min : end - p;
}
/** This method functions like `StringSupport.encLength`, but differs when a character sequence is too short. In
* such cases, it examines the return value from `Encoding#length` and if exceeds the length of the byte sequence,
* it returns the number of bytes required to make the character valid, but negated. Since the value is negated, the
* caller can distinguish between good character lengths ad bad ones by checking the sign of the value.
*
* It is intended to be called when then code range of the byte sequence is unknown. In such cases, it cannot be
* trusted like `StringSupport.encLength`. Nor is it safe to recover invalid byte sequences as is done with
* `StringSupport.length`.
*
* Corresponding MRI method: rb_enc_precise_mbclen */
private static int preciseLength(Encoding enc, byte[] bytes, int p, int end) {
if (p >= end) {
return MBCLEN_NEEDMORE(1);
}
int n = encLength(enc, bytes, p, end);
if (n > end - p) {
return MBCLEN_NEEDMORE(n - (end - p));
}
return n;
}
// MBCLEN_NEEDMORE_P, ONIGENC_MBCLEN_NEEDMORE_P
public static boolean MBCLEN_NEEDMORE_P(int r) {
return r < -1;
}
// MBCLEN_NEEDMORE_LEN, ONIGENC_MBCLEN_NEEDMORE_LEN
public static int MBCLEN_NEEDMORE_LEN(int r) {
return -1 - r;
}
// MBCLEN_NEEDMORE, ONIGENC_MBCLEN_NEEDMORE
public static int MBCLEN_NEEDMORE(int n) {
return -1 - n;
}
// MBCLEN_INVALID_P, ONIGENC_MBCLEN_INVALID_P
public static boolean MBCLEN_INVALID_P(int r) {
return r == -1;
}
// MBCLEN_CHARFOUND_LEN, ONIGENC_MBCLEN_CHARFOUND_LEN
public static int MBCLEN_CHARFOUND_LEN(int r) {
assert MBCLEN_CHARFOUND_P(r);
return r;
}
// MBCLEN_CHARFOUND_P, ONIGENC_MBCLEN_CHARFOUND_P
public static boolean MBCLEN_CHARFOUND_P(int r) {
return 0 < r;
}
@CompilationFinal(dimensions = 1) private static final byte[] NON_ASCII_NEEDLE = { (byte) 0b1111_1111 };
@CompilationFinal(dimensions = 1) private static final byte[] NON_ASCII_MASK = { 0b0111_1111 };
// MRI: search_nonascii
/** NOTE: this returns a logical offset, not the offset in the byteArray. */
public static int searchNonAscii(InternalByteArray byteArray, int start) {
final int offset = byteArray.getOffset();
return searchNonAscii(byteArray.getArray(), offset + start, byteArray.getEnd()) - offset;
}
// MRI: search_nonascii
public static int searchNonAscii(byte[] bytes, int p, int end) {
return com.oracle.truffle.api.ArrayUtils.indexOfWithOrMask(bytes, p, end - p, NON_ASCII_NEEDLE, NON_ASCII_MASK);
}
// MRI: rb_enc_strlen / enc_strlen
@TruffleBoundary
public static int strLength(RubyEncoding encoding, byte[] bytes, int p, int e) {
var tstring = FromByteArrayNode.getUncached().execute(bytes, p, e - p, encoding.tencoding, false);
return tstring.codePointLengthUncached(encoding.tencoding);
}
public static int codePoint(Encoding enc, byte[] bytes, int p, int end, Node node) {
return codePoint(enc, null, bytes, p, end, node);
}
@TruffleBoundary
public static int codePoint(Encoding enc, TruffleString.CodeRange codeRange, byte[] bytes, int p, int end,
Node node) {
if (p >= end) {
final RubyContext context = RubyContext.get(node);
throw new RaiseException(context, context.getCoreExceptions().argumentError("empty string", node));
}
int cl = characterLength(enc, codeRange, bytes, p, end);
if (cl <= 0) {
final RubyContext context = RubyContext.get(node);
throw new RaiseException(
context,
context.getCoreExceptions().argumentError("invalid byte sequence in " + enc, node));
}
return enc.mbcToCode(bytes, p, end);
}
/** Returns a negative value for invalid code points, callers should check for that unless they can guarantee the
* code point is valid. */
@TruffleBoundary
public static int codeLength(Encoding enc, int c) {
return enc.codeToMbcLength(c);
}
@TruffleBoundary
public static int mbcToCode(Encoding encoding, byte[] bytes, int p, int end) {
return encoding.mbcToCode(bytes, p, end);
}
public static int offset(int start, int end, int charEnd) {
return charEnd == -1 ? end - start : Math.min(end, charEnd) - start;
}
public static int scanHex(byte[] bytes, int p, int len) {
return scanHex(bytes, p, len, ASCIIEncoding.INSTANCE);
}
@TruffleBoundary
public static int scanHex(byte[] bytes, int p, int len, Encoding enc) {
int v = 0;
int c;
while (len-- > 0 && enc.isXDigit(c = bytes[p++] & 0xff)) {
v = (v << 4) + enc.xdigitVal(c);
}
return v;
}
public static int hexLength(byte[] bytes, int p, int len) {
return hexLength(bytes, p, len, ASCIIEncoding.INSTANCE);
}
@TruffleBoundary
public static int hexLength(byte[] bytes, int p, int len, Encoding enc) {
int hlen = 0;
while (len-- > 0 && enc.isXDigit(bytes[p++] & 0xff)) {
hlen++;
}
return hlen;
}
public static int scanOct(byte[] bytes, int p, int len) {
return scanOct(bytes, p, len, ASCIIEncoding.INSTANCE);
}
@TruffleBoundary
public static int scanOct(byte[] bytes, int p, int len, Encoding enc) {
int v = 0;
int c;
while (len-- > 0 && enc.isDigit(c = bytes[p++] & 0xff) && c < '8') {
v = (v << 3) + Encoding.digitVal(c);
}
return v;
}
public static int octLength(byte[] bytes, int p, int len) {
return octLength(bytes, p, len, ASCIIEncoding.INSTANCE);
}
@TruffleBoundary
public static int octLength(byte[] bytes, int p, int len, Encoding enc) {
int olen = 0;
int c;
while (len-- > 0 && enc.isDigit(c = bytes[p++] & 0xff) && c < '8') {
olen++;
}
return olen;
}
public static String escapedCharFormat(int c, boolean isUnicode) {
String format;
// c comparisons must be unsigned 32-bit
if (isUnicode) {
if ((c & 0xFFFFFFFFL) < 0x7F && Encoding.isAscii(c) && ASCIIEncoding.INSTANCE.isPrint(c)) {
format = "%c";
} else if (c < 0x10000) {
format = "\\u%04X";
} else {
format = "\\u{%X}";
}
} else {
if ((c & 0xFFFFFFFFL) < 0x100) {
format = "\\x%02X";
} else {
format = "\\x{%X}";
}
}
return format;
}
/** rb_str_count */
@TruffleBoundary
public static int strCount(InternalByteArray byteArray, TruffleString.CodeRange codeRange, boolean[] table,
TrTables tables, Encoding enc, Node node) {
final byte[] bytes = byteArray.getArray();
int p = byteArray.getOffset();
final int end = byteArray.getEnd();
final boolean asciiCompat = enc.isAsciiCompatible();
int count = 0;
while (p < end) {
int c;
if (asciiCompat && (c = bytes[p] & 0xff) < 0x80) {
if (table[c]) {
count++;
}
p++;
} else {
c = codePoint(enc, codeRange, bytes, p, end, node);
int cl = codeLength(enc, c);
if (trFind(c, table, tables)) {
count++;
}
p += cl;
}
}
return count;
}
public static char[] bytesToChars(InternalByteArray byteArray) {
final int byteLength = byteArray.getLength();
final char[] chars = new char[byteLength];
for (int n = 0; n < byteLength; n++) {
chars[n] = (char) byteArray.get(n);
}
return chars;
}
// rb_enc_ascget
private static int encAscget(byte[] pBytes, int p, int e, int[] len, Encoding enc,
TruffleString.CodeRange codeRange) {
int c;
int l;
if (e <= p) {
return -1;
}
if (EncodingUtils.encAsciicompat(enc)) {
c = pBytes[p] & 0xFF;
if (!Encoding.isAscii((byte) c)) {
return -1;
}
if (len != null) {
len[0] = 1;
}
return c;
}
l = characterLength(enc, codeRange, pBytes, p, e);
if (!MBCLEN_CHARFOUND_P(l)) {
return -1;
}
c = enc.mbcToCode(pBytes, p, e);
if (!Encoding.isAscii(c)) {
return -1;
}
if (len != null) {
len[0] = l;
}
return c;
}
// rb_enc_codepoint_len
@TruffleBoundary
private static int encCodepointLength(byte[] pBytes, int p, int e, int[] len_p, Encoding enc,
TruffleString.CodeRange codeRange, Node node) {
int r;
if (e <= p) {
final RubyContext context = RubyContext.get(node);
throw new RaiseException(context, context.getCoreExceptions().argumentError("empty string", node));
}
r = characterLength(enc, codeRange, pBytes, p, e);
if (!MBCLEN_CHARFOUND_P(r)) {
final RubyContext context = RubyContext.get(node);
throw new RaiseException(
context,
context.getCoreExceptions().argumentError("invalid byte sequence in " + enc, node));
}
if (len_p != null) {
len_p[0] = MBCLEN_CHARFOUND_LEN(r);
}
return codePoint(enc, codeRange, pBytes, p, e, node);
}
/** rb_str_tr / rb_str_tr_bang */
public static final class TR {
public TR(AbstractTruffleString string, RubyEncoding encoding) {
var bytes = string.getInternalByteArrayUncached(encoding.tencoding);
p = bytes.getOffset();
pend = bytes.getEnd();
buf = bytes.getArray();
now = max = 0;
gen = false;
}
final byte[] buf;
int p, pend, now, max;
boolean gen;
}
/** tr_setup_table */
public static final class TrTables {
IntHashMap<Object> del, noDel; // used as ~ Set
}
private static final Object DUMMY_VALUE = "";
@TruffleBoundary
public static TrTables trSetupTable(AbstractTruffleString str, RubyEncoding encoding, boolean[] stable,
TrTables tables, boolean first, Encoding enc, Node node) {
int i, l[] = { 0 };
final boolean cflag;
final TR tr = new TR(str, encoding);
var codeRange = str.getByteCodeRangeUncached(encoding.tencoding);
if (str.byteLength(encoding.tencoding) > 1 &&
encAscget(tr.buf, tr.p, tr.pend, l, enc, codeRange) == '^') {
cflag = true;
tr.p += l[0];
} else {
cflag = false;
}
if (first) {
for (i = 0; i < TRANS_SIZE; i++) {
stable[i] = true;
}
stable[TRANS_SIZE] = cflag;
} else if (stable[TRANS_SIZE] && !cflag) {
stable[TRANS_SIZE] = false;
}
if (tables == null) {
tables = new TrTables();
}
byte[] buf = null; // lazy initialized
IntHashMap<Object> table = null, ptable = null;
int c;
while ((c = trNext(tr, enc, codeRange, node)) != -1) {
if (c < TRANS_SIZE) {
if (buf == null) { // initialize buf
buf = new byte[TRANS_SIZE];
for (i = 0; i < TRANS_SIZE; i++) {
buf[i] = (byte) (cflag ? 1 : 0);
}
}
// update the buff at [c] :
buf[c & 0xff] = (byte) (cflag ? 0 : 1);
} else {
if (table == null && (first || tables.del != null || stable[TRANS_SIZE])) {
if (cflag) {
ptable = tables.noDel;
table = ptable != null ? ptable : new IntHashMap<>(8);
tables.noDel = table;
} else {
table = new IntHashMap<>(8);
ptable = tables.del;
tables.del = table;
}
}
if (table != null) {
final int key = c;
if (ptable == null) {
table.put(key, DUMMY_VALUE);
} else {
if (cflag) {
table.put(key, DUMMY_VALUE);
} else {
final boolean val = ptable.get(key) != null;
table.put(key, val ? DUMMY_VALUE : null);
}
}
}
}
}
if (buf != null) {
for (i = 0; i < TRANS_SIZE; i++) {
stable[i] = stable[i] && buf[i] != 0;
}
} else {
for (i = 0; i < TRANS_SIZE; i++) {
stable[i] = stable[i] && cflag;
}
}
if (table == null && !cflag) {
tables.del = null;
}
return tables;
}
public static boolean trFind(final int c, final boolean[] table, final TrTables tables) {
if (c < TRANS_SIZE) {
return table[c];
}
final IntHashMap<Object> del = tables.del, noDel = tables.noDel;
if (del != null) {
if (del.get(c) != null &&
(noDel == null || noDel.get(c) == null)) {
return true;
}
} else if (noDel != null && noDel.get(c) != null) {
return false;
}
return table[TRANS_SIZE];
}
@TruffleBoundary
public static int trNext(TR tr, Encoding enc, TruffleString.CodeRange codeRange, Node node) {
for (;;) {
if (!tr.gen) {
return trNext_nextpart(tr, enc, codeRange, node);
}
while (enc.codeToMbcLength(++tr.now) <= 0) {
if (tr.now == tr.max) {
tr.gen = false;
return trNext_nextpart(tr, enc, codeRange, node);
}
}
if (tr.now < tr.max) {
return tr.now;
} else {
tr.gen = false;
return tr.max;
}
}
}
private static int trNext_nextpart(TR tr, Encoding enc, TruffleString.CodeRange codeRange, Node node) {
final int[] n = { 0 };
if (tr.p == tr.pend) {
return -1;
}
if (encAscget(tr.buf, tr.p, tr.pend, n, enc, codeRange) == '\\' && tr.p + n[0] < tr.pend) {
tr.p += n[0];
}
tr.now = encCodepointLength(tr.buf, tr.p, tr.pend, n, enc, codeRange, node);
tr.p += n[0];
if (encAscget(tr.buf, tr.p, tr.pend, n, enc, codeRange) == '-' && tr.p + n[0] < tr.pend) {
tr.p += n[0];
if (tr.p < tr.pend) {
int c = encCodepointLength(tr.buf, tr.p, tr.pend, n, enc, codeRange, node);
tr.p += n[0];
if (tr.now > c) {
final RubyContext context = RubyContext.get(node);
if (tr.now < 0x80 && c < 0x80) {
final String message = "invalid range \"" + (char) tr.now + '-' + (char) c +
"\" in string transliteration";
throw new RaiseException(context, context.getCoreExceptions().argumentError(message, node));
}
throw new RaiseException(
context,
context.getCoreExceptions().argumentError("invalid range in string transliteration", node));
}
tr.gen = true;
tr.max = c;
}
}
return tr.now;
}
public enum NeighborChar {
NOT_CHAR,
FOUND,
WRAPPED
}
// MRI: str_succ
@TruffleBoundary
public static TStringBuilder succCommon(RubyString original, Node node) {
byte carry[] = new byte[Config.ENC_CODE_TO_MBC_MAXLEN];
int carryP = 0;
carry[0] = 1;
int carryLen = 1;
final RubyEncoding encoding = original.getEncodingUncached();
final Encoding enc = encoding.jcoding;
TStringBuilder valueCopy = TStringBuilder.create(original);
int p = 0;
int end = p + valueCopy.getLength();
int s = end;
byte[] bytes = valueCopy.getUnsafeBytes();
NeighborChar neighbor = NeighborChar.FOUND;
int lastAlnum = -1;
boolean alnumSeen = false;
while ((s = enc.prevCharHead(bytes, p, s, end)) != -1) {
if (neighbor == NeighborChar.NOT_CHAR && lastAlnum != -1) {
ASCIIEncoding ascii = ASCIIEncoding.INSTANCE;
if (ascii.isAlpha(bytes[lastAlnum] & 0xff)
? ascii.isDigit(bytes[s] & 0xff)
: ascii.isDigit(bytes[lastAlnum] & 0xff) ? ascii.isAlpha(bytes[s] & 0xff) : false) {
s = lastAlnum;
break;
}
}
int cl = characterLength(encoding, bytes, s, end);
if (cl <= 0) {
continue;
}
switch (neighbor = succAlnumChar(encoding, bytes, s, cl, carry, 0, node)) {
case NOT_CHAR:
continue;
case FOUND:
return valueCopy;
case WRAPPED:
lastAlnum = s;
}
alnumSeen = true;
carryP = s - p;
carryLen = cl;
}
if (!alnumSeen) {
s = end;
while ((s = enc.prevCharHead(bytes, p, s, end)) != -1) {
int cl = characterLength(encoding, bytes, s, end);
if (cl <= 0) {
continue;
}
neighbor = succChar(encoding, bytes, s, cl, node);
if (neighbor == NeighborChar.FOUND) {
return valueCopy;
}
if (characterLength(encoding, bytes, s, s + 1) != cl) {
succChar(encoding, bytes, s, cl, node); /* wrapped to \0...\0. search next valid char. */
}
if (!encoding.isAsciiCompatible) {
System.arraycopy(bytes, s, carry, 0, cl);
carryLen = cl;
}
carryP = s - p;
}
}
valueCopy.unsafeEnsureSpace(valueCopy.getLength() + carryLen);
s = carryP;
System.arraycopy(
valueCopy.getUnsafeBytes(),
s,
valueCopy.getUnsafeBytes(),
s + carryLen,
valueCopy.getLength() - carryP);
System.arraycopy(carry, 0, valueCopy.getUnsafeBytes(), s, carryLen);
valueCopy.setLength(valueCopy.getLength() + carryLen);
return valueCopy;
}
// MRI: enc_succ_char
public static NeighborChar succChar(RubyEncoding encoding, byte[] bytes, int p, int len, Node node) {
Encoding enc = encoding.jcoding;
int l;
if (enc.minLength() > 1) {
/* wchar, trivial case */
int r = characterLength(encoding, bytes, p, p + len), c;
if (!MBCLEN_CHARFOUND_P(r)) {
return NeighborChar.NOT_CHAR;
}
c = codePoint(enc, bytes, p, p + len, node) + 1;
l = codeLength(enc, c);
if (l == 0) {
return NeighborChar.NOT_CHAR;
}
if (l != len) {
return NeighborChar.WRAPPED;
}
enc.codeToMbc(c, bytes, p);
r = characterLength(encoding, bytes, p, p + len);
if (!MBCLEN_CHARFOUND_P(r)) {
return NeighborChar.NOT_CHAR;
}
return NeighborChar.FOUND;
}
while (true) {
int i = len - 1;
for (; i >= 0 && bytes[p + i] == (byte) 0xff; i--) {
bytes[p + i] = 0;
}
if (i < 0) {
return NeighborChar.WRAPPED;
}
bytes[p + i] = (byte) ((bytes[p + i] & 0xff) + 1);
l = characterLength(encoding, bytes, p, p + len);
if (MBCLEN_CHARFOUND_P(l)) {
l = MBCLEN_CHARFOUND_LEN(l);
if (l == len) {
return NeighborChar.FOUND;
} else {
int start = p + l;
int end = start + (len - l);
Arrays.fill(bytes, start, end, (byte) 0xff);
}
}
if (MBCLEN_INVALID_P(l) && i < len - 1) {
int len2;
int l2;
for (len2 = len - 1; 0 < len2; len2--) {
l2 = characterLength(encoding, bytes, p, p + len2);
if (!MBCLEN_INVALID_P(l2)) {
break;
}
}
int start = p + len2 + 1;
int end = start + len - (len2 + 1);
Arrays.fill(bytes, start, end, (byte) 0xff);
}
}
}
// MRI: enc_succ_alnum_char
private static NeighborChar succAlnumChar(RubyEncoding encoding, byte[] bytes, int p, int len, byte[] carry,
int carryP, Node node) {
Encoding enc = encoding.jcoding;
byte save[] = new byte[Config.ENC_CODE_TO_MBC_MAXLEN];
int c = enc.mbcToCode(bytes, p, p + len);
final int cType;
if (enc.isDigit(c)) {
cType = CharacterType.DIGIT;
} else if (enc.isAlpha(c)) {
cType = CharacterType.ALPHA;
} else {
return NeighborChar.NOT_CHAR;
}
System.arraycopy(bytes, p, save, 0, len);
NeighborChar ret = succChar(encoding, bytes, p, len, node);
if (ret == NeighborChar.FOUND) {
c = enc.mbcToCode(bytes, p, p + len);
if (enc.isCodeCType(c, cType)) {
return NeighborChar.FOUND;
}
}
System.arraycopy(save, 0, bytes, p, len);
int range = 1;
while (true) {
System.arraycopy(bytes, p, save, 0, len);
ret = predChar(encoding, bytes, p, len, node);
if (ret == NeighborChar.FOUND) {
c = enc.mbcToCode(bytes, p, p + len);
if (!enc.isCodeCType(c, cType)) {
System.arraycopy(save, 0, bytes, p, len);
break;
}
} else {
System.arraycopy(save, 0, bytes, p, len);
break;
}
range++;
}
if (range == 1) {
return NeighborChar.NOT_CHAR;
}
if (cType != CharacterType.DIGIT) {
System.arraycopy(bytes, p, carry, carryP, len);
return NeighborChar.WRAPPED;
}
System.arraycopy(bytes, p, carry, carryP, len);
succChar(encoding, carry, carryP, len, node);
return NeighborChar.WRAPPED;
}
private static NeighborChar predChar(RubyEncoding encoding, byte[] bytes, int p, int len, Node node) {
Encoding enc = encoding.jcoding;
int l;
if (enc.minLength() > 1) {
/* wchar, trivial case */
int r = characterLength(encoding, bytes, p, p + len), c;
if (!MBCLEN_CHARFOUND_P(r)) {
return NeighborChar.NOT_CHAR;
}
c = codePoint(enc, bytes, p, p + len, node);
if (c == 0) {
return NeighborChar.NOT_CHAR;
}
--c;
l = codeLength(enc, c);
if (l == 0) {
return NeighborChar.NOT_CHAR;
}
if (l != len) {
return NeighborChar.WRAPPED;
}
enc.codeToMbc(c, bytes, p);
r = characterLength(encoding, bytes, p, p + len);
if (!MBCLEN_CHARFOUND_P(r)) {
return NeighborChar.NOT_CHAR;
}
return NeighborChar.FOUND;
}
while (true) {
int i = len - 1;
for (; i >= 0 && bytes[p + i] == 0; i--) {
bytes[p + i] = (byte) 0xff;
}
if (i < 0) {
return NeighborChar.WRAPPED;
}
bytes[p + i] = (byte) ((bytes[p + i] & 0xff) - 1);
l = characterLength(encoding, bytes, p, p + len);
if (MBCLEN_CHARFOUND_P(l)) {
l = MBCLEN_CHARFOUND_LEN(l);
if (l == len) {
return NeighborChar.FOUND;
} else {
int start = p + l;
int end = start + (len - l);
Arrays.fill(bytes, start, end, (byte) 0x0);
}
}
if (!MBCLEN_CHARFOUND_P(l) && i < len - 1) {
int len2;
int l2;
for (len2 = len - 1; 0 < len2; len2--) {
l2 = characterLength(encoding, bytes, p, p + len2);
if (!MBCLEN_INVALID_P(l2)) {
break;
}
}
int start = p + len2 + 1;
int end = start + (len - (len2 + 1));
Arrays.fill(bytes, start, end, (byte) 0);
}
}
}
/** rb_str_delete_bang */
@TruffleBoundary
public static TruffleString delete_bangCommon19(ATStringWithEncoding rubyString, boolean[] squeeze, TrTables tables,
RubyEncoding encoding, Node node) {
Encoding enc = encoding.jcoding;
int s = 0;
int t = s;
int send = s + rubyString.byteLength();
byte[] bytes = rubyString.getBytesCopy();
boolean modified = false;
boolean asciiCompatible = encoding.isAsciiCompatible;
var cr = asciiCompatible ? ASCII : VALID;
while (s < send) {
int c;
if (asciiCompatible && Encoding.isAscii(c = bytes[s] & 0xff)) {
if (squeeze[c]) {
modified = true;
} else {
if (t != s) {
bytes[t] = (byte) c;
}
t++;
}
s++;
} else {
c = codePoint(enc, rubyString.getCodeRange(), bytes, s, send, node);
int cl = codeLength(enc, c);
if (trFind(c, squeeze, tables)) {
modified = true;
} else {
if (t != s) {
enc.codeToMbc(c, bytes, t);
}
t += cl;
if (cr == ASCII) {
cr = VALID;
}
}
s += cl;
}
}
return modified
? TStringUtils.fromByteArray(ArrayUtils.extractRange(bytes, 0, t), encoding)
/* cr */ : null;
}
/** rb_str_tr / rb_str_tr_bang */
private static TruffleString.CodeRange CHECK_IF_ASCII(int c, TruffleString.CodeRange currentCodeRange) {
if (currentCodeRange == ASCII && !Encoding.isAscii(c)) {
return VALID;
}
return currentCodeRange;
}
@TruffleBoundary
public static TruffleString trTransHelper(ATStringWithEncoding self, ATStringWithEncoding srcStr,
ATStringWithEncoding replStr, Encoding e1, RubyEncoding rubyEncoding,
boolean sflag, Node node) {
// This method does not handle the cases where either srcStr or replStr are empty. It is the responsibility
// of the caller to take the appropriate action in those cases.
final Encoding enc = rubyEncoding.jcoding;
var cr = self.getCodeRange();
final StringSupport.TR trSrc = new StringSupport.TR(srcStr.tstring, srcStr.encoding);
boolean cflag = false;
int[] l = { 0 };
if (srcStr.byteLength() > 1 &&
encAscget(trSrc.buf, trSrc.p, trSrc.pend, l, enc, srcStr.getCodeRange()) == '^' &&
trSrc.p + 1 < trSrc.pend) {
cflag = true;
trSrc.p++;
}
int c, c0, last = 0;
final int[] trans = new int[StringSupport.TRANS_SIZE];
final StringSupport.TR trRepl = new StringSupport.TR(replStr.tstring, replStr.encoding);
boolean modified = false;
IntHash<Integer> hash = null;
boolean singlebyte = self.isSingleByteOptimizable();
if (cflag) {