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.ParcelConverter;
020
021/**
022 * Convenience class to handle nullable objects.
023 *
024 * @author John Ericksen
025 */
026public abstract class NullableParcelConverter<T> implements ParcelConverter<T> {
027
028    private static final int NULL = -1;
029    private static final int NOT_NULL = 1;
030
031    @Override
032    public void toParcel(T input, Parcel parcel) {
033        if (input == null) {
034            parcel.writeInt(NULL);
035        } else {
036            parcel.writeInt(NOT_NULL);
037            nullSafeToParcel(input, parcel);
038        }
039    }
040
041    @Override
042    public T fromParcel(Parcel parcel) {
043        T result;
044        if (parcel .readInt() == NULL) {
045            result = null;
046        } else {
047            result = nullSafeFromParcel(parcel);
048        }
049        return result;
050    }
051
052    public abstract void nullSafeToParcel(T input, Parcel parcel);
053    public abstract T nullSafeFromParcel(Parcel parcel);
054}