forked from mozilla/pluotsorbet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
string.js
621 lines (511 loc) · 19 KB
/
string.js
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
/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
/**
* string.js: Native implementations of String and StringBuffer.
*
* Methods are defined in the same order as the Java source.
* Any missing methods have been noted in comments.
*/
//################################################################
// java.lang.String (manipulated via the 'str' property)
function isString(obj) {
return obj && obj.str !== undefined;
}
//****************************************************************
// Constructors
Native["java/lang/String.init.()V"] = function() {
this.str = "";
};
Native["java/lang/String.init.(Ljava/lang/String;)V"] = function(jStr) {
if (!jStr) {
throw $.newNullPointerException();
}
this.str = jStr.str;
};
Native["java/lang/String.init.([C)V"] = function(chars) {
if (!chars) {
throw $.newNullPointerException();
}
this.str = util.fromJavaChars(chars);
};
Native["java/lang/String.init.([CII)V"] = function(value, offset, count) {
if (offset < 0 || count < 0 || offset > value.length - count) {
throw $.newStringIndexOutOfBoundsException();
}
this.str = util.fromJavaChars(value, offset, count);
};
// Several constructors below share this implementation:
function constructFromByteArray(bytes, off, len, enc) {
enc = normalizeEncoding(enc);
bytes = bytes.subarray(off, off + len);
try {
this.str = new TextDecoder(enc).decode(bytes);
} catch(e) {
throw $.newUnsupportedEncodingException();
}
}
Native["java/lang/String.init.([BIILjava/lang/String;)V"] =
function(bytes, off, len, enc) {
constructFromByteArray.call(this, bytes, off, len, enc.str);
};
Native["java/lang/String.init.([BLjava/lang/String;)V"] =
function(bytes, enc) {
constructFromByteArray.call(this, bytes, 0, bytes.length, enc.str);
};
Native["java/lang/String.init.([BII)V"] =
function(bytes, offset, len) {
constructFromByteArray.call(this, bytes, offset, len, "UTF-8");
};
Native["java/lang/String.init.([B)V"] =
function(bytes) {
constructFromByteArray.call(this, bytes, 0, bytes.length, "UTF-8");
};
Native["java/lang/String.init.(Ljava/lang/StringBuffer;)V"] =
function(jBuffer) {
this.str = util.fromJavaChars(jBuffer.buf, 0, jBuffer.count);
};
Native["java/lang/String.init.(II[C)V"] =
function(offset, count, value) {
this.str = util.fromJavaChars(value, offset, count);
};
//****************************************************************
// Methods
Native["java/lang/String.length.()I"] = function() {
return this.str.length;
};
Native["java/lang/String.charAt.(I)C"] = function(index) {
if (index < 0 || index >= this.str.length) {
throw $.newStringIndexOutOfBoundsException();
}
return this.str.charCodeAt(index);
};
Native["java/lang/String.getChars.(II[CI)V"] = function(srcBegin, srcEnd, dst, dstBegin) {
if (srcBegin < 0 || srcEnd > this.str.length || srcBegin > srcEnd ||
dstBegin + (srcEnd - srcBegin) > dst.length || dstBegin < 0) {
throw $.newStringIndexOutOfBoundsException();
}
dst.set(util.stringToCharArray(this.str.substring(srcBegin, srcEnd)), dstBegin);
};
// Java returns encodings like "UTF_16"; TextEncoder and friends only
// like hyphens, not underscores.
function normalizeEncoding(enc) {
var encoding = enc.toLowerCase().replace(/_/g, '-');
if (encoding == "utf-16") {
encoding = "utf-16be"; // Java defaults to big-endian, JS to little-endian.
}
return encoding;
}
Native["java/lang/String.getBytes.(Ljava/lang/String;)[B"] = function(jEnc) {
try {
var encoding = normalizeEncoding(jEnc.str);
return new Int8Array(new TextEncoder(encoding).encode(this.str));
} catch (e) {
throw $.newUnsupportedEncodingException();
}
};
Native["java/lang/String.getBytes.()[B"] = function() {
return new Int8Array(new TextEncoder("utf-8").encode(this.str));
};
Native["java/lang/String.equals.(Ljava/lang/Object;)Z"] = function(anObject) {
return (isString(anObject) && anObject.str === this.str) ? 1 : 0;
};
Native["java/lang/String.equalsIgnoreCase.(Ljava/lang/String;)Z"] = function(anotherString) {
return (isString(anotherString) && anotherString.str.toLowerCase() === this.str.toLowerCase()) ? 1 : 0;
};
Native["java/lang/String.compareTo.(Ljava/lang/String;)I"] = function(anotherString) {
// Sadly, JS String doesn't have a compareTo() method, so we must
// replicate the Java algorithm. (There is String.localeCompare, but
// that only returns {-1, 0, 1}, not a distance measure, which this
// requires.
var len1 = this.str.length;
var len2 = anotherString.str.length;
var n = Math.min(len1, len2);
var v1 = this.str;
var v2 = anotherString.str;
for (var k = 0; k < n; k++) {
var c1 = v1.charCodeAt(k);
var c2 = v2.charCodeAt(k);
if (c1 != c2) {
return c1 - c2;
}
}
return len1 - len2;
};
Native["java/lang/String.regionMatches.(ZILjava/lang/String;II)Z"] = function(ignoreCase, toffset, other, ooffset, len) {
var a = (ignoreCase ? this.str.toLowerCase() : this.str);
var b = (ignoreCase ? other.str.toLowerCase() : other.str);
return a.substr(toffset, len) === b.substr(ooffset, len) ? 1 : 0;
};
Native["java/lang/String.startsWith.(Ljava/lang/String;I)Z"] = function(prefix, toffset) {
return this.str.substr(toffset, prefix.str.length) === prefix.str ? 1 : 0;
};
Native["java/lang/String.startsWith.(Ljava/lang/String;)Z"] = function(prefix) {
return this.str.substr(0, prefix.str.length) === prefix.str ? 1 : 0;
};
Native["java/lang/String.endsWith.(Ljava/lang/String;)Z"] = function(suffix) {
return this.str.indexOf(suffix.str, this.str.length - suffix.str.length) !== -1 ? 1 : 0;
};
Native["java/lang/String.hashCode.()I"] = function() {
var hash = 0;
for (var i = 0; i < this.str.length; i++) {
hash = Math.imul(31, hash) + this.str.charCodeAt(i) | 0;
}
return hash;
};
Native["java/lang/String.indexOf.(I)I"] = function(ch) {
return this.str.indexOf(String.fromCharCode(ch));
};
Native["java/lang/String.indexOf.(II)I"] = function(ch, fromIndex) {
return this.str.indexOf(String.fromCharCode(ch), fromIndex);
};
Native["java/lang/String.lastIndexOf.(I)I"] = function(ch) {
return this.str.lastIndexOf(String.fromCharCode(ch));
};
Native["java/lang/String.lastIndexOf.(II)I"] = function(ch, fromIndex) {
return this.str.lastIndexOf(String.fromCharCode(ch), fromIndex);
};
Native["java/lang/String.indexOf.(Ljava/lang/String;)I"] = function(s) {
return this.str.indexOf(s.str);
};
Native["java/lang/String.indexOf.(Ljava/lang/String;I)I"] = function(s, fromIndex) {
return this.str.indexOf(s.str, fromIndex);
};
Native["java/lang/String.substring.(I)Ljava/lang/String;"] = function(beginIndex) {
if (beginIndex < 0 || beginIndex > this.str.length) {
throw $.newStringIndexOutOfBoundsException();
}
return J2ME.newString(this.str.substring(beginIndex));
};
Native["java/lang/String.substring.(II)Ljava/lang/String;"] = function(beginIndex, endIndex) {
if (beginIndex < 0 || endIndex > this.str.length || beginIndex > endIndex) {
throw $.newStringIndexOutOfBoundsException();
}
return J2ME.newString(this.str.substring(beginIndex, endIndex));
};
Native["java/lang/String.concat.(Ljava/lang/String;)Ljava/lang/String;"] = function(s) {
return J2ME.newString(this.str + s.str);
};
// via MDN:
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Native["java/lang/String.replace.(CC)Ljava/lang/String;"] = function(oldChar, newChar) {
// Using a RegExp here to replace all matches of oldChar, rather than just the first.
return J2ME.newString(this.str.replace(
new RegExp(escapeRegExp(String.fromCharCode(oldChar)), "g"),
String.fromCharCode(newChar)));
};
Native["java/lang/String.toLowerCase.()Ljava/lang/String;"] = function() {
return J2ME.newString(this.str.toLowerCase());
};
Native["java/lang/String.toUpperCase.()Ljava/lang/String;"] = function() {
return J2ME.newString(this.str.toUpperCase());
};
Native["java/lang/String.trim.()Ljava/lang/String;"] = function() {
// Java's String.trim() removes any character <= ASCII 32;
// JavaScript's only removes a few whitespacey chars.
var start = 0;
var end = this.str.length;
while (start < end && this.str.charCodeAt(start) <= 32) {
start++;
}
while (start < end && this.str.charCodeAt(end - 1) <= 32) {
end--;
}
return J2ME.newString(this.str.substring(start, end));
};
Native["java/lang/String.toString.()Ljava/lang/String;"] = function() {
return this; // Note: returning "this" so that we keep the same object.
};
Native["java/lang/String.toCharArray.()[C"] = function() {
return util.stringToCharArray(this.str);
};
//****************************************************************
// String.valueOf() for various types
// NOTE: String.valueOf(Object) left in Java to avoid having to call
// back into Java for Object.toString().
Native["java/lang/String.valueOf.([C)Ljava/lang/String;"] = function(chars) {
if (!chars) {
throw $.newNullPointerException();
}
return J2ME.newString(util.fromJavaChars(chars));
};
Native["java/lang/String.valueOf.([CII)Ljava/lang/String;"] = function(chars, offset, count) {
if (!chars) {
throw $.newNullPointerException();
}
return J2ME.newString(util.fromJavaChars(chars, offset, count));
};
Native["java/lang/String.valueOf.(Z)Ljava/lang/String;"] = function(bool) {
return J2ME.newString(bool ? "true" : "false");
};
Native["java/lang/String.valueOf.(C)Ljava/lang/String;"] = function(ch) {
return J2ME.newString(String.fromCharCode(ch));
};
Native["java/lang/String.valueOf.(I)Ljava/lang/String;"] = function(n) {
return J2ME.newString(n.toString());
};
Native["java/lang/String.valueOf.(J)Ljava/lang/String;"] = function(n) {
return J2ME.newString(n.toString());
};
// String.valueOf(float) and String.valueOf(double) have been left in
// Java for now, as they require support for complex formatting rules.
// Additionally, their tests check for coverage of nuanced things like
// positive zero vs. negative zero, which we don't currently support.
var internedStrings = J2ME.internedStrings;
Native["java/lang/String.intern.()Ljava/lang/String;"] = function() {
var string = J2ME.fromJavaString(this);
var internedString = internedStrings.get(string);
if (internedString) {
return internedString;
} else {
internedStrings.set(string, this);
return this;
}
};
//################################################################
// java.lang.StringBuffer (manipulated via the 'buf' property)
Native["java/lang/StringBuffer.init.()V"] = function() {
this.buf = new Uint16Array(16); // Initial buffer size: 16, per the Java implementation.
this.count = 0;
};
Native["java/lang/StringBuffer.init.(I)V"] = function(length) {
if (length < 0) {
throw $.newNegativeArraySizeException();
}
this.buf = new Uint16Array(length);
this.count = 0;
};
Native["java/lang/StringBuffer.init.(Ljava/lang/String;)V"] = function(jStr) {
var stringBuf = util.stringToCharArray(jStr.str);
this.buf = new Uint16Array(stringBuf.length + 16); // Add 16, per the Java implementation.
this.buf.set(stringBuf, 0);
this.count = stringBuf.length;
};
Native["java/lang/StringBuffer.length.()I"] = function() {
return this.count;
};
Native["java/lang/StringBuffer.capacity.()I"] = function() {
return this.buf.length;
};
Native["java/lang/StringBuffer.copy.()V"] = function() {
// We don't support copying (there's no need unless we also support shared buffers).
};
/**
* Expand capacity to max(minCapacity, (capacity + 1) * 2).
*
* @this StringBuffer
* @param {number} minCapacity
*/
function expandCapacity(minCapacity) {
var newCapacity = (this.buf.length + 1) << 1;
if (minCapacity > newCapacity) {
newCapacity = minCapacity;
}
var oldBuf = this.buf;
this.buf = new Uint16Array(newCapacity);
this.buf.set(oldBuf, 0);
}
Native["java/lang/StringBuffer.ensureCapacity.(I)V"] = function(minCapacity) {
if (this.buf.length < minCapacity) {
expandCapacity.call(this, minCapacity);
}
};
// StringBuffer.expandCapacity is private and not needed with these overrides.
Native["java/lang/StringBuffer.setLength.(I)V"] = function(newLength) {
if (newLength < 0) {
throw $.newStringIndexOutOfBoundsException();
}
if (newLength > this.buf.length) {
expandCapacity.call(this, newLength);
}
for (; this.count < newLength; this.count++) {
this.buf[this.count] = '\0';
}
this.count = newLength;
};
Native["java/lang/StringBuffer.charAt.(I)C"] = function(index) {
if (index < 0 || index >= this.count) {
throw $.newStringIndexOutOfBoundsException();
}
return this.buf[index];
};
Native["java/lang/StringBuffer.getChars.(II[CI)V"] = function(srcBegin, srcEnd, dst, dstBegin) {
if (srcBegin < 0 || srcEnd < 0 || srcEnd > this.count || srcBegin > srcEnd) {
throw $.newStringIndexOutOfBoundsException();
}
if (dstBegin + (srcEnd - srcBegin) > dst.length || dstBegin < 0) {
throw $.newArrayIndexOutOfBoundsException();
}
dst.set(this.buf.subarray(srcBegin, srcEnd), dstBegin);
};
Native["java/lang/StringBuffer.setCharAt.(IC)V"] = function(index, ch) {
if (index < 0 || index >= this.count) {
throw $.newStringIndexOutOfBoundsException();
}
this.buf[index] = ch;
};
/**
* Append `data`, which should be either a JS String or a Uint16Array.
* Data must not be null.
*
* @this StringBuffer
* @param {Uint16Array|string} data
* @return this
*/
function stringBufferAppend(data) {
if (data == null) {
throw $.newNullPointerException();
}
if (!(data instanceof Uint16Array)) {
data = util.stringToCharArray(data);
}
if (this.buf.length < this.count + data.length) {
expandCapacity.call(this, this.count + data.length);
}
this.buf.set(data, this.count);
this.count += data.length;
return this;
}
// StringBuffer.append(java.lang.Object) left in Java to avoid Object.toString().
Native["java/lang/StringBuffer.append.(Ljava/lang/String;)Ljava/lang/StringBuffer;"] = function(jStr) {
return stringBufferAppend.call(this, jStr ? jStr.str : "null");
};
Native["java/lang/StringBuffer.append.([C)Ljava/lang/StringBuffer;"] = function(chars) {
if (chars == null) {
throw $.newNullPointerException();
}
return stringBufferAppend.call(this, chars);
};
Native["java/lang/StringBuffer.append.([CII)Ljava/lang/StringBuffer;"] = function(chars, offset, length) {
if (chars == null) {
throw $.newNullPointerException();
}
if (offset < 0 || offset + length > chars.length) {
throw $.newArrayIndexOutOfBoundsException();
}
return stringBufferAppend.call(this, chars.subarray(offset, offset + length));
};
Native["java/lang/StringBuffer.append.(Z)Ljava/lang/StringBuffer;"] = function(bool) {
return stringBufferAppend.call(this, bool ? "true" : "false");
};
Native["java/lang/StringBuffer.append.(C)Ljava/lang/StringBuffer;"] = function(ch) {
if (this.buf.length < this.count + 1) {
expandCapacity.call(this, this.count + 1);
}
this.buf[this.count++] = ch;
return this;
};
Native["java/lang/StringBuffer.append.(I)Ljava/lang/StringBuffer;"] = function(n) {
return stringBufferAppend.call(this, n + "");
};
Native["java/lang/StringBuffer.append.(J)Ljava/lang/StringBuffer;"] = function(n) {
return stringBufferAppend.call(this, n + "");
};
// StringBuffer.append(float) left in Java (see String.valueOf(float) above).
// StringBuffer.append(double) left in Java (see String.valueOf(double) above).
/**
* Delete characters between [start, end).
*
* @this StringBuffer
* @param {number} start
* @param {number} end
* @return this
*/
function stringBufferDelete(start, end) {
if (start < 0) {
throw $.newStringIndexOutOfBoundsException();
}
if (end > this.count) {
end = this.count;
}
if (start > end) {
throw $.newStringIndexOutOfBoundsException();
}
var len = end - start;
if (len > 0) {
// When Gecko 34 is released, we can use TypedArray.copyWithin() instead.
this.buf.set(this.buf.subarray(end, this.count), start);
this.count -= len;
}
return this;
}
Native["java/lang/StringBuffer.delete.(II)Ljava/lang/StringBuffer;"] = stringBufferDelete;
Native["java/lang/StringBuffer.deleteCharAt.(I)Ljava/lang/StringBuffer;"] = function(index) {
if (index >= this.count) {
// stringBufferDelete handles the other boundary checks; this check is specific to deleteCharAt.
throw $.newStringIndexOutOfBoundsException();
}
return stringBufferDelete.call(this, index, index + 1);
};
/**
* Insert `data` at the given `offset`.
*
* @this StringBuffer
* @param {number} offset
* @param {Uint16Array|string} data
* @return this
*/
function stringBufferInsert(offset, data) {
if (data == null) {
throw $.newNullPointerException();
}
if (offset < 0 || offset > this.count) {
throw $.newArrayIndexOutOfBoundsException();
}
if (!(data instanceof Uint16Array)) {
data = util.stringToCharArray(data);
}
if (this.buf.length < this.count + data.length) {
expandCapacity.call(this, this.count + data.length);
}
// When Gecko 34 is released, we can use TypedArray.copyWithin() instead.
this.buf.set(this.buf.subarray(offset, this.count), offset + data.length);
this.buf.set(data, offset);
this.count += data.length;
return this;
}
// StringBuffer.insert(Object) left in Java (for String.valueOf()).
Native["java/lang/StringBuffer.insert.(ILjava/lang/String;)Ljava/lang/StringBuffer;"] = function(offset, jStr) {
return stringBufferInsert.call(this, offset, jStr ? jStr.str : "null");
};
Native["java/lang/StringBuffer.insert.(I[C)Ljava/lang/StringBuffer;"] = function(offset, chars) {
return stringBufferInsert.call(this, offset, chars);
};
Native["java/lang/StringBuffer.insert.(IZ)Ljava/lang/StringBuffer;"] = function(offset, bool) {
return stringBufferInsert.call(this, offset, bool ? "true" : "false");
};
Native["java/lang/StringBuffer.insert.(IC)Ljava/lang/StringBuffer;"] = function(offset, ch) {
return stringBufferInsert.call(this, offset, String.fromCharCode(ch));
};
Native["java/lang/StringBuffer.insert.(II)Ljava/lang/StringBuffer;"] = function(offset, n) {
return stringBufferInsert.call(this, offset, n + "");
};
Native["java/lang/StringBuffer.insert.(IJ)Ljava/lang/StringBuffer;"] = function(offset, n) {
return stringBufferInsert.call(this, offset, n + "");
};
// StringBuffer.insert(float) left in Java.
// StringBuffer.insert(double) left in Java.
Native["java/lang/StringBuffer.reverse.()Ljava/lang/StringBuffer;"] = function() {
var buf = this.buf;
for (var i = 0, j = this.count - 1; i < j; i++, j--) {
var tmp = buf[i];
buf[i] = buf[j];
buf[j] = tmp;
}
return this;
};
Native["java/lang/StringBuffer.toString.()Ljava/lang/String;"] = function() {
return J2ME.newString(util.fromJavaChars(this.buf, 0, this.count));
};
Native["java/lang/StringBuffer.setShared.()V"] = function() {
// Our StringBuffers are never shared. Everyone gets their very own!
};
Native["java/lang/StringBuffer.getValue.()[C"] = function() {
// In theory, this method should only be called by String (which
// we've overridden to not do), so it should never be called. In any
// case, mutating this buf would have the same effect here as it
// would in Java.
return this.buf;
};