Skip to content

Commit 64b1a3a

Browse files
committed
Replace JavaScript TextDecoder with Wasm code because it is faster today (Node) and work better with future GC code.
1 parent b999bf7 commit 64b1a3a

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

src/de/inetsoftware/jwebassembly/api/java/lang/ReplacementForString.java

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -28,27 +28,56 @@ class ReplacementForString {
2828
/**
2929
* Replacement for new String(byte[])
3030
*/
31-
@Import( name="newBytes", js = "(value) => new TextDecoder().decode(value)")
3231
@Replace( "java/lang/String.<init>([B)V" )
33-
static String init(byte[] value) {
34-
return null; // for compiler
32+
private static String newFromBytes(byte[] bytes) {
33+
return newFromSubBytes( bytes, 0, bytes.length );
34+
}
35+
36+
/**
37+
* Replacement for new String(byte[],int,int). Decode the bytes with the platform default encoding UTF-8.
38+
*/
39+
@Replace( "java/lang/String.<init>([BII)V" )
40+
private static String newFromSubBytes( byte[] bytes, int offset, int length ) {
41+
int count = 0;
42+
char[] buffer = new char[length - offset];
43+
while( offset < length ) {
44+
int ch = bytes[offset++] & 0xFF;
45+
46+
if( ch <= 0x7F ) {
47+
//ch = ch;
48+
} else if( ch <= 0xDF ) {
49+
ch = ((ch & 0x1F) << 6) | (bytes[offset++] & 0x3F);
50+
} else if( ch <= 0xEF ) {
51+
ch = ((ch & 0x0F) << 12) | ((bytes[offset++] & 0x3F) << 6) | (bytes[offset++] & 0x3F);
52+
} else {
53+
ch = ((ch & 0x07) << 18) | ((bytes[offset++] & 0x3F) << 12) | ((bytes[offset++] & 0x3F) << 6) | (bytes[offset++] & 0x3F);
54+
// high surrogate
55+
buffer[count++] = (char)(0xD7C0 + ((ch >> 10) & 0x3ff));
56+
// low surrogate
57+
ch = 0xDC00 + (ch & 0x3ff);
58+
}
59+
60+
buffer[count++] = (char)ch;
61+
}
62+
63+
return new String( buffer, 0, count );
3564
}
3665

3766
/**
3867
* Replacement for new String(char[])
3968
*/
40-
@Import( name="newChars", js = "(value)=>String.fromCharCode.apply(null,value)")
69+
@Import( name = "newFromChars", js = "(value)=>String.fromCharCode.apply(null,value)" )
4170
@Replace( "java/lang/String.<init>([C)V" )
42-
static String init(char[] value) {
71+
static String newFromChars(char[] value) {
4372
return null; // for compiler
4473
}
4574

4675
/**
4776
* Replacement for new String(char[],int,int)
4877
*/
49-
@Import( name="newSubChars", js = "(value,off,count)=>String.fromCharCode.apply(null,value.subarray(off,off+count))")
78+
@Import( name = "newFromSubChars", js = "(value,off,count)=>String.fromCharCode.apply(null,value.subarray(off,off+count))")
5079
@Replace( "java/lang/String.<init>([CII)V" )
51-
static String init(char[] value, int offset, int count) {
80+
static String newFromSubChars(char[] value, int offset, int count) {
5281
return null; // for compiler
5382
}
5483
}

0 commit comments

Comments
 (0)