blob: 1a26ea46e566f5460f3ca8629f35bf9bc95b1b21 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
2 * Copyright 2014 Open Networking Laboratory
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 */
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070016package org.onlab.onos.store.serializers;
17
18import java.util.Collections;
19import java.util.HashMap;
20import java.util.Map;
21
Yuta HIGUCHI8d143d22014-10-19 23:15:09 -070022import org.onlab.util.KryoNamespace.FamilySerializer;
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070023
24import com.esotericsoftware.kryo.Kryo;
25import com.esotericsoftware.kryo.io.Input;
26import com.esotericsoftware.kryo.io.Output;
27import com.esotericsoftware.kryo.serializers.MapSerializer;
28import com.google.common.collect.ImmutableMap;
29
30/**
31* Kryo Serializer for {@link ImmutableMap}.
32*/
33public class ImmutableMapSerializer extends FamilySerializer<ImmutableMap<?, ?>> {
34
35 private final MapSerializer mapSerializer = new MapSerializer();
36
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070037 /**
38 * Creates {@link ImmutableMap} serializer instance.
39 */
Yuta HIGUCHI533ec322014-09-30 13:29:52 -070040 public ImmutableMapSerializer() {
41 // non-null, immutable
42 super(false, true);
43 }
44
45 @Override
46 public void write(Kryo kryo, Output output, ImmutableMap<?, ?> object) {
47 // wrapping with unmodifiableMap proxy
48 // to avoid Kryo from writing only the reference marker of this instance,
49 // which will be embedded right before this method call.
50 kryo.writeObject(output, Collections.unmodifiableMap(object), mapSerializer);
51 }
52
53 @Override
54 public ImmutableMap<?, ?> read(Kryo kryo, Input input,
55 Class<ImmutableMap<?, ?>> type) {
56 Map<?, ?> map = kryo.readObject(input, HashMap.class, mapSerializer);
57 return ImmutableMap.copyOf(map);
58 }
59
60 @Override
61 public void registerFamilies(Kryo kryo) {
62 kryo.register(ImmutableMap.of().getClass(), this);
63 kryo.register(ImmutableMap.of(1, 2).getClass(), this);
64 kryo.register(ImmutableMap.of(1, 2, 3, 4).getClass(), this);
65 // TODO register required ImmutableMap variants
66 }
67}