001/** 002 * Copyright 2011-2015 John Ericksen 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.parceler.converter; 017 018import android.os.Parcel; 019import org.parceler.TypeRangeParcelConverter; 020 021import java.util.Map; 022 023/** 024 * 025 * @author u61173 026 */ 027public abstract class MapParcelConverter<K, V, M extends Map<K, V>> implements TypeRangeParcelConverter<Map<K, V>, M> { 028 029 private static final int NULL = -1; 030 031 @Override 032 public void toParcel(Map<K, V> input, Parcel parcel) { 033 if (input == null) { 034 parcel.writeInt(NULL); 035 } else { 036 parcel.writeInt(input.size()); 037 for (Map.Entry<K, V> entry : input.entrySet()) { 038 mapKeyToParcel(entry.getKey(), parcel); 039 mapValueToParcel(entry.getValue(), parcel); 040 } 041 } 042 } 043 044 @Override 045 public M fromParcel(Parcel parcel) { 046 M map; 047 int size = parcel.readInt(); 048 if (size == NULL) { 049 map = null; 050 } else { 051 map = createMap(); 052 for (int i = 0; (i < size); i++) { 053 K key = mapKeyFromParcel(parcel); 054 V value = mapValueFromParcel(parcel); 055 map.put(key, value); 056 } 057 } 058 return map; 059 } 060 061 public abstract M createMap(); 062 063 public abstract void mapKeyToParcel(K key, Parcel parcel); 064 public abstract void mapValueToParcel(V value, Parcel parcel); 065 066 public abstract K mapKeyFromParcel(Parcel parcel); 067 public abstract V mapValueFromParcel(Parcel parcel); 068}