Skip to content

Commit

Permalink
PREDICATE_IS_ASCII
Browse files Browse the repository at this point in the history
  • Loading branch information
wenshao committed Jan 19, 2025
1 parent 64dd6f9 commit 2b50ce9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 19 deletions.
23 changes: 4 additions & 19 deletions core/src/main/java/com/alibaba/fastjson2/JSONReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -3240,13 +3240,8 @@ protected final String toString(Map object) {
}

public static JSONReader of(byte[] utf8Bytes) {
boolean ascii = false;
if (PREDICATE_IS_ASCII != null) {
ascii = PREDICATE_IS_ASCII.test(utf8Bytes);
}

Context context = createReadContext();
if (ascii) {
if (PREDICATE_IS_ASCII.test(utf8Bytes)) {
return new JSONReaderASCII(context, null, utf8Bytes, 0, utf8Bytes.length);
}

Expand All @@ -3255,25 +3250,15 @@ public static JSONReader of(byte[] utf8Bytes) {

@Deprecated
public static JSONReader of(Context context, byte[] utf8Bytes) {
boolean ascii = false;
if (PREDICATE_IS_ASCII != null) {
ascii = PREDICATE_IS_ASCII.test(utf8Bytes);
}

if (ascii) {
if (PREDICATE_IS_ASCII.test(utf8Bytes)) {
return new JSONReaderASCII(context, null, utf8Bytes, 0, utf8Bytes.length);
}

return new JSONReaderUTF8(context, null, utf8Bytes, 0, utf8Bytes.length);
}

public static JSONReader of(byte[] utf8Bytes, Context context) {
boolean ascii = false;
if (PREDICATE_IS_ASCII != null) {
ascii = PREDICATE_IS_ASCII.test(utf8Bytes);
}

if (ascii) {
if (PREDICATE_IS_ASCII.test(utf8Bytes)) {
return new JSONReaderASCII(context, null, utf8Bytes, 0, utf8Bytes.length);
}

Expand Down Expand Up @@ -3510,7 +3495,7 @@ public static JSONReader of(String str) {
}

Context context = JSONFactory.createReadContext();
if (STRING_VALUE != null && STRING_CODER != null && PREDICATE_IS_ASCII != null) {
if (STRING_VALUE != null && STRING_CODER != null) {
try {
final int LATIN1 = 0;
int coder = STRING_CODER.applyAsInt(str);
Expand Down
20 changes: 20 additions & 0 deletions core/src/main/java/com/alibaba/fastjson2/util/JDKUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,9 @@ public class JDKUtils {
initErrorLast = e;
}
}
if (isAscii == null) {
isAscii = JDKUtils::isASCII;
}

PREDICATE_IS_ASCII = isAscii;
}
Expand Down Expand Up @@ -506,4 +509,21 @@ public static String latin1StringJDK8(byte[] bytes, int offset, int strlen) {
}
return STRING_CREATOR_JDK8.apply(chars, Boolean.TRUE);
}

public static boolean isASCII(byte[] chars) {
int i = 0;
int strlen = chars.length;
for (int upperBound = (strlen & ~7); i < upperBound; i += 8) {
if ((UNSAFE.getLong(chars, ARRAY_BYTE_BASE_OFFSET + i) & 0x8080808080808080L) != 0) {
return false;
}
}

for (; i < strlen; ++i) {
if (UNSAFE.getByte(chars, ARRAY_BYTE_BASE_OFFSET + i) < 0) {
return false;
}
}
return true;
}
}

0 comments on commit 2b50ce9

Please sign in to comment.