001/*
002 * Copyright (c) 2022-2024 See AUTHORS file.
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 *
016 */
017
018package com.github.tommyettinger.kryo.jdkgdxds;
019
020import com.esotericsoftware.kryo.Kryo;
021import com.esotericsoftware.kryo.Serializer;
022import com.esotericsoftware.kryo.io.Input;
023import com.esotericsoftware.kryo.io.Output;
024import com.github.tommyettinger.ds.EnumMap;
025
026import java.util.Iterator;
027import java.util.Map;
028
029/**
030 * Kryo {@link Serializer} for jdkgdxds {@link EnumMap}s.
031 * Requires the type of any enum keys that are contained in an EnumMap to also be registered.
032 */
033public class EnumMapSerializer extends Serializer<EnumMap<?>> {
034
035    public EnumMapSerializer() {
036    }
037
038    @Override
039    public void write(final Kryo kryo, final Output output, final EnumMap<?> data) {
040        int length = data.size();
041        output.writeInt(length, true);
042        kryo.writeClassAndObject(output, data.getDefaultValue());
043        for(Iterator<? extends Map.Entry<Enum<?>, ?>> it = new EnumMap.Entries<>(data).iterator(); it.hasNext();) {
044            Map.Entry<Enum<?>, ?> ent = it.next();
045            kryo.writeClassAndObject(output, ent.getKey());
046            kryo.writeClassAndObject(output, ent.getValue());
047        }
048    }
049
050    @SuppressWarnings({"rawtypes", "unchecked", "UnnecessaryLocalVariable"})
051    @Override
052    public EnumMap<?> read(final Kryo kryo, final Input input, final Class<? extends EnumMap<?>> dataClass) {
053        int length = input.readInt(true);
054        EnumMap<?> data = new EnumMap<>();
055        EnumMap rawData = data;
056        rawData.setDefaultValue(kryo.readClassAndObject(input));
057        for (int i = 0; i < length; i++)
058            rawData.put((Enum<?>)kryo.readClassAndObject(input), kryo.readClassAndObject(input));
059        return data;
060    }
061
062    @SuppressWarnings({"rawtypes", "unchecked", "UnnecessaryLocalVariable"})
063    @Override
064    public EnumMap<?> copy(Kryo kryo, EnumMap<?> original) {
065        EnumMap<?> map = new EnumMap<>(original);
066        kryo.reference(map);
067        map.clear();
068        EnumMap rawMap = map;
069        for(Map.Entry<Enum<?>, ?> ent : original) {
070            rawMap.put(ent.getKey(), kryo.copy(ent.getValue()));
071        }
072        return map;
073    }
074}