yangys
2024-03-29 410eed616ce86a76ecfbd272be0a4463ac54a517
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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;
    }
}