f0258047be53f344773bbc26624096dd0c5eb817
[controller.git] / third-party / atomix / storage / src / main / java / io / atomix / utils / serializer / EntrySerializer.java
1 /*
2  * Copyright 2023 PANTHEON.tech, s.r.o.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.utils.serializer;
17
18 import static java.util.Objects.requireNonNull;
19
20 import com.esotericsoftware.kryo.Kryo;
21 import com.esotericsoftware.kryo.KryoException;
22 import com.esotericsoftware.kryo.Serializer;
23 import com.esotericsoftware.kryo.io.Input;
24 import com.esotericsoftware.kryo.io.Output;
25 import com.esotericsoftware.kryo.serializers.JavaSerializer;
26 import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
27 import java.io.IOException;
28
29 final class EntrySerializer<T> extends Serializer<T> {
30     // Note: uses identity to create things in Kryo, hence we want an instance for every serdes we wrap
31     private final JavaSerializer javaSerializer = new JavaSerializer();
32     private final EntrySerdes<T> serdes;
33
34     EntrySerializer(final EntrySerdes<T> serdes) {
35         this.serdes = requireNonNull(serdes);
36     }
37
38     @Override
39     public T read(final Kryo kryo, final Input input, final Class<T> type) {
40         try {
41             return serdes.read(new KryoEntryInput(kryo, input, javaSerializer));
42         } catch (IOException e) {
43             throw new KryoException(e);
44         }
45     }
46
47     @Override
48     public void write(final Kryo kryo, final Output output, final T object) {
49         try {
50             serdes.write(new KryoEntryOutput(kryo, output, javaSerializer), object);
51         } catch (IOException e) {
52             throw new KryoException(e);
53         }
54     }
55 }