Line data Source code
1 : // Copyright (C) 2018 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.cache.serialize; 16 : 17 : import com.google.common.base.Converter; 18 : 19 : /** 20 : * Interface for serializing/deserializing a type to/from a persistent cache. 21 : * 22 : * <p>Implementations are null-hostile and will throw exceptions from {@link #serialize} when passed 23 : * null values, unless otherwise specified. 24 : */ 25 : public interface CacheSerializer<T> { 26 : /** 27 : * Convert a serializer of one type to another type using a {@link Converter}. 28 : * 29 : * @param delegate underlying serializer. 30 : * @param converter converter between an arbitrary type {@code T} and {@code delegate}'s type. 31 : * @return serializer of type {@code T}. 32 : */ 33 : static <T, D> CacheSerializer<T> convert(CacheSerializer<D> delegate, Converter<T, D> converter) { 34 1 : return new CacheSerializer<>() { 35 : @Override 36 : public byte[] serialize(T object) { 37 1 : return delegate.serialize(converter.convert(object)); 38 : } 39 : 40 : @Override 41 : public T deserialize(byte[] in) { 42 1 : return converter.reverse().convert(delegate.deserialize(in)); 43 : } 44 : }; 45 : } 46 : 47 : /** 48 : * Serializes the object to a new byte array. 49 : * 50 : * @param object object to serialize. 51 : * @return serialized byte array representation. 52 : * @throws RuntimeException for malformed input, for example null or an otherwise unsupported 53 : * value. 54 : */ 55 : byte[] serialize(T object); 56 : 57 : /** 58 : * Deserializes a single object from the given byte array. 59 : * 60 : * @param in serialized byte array representation. 61 : * @throws RuntimeException for malformed input, for example null or an otherwise corrupt 62 : * serialized representation. 63 : */ 64 : T deserialize(byte[] in); 65 : }