blob: 858d45599dd196bccd2122a20b294ae3086604ad [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 HIGUCHI03fec1f2014-10-03 09:13:50 -070016package org.onlab.onos.store.serializers;
17
18import org.onlab.packet.IpAddress;
19import com.esotericsoftware.kryo.Kryo;
20import com.esotericsoftware.kryo.Serializer;
21import com.esotericsoftware.kryo.io.Input;
22import com.esotericsoftware.kryo.io.Output;
23
24/**
25 * Kryo Serializer for {@link IpAddress}.
26 */
27public class IpAddressSerializer extends Serializer<IpAddress> {
28
29 /**
30 * Creates {@link IpAddress} serializer instance.
31 */
32 public IpAddressSerializer() {
33 // non-null, immutable
34 super(false, true);
35 }
36
37 @Override
Yuta HIGUCHIb0995df2014-10-15 23:13:42 -070038 public void write(Kryo kryo, Output output, IpAddress object) {
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070039 byte[] octs = object.toOctets();
40 output.writeInt(octs.length);
41 output.writeBytes(octs);
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070042 }
43
44 @Override
Yuta HIGUCHIb0995df2014-10-15 23:13:42 -070045 public IpAddress read(Kryo kryo, Input input, Class<IpAddress> type) {
46 final int octLen = input.readInt();
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070047 byte[] octs = new byte[octLen];
Yuta HIGUCHIb0995df2014-10-15 23:13:42 -070048 input.readBytes(octs);
Pavlin Radoslavovb139f4d2014-10-31 21:14:14 -070049 // Use the address size to decide whether it is IPv4 or IPv6 address
50 if (octLen == IpAddress.INET_BYTE_LENGTH) {
51 return IpAddress.valueOf(IpAddress.Version.INET, octs);
52 }
53 if (octLen == IpAddress.INET6_BYTE_LENGTH) {
54 return IpAddress.valueOf(IpAddress.Version.INET6, octs);
55 }
56 return null; // Shouldn't be reached
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070057 }
Yuta HIGUCHI03fec1f2014-10-03 09:13:50 -070058}