blob: 244cc579f03e74fd47490cee8a8bd93c77887ebc [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
7import org.onlab.util.KryoPool.FamilySerializer;
8
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
22 public ImmutableMapSerializer() {
23 // non-null, immutable
24 super(false, true);
25 }
26
27 @Override
28 public void write(Kryo kryo, Output output, ImmutableMap<?, ?> object) {
29 // wrapping with unmodifiableMap proxy
30 // to avoid Kryo from writing only the reference marker of this instance,
31 // which will be embedded right before this method call.
32 kryo.writeObject(output, Collections.unmodifiableMap(object), mapSerializer);
33 }
34
35 @Override
36 public ImmutableMap<?, ?> read(Kryo kryo, Input input,
37 Class<ImmutableMap<?, ?>> type) {
38 Map<?, ?> map = kryo.readObject(input, HashMap.class, mapSerializer);
39 return ImmutableMap.copyOf(map);
40 }
41
42 @Override
43 public void registerFamilies(Kryo kryo) {
44 kryo.register(ImmutableMap.of().getClass(), this);
45 kryo.register(ImmutableMap.of(1, 2).getClass(), this);
46 kryo.register(ImmutableMap.of(1, 2, 3, 4).getClass(), this);
47 // TODO register required ImmutableMap variants
48 }
49}