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.IntDeque;
025import com.github.tommyettinger.ds.IntIntMap;
026import com.github.tommyettinger.ds.IntIntOrderedMap;
027import com.github.tommyettinger.ds.OrderType;
028
029import java.util.Iterator;
030
031/**
032 * Kryo {@link Serializer} for jdkgdxds {@link IntIntOrderedMap}s.
033 */
034public class IntIntOrderedMapSerializer extends Serializer<IntIntOrderedMap> {
035
036    private static final OrderType[] ORDER_TYPES = OrderType.values();
037
038    public IntIntOrderedMapSerializer() {
039        setAcceptsNull(false);
040    }
041
042    @Override
043    public void write(final Kryo kryo, final Output output, final IntIntOrderedMap data) {
044        int length = data.size();
045        output.writeInt(length, true);
046        output.writeVarInt(data.getOrderType().ordinal(), true);
047        output.writeVarInt(data.getDefaultValue(), false);
048        for(Iterator<IntIntMap.Entry> it = new IntIntOrderedMap.OrderedMapEntries(data).iterator(); it.hasNext();) {
049            IntIntOrderedMap.Entry ent = it.next();
050            output.writeVarInt(ent.key, false);
051            output.writeVarInt(ent.value, false);
052        }
053    }
054
055    @Override
056    public IntIntOrderedMap read(final Kryo kryo, final Input input, final Class<? extends IntIntOrderedMap> dataClass) {
057        int length = input.readInt(true);
058        IntIntOrderedMap data = new IntIntOrderedMap(length, ORDER_TYPES[input.readVarInt(true)]);
059        data.setDefaultValue(input.readVarInt(false));
060        for (int i = 0; i < length; i++)
061            data.put(input.readVarInt(false), input.readVarInt(false));
062        return data;
063    }
064
065    @Override
066    public IntIntOrderedMap copy(Kryo kryo, IntIntOrderedMap original) {
067        return new IntIntOrderedMap(original);
068    }
069}