Skip to content

Commit

Permalink
fix JSONWriterUTF16#putLong & add testcase
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jul 27, 2023
1 parent 5c090eb commit 59c7c76
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1315,7 +1315,7 @@ static void putLong(char[] buf, int off, int b0, int b1) {
long v = HEX256[b0 & 0xff] | (((long) HEX256[b1 & 0xff]) << 32);
UNSAFE.putLong(
buf,
ARRAY_BYTE_BASE_OFFSET + (off << 1),
ARRAY_CHAR_BASE_OFFSET + (off << 1),
BIG_ENDIAN ? Long.reverseBytes(v << 8) : v
);
}
Expand Down
41 changes: 41 additions & 0 deletions core/src/test/java/com/alibaba/fastjson2/JSONWriterUTF16Test.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

import static com.alibaba.fastjson2.JSONWriter.Feature.NullAsDefaultValue;
import static com.alibaba.fastjson2.JSONWriter.Feature.PrettyFormat;
import static com.alibaba.fastjson2.util.JDKUtils.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

Expand Down Expand Up @@ -535,4 +536,44 @@ public void writeStringLatin1Pretty() {
Object parse = JSON.parse(json);
assertEquals(str, parse);
}

@Test
public void testHex256() {
if (BIG_ENDIAN) {
return;
}

char[] buf = new char[4];
int b0 = 0xab, b1 = 0xcd;
int[] hex256 = JSONWriterUTF16.HEX256;
long v = hex256[b0 & 0xff] | (((long) hex256[b1 & 0xff]) << 32);
UNSAFE.putLong(
buf,
ARRAY_CHAR_BASE_OFFSET,
v
);
assertEquals("abcd", new String(buf));
}

@Test
public void testLHex256BigEndian() {
if (!BIG_ENDIAN) {
return;
}

char[] buf = new char[4];
int b0 = 0xab, b1 = 0xcd;
int[] hex256 = JSONWriterUTF16.HEX256.clone();
for (int i = 0; i < hex256.length; i++) {
hex256[i] = Integer.reverseBytes(hex256[i] << 8);
}
long v = hex256[b0 & 0xff]
| (((long) hex256[b1 & 0xff]) << 32);
UNSAFE.putLong(
buf,
ARRAY_CHAR_BASE_OFFSET,
Long.reverseBytes(v << 8)
);
assertEquals("abcd", new String(buf));
}
}

0 comments on commit 59c7c76

Please sign in to comment.