blob: cfa7cccea7aab29239a6b38a8b3f5095b5178ef6 [file] [log] [blame]
Yuta HIGUCHI533ec322014-09-30 13:29:52 -07001package org.onlab.onos.store.serializers;
2
3import java.util.Collections;
4import java.util.HashMap;
5import java.util.Map;
6
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -07007import org.onlab.util.KryoNamespace.FamilySerializer;
Yuta HIGUCHI533ec322014-09-30 13:29:52 -07008
9import com.esotericsoftware.kryo.Kryo;
10import com.esotericsoftware.kryo.io.Input;
11import com.esotericsoftware.kryo.io.Output;
12import com.esotericsoftware.kryo.serializers.MapSerializer;
13import com.google.common.collect.ImmutableMap;
14
15/**
16* Kryo Serializer for {@link ImmutableMap}.
17*/
18public class ImmutableMapSerializer extends FamilySerializer<ImmutableMap<?, ?>> {
19
20 private final MapSerializer mapSerializer = new MapSerializer();
21
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070022 /**
23 * Creates {@link ImmutableMap} serializer instance.
24 */
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070025 public ImmutableMapSerializer() {
26 // non-null, immutable
27 super(false, true);
28 }
29
30 @Override
31 public void write(Kryo kryo, Output output, ImmutableMap<?, ?> object) {
32 // wrapping with unmodifiableMap proxy
33 // to avoid Kryo from writing only the reference marker of this instance,
34 // which will be embedded right before this method call.
35 kryo.writeObject(output, Collections.unmodifiableMap(object), mapSerializer);
36 }
37
38 @Override
39 public ImmutableMap<?, ?> read(Kryo kryo, Input input,
40 Class<ImmutableMap<?, ?>> type) {
41 Map<?, ?> map = kryo.readObject(input, HashMap.class, mapSerializer);
42 return ImmutableMap.copyOf(map);
43 }
44
45 @Override
46 public void registerFamilies(Kryo kryo) {
47 kryo.register(ImmutableMap.of().getClass(), this);
48 kryo.register(ImmutableMap.of(1, 2).getClass(), this);
49 kryo.register(ImmutableMap.of(1, 2, 3, 4).getClass(), this);
50 // TODO register required ImmutableMap variants
51 }
52}