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.IntOrderedSet;
026import com.github.tommyettinger.ds.OrderType;
027import com.github.tommyettinger.ds.Utilities;
028
029/**
030 * Kryo {@link Serializer} for jdkgdxds {@link IntOrderedSet}s.
031 */
032public class IntOrderedSetSerializer extends Serializer<IntOrderedSet> {
033
034    private static final OrderType[] ORDER_TYPES = OrderType.values();
035
036    public IntOrderedSetSerializer() {
037        setAcceptsNull(false);
038    }
039
040    @Override
041    public void write(final Kryo kryo, final Output output, final IntOrderedSet data) {
042        int length = data.size();
043        output.writeInt(length, true);
044        output.writeVarInt(data.getOrderType().ordinal(), true);
045        for(IntOrderedSet.IntOrderedSetIterator it = new IntOrderedSet.IntOrderedSetIterator(data); it.hasNext();)
046            output.writeVarInt(it.nextInt(), false);
047    }
048
049    @Override
050    public IntOrderedSet read(final Kryo kryo, final Input input, final Class<? extends IntOrderedSet> dataClass) {
051        int length = input.readInt(true);
052        IntOrderedSet data = new IntOrderedSet(length, Utilities.getDefaultLoadFactor(), ORDER_TYPES[input.readVarInt(true)]);
053        for (int i = 0; i < length; i++)
054            data.add(input.readVarInt(false));
055        return data;
056    }
057
058    @Override
059    public IntOrderedSet copy(Kryo kryo, IntOrderedSet original) {
060        return new IntOrderedSet(original);
061    }
062}