package com.qianwen.core.tool.utils;
|
|
import io.protostuff.LinkedBuffer;
|
import io.protostuff.ProtostuffIOUtil;
|
import io.protostuff.Schema;
|
import io.protostuff.runtime.RuntimeSchema;
|
import java.util.Map;
|
import java.util.Objects;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
/* loaded from: blade-core-tool-9.3.0.0-SNAPSHOT.jar:org/springblade/core/tool/utils/ProtostuffUtil.class */
|
public class ProtostuffUtil {
|
private static final LinkedBuffer BUFFER = LinkedBuffer.allocate(512);
|
private static final Map<Class<?>, Schema<?>> SCHEMA_CACHE = new ConcurrentHashMap();
|
|
|
|
public static <T> byte[] serialize(T obj) {
|
byte[] data;
|
Class<T> clazz = (Class)obj.getClass();
|
Schema<T> schema = getSchema(clazz);
|
try {
|
data = ProtostuffIOUtil.toByteArray(obj, schema, BUFFER);
|
} finally {
|
BUFFER.clear();
|
}
|
return data;
|
}
|
|
public static <T> T deserialize(byte[] data, Class<T> clazz) {
|
Schema<T> schema = getSchema(clazz);
|
T obj = (T) schema.newMessage();
|
ProtostuffIOUtil.mergeFrom(data, obj, schema);
|
return obj;
|
}
|
|
private static <T> Schema<T> getSchema(Class<T> clazz) {
|
Schema<?> schema = SCHEMA_CACHE.get(clazz);
|
if (Objects.isNull(schema)) {
|
schema = RuntimeSchema.getSchema(clazz);
|
if (Objects.nonNull(schema)) {
|
SCHEMA_CACHE.put(clazz, schema);
|
}
|
}
|
return (Schema<T>) schema;
|
}
|
}
|