Yuta HIGUCHI | 533ec32 | 2014-09-30 13:29:52 -0700 | [diff] [blame] | 1 | package org.onlab.onos.store.serializers; |
| 2 | |
| 3 | import java.util.Collections; |
| 4 | import java.util.HashMap; |
| 5 | import java.util.Map; |
| 6 | |
Yuta HIGUCHI | 8d143d2 | 2014-10-19 23:15:09 -0700 | [diff] [blame^] | 7 | import org.onlab.util.KryoNamespace.FamilySerializer; |
Yuta HIGUCHI | 533ec32 | 2014-09-30 13:29:52 -0700 | [diff] [blame] | 8 | |
| 9 | import com.esotericsoftware.kryo.Kryo; |
| 10 | import com.esotericsoftware.kryo.io.Input; |
| 11 | import com.esotericsoftware.kryo.io.Output; |
| 12 | import com.esotericsoftware.kryo.serializers.MapSerializer; |
| 13 | import com.google.common.collect.ImmutableMap; |
| 14 | |
| 15 | /** |
| 16 | * Kryo Serializer for {@link ImmutableMap}. |
| 17 | */ |
| 18 | public class ImmutableMapSerializer extends FamilySerializer<ImmutableMap<?, ?>> { |
| 19 | |
| 20 | private final MapSerializer mapSerializer = new MapSerializer(); |
| 21 | |
Yuta HIGUCHI | 03fec1f | 2014-10-03 09:13:50 -0700 | [diff] [blame] | 22 | /** |
| 23 | * Creates {@link ImmutableMap} serializer instance. |
| 24 | */ |
Yuta HIGUCHI | 533ec32 | 2014-09-30 13:29:52 -0700 | [diff] [blame] | 25 | 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 | } |