import "copyrightAndOthers.stg"
import "primitiveEquals.stg"
import "primitiveHashCode.stg"
import "primitiveLiteral.stg"

targetPath() ::= "org/eclipse/collections/impl/bag/mutable/primitive"

fileName(primitive) ::= "<primitive.name>HashBag"

class(primitive) ::= <<
<body(primitive.type, primitive.name)>
>>

body(type, name) ::= <<
<copyrightAndOthers()>

package org.eclipse.collections.impl.bag.mutable.primitive;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.NoSuchElementException;

import org.eclipse.collections.api.<name>Iterable;
import org.eclipse.collections.api.RichIterable;
import org.eclipse.collections.api.bag.MutableBag;
import org.eclipse.collections.api.bag.primitive.<name>Bag;
import org.eclipse.collections.api.bag.primitive.Immutable<name>Bag;
import org.eclipse.collections.api.bag.primitive.Mutable<name>Bag;
import org.eclipse.collections.api.block.function.primitive.<name>ToObjectFunction;
import org.eclipse.collections.api.block.function.primitive.IntFunction;
import org.eclipse.collections.api.block.function.primitive.Object<name>ToObjectFunction;
import org.eclipse.collections.api.block.predicate.primitive.IntPredicate;
<if(!primitive.intPrimitive)>import org.eclipse.collections.api.block.predicate.primitive.<name>Predicate;<endif>
import org.eclipse.collections.api.block.procedure.primitive.<name>Procedure;
import org.eclipse.collections.api.block.procedure.primitive.<name>IntProcedure;
import org.eclipse.collections.api.factory.Lists;
import org.eclipse.collections.api.iterator.<name>Iterator;
import org.eclipse.collections.api.iterator.Mutable<name>Iterator;
import org.eclipse.collections.api.set.primitive.<name>Set;
import org.eclipse.collections.api.tuple.primitive.<name>IntPair;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.Counter;
import org.eclipse.collections.impl.bag.mutable.HashBag;
import org.eclipse.collections.impl.block.factory.primitive.IntToIntFunctions;
import org.eclipse.collections.impl.factory.primitive.<name>Bags;
import org.eclipse.collections.impl.map.mutable.primitive.<name>IntHashMap;
import org.eclipse.collections.impl.primitive.Abstract<name>Iterable;
import org.eclipse.collections.impl.set.mutable.primitive.<name>HashSet;
import org.eclipse.collections.impl.tuple.primitive.PrimitiveTuples;
import org.eclipse.collections.impl.factory.primitive.<name>Sets;
import org.eclipse.collections.api.set.primitive.Mutable<name>Set;

/**
 * <name>HashBag is similar to {@link HashBag}, and is memory-optimized for <type> primitives.
 * This file was automatically generated from template file primitiveHashBag.stg.
 *
 * @since 3.0.
 */
public class <name>HashBag
        extends Abstract<name>Iterable
        implements Mutable<name>Bag, Externalizable
{
    private static final long serialVersionUID = 1L;

    private <name>IntHashMap items;
    private int size;

    public <name>HashBag()
    {
        this.items = new <name>IntHashMap();
    }

    public <name>HashBag(int size)
    {
        this.items = new <name>IntHashMap(size);
    }

    public <name>HashBag(<name>Iterable iterable)
    {
        this();
        this.addAll(iterable);
    }

    public <name>HashBag(<type>... elements)
    {
        this();
        this.addAll(elements);
    }

    public <name>HashBag(<name>HashBag bag)
    {
        this.items = new <name>IntHashMap(bag.sizeDistinct());
        this.addAll(bag);
    }

    public static <name>HashBag newBag(int size)
    {
        return new <name>HashBag(size);
    }

    public static <name>HashBag newBagWith(<type>... source)
    {
        return new <name>HashBag(source);
    }

    public static <name>HashBag newBag(<name>Iterable source)
    {
        if (source instanceof <name>HashBag)
        {
            return new <name>HashBag((<name>HashBag) source);
        }
        return new <name>HashBag(source);
    }

    public static <name>HashBag newBag(<name>Bag source)
    {
        return new <name>HashBag(source);
    }

    @Override
    public boolean isEmpty()
    {
        return this.items.isEmpty();
    }

    @Override
    public boolean notEmpty()
    {
        return this.items.notEmpty();
    }

    @Override
    public int size()
    {
        return this.size;
    }

    @Override
    public int sizeDistinct()
    {
        return this.items.size();
    }

    @Override
    public void clear()
    {
        this.items.clear();
        this.size = 0;
    }

    @Override
    public <name>HashBag with(<type> element)
    {
        this.add(element);
        return this;
    }

    public <name>HashBag with(<type> element1, <type> element2)
    {
        this.add(element1);
        this.add(element2);
        return this;
    }

    public <name>HashBag with(<type> element1, <type> element2, <type> element3)
    {
        this.add(element1);
        this.add(element2);
        this.add(element3);
        return this;
    }

    @Override
    public <name>HashBag withAll(<name>Iterable iterable)
    {
        this.addAll(iterable);
        return this;
    }

    @Override
    public <name>HashBag without(<type> element)
    {
        this.remove(element);
        return this;
    }

    @Override
    public <name>HashBag withoutAll(<name>Iterable iterable)
    {
        this.removeAll(iterable);
        return this;
    }

    @Override
    public boolean contains(<type> value)
    {
        return this.items.containsKey(value);
    }

    @Override
    public int occurrencesOf(<type> item)
    {
        return this.items.get(item);
    }

    @Override
    public void forEachWithOccurrences(<name>IntProcedure procedure)
    {
        this.items.forEachKeyValue(procedure);
    }

    @Override
    public <name>HashBag selectByOccurrences(IntPredicate predicate)
    {
        <name>HashBag result = new <name>HashBag();
        this.forEachWithOccurrences((each, occurrences) ->
        {
            if (predicate.accept(occurrences))
            {
                result.addOccurrences(each, occurrences);
            }
        });
        return result;
    }

    @Override
    public Mutable<name>Set selectUnique()
    {
        Mutable<name>Set result = <name>Sets.mutable.empty();
        this.forEachWithOccurrences((each, occurrences) ->
        {
            if (occurrences == 1)
            {
                result.add(each);
            }
        });
        return result;
    }

    @Override
    public MutableList\<<name>IntPair> topOccurrences(int count)
    {
        return this.occurrencesSortingBy(count, item -> -item.getTwo(), Lists.mutable.empty());
    }

    @Override
    public MutableList\<<name>IntPair> bottomOccurrences(int count)
    {
        return this.occurrencesSortingBy(count, <name>IntPair::getTwo, Lists.mutable.empty());
    }

    protected MutableList\<<name>IntPair> occurrencesSortingBy(
            int n,
            IntFunction\<<name>IntPair> function,
            MutableList\<<name>IntPair> returnWhenEmpty)
    {
        if (n \< 0)
        {
            throw new IllegalArgumentException("Cannot use a value of n \< 0");
        }
        if (n == 0)
        {
            return returnWhenEmpty;
        }
        int keySize = Math.min(n, this.sizeDistinct());
        MutableList\<<name>IntPair> sorted = this.toListWithOccurrences().sortThisByInt(function);
        MutableList\<<name>IntPair> results = sorted.subList(0, keySize).toList();
        while (keySize \< sorted.size() && results.getLast().getTwo() == sorted.get(keySize).getTwo())
        {
            results.add(sorted.get(keySize));
            keySize++;
        }
        return results;
    }

    protected MutableList\<<name>IntPair> toListWithOccurrences()
    {
        MutableList\<<name>IntPair> result = Lists.mutable.withInitialCapacity(this.sizeDistinct());
        this.forEachWithOccurrences((each, count) -> result.add(PrimitiveTuples.pair(each, count)));
        return result;
    }

    @Override
    public boolean add(<type> item)
    {
        this.items.updateValue(item, 0, IntToIntFunctions.increment());
        this.size++;
        return true;
    }

    @Override
    public boolean remove(<type> item)
    {
        int newValue = this.items.updateValue(item, 0, IntToIntFunctions.decrement());
        if (newValue \<= 0)
        {
            this.items.removeKey(item);
            if (newValue == 0)
            {
                this.size--;
            }
            return newValue == 0;
        }
        this.size--;
        return true;
    }

    @Override
    public boolean removeIf(<name>Predicate predicate)
    {
        boolean changed = false;
        for (Mutable<name>Iterator iterator = this.items.keySet().<type>Iterator(); iterator.hasNext(); )
        {
            <type> key = iterator.next();
            if (predicate.accept(key))
            {
                this.size -= this.items.get(key);
                iterator.remove();
                changed = true;
            }
        }
        return changed;
    }

    @Override
    public boolean addAll(<type>... source)
    {
        if (source.length == 0)
        {
            return false;
        }

        for (<type> each : source)
        {
            this.add(each);
        }
        return true;
    }

    @Override
    public boolean addAll(<name>Iterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        if (source instanceof <name>Bag)
        {
            <name>Bag otherBag = (<name>Bag) source;
            otherBag.forEachWithOccurrences(this::addOccurrences);
        }
        else
        {
            <name>Iterator iterator = source.<type>Iterator();
            while (iterator.hasNext())
            {
                <type> each = iterator.next();
                this.add(each);
            }
        }
        return true;
    }

    @Override
    public boolean removeAll(<type>... source)
    {
        if (source.length == 0)
        {
            return false;
        }
        int oldSize = this.size();
        for (<type> each : source)
        {
            int occurrences = this.items.removeKeyIfAbsent(each, 0);
            this.size -= occurrences;
        }
        return this.size() != oldSize;
    }

    @Override
    public boolean removeAll(<name>Iterable source)
    {
        if (source.isEmpty())
        {
            return false;
        }
        int oldSize = this.size();
        if (source instanceof <name>Bag)
        {
            <name>Bag otherBag = (<name>Bag) source;
            otherBag.forEachWithOccurrences((<type> each, int occurrences) ->
            {
                int oldOccurrences = this.items.removeKeyIfAbsent(each, 0);
                <name>HashBag.this.size -= oldOccurrences;
            });
        }
        else
        {
            <name>Iterator iterator = source.<type>Iterator();
            while (iterator.hasNext())
            {
                <type> each = iterator.next();
                int occurrences = this.items.removeKeyIfAbsent(each, 0);
                this.size -= occurrences;
            }
        }
        return this.size() != oldSize;
    }

    @Override
    public boolean retainAll(<name>Iterable source)
    {
        int oldSize = this.size();
        <name>Set sourceSet = source instanceof <name>Set ? (<name>Set) source : source.toSet();
        <name>HashBag retained = this.select(sourceSet::contains);
        if (retained.size() != oldSize)
        {
            this.items = retained.items;
            this.size = retained.size;
            return true;
        }
        return false;
    }

    @Override
    public boolean retainAll(<type>... source)
    {
        return this.retainAll(<name>HashSet.newSetWith(source));
    }

    @Override
    public void addOccurrences(<type> item, int occurrences)
    {
        if (occurrences \< 0)
        {
            throw new IllegalArgumentException("Cannot add a negative number of occurrences");
        }
        if (occurrences > 0)
        {
            this.items.updateValue(item, 0, (int intParameter) -> intParameter + occurrences);
            this.size += occurrences;
        }
    }

    @Override
    public boolean removeOccurrences(<type> item, int occurrences)
    {
        if (occurrences \< 0)
        {
            throw new IllegalArgumentException("Cannot remove a negative number of occurrences");
        }

        if (occurrences == 0)
        {
            return false;
        }

        int newValue = this.items.updateValue(item, 0, (int intParameter) -> intParameter - occurrences);

        if (newValue \<= 0)
        {
            this.size -= occurrences - newValue;
            this.items.removeKey(item);
            return newValue + occurrences != 0;
        }

        this.size -= occurrences;
        return true;
    }

    /**
     * @since 7.0.
     */
    @Override
    public void each(<name>Procedure procedure)
    {
        this.items.forEachKeyValue((<type> key, int occurrences) ->
        {
            for (int i = 0; i \< occurrences; i++)
            {
                procedure.value(key);
            }
        });
    }

    @Override
    public <name>HashBag select(<name>Predicate predicate)
    {
        <name>HashBag result = new <name>HashBag();
        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            if (predicate.accept(each))
            {
                result.addOccurrences(each, occurrences);
            }
        });
        return result;
    }

    @Override
    public <name>HashBag reject(<name>Predicate predicate)
    {
        <name>HashBag result = new <name>HashBag();
        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            if (!predicate.accept(each))
            {
                result.addOccurrences(each, occurrences);
            }
        });
        return result;
    }

    @Override
    public \<T> T injectInto(T injectedValue, Object<name>ToObjectFunction\<? super T, ? extends T> function)
    {
        T[] result = (T[]) new Object[1];
        result[0] = injectedValue;
        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            for (int i = 0; i \< occurrences; i++)
            {
                result[0] = function.valueOf(result[0], each);
            }
        });
        return result[0];
    }

    @Override
    public RichIterable\<<name>Iterable> chunk(int size)
    {
        if (size \<= 0)
        {
            throw new IllegalArgumentException("Size for groups must be positive but was: " + size);
        }
        MutableList\<<name>Iterable> result = Lists.mutable.empty();
        if (this.notEmpty())
        {
            if (this.size() \<= size)
            {
                result.add(<name>Bags.mutable.withAll(this));
            }
            else
            {
                <name>Iterator iterator = this.<type>Iterator();
                while (iterator.hasNext())
                {
                    Mutable<name>Bag batch = <name>Bags.mutable.empty();
                    for (int i = 0; i \< size && iterator.hasNext(); i++)
                    {
                        batch.add(iterator.next());
                    }
                    result.add(batch);
                }
            }
        }
        return result;
    }

    @Override
    public boolean equals(Object otherBag)
    {
        if (otherBag == this)
        {
            return true;
        }
        if (!(otherBag instanceof <name>Bag))
        {
            return false;
        }
        <name>Bag bag = (<name>Bag) otherBag;
        if (this.sizeDistinct() != bag.sizeDistinct())
        {
            return false;
        }

        return this.items.keysView().allSatisfy((<type> key) ->
                <name>HashBag.this.occurrencesOf(key) == bag.occurrencesOf(key));
    }

    @Override
    public int hashCode()
    {
        Counter result = new Counter();
        this.forEachWithOccurrences((<type> eachItem, int occurrences) ->
                result.add(<(hashCode.(type))("eachItem")> ^ occurrences));
        return result.getCount();
    }

    @Override
    public void appendString(
            Appendable appendable,
            String start,
            String separator,
            String end)
    {
        boolean[] firstItem = {true};
        try
        {
            appendable.append(start);
            this.items.forEachKeyValue((<type> each, int occurrences) ->
            {
                try
                {
                    for (int i = 0; i \< occurrences; i++)
                    {
                        if (!firstItem[0])
                        {
                            appendable.append(separator);
                        }
                        appendable.append(String.valueOf(each));
                        firstItem[0] = false;
                    }
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            });
            appendable.append(end);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int count(<name>Predicate predicate)
    {
        Counter result = new Counter();
        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            if (predicate.accept(each))
            {
                result.add(occurrences);
            }
        });
        return result.getCount();
    }

    @Override
    public boolean anySatisfy(<name>Predicate predicate)
    {
        return this.items.keysView().anySatisfy(predicate);
    }

    @Override
    public boolean allSatisfy(<name>Predicate predicate)
    {
        return this.items.keysView().allSatisfy(predicate);
    }

    @Override
    public boolean noneSatisfy(<name>Predicate predicate)
    {
        return this.items.keysView().noneSatisfy(predicate);
    }

    @Override
    public <type> detectIfNone(<name>Predicate predicate, <type> ifNone)
    {
        return this.items.keysView().detectIfNone(predicate, ifNone);
    }

    @Override
    public \<V> MutableBag\<V> collect(<name>ToObjectFunction\<? extends V> function)
    {
        HashBag\<V> result = HashBag.newBag(this.items.size());
        this.forEachWithOccurrences((<type> each, int occurrences) ->
                result.addOccurrences(function.valueOf(each), occurrences));
        return result;
    }

    @Override
    public <type> max()
    {
        if (this.isEmpty())
        {
            throw new NoSuchElementException();
        }
        return this.items.keysView().max();
    }

    @Override
    public <type> min()
    {
        if (this.isEmpty())
        {
            throw new NoSuchElementException();
        }
        return this.items.keysView().min();
    }

    @Override
    <if(primitive.floatingPoint)>public <wideType.(type)> sum()
{
    <wideType.(type)>[] result = {<wideZero.(type)>};
    <wideType.(type)>[] compensation = {<wideZero.(type)>};
    this.forEachWithOccurrences((<type> each, int occurrences) ->
    {
        for (int i = 0; i \< occurrences; i++)
        {
            <wideType.(type)> adjustedValue = (<wideType.(type)>) each - compensation[0];
            <wideType.(type)> nextSum = result[0] + adjustedValue;
            compensation[0] = nextSum - result[0] - adjustedValue;
            result[0] = nextSum;
        }
    });
    return result[0];
}

    <else>public <wideType.(type)> sum()
{
    <wideType.(type)>[] result = {<wideZero.(type)>};
    this.forEachWithOccurrences((<type> each, int occurrences) ->
            result[0] += (<wideType.(type)>) each * occurrences);
    return result[0];
}

    <endif>
    @Override
    public <type>[] toArray()
    {
        <type>[] array = new <type>[this.size()];
        int[] index = {0};

        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            for (int i = 0; i \< occurrences; i++)
            {
                array[index[0]] = each;
                index[0]++;
            }
        });
        return array;
    }

    @Override
    public <type>[] toArray(<type>[] array)
    {
        if (array.length \< this.size())
        {
            array = new <type>[this.size()];
        }

        int[] index = {0};

        <type>[] finalBypass = array;
        this.forEachWithOccurrences((<type> each, int occurrences) ->
        {
            for (int i = 0; i \< occurrences; i++)
            {
                finalBypass[index[0]] = each;
                index[0]++;
            }
        });
        return array;
    }

    @Override
    public Mutable<name>Bag asUnmodifiable()
    {
        return new Unmodifiable<name>Bag(this);
    }

    @Override
    public Mutable<name>Bag asSynchronized()
    {
        return new Synchronized<name>Bag(this);
    }

    @Override
    public Immutable<name>Bag toImmutable()
    {
        return <name>Bags.immutable.withAll(this);
    }

    /**
     * Creates a new empty <name>HashBag.
     *
     * @since 9.2.
     */
    @Override
    public <name>HashBag newEmpty()
    {
        return new <name>HashBag();
    }

    @Override
    public Mutable<name>Iterator <type>Iterator()
    {
        return new InternalIterator();
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException
    {
        out.writeInt(this.items.size());
        try
        {
            this.items.forEachKeyValue((<type> each, int occurrences) ->
            {
                try
                {
                    out.write<name>(each);
                    out.writeInt(occurrences);
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            });
        }
        catch (RuntimeException e)
        {
            if (e.getCause() instanceof IOException)
            {
                throw (IOException) e.getCause();
            }
            throw e;
        }
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException
    {
        int size = in.readInt();
        this.items = new <name>IntHashMap(size);
        for (int i = 0; i \< size; i++)
        {
            this.addOccurrences(in.read<name>(), in.readInt());
        }
    }

    private class InternalIterator implements Mutable<name>Iterator
    {
        private Mutable<name>Iterator <type>Iterator = <name>HashBag.this.items.keySet().<type>Iterator();

        private <type> currentItem;
        private int occurrences;
        private boolean canRemove;

        @Override
        public boolean hasNext()
        {
            return this.occurrences > 0 || this.<type>Iterator.hasNext();
        }

        @Override
        public <type> next()
        {
            if (this.occurrences == 0)
            {
                this.currentItem = this.<type>Iterator.next();
                this.occurrences = <name>HashBag.this.occurrencesOf(this.currentItem);
            }
            this.occurrences--;
            this.canRemove = true;
            return this.currentItem;
        }

        @Override
        public void remove()
        {
            if (!this.canRemove)
            {
                throw new IllegalStateException();
            }
            if (this.occurrences == 0)
            {
                this.<type>Iterator.remove();
                <name>HashBag.this.size--;
            }
            else
            {
                <name>HashBag.this.remove(this.currentItem);
            }
            this.canRemove = false;
        }
    }
}

>>
