/*
 * Copyright (c) 2022 MiLaboratories Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.milaboratory.util;

import java.util.Arrays;
import java.util.List;

/**
 * Primitive type variant of {@link BottomN}
 */
public final class BottomNByte {
    private int len;
    private final byte[] elements;

    public BottomNByte(int n) {
        this.elements = new byte[n];
    }

    public void add(byte e) {
        int i = Arrays.binarySearch(elements, 0, len, e);
        if (len < elements.length) {
            if (i < 0)
                i = -1 - i;
            System.arraycopy(elements, i, elements, i + 1, len - i);
            len++;
        } else {
            if (i == len - 1 || i == -1 - len)
                // All elements in array are smaller or equal than e
                return;
            if (i < 0)
                i = -1 - i;
            System.arraycopy(elements, i, elements, i + 1, len - i - 1);
        }
        elements[i] = e;
    }

    public byte[] result() {
        if (len < elements.length)
            return Arrays.copyOf(elements, len);
        else
            return elements;
    }
}
