Add RegisteredType
[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 com.google.common.base.MoreObjects;
27 import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
28 import java.io.IOException;
29
30 final class EntrySerializer<T> extends Serializer<T> {
31     // Note: uses identity to create things in Kryo, hence we want an instance for every serdes we wrap
32     private final JavaSerializer javaSerializer = new JavaSerializer();
33     private final EntrySerdes<T> serdes;
34
35     EntrySerializer(final EntrySerdes<T> serdes) {
36         this.serdes = requireNonNull(serdes);
37     }
38
39     @Override
40     public T read(final Kryo kryo, final Input input, final Class<T> type) {
41         try {
42             return serdes.read(new KryoEntryInput(kryo, input, javaSerializer));
43         } catch (IOException e) {
44             throw new KryoException(e);
45         }
46     }
47
48     @Override
49     public void write(final Kryo kryo, final Output output, final T object) {
50         try {
51             serdes.write(new KryoEntryOutput(kryo, output, javaSerializer), object);
52         } catch (IOException e) {
53             throw new KryoException(e);
54         }
55     }
56
57     @Override
58     public String toString() {
59         return MoreObjects.toStringHelper(this).addValue(serdes).toString();
60     }
61 }