proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DateParseMultiFormat.java
|
DateParseMultiFormat
|
javaTimeFormatter
|
class DateParseMultiFormat {
static String[] inputs = {
"2012-06-23 12:13:14",
"2012-06-23T12:13:14",
"23/06/2012 12:13:14",
};
static final DateTimeFormatter formatter =
new DateTimeFormatterBuilder()
.appendPattern("[yyyy-MM-dd HH:mm:ss]")
.appendPattern("[yyyy-MM-dd'T'HH:mm:ss]")
.appendPattern("[yyyy/MM/dd HH:mm:ss]")
.appendPattern("[dd/MM/yyyy HH:mm:ss]")
.appendPattern("[dd MMM yyyy HH:mm:ss]")
.toFormatter();
@Benchmark
public void javaTimeFormatter(Blackhole bh) throws Throwable {<FILL_FUNCTION_BODY>}
@Benchmark
public void parseDate(Blackhole bh) throws Throwable {
Date[] dates = new Date[inputs.length];
for (int i = 0; i < inputs.length; i++) {
String input = inputs[i];
dates[i] = DateUtils.parseDate(input);
}
bh.consume(dates);
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(DateParseMultiFormat.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
}
}
|
Date[] dates = new Date[inputs.length];
for (int i = 0; i < inputs.length; i++) {
String input = inputs[i];
LocalDateTime ldt = LocalDateTime.parse(input, formatter);
ZoneId zoneId = DateUtils.DEFAULT_ZONE_ID;
ZonedDateTime zdt = ldt.atZone(zoneId);
Instant instant = zdt.toInstant();
dates[i] = Date.from(instant);
}
bh.consume(dates);
| 458
| 136
| 594
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DateToString.java
|
DateToString
|
main
|
class DateToString {
static final Date date = new Date(1693836447048L);
@Benchmark
public void dateToString(Blackhole bh) throws Throwable {
bh.consume(date.toString());
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(DateToString.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
| 100
| 83
| 183
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DecimalDToString.java
|
DecimalDToString
|
toStringCharWithInt8UTF16
|
class DecimalDToString {
static final BigInteger unscaledVal;
static int scale = 2;
static BigDecimal decimal;
static BiFunction<BigDecimal, Boolean, String> LAYOUT_CHARS;
static {
decimal = new BigDecimal("0.09313609545535894707057877894840203225612640380859375");
unscaledVal = decimal.unscaledValue();
try {
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(BigDecimal.class);
MethodHandle handle = lookup.findVirtual(
BigDecimal.class, "layoutChars", methodType(String.class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, BigDecimal.class, Boolean.class)
);
LAYOUT_CHARS = (BiFunction<BigDecimal, Boolean, String>) callSite.getTarget().invokeExact();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Benchmark
public void toPlainString(Blackhole bh) {
bh.consume(DecimalUtils.toString(unscaledVal, scale));
}
@Benchmark
public void layoutChars(Blackhole bh) {
bh.consume(
LAYOUT_CHARS.apply(decimal, Boolean.TRUE)
);
}
@Benchmark
public void toPlainStringDec(Blackhole bh) {
bh.consume(
decimal.toPlainString()
);
}
public void toStringCharWithInt8(Blackhole bh) {
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
}
public void toStringCharWithInt8UTF16(Blackhole bh) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder();
result.append('\u4e2d');
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
| 656
| 129
| 785
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DecimalHugToString.java
|
DecimalHugToString
|
toStringCharWithInt8UTF16
|
class DecimalHugToString {
static final BigInteger unscaledVal;
static int scale = 2;
static BigDecimal decimal;
static BiFunction<BigDecimal, Boolean, String> LAYOUT_CHARS;
static {
decimal = new BigDecimal("37335022433733502243.55");
unscaledVal = decimal.unscaledValue();
try {
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(BigDecimal.class);
MethodHandle handle = lookup.findVirtual(
BigDecimal.class, "layoutChars", methodType(String.class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, BigDecimal.class, Boolean.class)
);
LAYOUT_CHARS = (BiFunction<BigDecimal, Boolean, String>) callSite.getTarget().invokeExact();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Benchmark
public void toPlainString(Blackhole bh) {
bh.consume(DecimalUtils.toString(unscaledVal, scale));
}
@Benchmark
public void layoutChars(Blackhole bh) {
bh.consume(LAYOUT_CHARS.apply(decimal, Boolean.TRUE));
}
@Benchmark
public void toPlainStringDec(Blackhole bh) {
bh.consume(
decimal.toPlainString()
);
}
public void toStringCharWithInt8(Blackhole bh) {
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
}
public void toStringCharWithInt8UTF16(Blackhole bh) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder();
result.append('\u4e2d');
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
| 619
| 129
| 748
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DecimalLargeToString.java
|
DecimalLargeToString
|
toStringCharWithInt8UTF16
|
class DecimalLargeToString {
static final BigInteger unscaledVal;
static int scale = 2;
static BigDecimal decimal;
static BiFunction<BigDecimal, Boolean, String> LAYOUT_CHARS;
static {
decimal = new BigDecimal("2715737727.55");
unscaledVal = decimal.unscaledValue();
try {
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(BigDecimal.class);
MethodHandle handle = lookup.findVirtual(
BigDecimal.class, "layoutChars", methodType(String.class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, BigDecimal.class, Boolean.class)
);
LAYOUT_CHARS = (BiFunction<BigDecimal, Boolean, String>) callSite.getTarget().invokeExact();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Benchmark
public void toPlainString(Blackhole bh) {
bh.consume(DecimalUtils.toString(unscaledVal, scale));
}
@Benchmark
public void layoutChars(Blackhole bh) {
bh.consume(LAYOUT_CHARS.apply(decimal, Boolean.TRUE));
}
@Benchmark
public void toPlainStringDec(Blackhole bh) {
bh.consume(
decimal.toPlainString()
);
}
public void toStringCharWithInt8(Blackhole bh) {
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
}
public void toStringCharWithInt8UTF16(Blackhole bh) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder();
result.append('\u4e2d');
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
| 608
| 129
| 737
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DecimalSmallToString.java
|
DecimalSmallToString
|
toStringCharWithInt8
|
class DecimalSmallToString {
static final BigInteger unscaledVal;
static int scale = 2;
static BigDecimal decimal;
static BiFunction<BigDecimal, Boolean, String> LAYOUT_CHARS;
static {
decimal = new BigDecimal("415246.55");
unscaledVal = decimal.unscaledValue();
try {
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(BigDecimal.class);
MethodHandle handle = lookup.findVirtual(
BigDecimal.class, "layoutChars", methodType(String.class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, BigDecimal.class, Boolean.class)
);
LAYOUT_CHARS = (BiFunction<BigDecimal, Boolean, String>) callSite.getTarget().invokeExact();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Benchmark
public void toPlainString(Blackhole bh) {
bh.consume(DecimalUtils.toString(unscaledVal, scale));
}
@Benchmark
public void layoutChars(Blackhole bh) {
bh.consume(
LAYOUT_CHARS.apply(decimal, Boolean.TRUE)
);
}
@Benchmark
public void toPlainStringDec(Blackhole bh) {
bh.consume(
decimal.toPlainString()
);
}
public void toStringCharWithInt8(Blackhole bh) {<FILL_FUNCTION_BODY>}
public void toStringCharWithInt8UTF16(Blackhole bh) {
StringBuilder result = new StringBuilder();
result.append('\u4e2d');
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
}
}
|
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
| 623
| 116
| 739
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DecimalToString.java
|
DecimalToString
|
toStringCharWithInt8UTF16
|
class DecimalToString {
static final long unscaledVal = 123456;
static int scale = 2;
static BigDecimal decimal = BigDecimal.valueOf(unscaledVal, scale);
static BiFunction<BigDecimal, Boolean, String> LAYOUT_CHARS;
static {
try {
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(BigDecimal.class);
MethodHandle handle = lookup.findVirtual(
BigDecimal.class, "layoutChars", methodType(String.class, boolean.class)
);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"apply",
methodType(BiFunction.class),
methodType(Object.class, Object.class, Object.class),
handle,
methodType(String.class, BigDecimal.class, Boolean.class)
);
LAYOUT_CHARS = (BiFunction<BigDecimal, Boolean, String>) callSite.getTarget().invokeExact();
} catch (Throwable e) {
e.printStackTrace();
}
}
@Benchmark
public void toPlainString(Blackhole bh) {
bh.consume(DecimalUtils.toString(unscaledVal, scale));
}
@Benchmark
public void layoutChars(Blackhole bh) {
bh.consume(LAYOUT_CHARS.apply(decimal, Boolean.TRUE));
}
@Benchmark
public void toPlainStringDec(Blackhole bh) {
bh.consume(decimal.toPlainString());
}
public void toStringCharWithInt8(Blackhole bh) {
StringBuilder result = new StringBuilder();
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
}
public void toStringCharWithInt8UTF16(Blackhole bh) {<FILL_FUNCTION_BODY>}
}
|
StringBuilder result = new StringBuilder();
result.append('\u4e2d');
result.append(2048);
result.append(31337);
result.append(0xbeefcace);
result.append(9000);
result.append(4711);
result.append(1337);
result.append(2100);
result.append(2600);
bh.consume(result.toString());
| 585
| 129
| 714
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DoubleToBigDecimal.java
|
DoubleToBigDecimal
|
main
|
class DoubleToBigDecimal {
static final double value = 0.6730586701548151D;
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(TypeUtils.toBigDecimal(value));
}
@Benchmark
public void jdk(Blackhole bh) {
bh.consume(BigDecimal.valueOf(value));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(DoubleToBigDecimal.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
| 148
| 86
| 234
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/DoubleToString.java
|
DoubleToString
|
ryu
|
class DoubleToString {
static double d = 0.6730586701548151D;
static float f = 0.98163563F;
@Benchmark
public void jdk(Blackhole bh) throws Throwable {
bh.consume(Double.toString(d));
}
@Benchmark
public void ryu(Blackhole bh) throws Throwable {<FILL_FUNCTION_BODY>}
// @Benchmark
public void jdkFloat(Blackhole bh) throws Throwable {
bh.consume(Float.toString(f));
}
// @Benchmark
public void ryuFloat(Blackhole bh) throws Throwable {
byte[] bytes = new byte[15];
int size = DoubleToDecimal.toString(f, bytes, 0, false);
String str = new String(bytes, 0, 0, size);
bh.consume(str);
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(DoubleToString.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
}
}
|
byte[] bytes = new byte[24];
int size = DoubleToDecimal.toString(d, bytes, 0, true);
String str = new String(bytes, 0, 0, size);
bh.consume(str);
| 363
| 64
| 427
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/FloatToBigDecimal.java
|
FloatToBigDecimal
|
main
|
class FloatToBigDecimal {
static final float value = 123456.780F;
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(TypeUtils.toBigDecimal(value));
}
@Benchmark
public void jdk(Blackhole bh) {
bh.consume(BigDecimal.valueOf(value));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(FloatToBigDecimal.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
| 141
| 86
| 227
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/Invoke.java
|
Bean
|
main
|
class Bean {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>
|
Options options = new OptionsBuilder()
.include(Invoke.class.getName())
.include(InvokeFirst.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
| 128
| 96
| 224
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/InvokeFirst.java
|
InvokeFirst
|
genLambda
|
class InvokeFirst {
@Benchmark
public void genLambda(Blackhole bh) throws Throwable {<FILL_FUNCTION_BODY>}
@Benchmark
public void genLambdaASM(Blackhole bh) throws Throwable {
ObjIntConsumer<Bean> function = LambdaGenerator.createSetterInt(Bean.class, "setId");
Bean bean = new Bean();
function.accept(bean, 123);
bh.consume(bean);
}
@Benchmark
public void getMethod(Blackhole bh) throws Throwable {
Method method = Bean.class.getMethod("setId", int.class);
Bean bean = new Bean();
method.invoke(bean, 123);
bh.consume(bean);
}
public static class Bean {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(InvokeFirst.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
}
}
|
MethodHandles.Lookup lookup = JDKUtils.trustedLookup(Bean.class);
MethodType invokedType = MethodType.methodType(ObjIntConsumer.class);
MethodHandle target = lookup.findVirtual(Bean.class, "setId", MethodType.methodType(void.class, int.class));
MethodType instantiatedMethodType = MethodType.methodType(void.class, Bean.class, int.class);
MethodType samMethodType = MethodType.methodType(void.class, Object.class, int.class);
CallSite callSite = LambdaMetafactory.metafactory(
lookup,
"accept",
invokedType,
samMethodType,
target,
instantiatedMethodType
);
ObjIntConsumer function = (ObjIntConsumer) callSite.getTarget().invoke();
Bean bean = new Bean();
function.accept(bean, 123);
bh.consume(bean);
| 419
| 238
| 657
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/LocalDateTimeFormat19.java
|
LocalDateTimeFormat19
|
formatYMDHMS19
|
class LocalDateTimeFormat19 {
static final String pattern = "yyyy-MM-dd HH:mm:ss";
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
static LocalDateTime ldt = LocalDateTime.of(2023, 8, 16, 20, 21, 15);
@Benchmark
public void javaTimeFormatter(Blackhole bh) throws Throwable {
String str = formatter.format(ldt);
bh.consume(str);
}
@Benchmark
public void formatYMDHMS19(Blackhole bh) throws Throwable {
bh.consume(formatYMDHMS19(ldt));
}
@Benchmark
public void formatYMDHMS19_o(Blackhole bh) throws Throwable {
bh.consume(formatYMDHMS19_o(ldt));
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(LocalDateTimeFormat19.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
}
public static String formatYMDHMS19(LocalDateTime ldt) {<FILL_FUNCTION_BODY>}
static String formatYMDHMS19_o(LocalDateTime ldt) {
int year = ldt.getYear();
int month = ldt.getMonthValue();
int dayOfMonth = ldt.getDayOfMonth();
int hour = ldt.getHour();
int minute = ldt.getMinute();
int second = ldt.getSecond();
int y0 = year / 1000 + '0';
int y1 = (year / 100) % 10 + '0';
int y2 = (year / 10) % 10 + '0';
int y3 = year % 10 + '0';
int m0 = month / 10 + '0';
int m1 = month % 10 + '0';
int d0 = dayOfMonth / 10 + '0';
int d1 = dayOfMonth % 10 + '0';
int h0 = hour / 10 + '0';
int h1 = hour % 10 + '0';
int i0 = minute / 10 + '0';
int i1 = minute % 10 + '0';
int s0 = second / 10 + '0';
int s1 = second % 10 + '0';
byte[] bytes = new byte[19];
bytes[0] = (byte) y0;
bytes[1] = (byte) y1;
bytes[2] = (byte) y2;
bytes[3] = (byte) y3;
bytes[4] = '-';
bytes[5] = (byte) m0;
bytes[6] = (byte) m1;
bytes[7] = '-';
bytes[8] = (byte) d0;
bytes[9] = (byte) d1;
bytes[10] = ' ';
bytes[11] = (byte) h0;
bytes[12] = (byte) h1;
bytes[13] = ':';
bytes[14] = (byte) i0;
bytes[15] = (byte) i1;
bytes[16] = ':';
bytes[17] = (byte) s0;
bytes[18] = (byte) s1;
return JDKUtils.STRING_CREATOR_JDK11.apply(bytes, JDKUtils.LATIN1);
}
}
|
int year = ldt.getYear();
int month = ldt.getMonthValue();
int dayOfMonth = ldt.getDayOfMonth();
int hour = ldt.getHour();
int minute = ldt.getMinute();
int second = ldt.getSecond();
byte[] bytes = new byte[19];
int y01 = year / 100;
int y23 = year - y01 * 100;
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET, PACKED_DIGITS[y01]);
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 2, PACKED_DIGITS[y23]);
bytes[4] = '-';
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 5, PACKED_DIGITS[month]);
bytes[7] = '-';
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 8, PACKED_DIGITS[dayOfMonth]);
bytes[10] = ' ';
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 11, PACKED_DIGITS[hour]);
bytes[13] = ':';
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 14, PACKED_DIGITS[minute]);
bytes[16] = ':';
UNSAFE.putShort(bytes, ARRAY_BYTE_BASE_OFFSET + 17, PACKED_DIGITS[second]);
return STRING_CREATOR_JDK11.apply(bytes, LATIN1);
| 987
| 452
| 1,439
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/SimpleDateFormatX.java
|
SimpleDateFormatX
|
parse
|
class SimpleDateFormatX
extends SimpleDateFormat {
transient boolean format19;
transient boolean format10;
public SimpleDateFormatX(String pattern) {
super(pattern);
switch (pattern) {
case "yyyy-MM-dd HH:mm:ss":
format19 = true;
break;
case "yyyy-MM-dd":
format10 = true;
break;
default:
break;
}
}
@Override
public StringBuffer format(
Date date,
StringBuffer toAppendTo,
FieldPosition pos
) {
if (format19 || format10) {
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
toAppendTo.append(year).append('-');
if (month < 10) {
toAppendTo.append('0');
}
toAppendTo.append(month).append('-');
if (dayOfMonth < 10) {
toAppendTo.append('0');
}
toAppendTo.append(dayOfMonth);
if (format10) {
return toAppendTo;
}
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
toAppendTo.append(' ');
if (hour < 10) {
toAppendTo.append('0');
}
toAppendTo.append(hour).append(':');
if (minute < 10) {
toAppendTo.append('0');
}
toAppendTo.append(minute).append(':');
if (second < 10) {
toAppendTo.append('0');
}
toAppendTo.append(second);
return toAppendTo;
}
return super.format(date, toAppendTo, pos);
}
public Date parse(String text) throws ParseException {<FILL_FUNCTION_BODY>}
}
|
if (text != null) {
final int textLength = text.length();
if ((format10 && textLength == 10) || (format19 && textLength == 19)) {
char c0 = text.charAt(0);
char c1 = text.charAt(1);
char c2 = text.charAt(2);
char c3 = text.charAt(3);
char c4 = text.charAt(4);
char c5 = text.charAt(5);
char c6 = text.charAt(6);
char c7 = text.charAt(7);
char c8 = text.charAt(8);
char c9 = text.charAt(9);
int year, month, dayOfMonth;
if (c0 >= '0' && c0 <= '9'
&& c1 >= '0' && c1 <= '9'
&& c2 >= '0' && c2 <= '9'
&& c3 >= '0' && c3 <= '9'
&& c4 == '-'
&& c5 >= '0' && c5 <= '9'
&& c6 >= '0' && c6 <= '9'
&& c7 == '-'
&& c8 >= '0' && c8 <= '9'
&& c9 >= '0' && c9 <= '9'
) {
year = (c0 - '0') * 1000 + (c1 - '0') * 100 + (c2 - '0') * 10 + (c3 - '0');
month = (c5 - '0') * 10 + (c6 - '0');
dayOfMonth = (c8 - '0') * 10 + (c9 - '0');
} else {
return super.parse(text);
}
int dom = 31;
switch (month) {
case 2:
boolean isLeapYear = (year & 15) == 0 ? (year & 3) == 0 : (year & 3) == 0 && year % 100 != 0;
dom = isLeapYear ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
dom = 30;
break;
}
if (year >= -999999999 && year <= 999999999
&& month >= 1 && month <= 12
&& dayOfMonth >= 1 && dayOfMonth <= dom
) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
if (format10) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
} else {
return super.parse(text);
}
char c10 = text.charAt(10);
char c11 = text.charAt(11);
char c12 = text.charAt(12);
char c13 = text.charAt(13);
char c14 = text.charAt(14);
char c15 = text.charAt(15);
char c16 = text.charAt(16);
char c17 = text.charAt(17);
char c18 = text.charAt(18);
int hour, minute, second;
if (c10 == ' '
&& c11 >= '0' && c11 <= '9'
&& c12 >= '0' && c12 <= '9'
&& c13 == ':'
&& c14 >= '0' && c14 <= '9'
&& c15 >= '0' && c15 <= '9'
&& c16 == ':'
&& c17 >= '0' && c17 <= '9'
&& c18 >= '0' && c18 <= '9'
) {
hour = (c11 - '0') * 10 + (c12 - '0');
minute = (c14 - '0') * 10 + (c15 - '0');
second = (c17 - '0') * 10 + (c18 - '0');
if (hour >= 0 && hour <= 23
&& minute >= 0 && minute <= 59
&& second >= 0 && second <= 59
) {
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
} else {
return super.parse(text);
}
}
}
return super.parse(text);
| 564
| 1,303
| 1,867
|
<methods>public void <init>() ,public void <init>(java.lang.String) ,public void <init>(java.lang.String, java.util.Locale) ,public void <init>(java.lang.String, java.text.DateFormatSymbols) ,public void applyLocalizedPattern(java.lang.String) ,public void applyPattern(java.lang.String) ,public java.lang.Object clone() ,public boolean equals(java.lang.Object) ,public java.lang.StringBuffer format(java.util.Date, java.lang.StringBuffer, java.text.FieldPosition) ,public java.text.AttributedCharacterIterator formatToCharacterIterator(java.lang.Object) ,public java.util.Date get2DigitYearStart() ,public java.text.DateFormatSymbols getDateFormatSymbols() ,public int hashCode() ,public java.util.Date parse(java.lang.String, java.text.ParsePosition) ,public void set2DigitYearStart(java.util.Date) ,public void setDateFormatSymbols(java.text.DateFormatSymbols) ,public java.lang.String toLocalizedPattern() ,public java.lang.String toPattern() <variables>static final boolean $assertionsDisabled,private static final java.lang.String GMT,private static final int MILLIS_PER_MINUTE,private static final int[] PATTERN_INDEX_TO_CALENDAR_FIELD,private static final int[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD,private static final java.text.DateFormat.Field[] PATTERN_INDEX_TO_DATE_FORMAT_FIELD_ID,private static final int[] REST_OF_STYLES,private static final int TAG_QUOTE_ASCII_CHAR,private static final int TAG_QUOTE_CHARS,private static final ConcurrentMap<java.util.Locale,java.text.NumberFormat> cachedNumberFormatData,private transient char[] compiledPattern,static final int currentSerialVersion,private java.util.Date defaultCenturyStart,private transient int defaultCenturyStartYear,private transient boolean forceStandaloneForm,private java.text.DateFormatSymbols formatData,private transient boolean hasFollowingMinusSign,private java.util.Locale locale,private transient char minusSign,private transient java.text.NumberFormat originalNumberFormat,private transient java.lang.String originalNumberPattern,private java.lang.String pattern,private int serialVersionOnStream,static final long serialVersionUID,transient boolean useDateFormatSymbols,private transient char zeroDigit
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/StringFormatBenchmark.java
|
StringFormatBenchmark
|
main
|
class StringFormatBenchmark {
static int value = 10245;
static final String PREFIX = "id : ";
static final char[] PREFIX_CHARS = PREFIX.toCharArray();
static final byte[] PREFIX_BYTES = PREFIX.getBytes();
@Benchmark
public void format(Blackhole bh) throws Exception {
bh.consume(
String.format("id : %s", value)
);
}
@Benchmark
public void StringBuffer(Blackhole bh) {
bh.consume(
new StringBuilder().append(PREFIX).append(value).toString()
);
}
@Benchmark
public void creator(Blackhole bh) {
int i = value;
int size = (i < 0) ? IOUtils.stringSize(-i) + 1 : IOUtils.stringSize(i);
String str;
if (JDKUtils.JVM_VERSION == 8) {
char[] chars = new char[PREFIX_CHARS.length + size];
System.arraycopy(PREFIX_CHARS, 0, chars, 0, PREFIX_CHARS.length);
IOUtils.getChars(i, chars.length, chars);
str = JDKUtils.STRING_CREATOR_JDK8.apply(chars, Boolean.TRUE);
} else {
byte[] chars = new byte[PREFIX_BYTES.length + size];
System.arraycopy(PREFIX_BYTES, 0, chars, 0, PREFIX_BYTES.length);
IOUtils.getChars(i, chars.length, chars);
str = JDKUtils.STRING_CREATOR_JDK11.apply(chars, JDKUtils.LATIN1);
}
bh.consume(str);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(StringFormatBenchmark.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(1)
.forks(1)
.build();
new Runner(options).run();
| 505
| 86
| 591
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/fastcode/UUIDUtilsBenchmark.java
|
UUIDUtilsBenchmark
|
main
|
class UUIDUtilsBenchmark {
public static UUID uuid = UUID.randomUUID();
@Benchmark
public void jdk(Blackhole bh) {
bh.consume(uuid.toString());
}
@Benchmark
public void fj2(Blackhole bh) {
bh.consume(UUIDUtils.fastUUID(uuid));
}
@Benchmark
public void fj2utf16(Blackhole bh) {
bh.consume(UUIDUtils.fastUUID2(uuid));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(UUIDUtilsBenchmark.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.threads(1)
.build();
new Runner(options).run();
| 171
| 94
| 265
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/geoip/GeoIPParseString.java
|
GeoIPParseString
|
main
|
class GeoIPParseString {
static String str;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static {
try {
InputStream is = GeoIPParseString.class.getClassLoader().getResourceAsStream("data/geoip.json");
str = IOUtils.toString(is, "UTF-8");
JSON.parseObject(str, GeoIP.class);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(str, GeoIP.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(str, GeoIP.class));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(str, GeoIP.class));
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, GeoIP.class)
);
}
@Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(
gson.fromJson(str, GeoIP.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(GeoIPParseString.class.getName())
.exclude(EishayParseStringPretty.class.getName())
.exclude(EishayParseStringNoneCache.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.threads(16)
.build();
new Runner(options).run();
| 420
| 131
| 551
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/geoip/GeoIPWriteString.java
|
GeoIPWriteString
|
main
|
class GeoIPWriteString {
static GeoIP object;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static {
try {
InputStream is = GeoIPWriteString.class.getClassLoader().getResourceAsStream("data/geoip.json");
String str = IOUtils.toString(is, "UTF-8");
object = JSONReader.of(str).read(GeoIP.class);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.toJSONString(object));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.toJSONString(object));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsString(object));
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.toJsonString(object)
);
}
@Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(
gson.toJson(object)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(GeoIPWriteString.class.getName())
.mode(Mode.Throughput)
.warmupIterations(3)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.threads(16)
.build();
new Runner(options).run();
| 407
| 106
| 513
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/issues/Issue206ParseTreeStringPretty.java
|
Issue206ParseTreeStringPretty
|
fastjson1_perf
|
class Issue206ParseTreeStringPretty {
static String str;
static ObjectMapper mapper = new ObjectMapper();
static {
try {
InputStream is = Issue206ParseTreeStringPretty.class.getClassLoader().getResourceAsStream("issue/issue206.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(str));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(str));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(str, HashMap.class));
}
// @Test
public void fastjson1_perf_test() {
for (int i = 0; i < 10; i++) {
fastjson1_perf();
}
}
// @Test
public void fastjson2_perf_test() {
for (int i = 0; i < 10; i++) {
fastjson2_perf();
}
}
public static void fastjson2_perf() {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 100; ++i) {
JSON.parseObject(str);
}
long millis = System.currentTimeMillis() - start;
System.out.println("millis : " + millis);
// zulu17.32.13 :
// zulu11.52.13 :
// zulu8.58.0.13 : 929 928
}
public static void fastjson1_perf() {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws RunnerException {
// new Issue206ParseTreeStringPretty().fastjson2_perf_test();
Options options = new OptionsBuilder()
.include(Issue206ParseTreeStringPretty.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
}
}
|
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
com.alibaba.fastjson.JSON.parseObject(str);
}
long millis = System.currentTimeMillis() - start;
System.out.println("millis : " + millis);
// zulu17.32.13 :
// zulu11.52.13 : 928
// zulu8.58.0.13 :
| 657
| 141
| 798
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/Clients.java
|
Client
|
fromNumber
|
class Client {
private long id;
private int index;
private UUID guid;
@JSONField(name = "isActive")
private boolean isActive;
private BigDecimal balance;
private String picture;
private int age;
private EyeColor eyeColor;
private String name;
private String gender;
private String company;
private String[] emails;
private long[] phones;
private String address;
private String about;
private LocalDate registered;
private double latitude;
private double longitude;
@JsonAttribute(nullable = false)
private List<String> tags;
@JsonAttribute(nullable = false)
private List<Partner> partners;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public UUID getGuid() {
return guid;
}
public void setGuid(UUID guid) {
this.guid = guid;
}
public boolean getIsActive() {
return isActive;
}
public void setIsActive(boolean active) {
isActive = active;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public EyeColor getEyeColor() {
return eyeColor;
}
public void setEyeColor(EyeColor eyeColor) {
this.eyeColor = eyeColor;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String[] getEmails() {
return emails;
}
public void setEmails(String[] emails) {
this.emails = emails;
}
public long[] getPhones() {
return phones;
}
public void setPhones(long[] phones) {
this.phones = phones;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public LocalDate getRegistered() {
return registered;
}
public void setRegistered(LocalDate registered) {
this.registered = registered;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public List<Partner> getPartners() {
return partners;
}
public void setPartners(List<Partner> partners) {
this.partners = partners;
}
}
public enum EyeColor {
BROWN,
BLUE,
GREEN;
public static EyeColor fromNumber(int i) {<FILL_FUNCTION_BODY>
|
if (i == 0) {
return BROWN;
}
if (i == 1) {
return BLUE;
}
return GREEN;
| 1,100
| 46
| 1,146
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/ClientsParseUTF8Bytes.java
|
ClientsParseUTF8Bytes
|
gson
|
class ClientsParseUTF8Bytes {
static byte[] utf8Bytes;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader());
static {
try {
InputStream is = ClientsParseUTF8Bytes.class.getClassLoader().getResourceAsStream("data/jjb/client.json");
utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(utf8Bytes, Clients.class));
}
@Benchmark
public void dsljson(Blackhole bh) throws IOException {
bh.consume(dslJson.deserialize(Clients.class, utf8Bytes, utf8Bytes.length));
}
// @Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(utf8Bytes, Clients.class));
}
// @Benchmark
public void gson(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(ClientsParseUTF8Bytes.class.getName())
.exclude(EishayParseUTF8BytesPretty.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(2)
.threads(16)
.build();
new Runner(options).run();
}
}
|
bh.consume(gson
.fromJson(
new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8),
Clients.class)
);
| 496
| 56
| 552
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/ClientsWriteUTF8Bytes.java
|
ClientsWriteUTF8Bytes
|
main
|
class ClientsWriteUTF8Bytes {
static Clients clients;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader());
static final ThreadLocal<ByteArrayOutputStream> bytesOutLocal = ThreadLocal.withInitial(() -> new ByteArrayOutputStream());
static {
try {
InputStream is = ClientsWriteUTF8Bytes.class.getClassLoader().getResourceAsStream("data/jjb/client.json");
String str = IOUtils.toString(is, "UTF-8");
clients = JSONReader.of(str)
.read(Clients.class);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.toJSONBytes(clients));
}
public void jsonb(Blackhole bh) {
bh.consume(JSONB.toBytes(clients));
}
public void jsonb_beanToArray(Blackhole bh) {
bh.consume(JSONB.toBytes(clients, JSONWriter.Feature.BeanToArray, JSONWriter.Feature.FieldBased));
}
public void fastjson2_str(Blackhole bh) {
bh.consume(JSON.toJSONString(clients));
}
@Benchmark
public void dsljson(Blackhole bh) throws IOException {
ByteArrayOutputStream bytesOut = bytesOutLocal.get();
bytesOut.reset();
dslJson.serialize(clients, bytesOut);
byte[] bytes = bytesOut.toByteArray();
bh.consume(bytes);
}
// @Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsBytes(clients));
}
// @Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(gson
.toJson(clients)
.getBytes(StandardCharsets.UTF_8)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(ClientsWriteUTF8Bytes.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(2)
.threads(16)
.build();
new Runner(options).run();
| 598
| 97
| 695
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/JJBBenchmark.java
|
JJBBenchmark
|
main
|
class JJBBenchmark {
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(UsersWriteUTF8Bytes.class.getName())
.include(UsersParseUTF8Bytes.class.getName())
.include(ClientsWriteUTF8Bytes.class.getName())
.include(ClientsParseUTF8Bytes.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(2)
.threads(16)
.build();
new Runner(options).run();
| 39
| 144
| 183
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/UsersParseUTF8Bytes.java
|
UsersParseUTF8Bytes
|
gson
|
class UsersParseUTF8Bytes {
static byte[] utf8Bytes;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader());
static {
try {
InputStream is = UsersParseUTF8Bytes.class.getClassLoader().getResourceAsStream("data/jjb/user.json");
utf8Bytes = IOUtils.toString(is, "UTF-8").getBytes(StandardCharsets.UTF_8);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(utf8Bytes, Users.class));
// zulu17.40.19 : 3515
// zulu17.40.19_vec : 338
}
@Benchmark
public void dsljson(Blackhole bh) throws IOException {
bh.consume(dslJson.deserialize(Users.class, utf8Bytes, utf8Bytes.length));
// zulu17.40.19 : 3560
}
// @Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(utf8Bytes, Users.class));
}
// @Benchmark
public void gson(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(UsersParseUTF8Bytes.class.getName())
.exclude(EishayParseUTF8BytesPretty.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(2)
.threads(16)
.build();
new Runner(options).run();
}
}
|
bh.consume(gson
.fromJson(
new String(utf8Bytes, 0, utf8Bytes.length, StandardCharsets.UTF_8),
Users.class)
);
| 542
| 54
| 596
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jjb/UsersWriteUTF8Bytes.java
|
UsersWriteUTF8Bytes
|
main
|
class UsersWriteUTF8Bytes {
static Users users;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static final DslJson<Object> dslJson = new DslJson<>(Settings.withRuntime().includeServiceLoader());
static final ThreadLocal<ByteArrayOutputStream> bytesOutLocal = ThreadLocal.withInitial(() -> new ByteArrayOutputStream());
static {
try {
InputStream is = UsersWriteUTF8Bytes.class.getClassLoader().getResourceAsStream("data/jjb/user.json");
String str = IOUtils.toString(is, "UTF-8");
users = JSONReader.of(str)
.read(Users.class);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.toJSONBytes(users));
}
@Benchmark
public void fastjson2_str(Blackhole bh) {
bh.consume(JSON.toJSONString(users));
}
public void jsonb(Blackhole bh) {
bh.consume(JSONB.toBytes(users));
}
public void jsonb_beanToArray(Blackhole bh) {
bh.consume(JSONB.toBytes(users, JSONWriter.Feature.BeanToArray, JSONWriter.Feature.FieldBased));
}
@Benchmark
public void dsljson(Blackhole bh) throws IOException {
ByteArrayOutputStream bytesOut = bytesOutLocal.get();
bytesOut.reset();
dslJson.serialize(users, bytesOut);
byte[] bytes = bytesOut.toByteArray();
bh.consume(bytes);
}
// @Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsBytes(users));
}
// @Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(gson
.toJson(users)
.getBytes(StandardCharsets.UTF_8)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(UsersWriteUTF8Bytes.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(2)
.threads(16)
.build();
new Runner(options).run();
| 590
| 95
| 685
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jsonpath/BookStore.java
|
BookStore
|
main
|
class BookStore {
private static String str;
static {
try {
InputStream is = BookStore.class.getClassLoader().getResourceAsStream("data/bookstore.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSONPath.extract(str, "$.store.book[*].author")
);
}
@Benchmark
public void jayway(Blackhole bh) {
bh.consume(
JsonPath.read(str, "$.store.book[*].author")
);
}
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(BookStore.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
| 226
| 72
| 298
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jsonpath/JSONPathMultiBenchmark.java
|
JSONPathMultiBenchmark
|
evalMulti
|
class JSONPathMultiBenchmark {
private static String str;
static JSONPath jsonPath;
static JSONPath path0;
static JSONPath path1;
static {
try {
InputStream is = BookStore.class.getClassLoader().getResourceAsStream("data/path_02.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
jsonPath = JSONPath.of(
new String[] {"$.store.bicycle.color", "$.store.bicycle.price"},
new Type[] {String.class, BigDecimal.class}
);
path0 = JSONPath.of("$.store.bicycle.color");
path1 = JSONPath.of("$.store.bicycle.price");
}
@Benchmark
public void extract(Blackhole bh) throws Exception {
bh.consume(
jsonPath.extract(str)
);
}
@Benchmark
public void eval(Blackhole bh) throws Exception {
JSONObject object = JSON.parseObject(str);
bh.consume(
jsonPath.eval(object)
);
}
@Benchmark
public void evalMulti(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(JSONPathMultiBenchmark.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
}
}
|
JSONObject object = JSON.parseObject(str);
Object[] values = new Object[2];
values[0] = TypeUtils.cast(path0.eval(object), String.class);
values[1] = TypeUtils.cast(path1.eval(object), BigDecimal.class);
bh.consume(values);
| 460
| 85
| 545
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jsonpath/JSONPathMultiBenchmark2.java
|
JSONPathMultiBenchmark2
|
evalMulti
|
class JSONPathMultiBenchmark2 {
private static String str;
static String[] paths = {
"$.media.bitrate",
"$.media.duration",
"$.media.format",
"$.media.height",
"$.media.persons",
"$.media.player",
"$.media.size",
"$.media.title",
"$.media.uri",
"$.media.width"
};
static Type[] types = {
Integer.class,
Long.class,
String.class,
Integer.class,
String[].class,
String.class,
Long.class,
String.class,
String.class,
Long.class
};
static JSONPath jsonPathMulti = JSONPath.of(
paths,
types
);
static List<JSONPath> jsonPaths = Arrays.stream(paths)
.map(JSONPath::of)
.collect(Collectors.toList());
static {
try {
InputStream is = BookStore.class.getClassLoader().getResourceAsStream("data/eishay.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void extract(Blackhole bh) throws Exception {
bh.consume(
jsonPathMulti.extract(str)
);
}
@Benchmark
public void eval(Blackhole bh) throws Exception {
JSONObject object = JSON.parseObject(str);
bh.consume(
jsonPathMulti.eval(object)
);
}
@Benchmark
public void evalMulti(Blackhole bh) throws Exception {<FILL_FUNCTION_BODY>}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(JSONPathMultiBenchmark2.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
}
}
|
JSONObject object = JSON.parseObject(str);
Object[] values = new Object[jsonPaths.size()];
for (int i = 0; i < values.length; i++) {
JSONPath jsonPath = jsonPaths.get(i);
Object evalResult = jsonPath.eval(object);
values[i] = TypeUtils.cast(evalResult, types[i]);
}
bh.consume(values);
| 580
| 112
| 692
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/jsonschema/JSONSchemaBenchmark2.java
|
BenchmarkState
|
everit
|
class BenchmarkState {
// everit
private Schema jsonSchemaEverit;
private org.json.JSONObject schemasEverit;
private List<String> schemaNames;
// fastjson
private JSONSchema jsonSchemaFastjson2;
private JSONObject schemasFastjson2;
private JsonSchema jsonSchemaNetworknt;
private JsonNode schemasNetworknt;
public BenchmarkState() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
{
org.json.JSONObject root = new org.json.JSONObject(new org.json.JSONTokener(classLoader.getResourceAsStream("schema/perftest.json")));
org.json.JSONObject schemaObject = new org.json.JSONObject(new org.json.JSONTokener(classLoader.getResourceAsStream("schema/schema-draft4.json")));
jsonSchemaEverit = SchemaLoader.load(schemaObject);
schemasEverit = root.getJSONObject("schemas");
schemaNames = Arrays.asList(org.json.JSONObject.getNames(schemasEverit));
}
{
JSONObject root = JSON.parseObject(classLoader.getResource("schema/perftest.json"));
JSONObject schemaObject = JSON.parseObject(classLoader.getResource("schema/schema-draft4.json"));
jsonSchemaFastjson2 = JSONSchema.of(schemaObject);
schemasFastjson2 = root.getJSONObject("schemas");
}
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonSchemaFactory factory = JsonSchemaFactory.getInstance();
ObjectReader reader = objectMapper.reader();
JsonNode schemaNode = reader.readTree(classLoader.getResourceAsStream("schema/schema-draft4.json"));
jsonSchemaNetworknt = factory.getSchema(schemaNode);
JsonNode root = reader.readTree(classLoader.getResourceAsStream("schema/perftest.json"));
schemasNetworknt = root.get("schemas");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
@Benchmark
public void everit(BenchmarkState state) {<FILL_FUNCTION_BODY>
|
for (String name : state.schemaNames) {
org.json.JSONObject json = (org.json.JSONObject) state.schemasEverit.get(name);
state.jsonSchemaEverit.validate(json);
}
| 559
| 62
| 621
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/BigDecimal20.java
|
BigDecimal20
|
kryo
|
class BigDecimal20 {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
static Gson gson = new Gson();
static Kryo kryo;
static byte[] kryoBytes;
static byte[] hessianBytes;
// static io.fury.ThreadSafeFury furyCompatible = io.fury.Fury.builder()
// .withLanguage(io.fury.Language.JAVA)
// .withReferenceTracking(true)
// .disableSecureMode()
// .withCompatibleMode(io.fury.serializers.CompatibleMode.COMPATIBLE)
// .buildThreadSafeFury();
// static byte[] furyCompatibleBytes;
public BigDecimal20() {
try {
InputStream is = BigDecimal20.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
BigDecimal20Field bean = JSON.parseObject(str, BigDecimal20Field.class);
jsonbBytes = JSONB.toBytes(bean);
kryo = new Kryo();
kryo.register(BigDecimal20Field.class);
kryo.register(BigDecimal.class);
Output output = new Output(1024, -1);
kryo.writeObject(output, bean);
kryoBytes = output.toBytes();
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Hessian2Output hessian2Output = new Hessian2Output(byteArrayOutputStream);
hessian2Output.writeObject(bean);
hessian2Output.flush();
hessianBytes = byteArrayOutputStream.toByteArray();
}
// furyCompatibleBytes = furyCompatible.serialize(bean);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, BigDecimal20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, BigDecimal20Field.class)
);
}
@Benchmark
public void jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, BigDecimal20Field.class)
);
}
@Benchmark
public void kryo(Blackhole bh) {<FILL_FUNCTION_BODY>}
@Benchmark
public void hessian(Blackhole bh) throws Exception {
ByteArrayInputStream bytesIn = new ByteArrayInputStream(hessianBytes);
Hessian2Input hessian2Input = new Hessian2Input(bytesIn);
bh.consume(hessian2Input.readObject());
}
// @Benchmark
public void fury(Blackhole bh) {
// Object object = furyCompatible.deserialize(furyCompatibleBytes);
// bh.consume(object);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, BigDecimal20Field.class)
);
}
@Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(
gson.fromJson(str, BigDecimal20Field.class)
);
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, BigDecimal20Field.class)
);
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(BigDecimal20.class.getName())
.exclude(BigDecimal20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
}
}
|
Input input = new Input(kryoBytes);
BigDecimal20Field object = kryo.readObject(input, BigDecimal20Field.class);
bh.consume(object);
| 1,149
| 54
| 1,203
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/BigDecimal20Tree.java
|
BigDecimal20Tree
|
main
|
class BigDecimal20Tree {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public BigDecimal20Tree() {
try {
InputStream is = BigDecimal20Tree.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, Map.class)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, Map.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Map.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(BigDecimal20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 391
| 87
| 478
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/BigInteger20.java
|
BigInteger20
|
main
|
class BigInteger20 {
static BigInteger20Field bean;
static ObjectMapper mapper = new ObjectMapper();
static Gson gson = new Gson();
public BigInteger20() {
try {
InputStream is = BigInteger20.class.getClassLoader().getResourceAsStream("data/bigint20.json");
String str = IOUtils.toString(is, "UTF-8");
bean = JSON.parseObject(str, BigInteger20Field.class);
// furyCompatibleBytes = furyCompatible.serialize(bean);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.toJSONString(bean)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.toJSONString(bean)
);
}
public void fastjson2_array_bytes(Blackhole bh) {
bh.consume(
JSON.toJSONBytes(bean, JSONWriter.Feature.BeanToArray)
);
}
@Benchmark
public void jsonb(Blackhole bh) {
bh.consume(
JSONB.toBytes(bean)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.writeValueAsString(bean)
);
}
@Benchmark
public void gson(Blackhole bh) throws Exception {
bh.consume(
gson.toJson(bean)
);
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.toJsonString(bean)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(BigInteger20.class.getName())
.exclude(BigDecimal20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 546
| 102
| 648
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Date20.java
|
Date20
|
main
|
class Date20 {
static String str;
static byte[] jsonbBytes;
static String str_millis;
static ObjectMapper mapper = new ObjectMapper();
public Date20() {
try {
InputStream is = Date20.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
try {
InputStream is = Date20.class.getClassLoader().getResourceAsStream("data/millis20.json");
str_millis = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, Date20Field.class)
);
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, Date20Field.class)
);
}
@Benchmark
public void fastjson1_millis(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str_millis, Date20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Date20Field.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, Date20Field.class)
);
}
@Benchmark
public void fastjson2_millis(Blackhole bh) {
bh.consume(
JSON.parseObject(str_millis, Date20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Date20Field.class)
);
}
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, Date20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Date20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 664
| 84
| 748
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Date20TreeWrite.java
|
Date20TreeWrite
|
main
|
class Date20TreeWrite {
static String str;
static List array;
static ObjectMapper mapper = new ObjectMapper();
public Date20TreeWrite() {
try {
InputStream is = Date20TreeWrite.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
Date20Field object = JSON.parseObject(str, Date20Field.class);
array = JSONArray.of(
object.v0000, object.v0001, object.v0002, object.v0003, object.v0004,
object.v0005, object.v0006, object.v0007, object.v0008, object.v0009,
object.v0010, object.v0011, object.v0012, object.v0013, object.v0014,
object.v0015, object.v0016, object.v0017, object.v0018, object.v0019
);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.toJSONString(array)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.toJSONString(array)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.toBytes(array)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.writeValueAsString(array)
);
}
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.toJsonString(array)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Date20TreeWrite.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 625
| 86
| 711
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Date20Write.java
|
Date20Write
|
main
|
class Date20Write {
static String str;
static Date20Field object;
static ObjectMapper mapper = new ObjectMapper();
public Date20Write() {
try {
InputStream is = Date20Write.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
object = JSON.parseObject(str, Date20Field.class);
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.toJSONString(object)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.toJSONString(object)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.toBytes(object)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.writeValueAsString(object)
);
}
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.toJsonString(object)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Date20Write.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 442
| 85
| 527
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Double20Tree.java
|
Double20Tree
|
main
|
class Double20Tree {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public Double20Tree() {
try {
InputStream is = Double20Tree.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Map.class, JSONReader.Feature.UseBigDecimalForDoubles)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Map.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Double20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 251
| 85
| 336
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/DoubleValue20.java
|
DoubleValue20
|
main
|
class DoubleValue20 {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
static final Class<DoubleValue20Field> OBJECT_CLASS = DoubleValue20Field.class;
public DoubleValue20() {
try {
InputStream is = DoubleValue20.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, OBJECT_CLASS)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, OBJECT_CLASS)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, OBJECT_CLASS)
);
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, OBJECT_CLASS)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(DoubleValue20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 486
| 85
| 571
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/DoubleValue20L.java
|
DoubleValue20L
|
main
|
class DoubleValue20L {
static final String str = "{\"v0000\":0.7790456752571444,\"v0001\":0.660951133487578,\"v0002\":0.016859966762709178,\"v0003\":0.08792646995171371,\"v0004\":0.5004314371646074,\"v0005\":0.40819072662809397,\"v0006\":0.467977801426522,\"v0007\":0.5157402268914001,\"v0008\":0.02573911575880017,\"v0009\":0.3954472301618003,\"v0010\":0.8488319941451605,\"v0011\":0.16331853548023045,\"v0012\":0.15614021653886967,\"v0013\":0.13241092483919703,\"v0014\":0.5292598224995992,\"v0015\":0.5025147692434769,\"v0016\":0.042355711968873444,\"v0017\":0.3480302380487452,\"v0018\":0.5439821627623341,\"v0019\":0.8083989078490904}";
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
static final Class<DoubleValue20Field> OBJECT_CLASS = DoubleValue20Field.class;
public DoubleValue20L() {
try {
Random r = new Random();
DoubleValue20Field bean = JSON.parseObject(str, OBJECT_CLASS);
jsonbBytes = JSONB.toBytes(bean);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, OBJECT_CLASS)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, OBJECT_CLASS)
);
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, OBJECT_CLASS)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(DoubleValue20L.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 1,008
| 86
| 1,094
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Float20Tree.java
|
Float20Tree
|
main
|
class Float20Tree {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public Float20Tree() {
try {
InputStream is = Float20Tree.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Map.class, JSONReader.Feature.UseBigDecimalForFloats)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Map.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Float20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 253
| 85
| 338
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/FloatValue20.java
|
FloatValue20
|
main
|
class FloatValue20 {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public FloatValue20() {
try {
InputStream is = FloatValue20.class.getClassLoader().getResourceAsStream("data/dec20.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, FloatValue20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, FloatValue20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, FloatValue20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(FloatValue20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 312
| 85
| 397
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Instant20.java
|
Instant20
|
main
|
class Instant20 {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public Instant20() {
try {
InputStream is = Instant20.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, Instant20Field.class)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, Instant20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Instant20Field.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, Instant20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Instant20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Instant20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 406
| 85
| 491
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/Int20Tree.java
|
Int20Tree
|
main
|
class Int20Tree {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public Int20Tree() {
try {
InputStream is = Int20Tree.class.getClassLoader().getResourceAsStream("data/Int20.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Map.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(Int20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 355
| 85
| 440
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/IntValue20.java
|
IntValue20
|
main
|
class IntValue20 {
static final Class OBJECT_CLASS = Int20Field.class;
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public IntValue20() {
try {
InputStream is = IntValue20.class.getClassLoader().getResourceAsStream("data/Int20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, OBJECT_CLASS)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, OBJECT_CLASS)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, OBJECT_CLASS)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(OBJECT_CLASS.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 476
| 83
| 559
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/LocalDate20.java
|
LocalDate20
|
main
|
class LocalDate20 {
static String str = "{\n" +
" \"v0000\" : \"2001-07-01\",\n" +
" \"v0001\" : \"2011-06-02\",\n" +
" \"v0002\" : \"2021-11-03\",\n" +
" \"v0003\" : \"2001-11-14\",\n" +
" \"v0004\" : \"2002-10-07\",\n" +
" \"v0005\" : \"2003-09-12\",\n" +
" \"v0006\" : \"2006-08-16\",\n" +
" \"v0007\" : \"2002-01-30\",\n" +
" \"v0008\" : \"2009-02-27\",\n" +
" \"v0009\" : \"2011-04-26\",\n" +
" \"v0010\" : \"2012-06-23\",\n" +
" \"v0011\" : \"2022-02-18\",\n" +
" \"v0012\" : \"2021-08-17\",\n" +
" \"v0013\" : \"2021-01-17\",\n" +
" \"v0014\" : \"2020-03-14\",\n" +
" \"v0015\" : \"2019-02-14\",\n" +
" \"v0016\" : \"2018-12-14\",\n" +
" \"v0017\" : \"2007-10-14\",\n" +
" \"v0018\" : \"2008-02-14\",\n" +
" \"v0019\" : \"2011-03-14\"\n" +
"}\n";
static ObjectMapper mapper = new ObjectMapper();
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, LocalDate20Field.class, "yyyy-MM-dd")
);
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, LocalDateTime20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, LocalDate20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(LocalDate20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 822
| 85
| 907
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/LocalDateBench.java
|
LocalDateBench
|
utf16
|
class LocalDateBench {
private static final LocalDate VALUE = LocalDate.of(2024, 2, 20);
public void utf8(Blackhole BH) {
JSONWriter jsonWriter = JSONWriter.ofUTF8();
jsonWriter.startArray();
for (int i = 0; i < 1000; i++) {
if (i != 0) {
jsonWriter.writeComma();
}
jsonWriter.writeLocalDate(VALUE);
}
jsonWriter.endArray();
BH.consume(jsonWriter.getBytes());
jsonWriter.close();
}
public void utf16(Blackhole BH) {<FILL_FUNCTION_BODY>}
}
|
JSONWriter jsonWriter = JSONWriter.ofUTF16();
jsonWriter.startArray();
for (int i = 0; i < 1000; i++) {
if (i != 0) {
jsonWriter.writeComma();
}
jsonWriter.writeLocalDate(VALUE);
}
jsonWriter.endArray();
BH.consume(jsonWriter.toString());
jsonWriter.close();
| 189
| 112
| 301
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/LocalDateTime20.java
|
LocalDateTime20
|
main
|
class LocalDateTime20 {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public LocalDateTime20() {
try {
InputStream is = LocalDateTime20.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, LocalDateTime20Field.class)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, LocalDateTime20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, LocalDateTime20Field.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, LocalDateTime20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, LocalDateTime20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(LocalDateTime20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 406
| 85
| 491
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/OffsetDateTime20.java
|
OffsetDateTime20
|
main
|
class OffsetDateTime20 {
static ObjectMapper mapper = new ObjectMapper();
static OffsetDateTime20Field object = new OffsetDateTime20Field();
public OffsetDateTime20() {
try {
InputStream is = OffsetDateTime20.class.getClassLoader().getResourceAsStream("data/date20.json");
String str = IOUtils.toString(is, "UTF-8");
object = JSON.parseObject(str, OffsetDateTime20Field.class);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
String str = JSON.toJSONString(object);
bh.consume(
JSON.parseObject(str, OffsetDateTime20Field.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
byte[] jsonbBytes = JSONB.toBytes(object);
bh.consume(
JSONB.parseObject(jsonbBytes, OffsetDateTime20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
String str = mapper.writeValueAsString(object);
bh.consume(
mapper.readValue(str, OffsetDateTime20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(OffsetDateTime20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 387
| 85
| 472
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/ShortBench.java
|
ShortBench
|
bean_jsonBytes
|
class ShortBench {
private static final short[] VALUES;
static {
short[] shorts = new short[Short.MAX_VALUE - Short.MIN_VALUE];
for (int i = 0; i < shorts.length; i++) {
shorts[i] = (short) (Short.MIN_VALUE + i);
}
VALUES = shorts;
}
public void utf8(Blackhole BH) {
JSONWriter jsonWriter = JSONWriter.ofUTF8();
jsonWriter.writeAny(VALUES);
BH.consume(jsonWriter.getBytes());
jsonWriter.close();
}
public void utf16(Blackhole BH) {
JSONWriter jsonWriter = JSONWriter.ofUTF16();
jsonWriter.writeAny(VALUES);
BH.consume(jsonWriter.getBytes());
jsonWriter.close();
}
public void bean_jsonBytes(Blackhole BH) {<FILL_FUNCTION_BODY>}
public void bean_jsonStr(Blackhole BH) {
for (int i = 0; i + 10 <= VALUES.length; i += 10) {
Bean bean = new Bean();
bean.v0 = VALUES[i];
bean.v1 = VALUES[i + 1];
bean.v2 = VALUES[i + 2];
bean.v3 = VALUES[i + 3];
bean.v4 = VALUES[i + 4];
bean.v5 = VALUES[i + 5];
bean.v6 = VALUES[i + 6];
bean.v7 = VALUES[i + 7];
bean.v8 = VALUES[i + 8];
bean.v9 = VALUES[i + 9];
String jsonStr = JSON.toJSONString(bean);
BH.consume(jsonStr);
}
}
public void bean_jsonb(Blackhole BH) {
for (int i = 0; i + 10 <= VALUES.length; i += 10) {
Bean bean = new Bean();
bean.v0 = VALUES[i];
bean.v1 = VALUES[i + 1];
bean.v2 = VALUES[i + 2];
bean.v3 = VALUES[i + 3];
bean.v4 = VALUES[i + 4];
bean.v5 = VALUES[i + 5];
bean.v6 = VALUES[i + 6];
bean.v7 = VALUES[i + 7];
bean.v8 = VALUES[i + 8];
bean.v9 = VALUES[i + 9];
byte[] bytes = JSONB.toBytes(bean);
BH.consume(bytes);
}
}
public static class Bean {
public short v0;
public short v1;
public short v2;
public short v3;
public short v4;
public short v5;
public short v6;
public short v7;
public short v8;
public short v9;
}
}
|
for (int i = 0; i + 10 <= VALUES.length; i += 10) {
Bean bean = new Bean();
bean.v0 = VALUES[i];
bean.v1 = VALUES[i + 1];
bean.v2 = VALUES[i + 2];
bean.v3 = VALUES[i + 3];
bean.v4 = VALUES[i + 4];
bean.v5 = VALUES[i + 5];
bean.v6 = VALUES[i + 6];
bean.v7 = VALUES[i + 7];
bean.v8 = VALUES[i + 8];
bean.v9 = VALUES[i + 9];
byte[] bytes = JSON.toJSONBytes(bean);
BH.consume(bytes);
}
| 752
| 192
| 944
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/String20.java
|
String20
|
main
|
class String20 {
static final Class OBJECT_CLASS = com.alibaba.fastjson2.benchmark.primitves.vo.String20.class;
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public String20() {
try {
InputStream is = String20.class.getClassLoader().getResourceAsStream("data/String20_compact.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, OBJECT_CLASS)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(
io.github.wycst.wast.json.JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, OBJECT_CLASS)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, OBJECT_CLASS)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, OBJECT_CLASS)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(String20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 493
| 84
| 577
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/String20Tree.java
|
String20Tree
|
main
|
class String20Tree {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public String20Tree() {
try {
InputStream is = String20Tree.class.getClassLoader().getResourceAsStream("data/String20_compact.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, Map.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, Map.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(String20Tree.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 296
| 85
| 381
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/StringField20.java
|
StringField20
|
fastjson1_perf_test
|
class StringField20 {
static String str;
static ObjectMapper mapper = new ObjectMapper();
public StringField20() {
try {
InputStream is = StringField20.class.getClassLoader().getResourceAsStream("data/String20_compact.json");
str = IOUtils.toString(is, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public com.alibaba.fastjson2.benchmark.primitves.vo.StringField20 fastjson1() {
return com.alibaba.fastjson.JSON.parseObject(str, com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class);
}
@Benchmark
public com.alibaba.fastjson2.benchmark.primitves.vo.StringField20 fastjson2() {
return JSON.parseObject(str, com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class);
}
@Benchmark
public com.alibaba.fastjson2.benchmark.primitves.vo.StringField20 jackson() throws Exception {
return mapper.readValue(str, com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class);
}
// @Test
public void fastjson2_perf_test() {
for (int i = 0; i < 10; i++) {
fastjson2_perf();
}
}
public static void fastjson2_perf() {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
JSON.parseObject(str, com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class);
}
long millis = System.currentTimeMillis() - start;
System.out.println(com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class.getSimpleName() + " : " + millis);
// zulu17.32.13 : 418
// zulu11.52.13 :
// zulu8.58.0.13 : 598
}
// @Test
public void fastjson1_perf_test() {<FILL_FUNCTION_BODY>}
public static void fastjson1_perf() {
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000; ++i) {
com.alibaba.fastjson.JSON.parseObject(str, com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class);
}
long millis = System.currentTimeMillis() - start;
System.out.println(com.alibaba.fastjson2.benchmark.primitves.vo.StringField20.class.getSimpleName() + " : " + millis);
// zulu17.32.13 : 365
// zulu11.52.13 :
// zulu8.58.0.13 : 605
}
public static void main(String[] args) throws RunnerException {
Options options = new OptionsBuilder()
.include(StringField20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
}
}
|
for (int i = 0; i < 10; i++) {
fastjson1_perf();
}
| 953
| 33
| 986
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/primitves/ZonedDateTime20.java
|
ZonedDateTime20
|
main
|
class ZonedDateTime20 {
static String str;
static byte[] jsonbBytes;
static ObjectMapper mapper = new ObjectMapper();
public ZonedDateTime20() {
try {
InputStream is = ZonedDateTime20.class.getClassLoader().getResourceAsStream("data/date20.json");
str = IOUtils.toString(is, "UTF-8");
jsonbBytes = JSONB.toBytes(
JSON.parseObject(str, ZonedDateTime20Field.class)
);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(
com.alibaba.fastjson.JSON.parseObject(str, ZonedDateTime20Field.class)
);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.parseObject(str, ZonedDateTime20Field.class)
);
}
@Benchmark
public void fastjson2_jsonb(Blackhole bh) {
bh.consume(
JSONB.parseObject(jsonbBytes, ZonedDateTime20Field.class)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.readValue(str, ZonedDateTime20Field.class)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(ZonedDateTime20.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 413
| 86
| 499
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/protobuf/MediaContentTransform.java
|
MediaContentTransform
|
forwardSize
|
class MediaContentTransform {
public static MediaContent reverse(MediaContentHolder.MediaContent mc) {
List<Image> images = new ArrayList<Image>(mc.getImageCount());
for (MediaContentHolder.Image image : mc.getImageList()) {
images.add(reverseImage(image));
}
return new MediaContent(reverseMedia(mc.getMedia()), images);
}
public static Media reverseMedia(MediaContentHolder.Media media) {
return new Media(
media.getUri(),
media.hasTitle() ? media.getTitle() : null,
media.getWidth(),
media.getHeight(),
media.getFormat(),
media.getDuration(),
media.getSize(),
media.hasBitrate() ? media.getBitrate() : 0,
new ArrayList<String>(media.getPersonList()),
reversePlayer(media.getPlayer()),
media.hasCopyright() ? media.getCopyright() : null
);
}
public static Image reverseImage(MediaContentHolder.Image image)
{
return new Image(
image.getUri(),
image.getTitle(),
image.getWidth(),
image.getHeight(),
reverseSize(image.getSize()));
}
public static Image.Size reverseSize(MediaContentHolder.Image.Size s)
{
switch (s) {
case SMALL: return Image.Size.SMALL;
case LARGE: return Image.Size.LARGE;
default:
throw new AssertionError("invalid case: " + s);
}
}
public static Media.Player reversePlayer(MediaContentHolder.Media.Player p) {
switch (p) {
case JAVA:
return Media.Player.JAVA;
case FLASH:
return Media.Player.FLASH;
default:
throw new AssertionError("invalid case: " + p);
}
}
public static MediaContentHolder.MediaContent forward(MediaContent mc) {
MediaContentHolder.MediaContent.Builder cb = MediaContentHolder.MediaContent.newBuilder();
cb.setMedia(forwardMedia(mc.getMedia()));
for (Image image : mc.getImages()) {
cb.addImage(forwardImage(image));
}
return cb.build();
}
public static MediaContentHolder.Media forwardMedia(Media media) {
MediaContentHolder.Media.Builder mb = MediaContentHolder.Media.newBuilder();
mb.setUri(media.getUri());
String title = media.getTitle();
if (title != null) {
mb.setTitle(title);
}
mb.setWidth(media.getWidth());
mb.setHeight(media.getHeight());
mb.setFormat(media.getFormat());
mb.setDuration(media.getDuration());
mb.setSize(media.getSize());
mb.setBitrate(media.getBitrate());
for (String person : media.getPersons()) {
mb.addPerson(person);
}
mb.setPlayer(forwardPlayer(media.getPlayer()));
String copyright = media.getCopyright();
if (copyright != null) {
mb.setCopyright(copyright);
}
return mb.build();
}
public static MediaContentHolder.Media.Player forwardPlayer(Media.Player p) {
switch (p) {
case JAVA:
return MediaContentHolder.Media.Player.JAVA;
case FLASH:
return MediaContentHolder.Media.Player.FLASH;
default:
throw new AssertionError("invalid case: " + p);
}
}
public static MediaContentHolder.Image forwardImage(Image image) {
MediaContentHolder.Image.Builder ib = MediaContentHolder.Image.newBuilder();
ib.setUri(image.getUri());
String title = image.getTitle();
if (title != null) {
ib.setTitle(title);
}
ib.setWidth(image.getWidth());
ib.setHeight(image.getHeight());
ib.setSize(forwardSize(image.getSize()));
return ib.build();
}
public static MediaContentHolder.Image.Size forwardSize(Image.Size s) {<FILL_FUNCTION_BODY>}
}
|
switch (s) {
case SMALL:
return MediaContentHolder.Image.Size.SMALL;
case LARGE:
return MediaContentHolder.Image.Size.LARGE;
default:
throw new AssertionError("invalid case: " + s);
}
| 1,100
| 73
| 1,173
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/schema/JSONSchemaBenchmark1.java
|
JSONSchemaBenchmark1
|
format_perf
|
class JSONSchemaBenchmark1 {
static final JSONSchema SCHEMA_UUID = JSONObject.of("type", "string", "format", "uuid").to(JSONSchema::of);
static final JSONSchema SCHEMA_DATETIME = JSONObject.of("type", "string", "format", "date-time").to(JSONSchema::of);
static final JSONSchema SCHEMA_DATE = JSONObject.of("type", "string", "format", "date").to(JSONSchema::of);
static final JSONSchema SCHEMA_TIME = JSONObject.of("type", "string", "format", "time").to(JSONSchema::of);
static final JSONSchema SCHEMA_NUMBER = JSONObject.of("type", "number", "minimum", 10).to(JSONSchema::of);
static final JSONSchema SCHEMA_INTEGER = JSONObject.of("type", "integer", "minimum", 10).to(JSONSchema::of);
@Benchmark
public void format_uuid(Blackhole bh) {
bh.consume(
SCHEMA_UUID.isValid("a7f41390-39a9-4ca6-a13b-88cf07a41108")
);
}
@Benchmark
public void format_datetime(Blackhole bh) {
bh.consume(
SCHEMA_DATETIME.isValid("2017-07-21 12:13:14")
);
}
@Benchmark
public void format_date(Blackhole bh) {
bh.consume(
SCHEMA_DATE.isValid("2017-07-21")
);
}
@Benchmark
public void format_time(Blackhole bh) {
bh.consume(
SCHEMA_TIME.isValid("12:13:14")
);
}
public static void format_perf() {<FILL_FUNCTION_BODY>}
public static void format_perf_test() {
for (int i = 0; i < 10; i++) {
format_perf();
}
}
public static void main(String[] args) throws RunnerException {
format_perf_test();
//
// Options options = new OptionsBuilder()
// .include(JSONSchemaBenchmark.class.getName())
// .mode(Mode.Throughput)
// .timeUnit(TimeUnit.MILLISECONDS)
// .forks(1)
// .build();
// new Runner(options).run();
}
}
|
long start = System.currentTimeMillis();
for (int i = 0; i < 1000 * 1000 * 100; ++i) {
// SCHEMA_UUID.isValid("a7f41390-39a9-4ca6-a13b-88cf07a41108");
// SCHEMA_DATETIME.isValid("2017-07-21 12:13:14"); // 123
// SCHEMA_DATE.isValid("2017-07-21"); // 48
// SCHEMA_TIME.isValid("12:13:14"); //
// SCHEMA_NUMBER.isValid(9); // 42
// SCHEMA_NUMBER.isValid(11); // 302 120
// SCHEMA_NUMBER.isValid(11D); //
SCHEMA_NUMBER.isValid(9D); //
// SCHEMA_INTEGER.isValid(9); // 87
// SCHEMA_INTEGER.isValid(11); //
}
long millis = System.currentTimeMillis() - start;
System.out.println("millis : " + millis);
// zulu17.32.13 :
// zulu11.52.13 :
// zulu8.58.0.13 :
| 672
| 376
| 1,048
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/sonic/EishayTest.java
|
EishayTest
|
main
|
class EishayTest {
public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>}
public static class MediaContent
implements java.io.Serializable {
public Media media;
public List<Image> images;
public MediaContent() {
}
public void setMedia(Media media) {
this.media = media;
}
public void setImages(List<Image> images) {
this.images = images;
}
public Media getMedia() {
return media;
}
public List<Image> getImages() {
return images;
}
}
public enum Size {
SMALL, LARGE
}
public static class Image
implements java.io.Serializable {
private int height;
private Size size;
private String title;
private String uri;
private int width;
public Image() {
}
public void setUri(String uri) {
this.uri = uri;
}
public void setTitle(String title) {
this.title = title;
}
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public void setSize(Size size) {
this.size = size;
}
public String getUri() {
return uri;
}
public String getTitle() {
return title;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Size getSize() {
return size;
}
}
public enum Player {
JAVA, FLASH
}
public static class Media
implements java.io.Serializable {
private int bitrate; // Can be unset.
private long duration;
private String format;
private int height;
private List<String> persons;
private Player player;
private long size;
private String title;
private String uri;
private int width;
private String copyright;
public Media() {
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public int getBitrate() {
return bitrate;
}
public void setBitrate(int bitrate) {
this.bitrate = bitrate;
}
public List<String> getPersons() {
return persons;
}
public void setPersons(List<String> persons) {
this.persons = persons;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
}
}
|
String str = "{\"images\": [{\n" +
" \"height\":768,\n" +
" \"size\":\"LARGE\",\n" +
" \"title\":\"Javaone Keynote\",\n" +
" \"uri\":\"http://javaone.com/keynote_large.jpg\",\n" +
" \"width\":1024\n" +
" }, {\n" +
" \"height\":240,\n" +
" \"size\":\"SMALL\",\n" +
" \"title\":\"Javaone Keynote\",\n" +
" \"uri\":\"http://javaone.com/keynote_small.jpg\",\n" +
" \"width\":320\n" +
" }\n" +
" ],\n" +
" \"media\": {\n" +
" \"bitrate\":262144,\n" +
" \"duration\":18000000,\n" +
" \"format\":\"video/mpg4\",\n" +
" \"height\":480,\n" +
" \"persons\": [\n" +
" \"Bill Gates\",\n" +
" \"Steve Jobs\"\n" +
" ],\n" +
" \"player\":\"JAVA\",\n" +
" \"size\":58982400,\n" +
" \"title\":\"Javaone Keynote\",\n" +
" \"uri\":\"http://javaone.com/keynote.mpg\",\n" +
" \"width\":640\n" +
" }\n" +
"}";
System.out.println("JDKUtils_vector_bit_length : " + JDKUtils.VECTOR_BIT_LENGTH);
JSONReader reader = JSONReader.of(str);
reader.close();
System.out.println("reader class : " + reader.getClass().getName());
JSONWriter writer = JSONWriter.of();
writer.close();
System.out.println("writer class : " + writer.getClass().getName());
MediaContent mediaContent = JSON.parseObject(str, MediaContent.class);
int LOOP_COUNT = 1000000;
for (int j = 0; j < 5; ++j) {
long start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
JSON.toJSONString(mediaContent);
}
long millis = System.currentTimeMillis() - start;
System.out.println("fastjson2 eishay toJSONString time : " + millis);
}
for (int j = 0; j < 5; ++j) {
long start = System.currentTimeMillis();
for (int i = 0; i < LOOP_COUNT; i++) {
JSON.parseObject(str, MediaContent.class);
}
long millis = System.currentTimeMillis() - start;
System.out.println("fastjson2 eishay parseObject time : " + millis);
}
// write 325
// parse 599
// write_vec : 266
// parse_vec : 572
| 1,026
| 886
| 1,912
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/twitter/TwitterParseString.java
|
TwitterParseString
|
main
|
class TwitterParseString {
static String str;
static final ObjectMapper mapper = new ObjectMapper();
static final Gson gson = new Gson();
static {
try {
InputStream is = TwitterParseString.class.getClassLoader().getResourceAsStream("data/twitter.json");
str = IOUtils.toString(is, "UTF-8");
JSON.parseObject(str, Twitter.class);
} catch (Throwable ex) {
ex.printStackTrace();
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(str, Twitter.class));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(str, Twitter.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(TwitterParseString.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.threads(16)
.build();
new Runner(options).run();
| 246
| 94
| 340
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/utf8/UTF8Encode.java
|
CacheItem
|
encode
|
class CacheItem {
volatile char[] chars;
volatile byte[] bytes;
}
static final String STR_CN_SMALL = "規定了四種表";
static final String STR0 = "EEE 754規定了四種表示浮點數值的方式:單精確度(32位元)、雙精確度(64位元)、延伸單精確度(43位元以上,很少使用)與延伸雙精確度(79位元以上,通常以80位元實做)。只有32位元模式有強制要求,其他都是選擇性的。大部分程式語言都提供了IEEE浮点数格式與算術,但有些將其列為非必需的。例如,IEEE 754問世之前就有的C語言,現在包括了IEEE算術,但不算作強制要求(C語言的float通常是指IEEE單精確度,而double是指雙精確度)。";
static final String STR1 = "ISO/IEC 8859-1:1998, Information technology — 8-bit single-byte coded graphic character sets — Part 1: Latin alphabet No. 1, is part of the ISO/IEC 8859 series of ASCII-based standard character encodings, first edition published in 1987. ISO/IEC 8859-1 encodes what it refers to as \"Latin alphabet no. 1\", consisting of 191 characters from the Latin script. This character-encoding scheme is used throughout the Americas, Western Europe, Oceania, and much of Africa. It is the basis for some popular 8-bit character sets and the first two blocks of characters in Unicode.";
public void jdk(Blackhole bh) {
bh.consume(
STR0.getBytes(StandardCharsets.UTF_8)
);
}
public void jdk_small(Blackhole bh) {
bh.consume(
STR_CN_SMALL.getBytes(StandardCharsets.UTF_8)
);
}
public void fj(Blackhole bh) {
bh.consume(
encode(STR0)
);
}
public void fj_small(Blackhole bh) {
bh.consume(
encode(STR_CN_SMALL)
);
}
public void jdk_ascii(Blackhole bh) {
bh.consume(
STR1.getBytes(StandardCharsets.UTF_8)
);
}
public void fj_ascii(Blackhole bh) {
byte[] utf8 = encode(STR1);
bh.consume(utf8);
}
private static byte[] jdk8(String str) {
char[] chars = JDKUtils.getCharArray(str);
int cacheIndex = System.identityHashCode(Thread.currentThread()) & (CACHE_ITEMS.length - 1);
CacheItem cacheItem = CACHE_ITEMS[cacheIndex];
byte[] bytes = BYTES_UPDATER.getAndSet(cacheItem, null);
int bufferSize = chars.length * 3;
if (bytes == null || bytes.length < bufferSize) {
bytes = new byte[bufferSize];
}
int cnt = IOUtils.encodeUTF8(chars, 0, chars.length, bytes, 0);
byte[] utf8 = Arrays.copyOf(bytes, cnt);
BYTES_UPDATER.lazySet(cacheItem, bytes);
return utf8;
}
private static byte[] encode(String str) {<FILL_FUNCTION_BODY>
|
if (JDKUtils.JVM_VERSION <= 8 || JDKUtils.STRING_CODER == null) {
return jdk8(str);
}
int coder = JDKUtils.STRING_CODER.applyAsInt(str);
byte[] value = JDKUtils.STRING_VALUE.apply(str);
if (coder == 0) {
boolean hasNegative;
try {
hasNegative = (Boolean) JDKUtils.METHOD_HANDLE_HAS_NEGATIVE.invoke(value, 0, value.length);
} catch (Throwable e) {
throw new RuntimeException(e);
}
if (!hasNegative) {
return value;
}
return str.getBytes(StandardCharsets.UTF_8);
}
int cacheIndex = System.identityHashCode(Thread.currentThread()) & (CACHE_ITEMS.length - 1);
CacheItem cacheItem = CACHE_ITEMS[cacheIndex];
byte[] bytes = BYTES_UPDATER.getAndSet(cacheItem, null);
int bufferSize = str.length() * 3;
if (bytes == null || bytes.length < bufferSize) {
bytes = new byte[bufferSize];
}
int cnt = IOUtils.encodeUTF8(value, 0, value.length, bytes, 0);
byte[] utf8 = Arrays.copyOf(bytes, cnt);
BYTES_UPDATER.lazySet(cacheItem, bytes);
return utf8;
| 974
| 388
| 1,362
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/DateWriteCase.java
|
DateWriteCase
|
main
|
class DateWriteCase {
static DateBean2 object = new DateBean2();
static ObjectMapper mapper = new ObjectMapper();
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(
JSON.toJSONString(object)
);
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(
mapper.writeValueAsString(object)
);
}
@Benchmark
public void wastjson(Blackhole bh) throws Exception {
bh.consume(
io.github.wycst.wast.json.JSON.toJsonString(object)
);
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(DateWriteCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 215
| 84
| 299
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/EishayWriterCase.java
|
EishayWriterCase
|
main
|
class EishayWriterCase {
static String result = "{\"images\":[{\"height\":768,\"size\":\"LARGE\",\"title\":\"Javaone Keynote\",\"uri\":\"http://javaone.com/keynote_large.jpg\",\"width\":1024},{\"height\":240,\"size\":\"SMALL\",\"title\":\"Javaone Keynote\",\"uri\":\"http://javaone.com/keynote_small.jpg\",\"width\":320}],\"media\":{\"bitrate\":262144,\"duration\":18000000,\"format\":\"video/mpg4\",\"height\":480,\"persons\":[\"Bill Gates\",\"Steve Jobs\"],\"player\":\"JAVA\",\"size\":58982400,\"title\":\"Javaone Keynote\",\"uri\":\"http://javaone.com/keynote.mpg\",\"width\":640}}";
static Object object;
static {
object = JSON.parseObject(result);
}
static ObjectMapper mapper = new ObjectMapper();
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.toJSONString(object));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.toJsonString(object));
}
@Benchmark
public void jackson(Blackhole bh) throws IOException {
bh.consume(mapper.writeValueAsString(object));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(EishayWriterCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
| 485
| 75
| 560
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/Int32ValueBeanCase.java
|
Int32ValueBeanCase
|
main
|
class Int32ValueBeanCase {
static String result = "{\"a\":269072307,\"b\":-1518251888,\"c\":1718732377,\"d\":-680809737,\"e\":366417267,\"f\":-385913708,\"h\":-1059329988,\"i\":-1143820253,\"j\":1981317426,\"k\":141784471}";
static ObjectMapper mapper = new ObjectMapper();
@Benchmark
public void jackson(Blackhole bh) throws JsonProcessingException {
bh.consume(mapper.readValue(result, Int32ValueBean.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(result, Int32ValueBean.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(result, Int32ValueBean.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
// io.github.wycst.wast.json.JSON.parseObject(result, NumberValueBean.class);
Options options = new OptionsBuilder()
.include(Int32ValueBeanCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 370
| 116
| 486
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/LongTextParse2.java
|
LongTextParse2
|
main
|
class LongTextParse2 {
static final ObjectMapper mapper = new ObjectMapper();
private static String simpleResult;
static {
int length = 10000;
StringBuffer value = new StringBuffer();
for (int i = 0; i < length; i++) {
value.append("a");
}
Map map = new HashMap();
map.put("a", value);
map.put("b", value);
map.put("c", value);
map.put("d", value);
map.put("e", value);
map.put("f", value);
map.put("g", value);
map.put("h", value);
map.put("i", value);
map.put("j", value);
map.put("k", value);
map.put("l", value);
map.put("m", value);
map.put("n", value);
map.put("o", value);
map.put("p", value);
map.put("q", value);
map.put("r", value);
simpleResult = io.github.wycst.wast.json.JSON.toJsonString(map);
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(simpleResult, Map.class));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(simpleResult, Map.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(simpleResult, Map.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(LongTextParse2.class.getName())
.exclude(LongTextParse2Escape.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.SECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 490
| 100
| 590
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/LongTextParse2Escape.java
|
LongTextParse2Escape
|
main
|
class LongTextParse2Escape {
static final ObjectMapper mapper = new ObjectMapper();
private static String escapeResult;
static {
int length = 1000;
StringBuffer value = new StringBuffer();
for (int i = 0; i < length; i++) {
char ch = (char) (i % 32);
value.append(ch);
}
Map map = new HashMap();
map.put("a", value);
map.put("b", value);
map.put("c", value);
map.put("d", value);
map.put("e", value);
map.put("f", value);
map.put("g", value);
map.put("h", value);
map.put("i", value);
map.put("j", value);
map.put("k", value);
map.put("l", value);
map.put("m", value);
map.put("n", value);
map.put("o", value);
map.put("p", value);
map.put("q", value);
map.put("r", value);
escapeResult = io.github.wycst.wast.json.JSON.toJsonString(map);
}
// @Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(escapeResult, Map.class));
}
// @Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(escapeResult, Map.class));
}
// @Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(escapeResult, Map.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(LongTextParse2Escape.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.SECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 511
| 85
| 596
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/LongTextParseCase.java
|
LongTextParseCase
|
main
|
class LongTextParseCase {
static ObjectMapper mapper = new ObjectMapper();
private static String simpleResult;
private static String simplePrettyResult;
private static String escapeResult;
private static String escapePrettyResult;
static {
int length = 10000;
StringBuffer value = new StringBuffer();
for (int i = 0; i < length; i++) {
value.append("a");
}
Map map = new HashMap();
map.put("a", value);
map.put("b", value);
map.put("c", value);
map.put("d", value);
map.put("e", value);
map.put("f", value);
map.put("g", value);
map.put("h", value);
map.put("i", value);
map.put("j", value);
map.put("k", value);
map.put("l", value);
map.put("m", value);
map.put("n", value);
map.put("o", value);
map.put("p", value);
map.put("q", value);
map.put("r", value);
simpleResult = io.github.wycst.wast.json.JSON.toJsonString(map);
System.out.println("数据大小:" + (simpleResult.getBytes(StandardCharsets.UTF_8).length >> 10));
simplePrettyResult = io.github.wycst.wast.json.JSON.toJsonString(map, WriteOption.FormatOut);
// 随机添加转义字符
for (int j = 1; j < 32; j++) {
int index = ((int) (Math.random() * 10000)) % length;
value.setCharAt(index, (char) j);
}
escapeResult = io.github.wycst.wast.json.JSON.toJsonString(map);
escapePrettyResult = io.github.wycst.wast.json.JSON.toJsonString(map, WriteOption.FormatOut);
Map map1 = com.alibaba.fastjson2.JSON.parseObject(escapeResult, LinkedHashMap.class);
Map map2 = io.github.wycst.wast.json.JSON.parseObject(escapeResult, LinkedHashMap.class);
Map map3 = com.alibaba.fastjson2.JSON.parseObject(escapePrettyResult, LinkedHashMap.class);
Map map4 = io.github.wycst.wast.json.JSON.parseObject(escapePrettyResult, LinkedHashMap.class);
System.out.println(com.alibaba.fastjson2.JSON.toJSONString(map1).equals(com.alibaba.fastjson2.JSON.toJSONString(map2)));
System.out.println(com.alibaba.fastjson2.JSON.toJSONString(map3).equals(com.alibaba.fastjson2.JSON.toJSONString(map4)));
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(simpleResult, Map.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(simpleResult, Map.class));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(simpleResult, Map.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(simpleResult, Map.class));
}
@Benchmark
public void prettyFastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(simplePrettyResult, Map.class));
}
@Benchmark
public void prettyFastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(simplePrettyResult, Map.class));
}
@Benchmark
public void prettyJackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(simplePrettyResult, Map.class));
}
@Benchmark
public void prettyWastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(simplePrettyResult, Map.class));
}
@Benchmark
public void escapeFastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(escapeResult, Map.class));
}
@Benchmark
public void escapeFastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(escapeResult, Map.class));
}
@Benchmark
public void escapeJackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(escapeResult, Map.class));
}
@Benchmark
public void escapeWastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(escapeResult, Map.class));
}
@Benchmark
public void escapePrettyFastjson(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(escapePrettyResult, Map.class));
}
@Benchmark
public void escapePrettyFastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(escapePrettyResult, Map.class));
}
@Benchmark
public void escapePrettyJackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(escapePrettyResult, Map.class));
}
@Benchmark
public void escapePrettyWastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(escapePrettyResult, Map.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(LongTextParseCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.SECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 1,663
| 83
| 1,746
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/NumberValueBeanCase.java
|
NumberValueBeanCase
|
main
|
class NumberValueBeanCase {
static String result;
static ObjectMapper mapper = new ObjectMapper();
static {
NumberValueBean numberValueBean = new NumberValueBean();
numberValueBean.setValue1(-1547783865);
numberValueBean.setValue2(-764506995);
numberValueBean.setValue3(-3476207302658863324L);
numberValueBean.setValue4(-1673529357825104963L);
numberValueBean.setValue5(0.36136854F);
numberValueBean.setValue6(0.9946881F);
numberValueBean.setValue7(0.194469629135542);
numberValueBean.setValue8(0.18867346119788797);
numberValueBean.setValue9(1.23456789E107);
numberValueBean.setValue10(1.23456789E-97);
result = io.github.wycst.wast.json.JSON.toJsonString(numberValueBean);
}
@Benchmark
public void jackson(Blackhole bh) throws JsonProcessingException {
bh.consume(mapper.readValue(result, NumberValueBean.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(JSON.parseObject(result, NumberValueBean.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(result, NumberValueBean.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
// io.github.wycst.wast.json.JSON.parseObject(result, NumberValueBean.class);
Options options = new OptionsBuilder()
.include(NumberValueBeanCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.warmupIterations(3)
.forks(1)
.build();
new Runner(options).run();
| 514
| 114
| 628
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/SimpleBeanCase.java
|
SimpleBeanCase
|
main
|
class SimpleBeanCase {
private static String result;
static ObjectMapper mapper = new ObjectMapper();
static {
Map simpleMap = new HashMap();
simpleMap.put("id", 1);
simpleMap.put("date", new Date());
simpleMap.put("name", "simple");
simpleMap.put("percent", 12.34);
simpleMap.put("version", System.currentTimeMillis());
Map mapType = new HashMap();
mapType.put("v1", "v1 helldsdsd ");
mapType.put("v2", "v2 helldsdsd ");
simpleMap.put("mapInstance", mapType);
List<Object> versions = new ArrayList<Object>();
versions.add("v0.0.1");
versions.add("v0.0.2");
versions.add("v0.0.3");
simpleMap.put("versions", versions);
result = io.github.wycst.wast.json.JSON.toJsonString(simpleMap, WriteOption.FormatOut);
}
@Benchmark
public void fastjson1(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(result, SimpleBean.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(result, SimpleBean.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(result, SimpleBean.class));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(result, SimpleBean.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(SimpleBeanCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
| 512
| 73
| 585
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/SimpleBeanWriteCase.java
|
SimpleBeanWriteCase
|
main
|
class SimpleBeanWriteCase {
private static String result;
static ObjectMapper mapper = new ObjectMapper();
private static Object simpleBean;
static {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Map simpleMap = new HashMap();
simpleMap.put("id", 1);
simpleMap.put("date", new Date());
simpleMap.put("name", "simple");
simpleMap.put("percent", 12.34);
simpleMap.put("version", System.currentTimeMillis());
Map mapType = new HashMap();
mapType.put("v1", "v1 helldsdsd ");
mapType.put("v2", "v2 helldsdsd ");
simpleMap.put("mapInstance", mapType);
List<Object> versions = new ArrayList<Object>();
versions.add("v0.0.1");
versions.add("v0.0.2");
versions.add("v0.0.3");
simpleMap.put("versions", versions);
result = JSON.toJsonString(simpleMap, WriteOption.FormatOut);
simpleBean = JSON.parseObject(result, SimpleBean.class);
System.out.println(com.alibaba.fastjson2.JSON.toJSONString(simpleBean));
System.out.println(JSON.toJsonString(simpleBean));
try {
System.out.println(mapper.writeValueAsString(simpleBean));
} catch (JsonProcessingException e) {
}
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.toJSONString(simpleBean));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(JSON.toJsonString(simpleBean));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsString(simpleBean));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(SimpleBeanWriteCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
| 557
| 74
| 631
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/SuperLongText.java
|
SuperLongText
|
main
|
class SuperLongText {
private static String result;
static ObjectMapper mapper = new ObjectMapper();
static {
try (
InputStream fis = LargeFile26MTest.class.getClassLoader().getResourceAsStream("data/citylots.json.zip");
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zipIn = new ZipInputStream(bis)
) {
zipIn.getNextEntry();
result = IOUtils.toString(zipIn, "UTF-8");
} catch (Throwable ex) {
ex.printStackTrace();
}
}
// @Benchmark
public void fastjson(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.parseObject(result, Map.class));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.parseObject(result, Map.class, JSONReader.Feature.UseBigDecimalForDoubles));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.readValue(result, Map.class));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.parseObject(result, Map.class));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(SuperLongText.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MINUTES)
.forks(1)
.build();
new Runner(options).run();
| 404
| 71
| 475
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/benchmark/src/main/java/com/alibaba/fastjson2/benchmark/wast/WriteCase.java
|
WriteCase
|
main
|
class WriteCase {
private static Map map1;
private static Map escapeMap;
static ObjectMapper mapper = new ObjectMapper();
static {
int len = 200;
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < len; i++) {
buffer.append("a");
}
Map map = new HashMap();
map.put("abcdef", buffer.toString());
map.put("bbcdef", buffer.toString());
map.put("cbcdef", buffer.toString());
map.put("dbcdef", buffer.toString());
map.put("ebcdef", buffer.toString());
map.put("fbcdef", buffer.toString());
map.put("gbcdef", buffer.toString());
map.put("hbcdef", buffer.toString());
map.put("ibcdef", buffer.toString());
map.put("jbcdef", buffer.toString());
map.put("kbcdef", buffer.toString());
map.put("lbcdef", buffer.toString());
map.put("mbcdef", buffer.toString());
map.put("nbcdef", buffer.toString());
map1 = map;
buffer.setCharAt(100, '\n');
map = new HashMap();
map.put("abcdef", buffer.toString());
map.put("bbcdef", buffer.toString());
map.put("cbcdef", buffer.toString());
map.put("dbcdef", buffer.toString());
map.put("ebcdef", buffer.toString());
map.put("fbcdef", buffer.toString());
map.put("gbcdef", buffer.toString());
map.put("hbcdef", buffer.toString());
map.put("ibcdef", buffer.toString());
map.put("jbcdef", buffer.toString());
map.put("kbcdef", buffer.toString());
map.put("lbcdef", buffer.toString());
map.put("mbcdef", buffer.toString());
map.put("nbcdef", buffer.toString());
escapeMap = map;
}
@Benchmark
public void fastjson(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.toJSONString(map1));
}
@Benchmark
public void fastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.toJSONString(map1));
}
@Benchmark
public void jackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsString(map1));
}
@Benchmark
public void wastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.toJsonString(map1));
}
@Benchmark
public void escapeWastjson(Blackhole bh) {
bh.consume(io.github.wycst.wast.json.JSON.toJsonString(escapeMap));
}
@Benchmark
public void escapeFastjson(Blackhole bh) {
bh.consume(com.alibaba.fastjson.JSON.toJSONString(escapeMap));
}
@Benchmark
public void escapeFastjson2(Blackhole bh) {
bh.consume(com.alibaba.fastjson2.JSON.toJSONString(escapeMap));
}
@Benchmark
public void escapeJackson(Blackhole bh) throws Exception {
bh.consume(mapper.writeValueAsString(escapeMap));
}
public static void main(String[] args) throws RunnerException {<FILL_FUNCTION_BODY>}
}
|
Options options = new OptionsBuilder()
.include(WriteCase.class.getName())
.mode(Mode.Throughput)
.timeUnit(TimeUnit.MILLISECONDS)
.forks(1)
.build();
new Runner(options).run();
| 955
| 72
| 1,027
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/codegen/ClassWriter.java
|
ClassWriter
|
toString
|
class ClassWriter {
final String packageName;
final String name;
final Class superClass;
final Class[] interfaces;
private Set<String> imports = new TreeSet<>();
private List<FieldWriter> fields = new ArrayList<>();
private List<MethodWriter> methods = new ArrayList<>();
public ClassWriter(String packageName, String name, Class superClass, Class[] interfaces) {
this.packageName = packageName;
this.name = name;
this.superClass = superClass;
this.interfaces = interfaces;
}
public MethodWriter method(int modifiers, String name, Class returnType, Class[] paramTypes, String[] paramNames) {
MethodWriter mw = new MethodWriter(this, modifiers, name, returnType, paramTypes, paramNames);
methods.add(mw);
return mw;
}
static String getTypeName(Class type) {
Package pkg = type.getPackage();
if (pkg != null && "java.lang".equals(pkg.getName()) && !type.isArray()) {
return type.getSimpleName();
}
String className;
if (type.isArray()) {
className = getTypeName(type.getComponentType()) + "[]";
} else {
className = type.getName();
className = className.replace('$', '.');
}
return className;
}
public FieldWriter field(int modifier, String name, Class fieldClass) {
FieldWriter fw = new FieldWriter(modifier, name, fieldClass);
fields.add(fw);
return fw;
}
protected void toString(StringBuilder buf) {<FILL_FUNCTION_BODY>}
public String toString() {
StringBuilder buf = new StringBuilder();
toString(buf);
return buf.toString();
}
}
|
if (packageName != null && !packageName.isEmpty()) {
buf.append("package ").append(packageName).append(";\n\n");
}
if (!imports.isEmpty()) {
for (String item : imports) {
buf.append("import ").append(item).append(";\n");
}
}
buf.append("public final class ").append(name);
if (superClass != null) {
buf.append("\n\t\textends ").append(getTypeName(superClass));
}
buf.append(" {\n");
for (FieldWriter fw : fields) {
buf.append('\t')
.append(getTypeName(fw.fieldClass))
.append(' ')
.append(fw.name)
.append(";\n");
}
if (!fields.isEmpty()) {
buf.append("\n");
}
for (int i = 0; i < methods.size(); i++) {
if (i != 0) {
buf.append("\n");
}
MethodWriter mw = methods.get(i);
mw.toString(buf);
buf.append("\n");
}
buf.append("}");
| 467
| 322
| 789
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/codegen/MethodWriter.java
|
MethodWriter
|
toString
|
class MethodWriter
extends Block {
final ClassWriter classWriter;
final int modifiers;
final String name;
final Class returnType;
final Class[] paramTypes;
final String[] paramNames;
MethodWriter(ClassWriter classWriter, int modifiers, String name, Class returnType, Class[] paramTypes, String[] paramNames) {
this.classWriter = classWriter;
this.modifiers = modifiers;
this.name = name;
this.returnType = returnType;
this.paramTypes = paramTypes;
this.paramNames = paramNames;
}
public void toString(StringBuilder buf) {<FILL_FUNCTION_BODY>}
public void ident(StringBuilder buf, int indent) {
for (int i = 0; i < indent; i++) {
buf.append('\t');
}
}
}
|
if (Modifier.isPublic(modifiers)) {
buf.append("\tpublic ");
}
if ("<init>".equals(name)) {
buf.append(classWriter.name);
} else {
buf.append(getTypeName(returnType)).append(' ').append(name);
}
boolean newLine = paramTypes.length > 3;
buf.append('(');
if (newLine) {
buf.append("\n\t\t\t");
}
for (int i = 0; i < paramTypes.length; i++) {
if (i != 0) {
if (newLine) {
buf.append(",\n\t\t\t");
} else {
buf.append(", ");
}
}
Class paramType = paramTypes[i];
String paramName = paramNames[i];
buf.append(getTypeName(paramType)).append(' ').append(paramName);
}
if (newLine) {
buf.append("\n\t");
}
buf.append(") {\n");
for (int i = 0; i < statements.size(); i++) {
if (i != 0) {
buf.append('\n');
}
Statement stmt = statements.get(i);
stmt.toString(this, buf, 2);
}
buf.append("\n\t}");
| 223
| 368
| 591
|
<methods>public non-sealed void <init>() ,public void breakStmt() ,public void breakStmt(java.lang.String) ,public void continueStmt() ,public void continueStmt(java.lang.String) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement declare(Class#RAW, com.alibaba.fastjson2.internal.codegen.Opcodes.OpName) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement declare(java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.OpName) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement declare(Class#RAW, com.alibaba.fastjson2.internal.codegen.Opcodes.OpName, com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement declare(Class#RAW, com.alibaba.fastjson2.internal.codegen.Opcodes.OpName, java.lang.Object) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement declare(java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.OpName, com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.ForStmt forStmt(Class#RAW, com.alibaba.fastjson2.internal.codegen.Opcodes.Op, com.alibaba.fastjson2.internal.codegen.Opcodes.Op, com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.IfStmt ifNotNull(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.IfStmt ifNull(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.IfStmt ifStmt(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public transient void invoke(java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.Op[]) ,public transient void invoke(com.alibaba.fastjson2.internal.codegen.Opcodes.Op, java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.Op[]) ,public void label(java.lang.String) ,public void newLine() ,public void putField(java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public void putField(com.alibaba.fastjson2.internal.codegen.Opcodes.Op, java.lang.String, com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public void ret(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.Statement stmt(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) ,public com.alibaba.fastjson2.internal.codegen.Block.SwitchStmt switchStmt(com.alibaba.fastjson2.internal.codegen.Opcodes.Op, int[]) ,public com.alibaba.fastjson2.internal.codegen.Block.WhileStmt whileStmtStmt(com.alibaba.fastjson2.internal.codegen.Opcodes.Op) <variables>protected final List<com.alibaba.fastjson2.internal.codegen.Block.Statement> statements
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/codegen/Opcodes.java
|
Cast
|
toString
|
class Cast
implements Op {
public final String type;
public final Op value;
public Cast(String type, Op value) {
this.type = type;
this.value = value;
}
public void toString(MethodWriter mw, StringBuilder buf, int indent) {<FILL_FUNCTION_BODY>}
}
|
buf.append('(').append(type).append(") ");
boolean quote = value instanceof OpBinary;
if (quote) {
buf.append('(');
}
value.toString(mw, buf, indent);
if (quote) {
buf.append(')');
}
| 91
| 79
| 170
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/Analysis.java
|
Analysis
|
findRelatedReferences
|
class Analysis {
final ProcessingEnvironment processingEnv;
final Elements elements;
private final Types types;
final TypeElement jsonCompiledElement;
final TypeElement jsonTypeElement;
public final DeclaredType compiledJsonType;
final Map<String, StructInfo> structs = new LinkedHashMap<>();
public Analysis(ProcessingEnvironment processingEnv) {
this.processingEnv = processingEnv;
this.elements = processingEnv.getElementUtils();
this.types = processingEnv.getTypeUtils();
this.jsonCompiledElement = elements.getTypeElement(JSONCompiled.class.getName());
this.compiledJsonType = types.getDeclaredType(jsonCompiledElement);
this.jsonTypeElement = elements.getTypeElement(JSONType.class.getName());
}
public void processAnnotation(DeclaredType currentAnnotationType, Set<? extends Element> targets) {
Stack<String> path = new Stack<>();
for (Element el : targets) {
Element classElement;
ExecutableElement factory = null;
ExecutableElement builder = null;
if (el instanceof TypeElement) {
classElement = el;
} else if (el instanceof ExecutableElement && el.getKind() == ElementKind.METHOD) {
ExecutableElement ee = (ExecutableElement) el;
Element returnClass = types.asElement(ee.getReturnType());
Element enclosing = ee.getEnclosingElement();
if (!el.getModifiers().contains(Modifier.STATIC)
&& !types.isSameType(ee.getReturnType(), enclosing.asType())
&& returnClass.toString().equals(enclosing.getEnclosingElement().toString())) {
builder = ee;
}
factory = ee;
classElement = returnClass;
} else {
classElement = el.getEnclosingElement();
}
findStructs(classElement, currentAnnotationType, currentAnnotationType + " requires accessible public constructor", path, factory, builder);
}
}
private void findStructs(
Element el,
DeclaredType discoveredBy,
String errorMessage,
Stack<String> path,
ExecutableElement factory,
ExecutableElement builder
) {
if (!(el instanceof TypeElement)) {
return;
}
String typeName = el.toString();
final TypeElement element = (TypeElement) el;
String name = "struct" + structs.size();
String binaryName = elements.getBinaryName(element).toString();
StructInfo info = new StructInfo(types, element, discoveredBy, name, binaryName);
structs.put(typeName, info);
}
static int getModifiers(Set<Modifier> modifiers) {
int modifierValue = 0;
for (Modifier modifier : modifiers) {
switch (modifier) {
case PUBLIC:
modifierValue |= java.lang.reflect.Modifier.PUBLIC;
break;
case PRIVATE:
modifierValue |= java.lang.reflect.Modifier.PRIVATE;
break;
case FINAL:
modifierValue |= java.lang.reflect.Modifier.FINAL;
break;
default:
break;
}
}
return modifierValue;
}
public Map<String, StructInfo> analyze() {
findRelatedReferences();
return structs;
}
private void findRelatedReferences() {<FILL_FUNCTION_BODY>}
private List<TypeElement> getTypeHierarchy(TypeElement element) {
List<TypeElement> result = new ArrayList<TypeElement>();
getAllTypes(element, result, new HashSet<TypeElement>());
return result;
}
private void getAllTypes(TypeElement element, List<TypeElement> result, Set<TypeElement> processed) {
if (!processed.add(element) || element.getQualifiedName().contentEquals("java.lang.Object")) {
return;
}
result.add(element);
for (TypeMirror type : types.directSupertypes(element.asType())) {
Element current = types.asElement(type);
if (current instanceof TypeElement) {
getAllTypes((TypeElement) current, result, processed);
}
}
}
}
|
for (Map.Entry<String, StructInfo> entry : structs.entrySet()) {
StructInfo info = entry.getValue();
for (TypeElement inheritance : getTypeHierarchy(info.element)) {
for (VariableElement field : ElementFilter.fieldsIn(inheritance.getEnclosedElements())) {
Set<Modifier> modifiers = field.getModifiers();
if (modifiers.contains(Modifier.TRANSIENT)) {
continue;
}
if (modifiers.contains(Modifier.STATIC)) {
// TODO enum
continue;
}
FieldInfo fieldInfo = new FieldInfo();
String name = field.getSimpleName().toString();
JSONField[] annotations = field.getAnnotationsByType(JSONField.class);
for (JSONField annotation : annotations) {
CodeGenUtils.getFieldInfo(fieldInfo, annotation, false);
}
if (fieldInfo.fieldName != null) {
name = fieldInfo.fieldName;
}
info.getAttributeByField(name, field);
}
for (ExecutableElement method : ElementFilter.methodsIn(inheritance.getEnclosedElements())) {
List<? extends VariableElement> parameters = method.getParameters();
int parameterCount = parameters.size();
String methodName = method.getSimpleName().toString();
if (parameterCount > 2) {
continue;
}
boolean ignored = false;
if (parameterCount == 0) {
switch (methodName) {
case "hashCode":
ignored = true;
break;
default:
break;
}
} else if (parameterCount == 1) {
ignored = "equals".equals(methodName);
}
if (ignored) {
continue;
}
ExecutableElement getter = null, setter = null;
TypeMirror type = null;
String name = null;
if (parameters.size() == 0 && (methodName.startsWith("get") || methodName.startsWith("is"))) {
name = BeanUtils.getterName(methodName, null);
getter = method;
type = method.getReturnType();
} else if (methodName.startsWith("set") && method.getParameters().size() == 1) {
name = BeanUtils.setterName(methodName, null);
setter = method;
type = method.getParameters().get(0).asType();
} else {
continue;
}
AttributeInfo attr = info.getAttributeByMethod(name, type, getter, setter);
}
}
}
| 1,083
| 665
| 1,748
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/JSONBaseAnnotationProcessor.java
|
JSONBaseAnnotationProcessor
|
addOpensSinceJava9
|
class JSONBaseAnnotationProcessor
extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
addOpensSinceJava9();
super.init(unwrapProcessingEnv(processingEnv));
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
return false;
}
private static void addOpensSinceJava9() {<FILL_FUNCTION_BODY>}
private static Object getJdkCompilerModule() {
try {
Class<?> moduleLayer = Class.forName("java.lang.ModuleLayer");
Method boot = moduleLayer.getDeclaredMethod("boot");
Object bootLayer = boot.invoke(null);
Class<?> clazz = Class.forName("java.util.Optional");
Method findModule = moduleLayer.getDeclaredMethod("findModule", String.class);
Object compiler = findModule.invoke(bootLayer, "jdk.compiler");
return clazz.getDeclaredMethod("get").invoke(compiler);
} catch (Exception e) {
return null;
}
}
private static Object getOwnModule() {
try {
Class<Class> clazz = Class.class;
Method getModule = clazz.getDeclaredMethod("getModule");
return getModule.invoke(JSONBaseAnnotationProcessor.class);
} catch (Exception e) {
return null;
}
}
private static class Parent {
boolean first;
}
}
|
if (JVM_VERSION >= 9) {
Class<?> cModule = null;
try {
cModule = Class.forName("java.lang.Module");
} catch (ClassNotFoundException e) {
// just ignore
}
Object jdkCompilerModule = getJdkCompilerModule();
Object ownModule = getOwnModule();
String[] allPkgs = {
"com.sun.tools.javac.api",
"com.sun.tools.javac.code",
"com.sun.tools.javac.comp",
"com.sun.tools.javac.file",
"com.sun.tools.javac.main",
"com.sun.tools.javac.model",
"com.sun.tools.javac.parser",
"com.sun.tools.javac.processing",
"com.sun.tools.javac.tree",
"com.sun.tools.javac.util"
};
try {
Method m = cModule.getDeclaredMethod("implAddOpens", String.class, cModule);
long firstFieldOffset = UNSAFE.objectFieldOffset(Parent.class.getDeclaredField("first"));
UNSAFE.putBooleanVolatile(m, firstFieldOffset, true);
for (String p : allPkgs) {
m.invoke(jdkCompilerModule, p, ownModule);
}
} catch (Exception e) {
return;
}
}
| 378
| 369
| 747
|
<methods>public Iterable<? extends javax.annotation.processing.Completion> getCompletions(javax.lang.model.element.Element, javax.lang.model.element.AnnotationMirror, javax.lang.model.element.ExecutableElement, java.lang.String) ,public Set<java.lang.String> getSupportedAnnotationTypes() ,public Set<java.lang.String> getSupportedOptions() ,public javax.lang.model.SourceVersion getSupportedSourceVersion() ,public synchronized void init(javax.annotation.processing.ProcessingEnvironment) ,public abstract boolean process(Set<? extends javax.lang.model.element.TypeElement>, javax.annotation.processing.RoundEnvironment) <variables>static final boolean $assertionsDisabled,private boolean initialized,protected javax.annotation.processing.ProcessingEnvironment processingEnv
|
alibaba_fastjson2
|
fastjson2/codegen/src/main/java/com/alibaba/fastjson2/internal/processor/StructInfo.java
|
StructInfo
|
getAttributeByMethod
|
class StructInfo {
final int modifiers;
final boolean referenceDetect;
final boolean smartMatch;
String typeKey;
int readerFeatures;
int writerFeatures;
final TypeElement element;
final DeclaredType discoveredBy;
final String name;
final String binaryName;
final Map<String, AttributeInfo> attributes = new LinkedHashMap<>();
public StructInfo(
Types types,
TypeElement element,
DeclaredType discoveredBy,
String name,
String binaryName
) {
this.element = element;
this.discoveredBy = discoveredBy;
this.name = name;
this.binaryName = binaryName;
this.modifiers = Analysis.getModifiers(element.getModifiers());
AnnotationMirror anntation = null;
for (AnnotationMirror mirror : element.getAnnotationMirrors()) {
if (types.isSameType(mirror.getAnnotationType(), discoveredBy)) {
anntation = mirror;
}
}
boolean referenceDetect = true, smartMatch = true;
if (anntation != null) {
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : anntation.getElementValues().entrySet()) {
String annFieldName = entry.getKey().getSimpleName().toString();
AnnotationValue value = entry.getValue();
switch (annFieldName) {
case "referenceDetect":
referenceDetect = (Boolean) value.getValue();
break;
case "smartMatch":
smartMatch = (Boolean) value.getValue();
break;
default:
break;
}
}
}
this.referenceDetect = referenceDetect;
this.smartMatch = smartMatch;
}
public AttributeInfo getAttributeByField(String name, VariableElement field) {
AttributeInfo attr = attributes.get(name);
TypeMirror type = field.asType();
if (attr == null) {
attr = new AttributeInfo(name, field.asType(), field, null, null, null);
AttributeInfo origin = attributes.putIfAbsent(name, attr);
if (origin != null) {
attr = origin;
}
}
attr.field = field;
return attr;
}
public AttributeInfo getAttributeByMethod(
String name,
TypeMirror type,
ExecutableElement getter,
ExecutableElement setter
) {<FILL_FUNCTION_BODY>}
public List<AttributeInfo> getReaderAttributes() {
return attributes.values()
.stream()
.filter(AttributeInfo::supportSet)
.sorted()
.collect(Collectors.toList());
}
}
|
AttributeInfo attr = attributes.get(name);
if (attr == null) {
attr = new AttributeInfo(name, type, null, getter, setter, null);
AttributeInfo origin = attributes.putIfAbsent(name, attr);
if (origin != null) {
attr = origin;
}
}
if (getter != null) {
attr.getMethod = getter;
}
if (setter != null) {
attr.setMethod = setter;
}
return attr;
| 701
| 143
| 844
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONFactory.java
|
CacheItem
|
getDefaultObjectReaderProvider
|
class CacheItem {
volatile char[] chars;
volatile byte[] bytes;
}
static final Properties DEFAULT_PROPERTIES;
static final ObjectWriterProvider defaultObjectWriterProvider = new ObjectWriterProvider();
static final ObjectReaderProvider defaultObjectReaderProvider = new ObjectReaderProvider();
static final JSONPathCompiler defaultJSONPathCompiler;
static {
JSONPathCompilerReflect compiler = null;
switch (JSONFactory.CREATOR) {
case "reflect":
case "lambda":
compiler = JSONPathCompilerReflect.INSTANCE;
break;
default:
try {
if (!JDKUtils.ANDROID && !JDKUtils.GRAAL) {
compiler = JSONPathCompilerReflectASM.INSTANCE;
}
} catch (Throwable ignored) {
// ignored
}
if (compiler == null) {
compiler = JSONPathCompilerReflect.INSTANCE;
}
break;
}
defaultJSONPathCompiler = compiler;
}
static final ThreadLocal<ObjectReaderCreator> readerCreatorLocal = new ThreadLocal<>();
static final ThreadLocal<ObjectReaderProvider> readerProviderLocal = new ThreadLocal<>();
static final ThreadLocal<ObjectWriterCreator> writerCreatorLocal = new ThreadLocal<>();
static final ThreadLocal<JSONPathCompiler> jsonPathCompilerLocal = new ThreadLocal<>();
static final ObjectReader<JSONArray> ARRAY_READER = JSONFactory.getDefaultObjectReaderProvider().getObjectReader(JSONArray.class);
static final ObjectReader<JSONObject> OBJECT_READER = JSONFactory.getDefaultObjectReaderProvider().getObjectReader(JSONObject.class);
static final byte[] UUID_VALUES;
static {
UUID_VALUES = new byte['f' + 1 - '0'];
for (char c = '0'; c <= '9'; c++) {
UUID_VALUES[c - '0'] = (byte) (c - '0');
}
for (char c = 'a'; c <= 'f'; c++) {
UUID_VALUES[c - '0'] = (byte) (c - 'a' + 10);
}
for (char c = 'A'; c <= 'F'; c++) {
UUID_VALUES[c - '0'] = (byte) (c - 'A' + 10);
}
}
/**
* @param objectSupplier
* @since 2.0.15
*/
public static void setDefaultObjectSupplier(Supplier<Map> objectSupplier) {
defaultObjectSupplier = objectSupplier;
}
/**
* @param arraySupplier
* @since 2.0.15
*/
public static void setDefaultArraySupplier(Supplier<List> arraySupplier) {
defaultArraySupplier = arraySupplier;
}
public static Supplier<Map> getDefaultObjectSupplier() {
return defaultObjectSupplier;
}
public static Supplier<List> getDefaultArraySupplier() {
return defaultArraySupplier;
}
public static JSONWriter.Context createWriteContext() {
return new JSONWriter.Context(defaultObjectWriterProvider);
}
public static JSONWriter.Context createWriteContext(ObjectWriterProvider provider, JSONWriter.Feature... features) {
JSONWriter.Context context = new JSONWriter.Context(provider);
context.config(features);
return context;
}
public static JSONWriter.Context createWriteContext(JSONWriter.Feature... features) {
return new JSONWriter.Context(defaultObjectWriterProvider, features);
}
public static JSONReader.Context createReadContext() {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
return new JSONReader.Context(provider);
}
public static JSONReader.Context createReadContext(long features) {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
return new JSONReader.Context(provider, features);
}
public static JSONReader.Context createReadContext(JSONReader.Feature... features) {
JSONReader.Context context = new JSONReader.Context(
JSONFactory.getDefaultObjectReaderProvider()
);
for (int i = 0; i < features.length; i++) {
context.features |= features[i].mask;
}
return context;
}
public static JSONReader.Context createReadContext(Filter filter, JSONReader.Feature... features) {
JSONReader.Context context = new JSONReader.Context(
JSONFactory.getDefaultObjectReaderProvider()
);
if (filter instanceof JSONReader.AutoTypeBeforeHandler) {
context.autoTypeBeforeHandler = (JSONReader.AutoTypeBeforeHandler) filter;
}
if (filter instanceof ExtraProcessor) {
context.extraProcessor = (ExtraProcessor) filter;
}
for (int i = 0; i < features.length; i++) {
context.features |= features[i].mask;
}
return context;
}
public static JSONReader.Context createReadContext(ObjectReaderProvider provider, JSONReader.Feature... features) {
if (provider == null) {
provider = getDefaultObjectReaderProvider();
}
JSONReader.Context context = new JSONReader.Context(provider);
context.config(features);
return context;
}
public static JSONReader.Context createReadContext(SymbolTable symbolTable) {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
return new JSONReader.Context(provider, symbolTable);
}
public static JSONReader.Context createReadContext(SymbolTable symbolTable, JSONReader.Feature... features) {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
JSONReader.Context context = new JSONReader.Context(provider, symbolTable);
context.config(features);
return context;
}
public static JSONReader.Context createReadContext(Supplier<Map> objectSupplier, JSONReader.Feature... features) {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
JSONReader.Context context = new JSONReader.Context(provider);
context.setObjectSupplier(objectSupplier);
context.config(features);
return context;
}
public static JSONReader.Context createReadContext(
Supplier<Map> objectSupplier,
Supplier<List> arraySupplier,
JSONReader.Feature... features) {
ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
JSONReader.Context context = new JSONReader.Context(provider);
context.setObjectSupplier(objectSupplier);
context.setArraySupplier(arraySupplier);
context.config(features);
return context;
}
public static ObjectWriterProvider getDefaultObjectWriterProvider() {
return defaultObjectWriterProvider;
}
public static ObjectReaderProvider getDefaultObjectReaderProvider() {<FILL_FUNCTION_BODY>
|
ObjectReaderProvider providerLocal = readerProviderLocal.get();
if (providerLocal != null) {
return providerLocal;
}
return defaultObjectReaderProvider;
| 1,709
| 46
| 1,755
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathFilter.java
|
NameDecimalOpSegment
|
apply
|
class NameDecimalOpSegment
extends NameFilter {
final Operator operator;
final BigDecimal value;
public NameDecimalOpSegment(String name, long nameHashCode, Operator operator, BigDecimal value) {
super(name, nameHashCode);
this.operator = operator;
this.value = value;
}
protected boolean applyNull() {
return operator == Operator.NE;
}
@Override
public boolean apply(Object fieldValue) {<FILL_FUNCTION_BODY>}
}
|
if (fieldValue == null) {
return false;
}
BigDecimal fieldValueDecimal;
if (fieldValue instanceof Boolean) {
fieldValueDecimal = (Boolean) fieldValue ? BigDecimal.ONE : BigDecimal.ZERO;
} else if (fieldValue instanceof Byte
|| fieldValue instanceof Short
|| fieldValue instanceof Integer
|| fieldValue instanceof Long) {
fieldValueDecimal = BigDecimal.valueOf(
((Number) fieldValue).longValue()
);
} else if (fieldValue instanceof BigDecimal) {
fieldValueDecimal = ((BigDecimal) fieldValue);
} else if (fieldValue instanceof BigInteger) {
fieldValueDecimal = new BigDecimal((BigInteger) fieldValue);
} else {
throw new UnsupportedOperationException();
}
int cmp = fieldValueDecimal.compareTo(value);
switch (operator) {
case LT:
return cmp < 0;
case LE:
return cmp <= 0;
case EQ:
return cmp == 0;
case NE:
return cmp != 0;
case GT:
return cmp > 0;
case GE:
return cmp >= 0;
default:
throw new UnsupportedOperationException();
}
| 138
| 329
| 467
|
<methods>public abstract void accept(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.JSONPath.Context) ,public boolean contains(com.alibaba.fastjson2.JSONPath.Context) ,public abstract void eval(com.alibaba.fastjson2.JSONPath.Context) ,public boolean remove(com.alibaba.fastjson2.JSONPath.Context) ,public void set(com.alibaba.fastjson2.JSONPath.Context, java.lang.Object) ,public void setCallback(com.alibaba.fastjson2.JSONPath.Context, BiFunction#RAW) ,public void setInt(com.alibaba.fastjson2.JSONPath.Context, int) ,public void setLong(com.alibaba.fastjson2.JSONPath.Context, long) <variables>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSegment.java
|
RangeIndexSegment
|
remove
|
class RangeIndexSegment
extends JSONPathSegment {
final int begin;
final int end;
public RangeIndexSegment(int begin, int end) {
this.begin = begin;
this.end = end;
}
@Override
public void eval(JSONPath.Context context) {
Object object = context.parent == null
? context.root
: context.parent.value;
List result = new JSONArray();
if (object instanceof List) {
List list = (List) object;
for (int i = 0, size = list.size(); i < size; i++) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
result.add(list.get(i));
}
}
context.value = result;
context.eval = true;
return;
}
if (object instanceof Object[]) {
Object[] array = (Object[]) object;
for (int i = 0; i < array.length; i++) {
boolean match = i >= begin && i <= end
|| i - array.length > begin && i - array.length <= end;
if (match) {
result.add(array[i]);
}
}
context.value = result;
context.eval = true;
return;
}
throw new JSONException("TODO");
}
@Override
public void accept(JSONReader jsonReader, JSONPath.Context context) {
if (context.parent != null
&& (context.parent.eval
|| (context.parent.current instanceof CycleNameSegment && context.next == null))
) {
eval(context);
return;
}
if (jsonReader.jsonb) {
JSONArray array = new JSONArray();
{
int itemCnt = jsonReader.startArray();
for (int i = 0; i < itemCnt; i++) {
boolean match = begin < 0 || i >= begin && i < end;
if (!match) {
jsonReader.skipValue();
continue;
}
array.add(
jsonReader.readAny());
}
}
if (begin < 0) {
for (int size = array.size(), i = size - 1; i >= 0; i--) {
int ni = i - size;
if (ni < begin || ni >= end) {
array.remove(i);
}
}
}
context.value = array;
context.eval = true;
return;
}
JSONArray array = new JSONArray();
jsonReader.next();
for (int i = 0; jsonReader.ch != EOI; ++i) {
if (jsonReader.ch == ']') {
jsonReader.next();
break;
}
boolean match = begin < 0 || i >= begin && i < end;
if (!match) {
jsonReader.skipValue();
if (jsonReader.ch == ',') {
jsonReader.next();
}
continue;
}
Object val;
switch (jsonReader.ch) {
case '-':
case '+':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '.':
jsonReader.readNumber0();
val = jsonReader.getNumber();
break;
case '[':
val = jsonReader.readArray();
break;
case '{':
val = jsonReader.readObject();
break;
case '"':
case '\'':
val = jsonReader.readString();
break;
case 't':
case 'f':
val = jsonReader.readBoolValue();
break;
case 'n':
jsonReader.readNull();
val = null;
break;
default:
throw new JSONException("TODO : " + jsonReader.ch);
}
array.add(val);
}
if (begin < 0) {
for (int size = array.size(), i = size - 1; i >= 0; i--) {
int ni = i - size;
if (ni < begin || ni >= end) {
array.remove(i);
}
}
}
context.value = array;
context.eval = true;
}
@Override
public void set(JSONPath.Context context, Object value) {
Object object = context.parent == null
? context.root
: context.parent.value;
if (object instanceof List) {
List list = (List) object;
for (int i = 0, size = list.size(); i < size; i++) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
list.set(i, value);
}
}
return;
}
if (object != null) {
Class objectClass = object.getClass();
if (objectClass.isArray()) {
int size = Array.getLength(object);
for (int i = 0; i < size; i++) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
Array.set(object, i, value);
}
}
return;
}
}
throw new JSONException("UnsupportedOperation " + getClass());
}
public void setCallback(JSONPath.Context context, BiFunction callback) {
Object object = context.parent == null
? context.root
: context.parent.value;
if (object instanceof List) {
List list = (List) object;
for (int i = 0, size = list.size(); i < size; i++) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
Object item = list.get(i);
item = callback.apply(list, item);
list.set(index, item);
}
}
return;
}
if (object != null) {
Class objectClass = object.getClass();
if (objectClass.isArray()) {
int size = Array.getLength(object);
for (int i = 0; i < size; i++) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
Object item = Array.get(object, i);
item = callback.apply(object, item);
Array.set(object, i, item);
}
}
return;
}
}
throw new JSONException("UnsupportedOperation " + getClass());
}
@Override
public boolean remove(JSONPath.Context context) {<FILL_FUNCTION_BODY>}
}
|
Object object = context.parent == null
? context.root
: context.parent.value;
if (object instanceof List) {
List list = (List) object;
int removeCount = 0;
for (int size = list.size(), i = size - 1; i >= 0; i--) {
int index = begin >= 0 ? i : i - size;
if (index >= begin && index < end) {
list.remove(i);
removeCount++;
}
}
return removeCount > 0;
}
throw new JSONException("UnsupportedOperation " + getClass());
| 1,781
| 157
| 1,938
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingle.java
|
JSONPathSingle
|
setInt
|
class JSONPathSingle
extends JSONPath {
final JSONPathSegment segment;
final boolean ref;
final boolean extractSupport;
JSONPathSingle(JSONPathSegment segment, String path, Feature... features) {
super(path, features);
this.segment = segment;
this.ref = segment instanceof JSONPathSegmentIndex || segment instanceof JSONPathSegmentName;
boolean extractSupport = true;
if (segment instanceof JSONPathSegment.EvalSegment) {
extractSupport = false;
} else if (segment instanceof JSONPathSegmentIndex && ((JSONPathSegmentIndex) segment).index < 0) {
extractSupport = false;
} else if (segment instanceof JSONPathSegment.CycleNameSegment && ((JSONPathSegment.CycleNameSegment) segment).shouldRecursive()) {
extractSupport = false;
}
this.extractSupport = extractSupport;
}
@Override
public boolean remove(Object root) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
return segment.remove(context);
}
@Override
public boolean contains(Object root) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
return segment.contains(context);
}
@Override
public boolean isRef() {
return ref;
}
@Override
public Object eval(Object root) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.eval(context);
return context.value;
}
@Override
public void set(Object root, Object value) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.set(context, value);
}
@Override
public void set(Object root, Object value, JSONReader.Feature... readerFeatures) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.set(context, value);
}
@Override
public void setCallback(Object root, BiFunction callback) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.setCallback(context, callback);
}
@Override
public void setInt(Object root, int value) {<FILL_FUNCTION_BODY>}
@Override
public void setLong(Object root, long value) {
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.setLong(context, value);
}
@Override
public Object extract(JSONReader jsonReader) {
Context context = new Context(this, null, segment, null, 0);
if (!extractSupport) {
context.root = jsonReader.readAny();
segment.eval(context);
} else {
segment.accept(jsonReader, context);
}
return context.value;
}
@Override
public String extractScalar(JSONReader jsonReader) {
Context context = new Context(this, null, segment, null, 0);
segment.accept(jsonReader, context);
return JSON.toJSONString(context.value);
}
@Override
public final JSONPath getParent() {
return RootPath.INSTANCE;
}
}
|
Context context = new Context(this, null, segment, null, 0);
context.root = root;
segment.setInt(context, value);
| 869
| 41
| 910
|
<methods>public transient void arrayAdd(java.lang.Object, java.lang.Object[]) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String, Class#RAW) ,public static boolean contains(java.lang.Object, java.lang.String) ,public abstract boolean contains(java.lang.Object) ,public boolean endsWithFilter() ,public static java.lang.Object eval(java.lang.String, java.lang.String) ,public static java.lang.Object eval(java.lang.Object, java.lang.String) ,public abstract java.lang.Object eval(java.lang.Object) ,public static java.lang.Object extract(java.lang.String, java.lang.String) ,public static transient java.lang.Object extract(java.lang.String, java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public java.lang.Object extract(java.lang.String) ,public java.lang.Object extract(byte[]) ,public java.lang.Object extract(byte[], int, int, java.nio.charset.Charset) ,public abstract java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public void extract(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public java.lang.Integer extractInt32(com.alibaba.fastjson2.JSONReader) ,public int extractInt32Value(com.alibaba.fastjson2.JSONReader) ,public java.lang.Long extractInt64(com.alibaba.fastjson2.JSONReader) ,public long extractInt64Value(com.alibaba.fastjson2.JSONReader) ,public abstract java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public void extractScalar(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public abstract com.alibaba.fastjson2.JSONPath getParent() ,public com.alibaba.fastjson2.JSONReader.Context getReaderContext() ,public com.alibaba.fastjson2.JSONWriter.Context getWriterContext() ,public boolean isPrevious() ,public abstract boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], java.lang.String[], long[], java.time.ZoneId, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static Map<java.lang.String,java.lang.Object> paths(java.lang.Object) ,public static java.lang.String remove(java.lang.String, java.lang.String) ,public static void remove(java.lang.Object, java.lang.String) ,public abstract boolean remove(java.lang.Object) ,public static java.lang.String set(java.lang.String, java.lang.String, java.lang.Object) ,public static java.lang.Object set(java.lang.Object, java.lang.String, java.lang.Object) ,public abstract void set(java.lang.Object, java.lang.Object) ,public transient abstract void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, Function#RAW) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, BiFunction#RAW) ,public void setCallback(java.lang.Object, Function#RAW) ,public abstract void setCallback(java.lang.Object, BiFunction#RAW) ,public abstract void setInt(java.lang.Object, int) ,public abstract void setLong(java.lang.Object, long) ,public com.alibaba.fastjson2.JSONPath setReaderContext(com.alibaba.fastjson2.JSONReader.Context) ,public com.alibaba.fastjson2.JSONPath setWriterContext(com.alibaba.fastjson2.JSONWriter.Context) ,public final java.lang.String toString() <variables>static final com.alibaba.fastjson2.JSONReader.Context PARSE_CONTEXT,final non-sealed long features,final non-sealed java.lang.String path,com.alibaba.fastjson2.JSONReader.Context readerContext,com.alibaba.fastjson2.JSONWriter.Context writerContext
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingleIndex.java
|
JSONPathSingleIndex
|
extract
|
class JSONPathSingleIndex
extends JSONPathSingle {
final JSONPathSegmentIndex segment;
final int index;
public JSONPathSingleIndex(String path, JSONPathSegmentIndex segment, Feature... features) {
super(segment, path, features);
this.segment = segment;
this.index = segment.index;
}
@Override
public Object eval(Object object) {
if (object == null) {
return null;
}
if (object instanceof java.util.List) {
Object value = null;
List list = (List) object;
if (index < list.size()) {
value = list.get(index);
}
return value;
}
Context context = new Context(this, null, segment, null, 0);
context.root = object;
segment.eval(context);
return context.value;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.nextIfNull()) {
return null;
}
int max = jsonReader.startArray();
if (jsonReader.jsonb && index >= max) {
return null;
}
if ((!jsonReader.jsonb) && jsonReader.nextIfArrayEnd()) {
return null;
}
for (int i = 0; i < index && i < max; i++) {
jsonReader.skipValue();
if ((!jsonReader.jsonb) && jsonReader.nextIfArrayEnd()) {
return null;
}
}
return jsonReader.readAny();
| 257
| 159
| 416
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public final com.alibaba.fastjson2.JSONPath getParent() ,public boolean isRef() ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed boolean extractSupport,final non-sealed boolean ref,final non-sealed com.alibaba.fastjson2.JSONPathSegment segment
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingleNameDecimal.java
|
JSONPathSingleNameDecimal
|
extract
|
class JSONPathSingleNameDecimal
extends JSONPathTyped {
final long nameHashCode;
final String name;
public JSONPathSingleNameDecimal(JSONPathSingleName jsonPath) {
super(jsonPath, BigDecimal.class);
this.nameHashCode = jsonPath.nameHashCode;
this.name = jsonPath.name;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.jsonb) {
if (jsonReader.isObject()) {
jsonReader.nextIfObjectStart();
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
if (nameHashCode == 0) {
continue;
}
boolean match = nameHashCode == this.nameHashCode;
if (!match && (!jsonReader.isObject()) && !jsonReader.isArray()) {
jsonReader.skipValue();
continue;
}
return jsonReader.readBigDecimal();
}
}
} else if (jsonReader.nextIfObjectStart()) {
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == this.nameHashCode;
if (!match) {
jsonReader.skipValue();
continue;
}
return jsonReader.readBigDecimal();
}
}
return null;
| 122
| 259
| 381
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public java.lang.reflect.Type getType() ,public boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(com.alibaba.fastjson2.JSONPath, java.lang.reflect.Type) ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed com.alibaba.fastjson2.JSONPath jsonPath,final non-sealed java.lang.reflect.Type type
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingleNameInteger.java
|
JSONPathSingleNameInteger
|
extract
|
class JSONPathSingleNameInteger
extends JSONPathTyped {
final long nameHashCode;
final String name;
public JSONPathSingleNameInteger(JSONPathSingleName jsonPath) {
super(jsonPath, Integer.class);
this.nameHashCode = jsonPath.nameHashCode;
this.name = jsonPath.name;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.jsonb) {
if (jsonReader.isObject()) {
jsonReader.nextIfObjectStart();
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
if (nameHashCode == 0) {
continue;
}
boolean match = nameHashCode == this.nameHashCode;
if (!match && (!jsonReader.isObject()) && !jsonReader.isArray()) {
jsonReader.skipValue();
continue;
}
return jsonReader.readInt32();
}
}
} else if (jsonReader.nextIfObjectStart()) {
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == this.nameHashCode;
if (!match) {
jsonReader.skipValue();
continue;
}
return jsonReader.readInt32();
}
}
return null;
| 118
| 259
| 377
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public java.lang.reflect.Type getType() ,public boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(com.alibaba.fastjson2.JSONPath, java.lang.reflect.Type) ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed com.alibaba.fastjson2.JSONPath jsonPath,final non-sealed java.lang.reflect.Type type
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingleNameLong.java
|
JSONPathSingleNameLong
|
extract
|
class JSONPathSingleNameLong
extends JSONPathTyped {
final long nameHashCode;
final String name;
public JSONPathSingleNameLong(JSONPathSingleName jsonPath) {
super(jsonPath, Long.class);
this.nameHashCode = jsonPath.nameHashCode;
this.name = jsonPath.name;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.jsonb) {
if (jsonReader.isObject()) {
jsonReader.nextIfObjectStart();
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
if (nameHashCode == 0) {
continue;
}
boolean match = nameHashCode == this.nameHashCode;
if (!match && (!jsonReader.isObject()) && !jsonReader.isArray()) {
jsonReader.skipValue();
continue;
}
return jsonReader.readInt64();
}
}
} else if (jsonReader.nextIfObjectStart()) {
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == this.nameHashCode;
if (!match) {
jsonReader.skipValue();
continue;
}
return jsonReader.readInt64();
}
}
return null;
| 118
| 259
| 377
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public java.lang.reflect.Type getType() ,public boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(com.alibaba.fastjson2.JSONPath, java.lang.reflect.Type) ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed com.alibaba.fastjson2.JSONPath jsonPath,final non-sealed java.lang.reflect.Type type
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathSingleNameString.java
|
JSONPathSingleNameString
|
extract
|
class JSONPathSingleNameString
extends JSONPathTyped {
final long nameHashCode;
final String name;
public JSONPathSingleNameString(JSONPathSingleName jsonPath) {
super(jsonPath, String.class);
this.nameHashCode = jsonPath.nameHashCode;
this.name = jsonPath.name;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.jsonb) {
if (jsonReader.isObject()) {
jsonReader.nextIfObjectStart();
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
if (nameHashCode == 0) {
continue;
}
boolean match = nameHashCode == this.nameHashCode;
if (!match && (!jsonReader.isObject()) && !jsonReader.isArray()) {
jsonReader.skipValue();
continue;
}
return jsonReader.readString();
}
}
} else if (jsonReader.nextIfObjectStart()) {
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == this.nameHashCode;
if (!match) {
jsonReader.skipValue();
continue;
}
return jsonReader.readString();
}
}
return null;
| 118
| 255
| 373
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public java.lang.reflect.Type getType() ,public boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(com.alibaba.fastjson2.JSONPath, java.lang.reflect.Type) ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed com.alibaba.fastjson2.JSONPath jsonPath,final non-sealed java.lang.reflect.Type type
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTyped.java
|
JSONPathTyped
|
of
|
class JSONPathTyped
extends JSONPath {
final JSONPath jsonPath;
final Type type;
protected JSONPathTyped(JSONPath jsonPath, Type type) {
super(jsonPath.path, jsonPath.features);
this.type = type;
this.jsonPath = jsonPath;
}
@Override
public JSONPath getParent() {
return jsonPath.getParent();
}
@Override
public boolean isRef() {
return jsonPath.isRef();
}
@Override
public boolean contains(Object object) {
return jsonPath.contains(object);
}
@Override
public Object eval(Object object) {
Object result = jsonPath.eval(object);
return TypeUtils.cast(result, type);
}
@Override
public Object extract(JSONReader jsonReader) {
Object result = jsonPath.extract(jsonReader);
return TypeUtils.cast(result, type);
}
@Override
public String extractScalar(JSONReader jsonReader) {
return jsonPath.extractScalar(jsonReader);
}
@Override
public void set(Object object, Object value) {
jsonPath.set(object, value);
}
@Override
public void set(Object object, Object value, JSONReader.Feature... readerFeatures) {
jsonPath.set(object, value, readerFeatures);
}
@Override
public void setCallback(Object object, BiFunction callback) {
jsonPath.setCallback(object, callback);
}
@Override
public void setInt(Object object, int value) {
jsonPath.setInt(object, value);
}
@Override
public void setLong(Object object, long value) {
jsonPath.setLong(object, value);
}
@Override
public boolean remove(Object object) {
return jsonPath.remove(object);
}
public Type getType() {
return type;
}
public static JSONPath of(JSONPath jsonPath, Type type) {<FILL_FUNCTION_BODY>}
}
|
if (type == null || type == Object.class) {
return jsonPath;
}
if (jsonPath instanceof JSONPathTyped) {
JSONPathTyped jsonPathTyped = (JSONPathTyped) jsonPath;
if (jsonPathTyped.type.equals(type)) {
return jsonPath;
}
}
if (jsonPath instanceof JSONPathSingleName) {
if (type == Integer.class) {
return new JSONPathSingleNameInteger((JSONPathSingleName) jsonPath);
}
if (type == Long.class) {
return new JSONPathSingleNameLong((JSONPathSingleName) jsonPath);
}
if (type == String.class) {
return new JSONPathSingleNameString((JSONPathSingleName) jsonPath);
}
if (type == BigDecimal.class) {
return new JSONPathSingleNameDecimal((JSONPathSingleName) jsonPath);
}
}
return new JSONPathTyped(jsonPath, type);
| 537
| 255
| 792
|
<methods>public transient void arrayAdd(java.lang.Object, java.lang.Object[]) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String, Class#RAW) ,public static boolean contains(java.lang.Object, java.lang.String) ,public abstract boolean contains(java.lang.Object) ,public boolean endsWithFilter() ,public static java.lang.Object eval(java.lang.String, java.lang.String) ,public static java.lang.Object eval(java.lang.Object, java.lang.String) ,public abstract java.lang.Object eval(java.lang.Object) ,public static java.lang.Object extract(java.lang.String, java.lang.String) ,public static transient java.lang.Object extract(java.lang.String, java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public java.lang.Object extract(java.lang.String) ,public java.lang.Object extract(byte[]) ,public java.lang.Object extract(byte[], int, int, java.nio.charset.Charset) ,public abstract java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public void extract(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public java.lang.Integer extractInt32(com.alibaba.fastjson2.JSONReader) ,public int extractInt32Value(com.alibaba.fastjson2.JSONReader) ,public java.lang.Long extractInt64(com.alibaba.fastjson2.JSONReader) ,public long extractInt64Value(com.alibaba.fastjson2.JSONReader) ,public abstract java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public void extractScalar(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public abstract com.alibaba.fastjson2.JSONPath getParent() ,public com.alibaba.fastjson2.JSONReader.Context getReaderContext() ,public com.alibaba.fastjson2.JSONWriter.Context getWriterContext() ,public boolean isPrevious() ,public abstract boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], java.lang.String[], long[], java.time.ZoneId, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static Map<java.lang.String,java.lang.Object> paths(java.lang.Object) ,public static java.lang.String remove(java.lang.String, java.lang.String) ,public static void remove(java.lang.Object, java.lang.String) ,public abstract boolean remove(java.lang.Object) ,public static java.lang.String set(java.lang.String, java.lang.String, java.lang.Object) ,public static java.lang.Object set(java.lang.Object, java.lang.String, java.lang.Object) ,public abstract void set(java.lang.Object, java.lang.Object) ,public transient abstract void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, Function#RAW) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, BiFunction#RAW) ,public void setCallback(java.lang.Object, Function#RAW) ,public abstract void setCallback(java.lang.Object, BiFunction#RAW) ,public abstract void setInt(java.lang.Object, int) ,public abstract void setLong(java.lang.Object, long) ,public com.alibaba.fastjson2.JSONPath setReaderContext(com.alibaba.fastjson2.JSONReader.Context) ,public com.alibaba.fastjson2.JSONPath setWriterContext(com.alibaba.fastjson2.JSONWriter.Context) ,public final java.lang.String toString() <variables>static final com.alibaba.fastjson2.JSONReader.Context PARSE_CONTEXT,final non-sealed long features,final non-sealed java.lang.String path,com.alibaba.fastjson2.JSONReader.Context readerContext,com.alibaba.fastjson2.JSONWriter.Context writerContext
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMulti.java
|
JSONPathTypedMulti
|
contains
|
class JSONPathTypedMulti
extends JSONPath {
final JSONPath[] paths;
final Type[] types;
final String[] formats;
final long[] pathFeatures;
final ZoneId zoneId;
protected JSONPathTypedMulti(
JSONPath[] paths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features
) {
super(JSON.toJSONString(paths), features);
this.types = types;
this.paths = paths;
this.formats = formats;
this.pathFeatures = pathFeatures;
this.zoneId = zoneId;
}
@Override
public JSONPath getParent() {
return paths[0].getParent();
}
@Override
public boolean isRef() {
for (JSONPath jsonPath : paths) {
if (!jsonPath.isRef()) {
return false;
}
}
return true;
}
@Override
public boolean contains(Object object) {<FILL_FUNCTION_BODY>}
protected final boolean ignoreError(int index) {
return pathFeatures != null
&& index < pathFeatures.length
&& (pathFeatures[index] & Feature.NullOnError.mask) != 0;
}
@Override
public Object eval(Object object) {
Object[] array = new Object[paths.length];
for (int i = 0; i < paths.length; i++) {
JSONPath jsonPath = paths[i];
Object result = jsonPath.eval(object);
try {
array[i] = TypeUtils.cast(result, types[i]);
} catch (Exception e) {
if (!ignoreError(i)) {
throw new JSONException("jsonpath eval path, path : " + jsonPath + ", msg : " + e.getMessage(), e);
}
}
}
return array;
}
protected JSONReader.Context createContext() {
JSONReader.Context context = JSONFactory.createReadContext(features);
if (zoneId != null && zoneId != DEFAULT_ZONE_ID) {
context.zoneId = zoneId;
}
return context;
}
@Override
public Object extract(JSONReader jsonReader) {
Object object = jsonReader.readAny();
return eval(object);
}
@Override
public String extractScalar(JSONReader jsonReader) {
Object object = extract(jsonReader);
return JSON.toJSONString(object);
}
@Override
public void set(Object object, Object value) {
throw new JSONException("unsupported operation");
}
@Override
public void set(Object object, Object value, JSONReader.Feature... readerFeatures) {
throw new JSONException("unsupported operation");
}
@Override
public void setCallback(Object object, BiFunction callback) {
throw new JSONException("unsupported operation");
}
@Override
public void setInt(Object object, int value) {
throw new JSONException("unsupported operation");
}
@Override
public void setLong(Object object, long value) {
throw new JSONException("unsupported operation");
}
@Override
public boolean remove(Object object) {
throw new JSONException("unsupported operation");
}
}
|
for (JSONPath jsonPath : paths) {
if (jsonPath.contains(object)) {
return true;
}
}
return false;
| 845
| 43
| 888
|
<methods>public transient void arrayAdd(java.lang.Object, java.lang.Object[]) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath compile(java.lang.String, Class#RAW) ,public static boolean contains(java.lang.Object, java.lang.String) ,public abstract boolean contains(java.lang.Object) ,public boolean endsWithFilter() ,public static java.lang.Object eval(java.lang.String, java.lang.String) ,public static java.lang.Object eval(java.lang.Object, java.lang.String) ,public abstract java.lang.Object eval(java.lang.Object) ,public static java.lang.Object extract(java.lang.String, java.lang.String) ,public static transient java.lang.Object extract(java.lang.String, java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public java.lang.Object extract(java.lang.String) ,public java.lang.Object extract(byte[]) ,public java.lang.Object extract(byte[], int, int, java.nio.charset.Charset) ,public abstract java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public void extract(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public java.lang.Integer extractInt32(com.alibaba.fastjson2.JSONReader) ,public int extractInt32Value(com.alibaba.fastjson2.JSONReader) ,public java.lang.Long extractInt64(com.alibaba.fastjson2.JSONReader) ,public long extractInt64Value(com.alibaba.fastjson2.JSONReader) ,public abstract java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public void extractScalar(com.alibaba.fastjson2.JSONReader, com.alibaba.fastjson2.reader.ValueConsumer) ,public abstract com.alibaba.fastjson2.JSONPath getParent() ,public com.alibaba.fastjson2.JSONReader.Context getReaderContext() ,public com.alibaba.fastjson2.JSONWriter.Context getWriterContext() ,public boolean isPrevious() ,public abstract boolean isRef() ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, java.lang.reflect.Type, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String[], java.lang.reflect.Type[], java.lang.String[], long[], java.time.ZoneId, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static transient com.alibaba.fastjson2.JSONPath of(java.lang.String, com.alibaba.fastjson2.JSONPath.Feature[]) ,public static Map<java.lang.String,java.lang.Object> paths(java.lang.Object) ,public static java.lang.String remove(java.lang.String, java.lang.String) ,public static void remove(java.lang.Object, java.lang.String) ,public abstract boolean remove(java.lang.Object) ,public static java.lang.String set(java.lang.String, java.lang.String, java.lang.Object) ,public static java.lang.Object set(java.lang.Object, java.lang.String, java.lang.Object) ,public abstract void set(java.lang.Object, java.lang.Object) ,public transient abstract void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, Function#RAW) ,public static java.lang.Object setCallback(java.lang.Object, java.lang.String, BiFunction#RAW) ,public void setCallback(java.lang.Object, Function#RAW) ,public abstract void setCallback(java.lang.Object, BiFunction#RAW) ,public abstract void setInt(java.lang.Object, int) ,public abstract void setLong(java.lang.Object, long) ,public com.alibaba.fastjson2.JSONPath setReaderContext(com.alibaba.fastjson2.JSONReader.Context) ,public com.alibaba.fastjson2.JSONPath setWriterContext(com.alibaba.fastjson2.JSONWriter.Context) ,public final java.lang.String toString() <variables>static final com.alibaba.fastjson2.JSONReader.Context PARSE_CONTEXT,final non-sealed long features,final non-sealed java.lang.String path,com.alibaba.fastjson2.JSONReader.Context readerContext,com.alibaba.fastjson2.JSONWriter.Context writerContext
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMultiIndexes.java
|
JSONPathTypedMultiIndexes
|
extract
|
class JSONPathTypedMultiIndexes
extends JSONPathTypedMulti {
final JSONPath prefix;
final JSONPath[] indexPaths;
final int[] indexes;
final int maxIndex;
final boolean duplicate;
JSONPathTypedMultiIndexes(
JSONPath[] paths,
JSONPath prefix,
JSONPath[] indexPaths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features
) {
super(paths, types, formats, pathFeatures, zoneId, features);
this.prefix = prefix;
this.indexPaths = indexPaths;
int[] indexes = new int[paths.length];
for (int i = 0; i < indexPaths.length; i++) {
JSONPathSingleIndex indexPath = (JSONPathSingleIndex) indexPaths[i];
indexes[i] = indexPath.index;
}
this.indexes = indexes;
boolean duplicate = false;
int maxIndex = -1;
for (int i = 0; i < indexes.length; i++) {
int index = indexes[i];
if (i == 0) {
maxIndex = index;
} else {
maxIndex = Math.max(maxIndex, index);
}
for (int j = 0; j < indexes.length && !duplicate; j++) {
if (j != i && index == indexes[j]) {
duplicate = true;
break;
}
}
}
this.duplicate = duplicate;
this.maxIndex = maxIndex;
}
@Override
public Object eval(Object root) {
Object[] array = new Object[paths.length];
Object object = root;
if (prefix != null) {
object = prefix.eval(root);
}
if (object == null) {
return array;
}
if (object instanceof List) {
List list = (List) object;
for (int i = 0; i < indexes.length; i++) {
int index = indexes[i];
Object result = index < list.size() ? list.get(index) : null;
Type type = types[i];
try {
if (result != null && result.getClass() != type) {
if (type == Long.class) {
result = TypeUtils.toLong(result);
} else if (type == BigDecimal.class) {
result = TypeUtils.toBigDecimal(result);
} else if (type == String[].class) {
result = TypeUtils.toStringArray(result);
} else {
result = TypeUtils.cast(result, type);
}
}
array[i] = result;
} catch (Exception e) {
if (!ignoreError(i)) {
throw new JSONException("jsonpath eval path, path : " + paths[i] + ", msg : " + e.getMessage(), e);
}
}
}
} else {
for (int i = 0; i < paths.length; i++) {
JSONPath jsonPath = indexPaths[i];
Type type = types[i];
try {
Object result = jsonPath.eval(object);
if (result != null && result.getClass() != type) {
if (type == Long.class) {
result = TypeUtils.toLong(result);
} else if (type == BigDecimal.class) {
result = TypeUtils.toBigDecimal(result);
} else if (type == String[].class) {
result = TypeUtils.toStringArray(result);
} else {
result = TypeUtils.cast(result, type);
}
}
array[i] = result;
} catch (Exception e) {
if (!ignoreError(i)) {
throw new JSONException("jsonpath eval path, path : " + paths[i] + ", msg : " + e.getMessage(), e);
}
}
}
}
return array;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.nextIfNull()) {
return new Object[indexes.length];
}
if (prefix instanceof JSONPathSingleName) {
JSONPathSingleName prefixName = (JSONPathSingleName) prefix;
long prefixNameHash = prefixName.nameHashCode;
if (!jsonReader.nextIfObjectStart()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
while (!jsonReader.nextIfObjectEnd()) {
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == prefixNameHash;
if (!match) {
jsonReader.skipValue();
continue;
}
break;
}
if (jsonReader.nextIfNull()) {
return new Object[indexes.length];
}
} else if (prefix instanceof JSONPathSingleIndex) {
int index = ((JSONPathSingleIndex) prefix).index;
int max = jsonReader.startArray();
for (int i = 0; i < index && i < max; i++) {
jsonReader.skipValue();
}
if (jsonReader.nextIfNull()) {
return null;
}
} else if (prefix != null) {
Object object = jsonReader.readAny();
return eval(object);
}
int max = jsonReader.startArray();
Object[] array = new Object[indexes.length];
for (int i = 0; i <= maxIndex && i < max; ++i) {
if ((!jsonReader.jsonb) && jsonReader.nextIfArrayEnd()) {
break;
}
Integer index = null;
for (int j = 0; j < indexes.length; j++) {
if (indexes[j] == i) {
index = j;
break;
}
}
if (index == null) {
jsonReader.skipValue();
continue;
}
Type type = types[index];
Object value;
try {
value = jsonReader.read(type);
} catch (Exception e) {
if (!ignoreError(index)) {
throw e;
}
value = null;
}
array[index] = value;
if (!duplicate) {
continue;
}
for (int j = index + 1; j < indexes.length; j++) {
if (indexes[j] == i) {
Type typeJ = types[j];
Object valueJ;
if (typeJ == type) {
valueJ = value;
} else {
valueJ = TypeUtils.cast(value, typeJ);
}
array[j] = valueJ;
}
}
}
return array;
| 1,050
| 706
| 1,756
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public boolean isRef() ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed java.lang.String[] formats,final non-sealed long[] pathFeatures,final non-sealed com.alibaba.fastjson2.JSONPath[] paths,final non-sealed java.lang.reflect.Type[] types,final non-sealed java.time.ZoneId zoneId
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMultiNames.java
|
JSONPathTypedMultiNames
|
eval
|
class JSONPathTypedMultiNames
extends JSONPathTypedMulti {
final JSONPath prefix;
final JSONPath[] namePaths;
final String[] names;
final FieldReader[] fieldReaders;
final ObjectReaderAdapter<Object[]> objectReader;
JSONPathTypedMultiNames(
JSONPath[] paths,
JSONPath prefix,
JSONPath[] namePaths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features
) {
super(paths, types, formats, pathFeatures, zoneId, features);
this.prefix = prefix;
this.namePaths = namePaths;
this.names = new String[paths.length];
for (int i = 0; i < paths.length; i++) {
JSONPathSingleName jsonPathSingleName = (JSONPathSingleName) namePaths[i];
String fieldName = jsonPathSingleName.name;
names[i] = fieldName;
}
long[] fieldReaderFeatures = new long[names.length];
if (pathFeatures != null) {
for (int i = 0; i < pathFeatures.length; i++) {
if ((pathFeatures[i] & Feature.NullOnError.mask) != 0) {
fieldReaderFeatures[i] |= JSONReader.Feature.NullOnError.mask;
}
}
}
Type[] fieldTypes = types.clone();
for (int i = 0; i < fieldTypes.length; i++) {
Type fieldType = fieldTypes[i];
if (fieldType == boolean.class) {
fieldTypes[i] = Boolean.class;
} else if (fieldType == char.class) {
fieldTypes[i] = Character.class;
} else if (fieldType == byte.class) {
fieldTypes[i] = Byte.class;
} else if (fieldType == short.class) {
fieldTypes[i] = Short.class;
} else if (fieldType == int.class) {
fieldTypes[i] = Integer.class;
} else if (fieldType == long.class) {
fieldTypes[i] = Long.class;
} else if (fieldType == float.class) {
fieldTypes[i] = Float.class;
} else if (fieldType == double.class) {
fieldTypes[i] = Double.class;
}
}
final int length = names.length;
objectReader = (ObjectReaderAdapter<Object[]>) JSONFactory.getDefaultObjectReaderProvider()
.createObjectReader(
names,
fieldTypes,
fieldReaderFeatures,
() -> new Object[length],
(o, i, v) -> o[i] = v
);
this.fieldReaders = objectReader.getFieldReaders();
}
@Override
public boolean isRef() {
return true;
}
@Override
public Object eval(Object root) {<FILL_FUNCTION_BODY>}
@Override
public Object extract(JSONReader jsonReader) {
if (prefix != null) {
Object object = jsonReader.readAny();
return eval(object);
}
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfObjectStart()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
return objectReader.readObject(jsonReader, null, null, 0);
}
}
|
Object[] array = new Object[paths.length];
Object object = root;
if (prefix != null) {
object = prefix.eval(root);
}
if (object == null) {
return new Object[paths.length];
}
if (object instanceof Map) {
return objectReader.createInstance((Map) object, 0);
} else {
ObjectWriter objectReader = JSONFactory.defaultObjectWriterProvider
.getObjectWriter(
object.getClass()
);
for (int i = 0; i < names.length; i++) {
FieldWriter fieldWriter = objectReader.getFieldWriter(names[i]);
if (fieldWriter == null) {
continue;
}
Object result = fieldWriter.getFieldValue(object);
Type type = types[i];
if (result != null && result.getClass() != type) {
if (type == Long.class) {
result = TypeUtils.toLong(result);
} else if (type == BigDecimal.class) {
result = TypeUtils.toBigDecimal(result);
} else if (type == String[].class) {
result = TypeUtils.toStringArray(result);
} else {
result = TypeUtils.cast(result, type);
}
}
array[i] = result;
}
}
return array;
| 902
| 354
| 1,256
|
<methods>public boolean contains(java.lang.Object) ,public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public java.lang.String extractScalar(com.alibaba.fastjson2.JSONReader) ,public com.alibaba.fastjson2.JSONPath getParent() ,public boolean isRef() ,public boolean remove(java.lang.Object) ,public void set(java.lang.Object, java.lang.Object) ,public transient void set(java.lang.Object, java.lang.Object, com.alibaba.fastjson2.JSONReader.Feature[]) ,public void setCallback(java.lang.Object, BiFunction#RAW) ,public void setInt(java.lang.Object, int) ,public void setLong(java.lang.Object, long) <variables>final non-sealed java.lang.String[] formats,final non-sealed long[] pathFeatures,final non-sealed com.alibaba.fastjson2.JSONPath[] paths,final non-sealed java.lang.reflect.Type[] types,final non-sealed java.time.ZoneId zoneId
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMultiNamesPrefixIndex1.java
|
JSONPathTypedMultiNamesPrefixIndex1
|
extract
|
class JSONPathTypedMultiNamesPrefixIndex1
extends JSONPathTypedMultiNames {
final int index;
JSONPathTypedMultiNamesPrefixIndex1(
JSONPath[] paths,
JSONPathSingleIndex prefix,
JSONPath[] namePaths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features) {
super(paths, prefix, namePaths, types, formats, pathFeatures, zoneId, features);
index = prefix.index;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfArrayStart()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
for (int i = 0; i < index; ++i) {
if (jsonReader.nextIfArrayEnd()) {
return new Object[paths.length];
}
if (jsonReader.isEnd()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
jsonReader.skipValue();
}
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (jsonReader.nextIfArrayEnd()) {
return new Object[paths.length];
}
return objectReader.readObject(jsonReader);
| 162
| 238
| 400
|
<methods>public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public boolean isRef() <variables>final non-sealed FieldReader#RAW[] fieldReaders,final non-sealed com.alibaba.fastjson2.JSONPath[] namePaths,final non-sealed java.lang.String[] names,final non-sealed ObjectReaderAdapter<java.lang.Object[]> objectReader,final non-sealed com.alibaba.fastjson2.JSONPath prefix
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMultiNamesPrefixName1.java
|
JSONPathTypedMultiNamesPrefixName1
|
extract
|
class JSONPathTypedMultiNamesPrefixName1
extends JSONPathTypedMultiNames {
final JSONPathSingleName prefixName;
final long prefixNameHash;
JSONPathTypedMultiNamesPrefixName1(
JSONPath[] paths,
JSONPath prefix,
JSONPath[] namePaths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features) {
super(paths, prefix, namePaths, types, formats, pathFeatures, zoneId, features);
prefixName = (JSONPathSingleName) prefix;
prefixNameHash = prefixName.nameHashCode;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
}
|
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfObjectStart()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
while (true) {
if (jsonReader.nextIfObjectEnd()) {
return new Object[paths.length];
}
if (jsonReader.isEnd()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
long nameHashCode = jsonReader.readFieldNameHashCode();
boolean match = nameHashCode == prefixNameHash;
if (!match) {
jsonReader.skipValue();
continue;
}
break;
}
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfObjectStart()) {
throw new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
return objectReader.readObject(jsonReader);
| 190
| 294
| 484
|
<methods>public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public boolean isRef() <variables>final non-sealed FieldReader#RAW[] fieldReaders,final non-sealed com.alibaba.fastjson2.JSONPath[] namePaths,final non-sealed java.lang.String[] names,final non-sealed ObjectReaderAdapter<java.lang.Object[]> objectReader,final non-sealed com.alibaba.fastjson2.JSONPath prefix
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONPathTypedMultiNamesPrefixName2.java
|
JSONPathTypedMultiNamesPrefixName2
|
extract
|
class JSONPathTypedMultiNamesPrefixName2
extends JSONPathTypedMultiNames {
final String prefixName0;
final long prefixNameHash0;
final String prefixName1;
final long prefixNameHash1;
JSONPathTypedMultiNamesPrefixName2(
JSONPath[] paths,
JSONPath prefix,
JSONPath[] namePaths,
Type[] types,
String[] formats,
long[] pathFeatures,
ZoneId zoneId,
long features) {
super(paths, prefix, namePaths, types, formats, pathFeatures, zoneId, features);
JSONPathTwoSegment prefixTwo = (JSONPathTwoSegment) prefix;
prefixName0 = ((JSONPathSegmentName) prefixTwo.first).name;
prefixNameHash0 = ((JSONPathSegmentName) prefixTwo.first).nameHashCode;
prefixName1 = ((JSONPathSegmentName) prefixTwo.second).name;
prefixNameHash1 = ((JSONPathSegmentName) prefixTwo.second).nameHashCode;
}
@Override
public Object extract(JSONReader jsonReader) {<FILL_FUNCTION_BODY>}
private static JSONException error(JSONReader jsonReader) {
return new JSONException(jsonReader.info("illegal input, expect '[', but " + jsonReader.current()));
}
}
|
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfObjectStart()) {
throw error(jsonReader);
}
while (true) {
if (jsonReader.nextIfObjectEnd()) {
return new Object[paths.length];
}
if (jsonReader.isEnd()) {
throw error(jsonReader);
}
boolean match = jsonReader.readFieldNameHashCode() == prefixNameHash0;
if (!match) {
jsonReader.skipValue();
continue;
}
break;
}
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
if (!jsonReader.nextIfObjectStart()) {
throw error(jsonReader);
}
while (true) {
if (jsonReader.nextIfObjectEnd()) {
return new Object[paths.length];
}
if (jsonReader.isEnd()) {
throw error(jsonReader);
}
boolean match = jsonReader.readFieldNameHashCode() == prefixNameHash1;
if (!match) {
jsonReader.skipValue();
continue;
}
break;
}
if (jsonReader.nextIfNull()) {
return new Object[paths.length];
}
return objectReader.readObject(jsonReader);
| 328
| 359
| 687
|
<methods>public java.lang.Object eval(java.lang.Object) ,public java.lang.Object extract(com.alibaba.fastjson2.JSONReader) ,public boolean isRef() <variables>final non-sealed FieldReader#RAW[] fieldReaders,final non-sealed com.alibaba.fastjson2.JSONPath[] namePaths,final non-sealed java.lang.String[] names,final non-sealed ObjectReaderAdapter<java.lang.Object[]> objectReader,final non-sealed com.alibaba.fastjson2.JSONPath prefix
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONValidator.java
|
JSONValidator
|
validate
|
class JSONValidator {
public enum Type {
Object, Array, Value
}
private final JSONReader jsonReader;
private Boolean validateResult;
private Type type;
protected JSONValidator(JSONReader jsonReader) {
this.jsonReader = jsonReader;
}
public static JSONValidator fromUtf8(byte[] jsonBytes) {
return new JSONValidator(JSONReader.of(jsonBytes));
}
public static JSONValidator from(String jsonStr) {
return new JSONValidator(JSONReader.of(jsonStr));
}
public static JSONValidator from(JSONReader jsonReader) {
return new JSONValidator(jsonReader);
}
public boolean validate() {<FILL_FUNCTION_BODY>}
public Type getType() {
if (type == null) {
validate();
}
return type;
}
}
|
if (validateResult != null) {
return validateResult;
}
char firstChar;
try {
firstChar = jsonReader.current();
jsonReader.skipValue();
} catch (JSONException error) {
return validateResult = false;
} finally {
jsonReader.close();
}
if (firstChar == '{') {
type = Type.Object;
} else if (firstChar == '[') {
type = Type.Array;
} else {
type = Type.Value;
}
return validateResult = jsonReader.isEnd();
| 222
| 155
| 377
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8.java
|
JSONWriterUTF16JDK8
|
writeString
|
class JSONWriterUTF16JDK8
extends JSONWriterUTF16 {
JSONWriterUTF16JDK8(Context ctx) {
super(ctx);
}
@Override
public void writeString(String str) {<FILL_FUNCTION_BODY>}
}
|
if (str == null) {
if (isEnabled(Feature.NullAsDefaultValue.mask | Feature.WriteNullStringAsEmpty.mask)) {
writeString("");
return;
}
writeNull();
return;
}
boolean browserSecure = (context.features & BrowserSecure.mask) != 0;
boolean escapeNoneAscii = (context.features & EscapeNoneAscii.mask) != 0;
char[] value = JDKUtils.getCharArray(str);
final int strlen = value.length;
boolean escape = false;
for (int i = 0; i < value.length; i++) {
char ch = value[i];
if (ch == quote || ch == '\\' || ch < ' '
|| (browserSecure && (ch == '<' || ch == '>' || ch == '(' || ch == ')'))
|| (escapeNoneAscii && ch > 0x007F)
) {
escape = true;
break;
}
}
if (!escape) {
// inline ensureCapacity(off + strlen + 2);
int minCapacity = off + strlen + 2;
if (minCapacity >= chars.length) {
ensureCapacity(minCapacity);
}
chars[off++] = quote;
System.arraycopy(value, 0, chars, off, value.length);
off += strlen;
chars[off++] = quote;
return;
}
writeStringEscape(str);
| 73
| 399
| 472
|
<methods>public final void close() ,public final void endArray() ,public final void endObject() ,public final void flushTo(java.io.Writer) ,public final int flushTo(java.io.OutputStream) throws java.io.IOException,public final int flushTo(java.io.OutputStream, java.nio.charset.Charset) throws java.io.IOException,public final byte[] getBytes() ,public final byte[] getBytes(java.nio.charset.Charset) ,public final int size() ,public final void startArray() ,public final void startObject() ,public final java.lang.String toString() ,public final void write(com.alibaba.fastjson2.JSONObject) ,public final void write(List#RAW) ,public final void writeBase64(byte[]) ,public final void writeBigInt(java.math.BigInteger, long) ,public void writeBool(boolean) ,public final void writeChar(char) ,public final void writeColon() ,public final void writeComma() ,public final void writeDateTime14(int, int, int, int, int, int) ,public final void writeDateTime19(int, int, int, int, int, int) ,public final void writeDateTimeISO8601(int, int, int, int, int, int, int, int, boolean) ,public final void writeDateYYYMMDD10(int, int, int) ,public final void writeDateYYYMMDD8(int, int, int) ,public final void writeDecimal(java.math.BigDecimal, long, java.text.DecimalFormat) ,public final void writeDouble(double) ,public final void writeDouble(double[]) ,public final void writeDoubleArray(double, double) ,public final void writeFloat(float) ,public final void writeFloat(float[]) ,public final void writeHex(byte[]) ,public final void writeInt16(short) ,public final void writeInt32(int[]) ,public final void writeInt32(int) ,public final void writeInt32(java.lang.Integer) ,public final void writeInt64(long[]) ,public final void writeInt64(long) ,public final void writeInt64(java.lang.Long) ,public final void writeInt8(byte) ,public final void writeInt8(byte[]) ,public final void writeListInt32(List<java.lang.Integer>) ,public final void writeListInt64(List<java.lang.Long>) ,public final void writeLocalDate(java.time.LocalDate) ,public final void writeLocalDateTime(java.time.LocalDateTime) ,public final void writeLocalTime(java.time.LocalTime) ,public final void writeName10Raw(long, long) ,public final void writeName11Raw(long, long) ,public final void writeName12Raw(long, long) ,public final void writeName13Raw(long, long) ,public final void writeName14Raw(long, long) ,public final void writeName15Raw(long, long) ,public final void writeName16Raw(long, long) ,public final void writeName2Raw(long) ,public final void writeName3Raw(long) ,public final void writeName4Raw(long) ,public final void writeName5Raw(long) ,public final void writeName6Raw(long) ,public final void writeName7Raw(long) ,public final void writeName8Raw(long) ,public final void writeName9Raw(long, int) ,public final void writeNameRaw(char[]) ,public final void writeNameRaw(char[], int, int) ,public final void writeNameRaw(byte[]) ,public final void writeNull() ,public final void writeOffsetDateTime(java.time.OffsetDateTime) ,public final void writeOffsetTime(java.time.OffsetTime) ,public final void writeRaw(java.lang.String) ,public final void writeRaw(char[], int, int) ,public final void writeRaw(char) ,public final void writeRaw(char, char) ,public final void writeRaw(byte[]) ,public final void writeReference(java.lang.String) ,public final void writeString(List<java.lang.String>) ,public void writeString(java.lang.String) ,public final void writeString(char[], int, int, boolean) ,public final void writeString(java.lang.String[]) ,public final void writeString(boolean) ,public final void writeString(byte) ,public final void writeString(short) ,public final void writeString(int) ,public final void writeString(long) ,public final void writeString(char[]) ,public final void writeString(char[], int, int) ,public void writeStringLatin1(byte[]) ,public void writeStringUTF16(byte[]) ,public final void writeTimeHHMMSS8(int, int, int) ,public final void writeUUID(java.util.UUID) ,public final void writeZonedDateTime(java.time.ZonedDateTime) <variables>static final non-sealed int[] HEX256,static final char[] REF_PREF,final non-sealed com.alibaba.fastjson2.JSONFactory.CacheItem cacheItem,protected char[] chars
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK8UF.java
|
JSONWriterUTF16JDK8UF
|
writeString
|
class JSONWriterUTF16JDK8UF
extends JSONWriterUTF16 {
JSONWriterUTF16JDK8UF(Context ctx) {
super(ctx);
}
@Override
public void writeString(String str) {<FILL_FUNCTION_BODY>}
}
|
if (str == null) {
writeStringNull();
return;
}
boolean browserSecure = (context.features & BrowserSecure.mask) != 0;
boolean escapeNoneAscii = (context.features & EscapeNoneAscii.mask) != 0;
char[] value = (char[]) UNSAFE.getObject(str, JDKUtils.FIELD_STRING_VALUE_OFFSET);
final int strlen = value.length;
boolean escape = false;
for (int i = 0; i < value.length; i++) {
char ch = value[i];
if (ch == quote || ch == '\\' || ch < ' '
|| (browserSecure && (ch == '<' || ch == '>' || ch == '(' || ch == ')'))
|| (escapeNoneAscii && ch > 0x007F)
) {
escape = true;
break;
}
}
if (!escape) {
int off = this.off;
// inline ensureCapacity(off + strlen + 2);
int minCapacity = off + strlen + 2;
if (minCapacity >= chars.length) {
ensureCapacity(minCapacity);
}
final char[] chars = this.chars;
chars[off++] = quote;
System.arraycopy(value, 0, chars, off, value.length);
off += strlen;
chars[off] = quote;
this.off = off + 1;
return;
}
writeStringEscape(str);
| 77
| 407
| 484
|
<methods>public final void close() ,public final void endArray() ,public final void endObject() ,public final void flushTo(java.io.Writer) ,public final int flushTo(java.io.OutputStream) throws java.io.IOException,public final int flushTo(java.io.OutputStream, java.nio.charset.Charset) throws java.io.IOException,public final byte[] getBytes() ,public final byte[] getBytes(java.nio.charset.Charset) ,public final int size() ,public final void startArray() ,public final void startObject() ,public final java.lang.String toString() ,public final void write(com.alibaba.fastjson2.JSONObject) ,public final void write(List#RAW) ,public final void writeBase64(byte[]) ,public final void writeBigInt(java.math.BigInteger, long) ,public void writeBool(boolean) ,public final void writeChar(char) ,public final void writeColon() ,public final void writeComma() ,public final void writeDateTime14(int, int, int, int, int, int) ,public final void writeDateTime19(int, int, int, int, int, int) ,public final void writeDateTimeISO8601(int, int, int, int, int, int, int, int, boolean) ,public final void writeDateYYYMMDD10(int, int, int) ,public final void writeDateYYYMMDD8(int, int, int) ,public final void writeDecimal(java.math.BigDecimal, long, java.text.DecimalFormat) ,public final void writeDouble(double) ,public final void writeDouble(double[]) ,public final void writeDoubleArray(double, double) ,public final void writeFloat(float) ,public final void writeFloat(float[]) ,public final void writeHex(byte[]) ,public final void writeInt16(short) ,public final void writeInt32(int[]) ,public final void writeInt32(int) ,public final void writeInt32(java.lang.Integer) ,public final void writeInt64(long[]) ,public final void writeInt64(long) ,public final void writeInt64(java.lang.Long) ,public final void writeInt8(byte) ,public final void writeInt8(byte[]) ,public final void writeListInt32(List<java.lang.Integer>) ,public final void writeListInt64(List<java.lang.Long>) ,public final void writeLocalDate(java.time.LocalDate) ,public final void writeLocalDateTime(java.time.LocalDateTime) ,public final void writeLocalTime(java.time.LocalTime) ,public final void writeName10Raw(long, long) ,public final void writeName11Raw(long, long) ,public final void writeName12Raw(long, long) ,public final void writeName13Raw(long, long) ,public final void writeName14Raw(long, long) ,public final void writeName15Raw(long, long) ,public final void writeName16Raw(long, long) ,public final void writeName2Raw(long) ,public final void writeName3Raw(long) ,public final void writeName4Raw(long) ,public final void writeName5Raw(long) ,public final void writeName6Raw(long) ,public final void writeName7Raw(long) ,public final void writeName8Raw(long) ,public final void writeName9Raw(long, int) ,public final void writeNameRaw(char[]) ,public final void writeNameRaw(char[], int, int) ,public final void writeNameRaw(byte[]) ,public final void writeNull() ,public final void writeOffsetDateTime(java.time.OffsetDateTime) ,public final void writeOffsetTime(java.time.OffsetTime) ,public final void writeRaw(java.lang.String) ,public final void writeRaw(char[], int, int) ,public final void writeRaw(char) ,public final void writeRaw(char, char) ,public final void writeRaw(byte[]) ,public final void writeReference(java.lang.String) ,public final void writeString(List<java.lang.String>) ,public void writeString(java.lang.String) ,public final void writeString(char[], int, int, boolean) ,public final void writeString(java.lang.String[]) ,public final void writeString(boolean) ,public final void writeString(byte) ,public final void writeString(short) ,public final void writeString(int) ,public final void writeString(long) ,public final void writeString(char[]) ,public final void writeString(char[], int, int) ,public void writeStringLatin1(byte[]) ,public void writeStringUTF16(byte[]) ,public final void writeTimeHHMMSS8(int, int, int) ,public final void writeUUID(java.util.UUID) ,public final void writeZonedDateTime(java.time.ZonedDateTime) <variables>static final non-sealed int[] HEX256,static final char[] REF_PREF,final non-sealed com.alibaba.fastjson2.JSONFactory.CacheItem cacheItem,protected char[] chars
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF16JDK9UF.java
|
JSONWriterUTF16JDK9UF
|
writeString
|
class JSONWriterUTF16JDK9UF
extends JSONWriterUTF16 {
JSONWriterUTF16JDK9UF(Context ctx) {
super(ctx);
}
@Override
public void writeString(String str) {<FILL_FUNCTION_BODY>}
}
|
if (str == null) {
writeStringNull();
return;
}
boolean escapeNoneAscii = (context.features & Feature.EscapeNoneAscii.mask) != 0;
boolean browserSecure = (context.features & BrowserSecure.mask) != 0;
boolean escape = false;
final char quote = this.quote;
final int strlen = str.length();
int minCapacity = off + strlen + 2;
if (minCapacity >= chars.length) {
ensureCapacity(minCapacity);
}
final int coder = STRING_CODER.applyAsInt(str);
final byte[] value = STRING_VALUE.apply(str);
int off = this.off;
final char[] chars = this.chars;
chars[off++] = quote;
for (int i = 0; i < strlen; ++i) {
int c;
if (coder == 0) {
c = value[i];
} else {
c = UNSAFE.getChar(str, (long) Unsafe.ARRAY_CHAR_BASE_OFFSET + i * 2);
}
if (c == '\\'
|| c == quote
|| c < ' '
|| (browserSecure && (c == '<' || c == '>' || c == '(' || c == ')'))
|| (escapeNoneAscii && c > 0x007F)
) {
escape = true;
break;
}
chars[off++] = (char) c;
}
if (!escape) {
chars[off++] = quote;
this.off = off;
return;
}
writeStringEscape(str);
| 77
| 454
| 531
|
<methods>public final void close() ,public final void endArray() ,public final void endObject() ,public final void flushTo(java.io.Writer) ,public final int flushTo(java.io.OutputStream) throws java.io.IOException,public final int flushTo(java.io.OutputStream, java.nio.charset.Charset) throws java.io.IOException,public final byte[] getBytes() ,public final byte[] getBytes(java.nio.charset.Charset) ,public final int size() ,public final void startArray() ,public final void startObject() ,public final java.lang.String toString() ,public final void write(com.alibaba.fastjson2.JSONObject) ,public final void write(List#RAW) ,public final void writeBase64(byte[]) ,public final void writeBigInt(java.math.BigInteger, long) ,public void writeBool(boolean) ,public final void writeChar(char) ,public final void writeColon() ,public final void writeComma() ,public final void writeDateTime14(int, int, int, int, int, int) ,public final void writeDateTime19(int, int, int, int, int, int) ,public final void writeDateTimeISO8601(int, int, int, int, int, int, int, int, boolean) ,public final void writeDateYYYMMDD10(int, int, int) ,public final void writeDateYYYMMDD8(int, int, int) ,public final void writeDecimal(java.math.BigDecimal, long, java.text.DecimalFormat) ,public final void writeDouble(double) ,public final void writeDouble(double[]) ,public final void writeDoubleArray(double, double) ,public final void writeFloat(float) ,public final void writeFloat(float[]) ,public final void writeHex(byte[]) ,public final void writeInt16(short) ,public final void writeInt32(int[]) ,public final void writeInt32(int) ,public final void writeInt32(java.lang.Integer) ,public final void writeInt64(long[]) ,public final void writeInt64(long) ,public final void writeInt64(java.lang.Long) ,public final void writeInt8(byte) ,public final void writeInt8(byte[]) ,public final void writeListInt32(List<java.lang.Integer>) ,public final void writeListInt64(List<java.lang.Long>) ,public final void writeLocalDate(java.time.LocalDate) ,public final void writeLocalDateTime(java.time.LocalDateTime) ,public final void writeLocalTime(java.time.LocalTime) ,public final void writeName10Raw(long, long) ,public final void writeName11Raw(long, long) ,public final void writeName12Raw(long, long) ,public final void writeName13Raw(long, long) ,public final void writeName14Raw(long, long) ,public final void writeName15Raw(long, long) ,public final void writeName16Raw(long, long) ,public final void writeName2Raw(long) ,public final void writeName3Raw(long) ,public final void writeName4Raw(long) ,public final void writeName5Raw(long) ,public final void writeName6Raw(long) ,public final void writeName7Raw(long) ,public final void writeName8Raw(long) ,public final void writeName9Raw(long, int) ,public final void writeNameRaw(char[]) ,public final void writeNameRaw(char[], int, int) ,public final void writeNameRaw(byte[]) ,public final void writeNull() ,public final void writeOffsetDateTime(java.time.OffsetDateTime) ,public final void writeOffsetTime(java.time.OffsetTime) ,public final void writeRaw(java.lang.String) ,public final void writeRaw(char[], int, int) ,public final void writeRaw(char) ,public final void writeRaw(char, char) ,public final void writeRaw(byte[]) ,public final void writeReference(java.lang.String) ,public final void writeString(List<java.lang.String>) ,public void writeString(java.lang.String) ,public final void writeString(char[], int, int, boolean) ,public final void writeString(java.lang.String[]) ,public final void writeString(boolean) ,public final void writeString(byte) ,public final void writeString(short) ,public final void writeString(int) ,public final void writeString(long) ,public final void writeString(char[]) ,public final void writeString(char[], int, int) ,public void writeStringLatin1(byte[]) ,public void writeStringUTF16(byte[]) ,public final void writeTimeHHMMSS8(int, int, int) ,public final void writeUUID(java.util.UUID) ,public final void writeZonedDateTime(java.time.ZonedDateTime) <variables>static final non-sealed int[] HEX256,static final char[] REF_PREF,final non-sealed com.alibaba.fastjson2.JSONFactory.CacheItem cacheItem,protected char[] chars
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/JSONWriterUTF8JDK9.java
|
JSONWriterUTF8JDK9
|
writeString
|
class JSONWriterUTF8JDK9
extends JSONWriterUTF8 {
JSONWriterUTF8JDK9(Context ctx) {
super(ctx);
}
@Override
public void writeString(String str) {<FILL_FUNCTION_BODY>}
}
|
if (str == null) {
writeStringNull();
return;
}
int coder = STRING_CODER.applyAsInt(str);
byte[] value = STRING_VALUE.apply(str);
if (coder == 0) {
writeStringLatin1(value);
} else {
writeStringUTF16(value);
}
| 70
| 98
| 168
|
<methods>public final void close() ,public final void endArray() ,public final void endObject() ,public final int flushTo(java.io.OutputStream) throws java.io.IOException,public final int flushTo(java.io.OutputStream, java.nio.charset.Charset) throws java.io.IOException,public final byte[] getBytes() ,public final byte[] getBytes(java.nio.charset.Charset) ,public final int size() ,public final void startArray() ,public final void startObject() ,public final java.lang.String toString() ,public final void write(com.alibaba.fastjson2.JSONObject) ,public final void write(List#RAW) ,public final void writeBase64(byte[]) ,public final void writeBigInt(java.math.BigInteger, long) ,public void writeBool(boolean) ,public final void writeChar(char) ,public final void writeColon() ,public final void writeComma() ,public final void writeDateTime14(int, int, int, int, int, int) ,public final void writeDateTime19(int, int, int, int, int, int) ,public final void writeDateTimeISO8601(int, int, int, int, int, int, int, int, boolean) ,public final void writeDateYYYMMDD10(int, int, int) ,public final void writeDateYYYMMDD8(int, int, int) ,public final void writeDecimal(java.math.BigDecimal, long, java.text.DecimalFormat) ,public final void writeDouble(double) ,public final void writeDouble(double[]) ,public final void writeFloat(float) ,public final void writeFloat(float[]) ,public final void writeHex(byte[]) ,public final void writeInt16(short) ,public final void writeInt32(int[]) ,public final void writeInt32(java.lang.Integer) ,public final void writeInt32(int) ,public final void writeInt64(long[]) ,public final void writeInt64(long) ,public final void writeInt64(java.lang.Long) ,public final void writeInt8(byte) ,public final void writeInt8(byte[]) ,public final void writeListInt32(List<java.lang.Integer>) ,public final void writeListInt64(List<java.lang.Long>) ,public final void writeLocalDate(java.time.LocalDate) ,public final void writeLocalDateTime(java.time.LocalDateTime) ,public final void writeLocalTime(java.time.LocalTime) ,public final void writeName10Raw(long, long) ,public final void writeName11Raw(long, long) ,public final void writeName12Raw(long, long) ,public final void writeName13Raw(long, long) ,public final void writeName14Raw(long, long) ,public final void writeName15Raw(long, long) ,public final void writeName16Raw(long, long) ,public final void writeName2Raw(long) ,public final void writeName3Raw(long) ,public final void writeName4Raw(long) ,public final void writeName5Raw(long) ,public final void writeName6Raw(long) ,public final void writeName7Raw(long) ,public final void writeName8Raw(long) ,public final void writeName9Raw(long, int) ,public final void writeNameRaw(byte[]) ,public final void writeNameRaw(byte[], int, int) ,public final void writeNameRaw(char[]) ,public final void writeNameRaw(char[], int, int) ,public final void writeNull() ,public final void writeOffsetDateTime(java.time.OffsetDateTime) ,public final void writeOffsetTime(java.time.OffsetTime) ,public final void writeRaw(java.lang.String) ,public final void writeRaw(byte[]) ,public final void writeRaw(char) ,public final void writeRaw(char, char) ,public final void writeReference(java.lang.String) ,public final void writeString(List<java.lang.String>) ,public final void writeString(boolean) ,public final void writeString(byte) ,public final void writeString(short) ,public final void writeString(int) ,public final void writeString(long) ,public void writeString(java.lang.String) ,public final void writeString(char[]) ,public final void writeString(char[], int, int) ,public final void writeString(char[], int, int, boolean) ,public final void writeString(java.lang.String[]) ,public void writeStringLatin1(byte[]) ,public final void writeStringUTF16(byte[]) ,public final void writeTimeHHMMSS8(int, int, int) ,public final void writeUUID(java.util.UUID) ,public final void writeZonedDateTime(java.time.ZonedDateTime) <variables>static final non-sealed short[] HEX256,static final byte[] REF_PREF,protected byte[] bytes,final non-sealed com.alibaba.fastjson2.JSONFactory.CacheItem cacheItem
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/SymbolTable.java
|
SymbolTable
|
getNameByHashCode
|
class SymbolTable {
private final String[] names;
private final long hashCode64;
private final short[] mapping;
private final long[] hashCodes;
private final long[] hashCodesOrigin;
public SymbolTable(String... input) {
Set<String> set = new TreeSet<>(Arrays.asList(input));
names = new String[set.size()];
Iterator<String> it = set.iterator();
for (int i = 0; i < names.length; i++) {
if (it.hasNext()) {
names[i] = it.next();
}
}
long[] hashCodes = new long[names.length];
for (int i = 0; i < names.length; i++) {
long hashCode = Fnv.hashCode64(names[i]);
hashCodes[i] = hashCode;
}
this.hashCodesOrigin = hashCodes;
this.hashCodes = Arrays.copyOf(hashCodes, hashCodes.length);
Arrays.sort(this.hashCodes);
mapping = new short[this.hashCodes.length];
for (int i = 0; i < hashCodes.length; i++) {
long hashCode = hashCodes[i];
int index = Arrays.binarySearch(this.hashCodes, hashCode);
mapping[index] = (short) i;
}
long hashCode64 = Fnv.MAGIC_HASH_CODE;
for (long hashCode : hashCodes) {
hashCode64 ^= hashCode;
hashCode64 *= Fnv.MAGIC_PRIME;
}
this.hashCode64 = hashCode64;
}
public int size() {
return names.length;
}
public long hashCode64() {
return hashCode64;
}
public String getNameByHashCode(long hashCode) {<FILL_FUNCTION_BODY>}
public int getOrdinalByHashCode(long hashCode) {
int m = Arrays.binarySearch(hashCodes, hashCode);
if (m < 0) {
return -1;
}
return this.mapping[m] + 1;
}
public int getOrdinal(String name) {
int m = Arrays.binarySearch(hashCodes, Fnv.hashCode64(name));
if (m < 0) {
return -1;
}
return this.mapping[m] + 1;
}
public String getName(int ordinal) {
return names[ordinal - 1];
}
public long getHashCode(int ordinal) {
return hashCodesOrigin[ordinal - 1];
}
}
|
int m = Arrays.binarySearch(hashCodes, hashCode);
if (m < 0) {
return null;
}
int index = this.mapping[m];
return names[index];
| 715
| 57
| 772
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/codec/BeanInfo.java
|
BeanInfo
|
required
|
class BeanInfo {
public String typeKey;
public String typeName;
public Class builder;
public Method buildMethod;
public String builderWithPrefix;
public Class[] seeAlso;
public String[] seeAlsoNames;
public Class seeAlsoDefault;
public Constructor creatorConstructor;
public Constructor markerConstructor;
public Method createMethod;
public String[] createParameterNames;
public long readerFeatures;
public long writerFeatures;
public boolean writeEnumAsJavaBean;
public String namingStrategy;
public String[] ignores;
public String[] orders;
public String[] includes;
public boolean mixIn;
public boolean kotlin;
public Class serializer;
public Class deserializer;
public Class<? extends Filter>[] serializeFilters;
public String schema;
public String format;
public Locale locale;
public boolean alphabetic = true;
public String objectWriterFieldName;
public String objectReaderFieldName;
public Class<? extends JSONReader.AutoTypeBeforeHandler> autoTypeBeforeHandler;
public void required(String fieldName) {<FILL_FUNCTION_BODY>}
}
|
if (schema == null) {
schema = JSONObject.of("required", JSONArray.of(fieldName)).toString();
} else {
JSONObject object = JSONObject.parseObject(schema);
JSONArray array = object.getJSONArray("required");
array.add(fieldName);
schema = object.toString();
}
| 297
| 86
| 383
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/codec/DateTimeCodec.java
|
DateTimeCodec
|
getDateFormatter
|
class DateTimeCodec {
public final String format;
public final boolean formatUnixTime;
public final boolean formatMillis;
public final boolean formatISO8601;
protected final boolean formatHasDay;
protected final boolean formatHasHour;
public final boolean useSimpleFormatter;
public final Locale locale;
protected final boolean yyyyMMddhhmmss19;
protected final boolean yyyyMMddhhmm16;
protected final boolean yyyyMMddhhmmss14;
protected final boolean yyyyMMdd10;
protected final boolean yyyyMMdd8;
protected final boolean useSimpleDateFormat;
DateTimeFormatter dateFormatter;
public DateTimeCodec(String format) {
this(format, null);
}
public DateTimeCodec(String format, Locale locale) {
if (format != null) {
format = format.replaceAll("aa", "a");
}
this.format = format;
this.locale = locale;
this.yyyyMMddhhmmss14 = "yyyyMMddHHmmss".equals(format);
this.yyyyMMddhhmmss19 = "yyyy-MM-dd HH:mm:ss".equals(format);
this.yyyyMMddhhmm16 = "yyyy-MM-dd HH:mm".equals(format);
this.yyyyMMdd10 = "yyyy-MM-dd".equals(format);
this.yyyyMMdd8 = "yyyyMMdd".equals(format);
this.useSimpleDateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX".equals(format);
boolean formatUnixTime = false, formatISO8601 = false, formatMillis = false, hasDay = false, hasHour = false;
if (format != null) {
switch (format) {
case "unixtime":
formatUnixTime = true;
break;
case "iso8601":
formatISO8601 = true;
break;
case "millis":
formatMillis = true;
break;
default:
hasDay = format.indexOf('d') != -1;
hasHour = format.indexOf('H') != -1
|| format.indexOf('h') != -1
|| format.indexOf('K') != -1
|| format.indexOf('k') != -1;
break;
}
}
this.formatUnixTime = formatUnixTime;
this.formatMillis = formatMillis;
this.formatISO8601 = formatISO8601;
this.formatHasDay = hasDay;
this.formatHasHour = hasHour;
this.useSimpleFormatter = "yyyyMMddHHmmssSSSZ".equals(format);
}
public DateTimeFormatter getDateFormatter() {<FILL_FUNCTION_BODY>}
public DateTimeFormatter getDateFormatter(Locale locale) {
if (format == null || formatMillis || formatISO8601 || formatUnixTime) {
return null;
}
if (dateFormatter != null) {
if ((this.locale == null && (locale == null || locale == Locale.getDefault()))
|| this.locale != null && this.locale.equals(locale)
) {
return dateFormatter;
}
}
if (locale == null) {
if (this.locale == null) {
return dateFormatter = DateTimeFormatter.ofPattern(format);
} else {
return dateFormatter = DateTimeFormatter.ofPattern(format, this.locale);
}
}
return dateFormatter = DateTimeFormatter.ofPattern(format, locale);
}
}
|
if (dateFormatter == null && format != null && !formatMillis && !formatISO8601 && !formatUnixTime) {
if (locale == null) {
dateFormatter = DateTimeFormatter.ofPattern(format);
} else {
dateFormatter = DateTimeFormatter.ofPattern(format, locale);
}
}
return dateFormatter;
| 961
| 97
| 1,058
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/codec/FieldInfo.java
|
FieldInfo
|
getInitReader
|
class FieldInfo {
public static final long VALUE_MASK = 1L << 48;
public static final long UNWRAPPED_MASK = 1L << 49;
public static final long RAW_VALUE_MASK = 1L << 50;
public static final long READ_USING_MASK = 1L << 51;
public static final long FIELD_MASK = 1L << 52;
// public static final long JSON_AUTO_WIRED_ANNOTATED = 1L << 53;
public static final long JIT = 1L << 54;
public static final long DISABLE_UNSAFE = 1L << 55;
public String fieldName;
public String format;
public String label;
public int ordinal;
public long features;
public boolean ignore;
public String[] alternateNames;
public Class<?> writeUsing;
public Class<?> keyUsing;
public Class<?> valueUsing;
public Class<?> readUsing;
public boolean fieldClassMixIn;
public boolean isTransient;
public String defaultValue;
public Locale locale;
public String schema;
public boolean required;
public ObjectReader getInitReader() {<FILL_FUNCTION_BODY>}
public void init() {
fieldName = null;
format = null;
label = null;
ordinal = 0;
features = 0;
ignore = false;
required = false;
alternateNames = null;
writeUsing = null;
keyUsing = null;
valueUsing = null;
readUsing = null;
fieldClassMixIn = false;
isTransient = false;
defaultValue = null;
locale = null;
schema = null;
}
}
|
if (readUsing != null && ObjectReader.class.isAssignableFrom(readUsing)) {
try {
Constructor<?> constructor = readUsing.getDeclaredConstructor();
constructor.setAccessible(true);
return (ObjectReader) constructor.newInstance();
} catch (Exception ignored) {
// ignored
}
return null;
}
return null;
| 441
| 100
| 541
|
<no_super_class>
|
alibaba_fastjson2
|
fastjson2/core/src/main/java/com/alibaba/fastjson2/filter/AfterFilter.java
|
AfterFilter
|
writeKeyValue
|
class AfterFilter
implements Filter {
private static final ThreadLocal<JSONWriter> writerLocal = new ThreadLocal<>();
public void writeAfter(JSONWriter serializer, Object object) {
JSONWriter last = writerLocal.get();
writerLocal.set(serializer);
writeAfter(object);
writerLocal.set(last);
}
protected final void writeKeyValue(String key, Object value) {<FILL_FUNCTION_BODY>}
public abstract void writeAfter(Object object);
}
|
JSONWriter serializer = writerLocal.get();
boolean ref = serializer.containsReference(value);
serializer.writeName(key);
serializer.writeColon();
serializer.writeAny(value);
if (!ref) {
serializer.removeReference(value);
}
| 128
| 77
| 205
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.