Carmelo Cascone | 804c001 | 2016-06-23 13:05:40 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | a09fe5b | 2017-08-03 21:12:30 -0700 | [diff] [blame] | 2 | * Copyright 2016-present Open Networking Foundation |
Carmelo Cascone | 804c001 | 2016-06-23 13:05:40 -0700 | [diff] [blame] | 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 | */ |
| 16 | |
| 17 | package org.onosproject.store.serializers; |
| 18 | |
| 19 | import com.esotericsoftware.kryo.Kryo; |
| 20 | import com.esotericsoftware.kryo.Serializer; |
| 21 | import com.esotericsoftware.kryo.io.Input; |
| 22 | import com.esotericsoftware.kryo.io.Output; |
| 23 | import org.onlab.util.ImmutableByteSequence; |
| 24 | |
| 25 | /** |
| 26 | * Kryo serializer for {@link ImmutableByteSequence}. |
| 27 | */ |
| 28 | public class ImmutableByteSequenceSerializer extends Serializer<ImmutableByteSequence> { |
| 29 | |
| 30 | /** |
| 31 | * Creates a new {@link ImmutableByteSequence} serializer instance. |
| 32 | */ |
| 33 | public ImmutableByteSequenceSerializer() { |
| 34 | // non-null, immutable. |
| 35 | super(false, true); |
| 36 | } |
| 37 | |
| 38 | @Override |
| 39 | public void write(Kryo kryo, Output output, ImmutableByteSequence object) { |
| 40 | byte[] data = object.asArray(); |
| 41 | output.writeInt(data.length); |
| 42 | output.write(data); |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public ImmutableByteSequence read(Kryo kryo, Input input, Class<ImmutableByteSequence> type) { |
| 47 | int length = input.readInt(); |
| 48 | byte[] data = new byte[length]; |
Ray Milkey | 3e0e92e | 2018-01-12 16:41:29 -0800 | [diff] [blame] | 49 | int bytesRead = input.read(data); |
| 50 | if (bytesRead != length) { |
| 51 | throw new IllegalStateException("Byte sequence serializer read expected " + length + |
| 52 | " but got " + bytesRead); |
| 53 | } |
Carmelo Cascone | 804c001 | 2016-06-23 13:05:40 -0700 | [diff] [blame] | 54 | return ImmutableByteSequence.copyFrom(data); |
| 55 | } |
| 56 | } |