forked from jruby/jruby
/
RubyString.java
1688 lines (1465 loc) · 44.9 KB
/
RubyString.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: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.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/cpl-v10.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.
*
* Copyright (C) 2001 Alan Moore <alan_moore@gmx.net>
* Copyright (C) 2001-2002 Benoit Cerrina <b.cerrina@wanadoo.fr>
* Copyright (C) 2001-2004 Jan Arne Petersen <jpetersen@uni-bonn.de>
* Copyright (C) 2002-2004 Anders Bengtsson <ndrsbngtssn@yahoo.se>
* Copyright (C) 2002-2006 Thomas E Enebo <enebo@acm.org>
* Copyright (C) 2004 Stefan Matthias Aust <sma@3plus4.de>
* Copyright (C) 2004 David Corbin <dcorbin@users.sourceforge.net>
* Copyright (C) 2005 Tim Azzopardi <tim@tigerfive.com>
* Copyright (C) 2006 Miguel Covarrubias <mlcovarrubias@gmail.com>
*
* 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 CPL, 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 CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby;
import org.jruby.internal.runtime.methods.DirectInvocationMethod;
import org.jruby.runtime.Arity;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.Visibility;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.runtime.builtin.meta.StringMetaClass;
import org.jruby.runtime.marshal.MarshalStream;
import org.jruby.runtime.marshal.UnmarshalStream;
import org.jruby.util.Pack;
import org.jruby.util.PrintfFormat;
import org.jruby.util.Split;
/**
*
* @author jpetersen
*/
public class RubyString extends RubyObject {
// Default record seperator
private static final String DEFAULT_RS = "\n";
private static final String encoding = "ISO8859_1";
private StringBuffer value;
private CharSequence chars;
public static abstract class StringMethod extends DirectInvocationMethod {
public StringMethod(RubyModule implementationClass, Arity arity, Visibility visibility) {
super(implementationClass, arity, visibility);
}
public IRubyObject internalCall(ThreadContext context, IRubyObject receiver, RubyModule lastClass, String name, IRubyObject[] args, boolean noSuper) {
RubyString s = (RubyString)receiver;
return invoke(context, s, args);
}
public abstract IRubyObject invoke(ThreadContext context, RubyString target, IRubyObject[] args);
};
// @see IRuby.newString(...)
private RubyString(IRuby runtime, CharSequence value) {
this(runtime, runtime.getString(), value);
}
private RubyString(IRuby runtime, RubyClass rubyClass, CharSequence value) {
super(runtime, rubyClass);
assert value != null;
// defer creation of StringBuffer until needed
chars = value;
}
public Class getJavaClass() {
return String.class;
}
public String toString() {
return getValue().toString();
}
public static String bytesToString(byte[] bytes) {
try {
return new String(bytes, encoding);
} catch (java.io.UnsupportedEncodingException e) {
assert false : "unsupported encoding " + e;
return null;
}
}
public static byte[] stringToBytes(String string) {
try {
return string.getBytes(encoding);
} catch (java.io.UnsupportedEncodingException e) {
assert false : "unsupported encoding " + e;
return null;
}
}
public byte[] toByteArray() {
return stringToBytes(toString());
}
public static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
public static boolean isUpper(char c) {
return c >= 'A' && c <= 'Z';
}
public static boolean isLower(char c) {
return c >= 'a' && c <= 'z';
}
public static boolean isLetter(char c) {
return isUpper(c) || isLower(c);
}
public static boolean isAlnum(char c) {
return isUpper(c) || isLower(c) || isDigit(c);
}
public static boolean isPrint(char c) {
return c >= 0x20 && c <= 0x7E;
}
public RubyFixnum hash() {
return getRuntime().newFixnum(toString().hashCode());
}
// Common enough check to make it a convenience method.
private boolean sameAs(Object other) {
return toString().equals(other.toString());
}
/** rb_obj_as_string
*
*/
public static RubyString objAsString(IRubyObject obj) {
return (RubyString) (obj instanceof RubyString ? obj :
obj.callMethod(obj.getRuntime().getCurrentContext(), "to_s"));
}
/** rb_str_cmp
*
*/
public int cmp(RubyString other) {
int cmp = toString().compareTo(other.toString());
return cmp < 0 ? -1 : cmp > 0 ? 1 : 0;
}
/** rb_to_id
*
*/
public String asSymbol() {
return toString();
}
/** Create a new String which uses the same Ruby runtime and the same
* class like this String.
*
* This method should be used to satisfy RCR #38.
*
*/
public RubyString newString(CharSequence s) {
return new RubyString(getRuntime(), getType(), s);
}
// Methods of the String class (rb_str_*):
/** rb_str_new2
*
*/
public static RubyString newString(IRuby runtime, CharSequence str) {
return new RubyString(runtime, str);
}
public static RubyString newString(IRuby runtime, byte[] bytes) {
return runtime.newString(bytesToString(bytes));
}
/** rb_str_dup
*
*/
public IRubyObject dup() {
return newString(toString()).infectBy(this);
}
/** rb_str_clone
*
*/
public IRubyObject rbClone() {
IRubyObject newObject = dup();
newObject.initCopy(this);
newObject.setFrozen(isFrozen());
return newObject;
}
public RubyString cat(CharSequence str) {
getMutableValue().append(str);
return this;
}
public IRubyObject to_str() {
return this;
}
/** rb_str_replace_m
*
*/
public RubyString replace(IRubyObject other) {
RubyString newValue = stringValue(other);
if (this == other || sameAs(newValue)) {
return this;
}
setValue(new StringBuffer(newValue.getValue().toString()));
return (RubyString) infectBy(newValue);
}
public RubyString reverse() {
return newString(toString()).reverse_bang();
}
public RubyString reverse_bang() {
getMutableValue().reverse();
return this;
}
/** rb_str_s_new
*
*/
public static RubyString newInstance(IRubyObject recv, IRubyObject[] args) {
RubyString newString = recv.getRuntime().newString("");
newString.setMetaClass((RubyClass) recv);
newString.callInit(args);
return newString;
}
public IRubyObject initialize(IRubyObject[] args) {
if (checkArgumentCount(args, 0, 1) == 1) {
replace(args[0]);
}
return this;
}
public IRubyObject casecmp(IRubyObject other) {
RubyString thisLCString = getRuntime().newString(toString().toLowerCase());
RubyString lcString = getRuntime().newString(stringValue(other).toString().toLowerCase());
return ((StringMetaClass)thisLCString.getMetaClass()).op_cmp.call(getRuntime().getCurrentContext(), thisLCString, thisLCString.getMetaClass(), "<=>", new IRubyObject[] {lcString}, false);
}
/** rb_str_match
*
*/
public IRubyObject match(IRubyObject other) {
if (other instanceof RubyRegexp) {
return ((RubyRegexp) other).match(this);
} else if (other instanceof RubyString) {
return RubyRegexp.newRegexp((RubyString) other, 0, null).match(this);
}
return other.callMethod(getRuntime().getCurrentContext(), "=~", this);
}
/** rb_str_match2
*
*/
public IRubyObject match2() {
return RubyRegexp.newRegexp(this, 0, null).match2();
}
/**
* String#match(pattern)
*
* @param pattern Regexp or String
*/
public IRubyObject match3(IRubyObject pattern) {
if (pattern instanceof RubyRegexp) {
return ((RubyRegexp)pattern).search2(toString());
} else if (pattern instanceof RubyString) {
RubyRegexp regexp = RubyRegexp.newRegexp((RubyString) pattern, 0, null);
return regexp.search2(toString());
}
return getRuntime().getNil();
}
/** rb_str_capitalize
*
*/
public IRubyObject capitalize() {
RubyString result = (RubyString) dup();
result.capitalize_bang();
return result;
}
/** rb_str_capitalize_bang
*
*/
public IRubyObject capitalize_bang() {
if (isEmpty()) {
return getRuntime().getNil();
}
StringBuffer buffer = new StringBuffer(toString().toLowerCase());
char capital = buffer.charAt(0);
if (Character.isLowerCase(capital)) {
buffer.setCharAt(0, Character.toUpperCase(capital));
}
if (sameAs(buffer)) {
return getRuntime().getNil();
}
setValue(buffer);
return this;
}
/** rb_str_upcase
*
*/
public RubyString upcase() {
return newString(toString().toUpperCase());
}
/** rb_str_upcase_bang
*
*/
public IRubyObject upcase_bang() {
String result = toString().toUpperCase();
if (sameAs(result)) {
return getRuntime().getNil();
}
setValue(new StringBuffer(result));
return this;
}
/** rb_str_downcase
*
*/
public RubyString downcase() {
return newString(toString().toLowerCase());
}
/** rb_str_downcase_bang
*
*/
public IRubyObject downcase_bang() {
String result = toString().toLowerCase();
if (sameAs(result)) {
return getRuntime().getNil();
}
setValue(new StringBuffer(result));
return this;
}
/** rb_str_swapcase
*
*/
public RubyString swapcase() {
RubyString newString = newString(toString());
IRubyObject swappedString = newString.swapcase_bang();
return (RubyString) (swappedString.isNil() ? newString : swappedString);
}
/** rb_str_swapcase_bang
*
*/
public IRubyObject swapcase_bang() {
StringBuffer string = getMutableValue();
int length = string.length();
boolean changesMade = false;
for (int i = 0; i < length; i++) {
char c = string.charAt(i);
if (!Character.isLetter(c)) {
continue;
} else if (Character.isLowerCase(c)) {
changesMade = true;
string.setCharAt(i, Character.toUpperCase(c));
} else {
changesMade = true;
string.setCharAt(i, Character.toLowerCase(c));
}
}
return changesMade ? this : getRuntime().getNil();
}
/** rb_str_dump
*
*/
public RubyString dump() {
return inspect(true);
}
public IRubyObject insert(IRubyObject indexArg, IRubyObject stringArg) {
int index = (int) indexArg.convertToInteger().getLongValue();
if (index < 0) {
index += getValue().length() + 1;
}
if (index < 0 || index > getValue().length()) {
throw getRuntime().newIndexError("index " + index + " out of range");
}
String insert = stringArg.convertToString().toString();
getMutableValue().insert(index, insert);
return this;
}
/** rb_str_inspect
*
*/
public IRubyObject inspect() {
return inspect(false);
}
private RubyString inspect(boolean dump) {
final int length = getValue().length();
StringBuffer sb = new StringBuffer(length + 2 + length / 100);
sb.append('\"');
for (int i = 0; i < length; i++) {
char c = getValue().charAt(i);
if (isAlnum(c)) {
sb.append(c);
} else if (c == '\"' || c == '\\') {
sb.append('\\').append(c);
} else if (dump && c == '#') {
sb.append('\\').append(c);
} else if (isPrint(c)) {
sb.append(c);
} else if (c == '\n') {
sb.append('\\').append('n');
} else if (c == '\r') {
sb.append('\\').append('r');
} else if (c == '\t') {
sb.append('\\').append('t');
} else if (c == '\f') {
sb.append('\\').append('f');
} else if (c == '\u000B') {
sb.append('\\').append('v');
} else if (c == '\u0007') {
sb.append('\\').append('a');
} else if (c == '\u001B') {
sb.append('\\').append('e');
} else {
sb.append(new PrintfFormat("\\%.3o").sprintf(c));
}
}
sb.append('\"');
return getRuntime().newString(sb.toString());
}
/** rb_str_length
*
*/
public RubyFixnum length() {
return getRuntime().newFixnum(getValue().length());
}
/** rb_str_empty
*
*/
public RubyBoolean empty() {
return getRuntime().newBoolean(isEmpty());
}
private boolean isEmpty() {
return getValue().length() == 0;
}
/** rb_str_append
*
*/
public RubyString append(IRubyObject other) {
infectBy(other);
return cat(stringValue(other).getValue());
}
/** rb_str_concat
*
*/
public RubyString concat(IRubyObject other) {
if ((other instanceof RubyFixnum) && ((RubyFixnum) other).getLongValue() < 256) {
return cat("" + (char) ((RubyFixnum) other).getLongValue());
}
return append(other);
}
/* rb_str_to_str */
public static RubyString stringValue(IRubyObject object) {
return (RubyString) (object instanceof RubyString ? object :
object.convertType(RubyString.class, "String", "to_str"));
}
/** rb_str_sub
*
*/
public IRubyObject sub(IRubyObject[] args) {
return sub(args, false);
}
/** rb_str_sub_bang
*
*/
public IRubyObject sub_bang(IRubyObject[] args) {
return sub(args, true);
}
private IRubyObject sub(IRubyObject[] args, boolean bang) {
IRubyObject repl = getRuntime().getNil();
boolean iter = false;
ThreadContext tc = getRuntime().getCurrentContext();
if (args.length == 1 && tc.isBlockGiven()) {
iter = true;
} else if (args.length == 2) {
repl = args[1];
} else {
throw getRuntime().newArgumentError("wrong number of arguments");
}
RubyRegexp pat = RubyRegexp.regexpValue(args[0]);
if (pat.search(toString(), 0) >= 0) {
RubyMatchData match = (RubyMatchData) tc.getBackref();
RubyString newStr = match.pre_match();
newStr.append(iter ? tc.yield(match.group(0)) : pat.regsub(repl, match));
newStr.append(match.post_match());
newStr.setTaint(isTaint() || repl.isTaint());
if (bang) {
replace(newStr);
return this;
}
return newStr;
}
return bang ? getRuntime().getNil() : this;
}
/** rb_str_gsub
*
*/
public IRubyObject gsub(IRubyObject[] args) {
return gsub(args, false);
}
/** rb_str_gsub_bang
*
*/
public IRubyObject gsub_bang(IRubyObject[] args) {
return gsub(args, true);
}
private IRubyObject gsub(IRubyObject[] args, boolean bang) {
IRubyObject repl = getRuntime().getNil();
RubyMatchData match;
boolean iter = false;
ThreadContext tc = getRuntime().getCurrentContext();
if (args.length == 1 && tc.isBlockGiven()) {
iter = true;
} else if (args.length == 2) {
repl = args[1];
} else {
throw getRuntime().newArgumentError("wrong number of arguments");
}
boolean taint = repl.isTaint();
RubyRegexp pat = RubyRegexp.regexpValue(args[0]);
int beg = pat.search(toString(), 0);
if (beg < 0) {
return bang ? getRuntime().getNil() : dup();
}
StringBuffer sbuf = new StringBuffer();
String str = toString();
IRubyObject newStr;
int offset = 0;
while (beg >= 0) {
match = (RubyMatchData) tc.getBackref();
sbuf.append(str.substring(offset, beg));
newStr = iter ? tc.yield(match.group(0)) : pat.regsub(repl, match);
taint |= newStr.isTaint();
sbuf.append(newStr.toString());
offset = match.matchEndPosition();
beg = pat.search(toString(), offset == beg ? beg + 1 : offset);
}
sbuf.append(str.substring(offset, str.length()));
if (bang) {
setTaint(isTaint() || taint);
setValue(sbuf);
return this;
}
RubyString result = newString(sbuf.toString());
result.setTaint(isTaint() || taint);
return result;
}
/** rb_str_index_m
*
*/
public IRubyObject index(IRubyObject[] args) {
return index(args, false);
}
/** rb_str_rindex_m
*
*/
public IRubyObject rindex(IRubyObject[] args) {
return index(args, true);
}
/**
* @fixme may be a problem with pos when doing reverse searches
*/
private IRubyObject index(IRubyObject[] args, boolean reverse) {
//FIXME may be a problem with pos when doing reverse searches
int pos = 0;
if (reverse) {
pos = getValue().length();
}
if (checkArgumentCount(args, 1, 2) == 2) {
pos = RubyNumeric.fix2int(args[1]);
}
if (pos < 0) {
pos += getValue().length();
if (pos < 0) {
return getRuntime().getNil();
}
}
if (args[0] instanceof RubyRegexp) {
int doNotLookPastIfReverse = pos;
// RubyRegexp doesn't (yet?) support reverse searches, so we
// find all matches and use the last one--very inefficient.
// XXX - find a better way
pos = ((RubyRegexp) args[0]).search(toString(), reverse ? 0 : pos);
int dummy = pos;
while (reverse && dummy > -1 && dummy <= doNotLookPastIfReverse) {
pos = dummy;
dummy = ((RubyRegexp) args[0]).search(toString(), pos + 1);
}
} else if (args[0] instanceof RubyString) {
String sub = ((RubyString) args[0]).toString();
pos = reverse ? getMutableValue().lastIndexOf(sub, pos) : getMutableValue().indexOf(sub, pos);
} else if (args[0] instanceof RubyFixnum) {
char c = (char) ((RubyFixnum) args[0]).getLongValue();
pos = reverse ? toString().lastIndexOf(c, pos) : toString().indexOf(c, pos);
} else {
throw getRuntime().newArgumentError("wrong type of argument");
}
return pos == -1 ? getRuntime().getNil() : getRuntime().newFixnum(pos);
}
/* rb_str_substr */
private IRubyObject substr(int beg, int len) {
int length = getValue().length();
if (len < 0 || beg > length) {
return getRuntime().getNil();
}
if (beg < 0) {
beg += length;
if (beg < 0) {
return getRuntime().getNil();
}
}
int end = Math.min(length, beg + len);
return newString(getMutableValue().substring(beg, end)).infectBy(this);
}
/* rb_str_replace */
private IRubyObject replace(int beg, int len, RubyString replaceWith) {
if (beg + len >= getValue().length()) {
len = getValue().length() - beg;
}
getMutableValue().delete(beg, beg + len);
getMutableValue().insert(beg, replaceWith.toString());
return infectBy(replaceWith);
}
/** rb_str_aref, rb_str_aref_m
*
*/
public IRubyObject aref(IRubyObject[] args) {
if (checkArgumentCount(args, 1, 2) == 2) {
if (args[0] instanceof RubyRegexp) {
IRubyObject match = RubyRegexp.regexpValue(args[0]).match(toString(), 0);
long idx = args[1].convertToInteger().getLongValue();
return RubyRegexp.nth_match((int) idx, match);
}
return substr(RubyNumeric.fix2int(args[0]), RubyNumeric.fix2int(args[1]));
}
if (args[0] instanceof RubyRegexp) {
return RubyRegexp.regexpValue(args[0]).search(toString(), 0) >= 0 ?
RubyRegexp.last_match(getRuntime().getCurrentContext().getBackref()) :
getRuntime().getNil();
} else if (args[0] instanceof RubyString) {
return toString().indexOf(stringValue(args[0]).toString()) != -1 ?
args[0] : getRuntime().getNil();
} else if (args[0] instanceof RubyRange) {
long[] begLen = ((RubyRange) args[0]).getBeginLength(getValue().length(), true, false);
return begLen == null ? getRuntime().getNil() :
substr((int) begLen[0], (int) begLen[1]);
}
int idx = (int) args[0].convertToInteger().getLongValue();
if (idx < 0) {
idx += getValue().length();
}
return idx < 0 || idx >= getValue().length() ? getRuntime().getNil() :
getRuntime().newFixnum(getValue().charAt(idx));
}
/**
* rb_str_subpat_set
*
*/
private void subpatSet(RubyRegexp regexp, int nth, IRubyObject repl) {
int found = regexp.search(this.toString(), 0);
if (found == -1) {
throw getRuntime().newIndexError("regexp not matched");
}
RubyMatchData match = (RubyMatchData) getRuntime().getCurrentContext()
.getBackref();
if (nth >= match.getSize()) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
if (nth < 0) {
if (-nth >= match.getSize()) {
throw getRuntime().newIndexError("index " + nth + " out of regexp");
}
nth += match.getSize();
}
IRubyObject group = match.group(nth);
if (getRuntime().getNil().equals(group)) {
throw getRuntime().newIndexError(
"regexp group " + nth + " not matched");
}
int beg = (int) match.begin(nth);
int len = (int) (match.end(nth) - beg);
replace(beg, len, stringValue(repl));
}
/** rb_str_aset, rb_str_aset_m
*
*/
public IRubyObject aset(IRubyObject[] args) {
testFrozen("class");
int strLen = getValue().length();
if (checkArgumentCount(args, 2, 3) == 3) {
if (args[0] instanceof RubyFixnum) {
RubyString repl = stringValue(args[2]);
int beg = RubyNumeric.fix2int(args[0]);
int len = RubyNumeric.fix2int(args[1]);
if (len < 0) {
throw getRuntime().newIndexError("negative length");
}
if (beg < 0) {
beg += strLen;
}
if (beg < 0 || (beg > 0 && beg >= strLen)) {
throw getRuntime().newIndexError(
"string index out of bounds");
}
if (beg + len > strLen) {
len = strLen - beg;
}
replace(beg, len, repl);
return repl;
}
if (args[0] instanceof RubyRegexp) {
RubyString repl = stringValue(args[2]);
int nth = RubyNumeric.fix2int(args[1]);
subpatSet((RubyRegexp) args[0], nth, repl);
return repl;
}
}
if (args[0] instanceof RubyFixnum) { // RubyNumeric?
int idx = RubyNumeric.fix2int(args[0]); // num2int?
if (idx < 0) {
idx += getValue().length();
}
if (idx < 0 || idx >= getValue().length()) {
throw getRuntime().newIndexError("string index out of bounds");
}
if (args[1] instanceof RubyFixnum) {
getMutableValue().setCharAt(idx, (char) RubyNumeric.fix2int(args[1]));
} else {
replace(idx, 1, stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRegexp) {
sub_bang(args);
return args[1];
}
if (args[0] instanceof RubyString) {
RubyString orig = stringValue(args[0]);
int beg = toString().indexOf(orig.toString());
if (beg != -1) {
replace(beg, orig.getValue().length(), stringValue(args[1]));
}
return args[1];
}
if (args[0] instanceof RubyRange) {
long[] idxs = ((RubyRange) args[0]).getBeginLength(getValue().length(), true, true);
replace((int) idxs[0], (int) idxs[1], stringValue(args[1]));
return args[1];
}
throw getRuntime().newTypeError("wrong argument type");
}
/** rb_str_slice_bang
*
*/
public IRubyObject slice_bang(IRubyObject[] args) {
int argc = checkArgumentCount(args, 1, 2);
IRubyObject[] newArgs = new IRubyObject[argc + 1];
newArgs[0] = args[0];
if (argc > 1) {
newArgs[1] = args[1];
}
newArgs[argc] = newString("");
IRubyObject result = aref(args);
if (result.isNil()) {
return result;
}
aset(newArgs);
return result;
}
public IRubyObject succ() {
return ((RubyString) dup()).succ_bang();
}
public IRubyObject succ_bang() {
if (getValue().length() == 0) {
return this;
}
StringBuffer sbuf = getMutableValue();
boolean alnumSeen = false;
int pos = -1;
char c = 0;
char n = 0;
for (int i = sbuf.length() - 1; i >= 0; i--) {
c = sbuf.charAt(i);
if (isAlnum(c)) {
alnumSeen = true;
if ((isDigit(c) && c < '9') || (isLower(c) && c < 'z') || (isUpper(c) && c < 'Z')) {
sbuf.setCharAt(i, (char) (c + 1));
pos = -1;
break;
}
pos = i;
n = isDigit(c) ? '0' : (isLower(c) ? 'a' : 'A');
sbuf.setCharAt(i, n);
}
}
if (!alnumSeen) {
for (int i = sbuf.length() - 1; i >= 0; i--) {
c = sbuf.charAt(i);
if (c < 0xff) {
sbuf.setCharAt(i, (char) (c + 1));
pos = -1;
break;
}
pos = i;
n = '\u0001';
sbuf.setCharAt(i, '\u0000');
}
}
if (pos > -1) {
// This represents left most digit in a set of incremented
// values? Therefore leftmost numeric must be '1' and not '0'
// 999 -> 1000, not 999 -> 0000. whereas chars should be
// zzz -> aaaa
sbuf.insert(pos, isDigit(c) ? '1' : (isLower(c) ? 'a' : 'A'));
}
return this;
}
/** rb_str_upto_m
*
*/
public IRubyObject upto(IRubyObject str) {
return upto(str, false);
}
/* rb_str_upto */
public IRubyObject upto(IRubyObject str, boolean excl) {
// alias 'this' to 'beg' for ease of comparison with MRI
RubyString beg = this;
RubyString end = stringValue(str);
int n = beg.cmp(end);
if (n > 0 || (excl && n == 0)) {
return beg;
}
RubyString afterEnd = stringValue(end.succ());
RubyString current = beg;
while (!current.equals(afterEnd)) {
getRuntime().getCurrentContext().yield(current);
if (!excl && current.equals(end)) {
break;
}
current = (RubyString) current.succ();
if (excl && current.equals(end)) {
break;
}
if (current.length().getLongValue() > end.length().getLongValue()) {
break;
}
}
return beg;
}
/** rb_str_include
*
*/
public RubyBoolean include(IRubyObject obj) {
if (obj instanceof RubyFixnum) {
char c = (char) RubyNumeric.fix2int(obj);
return getRuntime().newBoolean(toString().indexOf(c) != -1);
}
String str = stringValue(obj).toString();
return getRuntime().newBoolean(getMutableValue().indexOf(str) != -1);
}
/** rb_str_to_i
*
*/
public IRubyObject to_i(IRubyObject[] args) {
long base = checkArgumentCount(args, 0, 1) == 0 ? 10 : ((RubyInteger) args[0].convertType(RubyInteger.class,
"Integer", "to_i")).getLongValue();
return RubyNumeric.str2inum(getRuntime(), this, (int) base);
}
/** rb_str_oct
*
*/
public IRubyObject oct() {
if (isEmpty()) {
return getRuntime().newFixnum(0);
}
int base = 8;
String str = toString().trim();
int pos = (str.charAt(0) == '-' || str.charAt(0) == '+') ? 1 : 0;
if (str.indexOf("0x") == pos || str.indexOf("0X") == pos) {
base = 16;
} else if (str.indexOf("0b") == pos || str.indexOf("0B") == pos) {