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.Collection;
022
023/**
024 *
025 * @author u61173
026 */
027public abstract class CollectionParcelConverter<T, C extends Collection<T>> implements TypeRangeParcelConverter<Collection<T>, C> {
028
029    private static final int NULL = -1;
030
031    @Override
032    public void toParcel(Collection<T> input, Parcel parcel) {
033        if (input == null) {
034            parcel.writeInt(NULL);
035        } else {
036            parcel.writeInt(input.size());
037            for (T item : input) {
038                itemToParcel(item, parcel);
039            }
040        }
041    }
042
043    @Override
044    public C fromParcel(Parcel parcel) {
045        C list;
046        int size = parcel.readInt();
047        if (size == NULL) {
048            list = null;
049        } else {
050            list = createCollection();
051            for (int i = 0; (i < size); i++) {
052                list.add(itemFromParcel(parcel));
053            }
054        }
055        return list;
056    }
057
058    public abstract void itemToParcel(T input, Parcel parcel);
059    public abstract T itemFromParcel(Parcel parcel);
060    public abstract C createCollection();
061}