LinkedCycle.java

/*
 * SPDX-FileCopyrightText: 2025 kaumei.io
 * SPDX-License-Identifier: Apache-2.0
 */
package io.kaumei.jdbc.anno.store;

import org.jspecify.annotations.Nullable;

import java.util.*;

public class LinkedCycle<T> {
    private final Set<T> set = new HashSet<>();
    private final LinkedList<T> list = new LinkedList<>();

    public boolean hasLast(@Nullable T value) {
        return value != null && !list.isEmpty() && value.equals(list.getLast());
    }

    public boolean push(T value) {
        var result = this.set.add(value);
        if (result) {
            list.add(value);
        }
        return result;
    }

    public void pop() {
        set.remove(list.removeLast());
    }

    public List<T> asList() {
        return new ArrayList<>(list);
    }

    public List<T> calculateCycle(List<T> fullCycle) {
        var cycle = new ArrayList<T>();
        int start = this.list.size() - 1;
        for (int i = start; i < fullCycle.size(); i++) {
            cycle.add(fullCycle.get(i));
        }
        cycle.add(fullCycle.get(start));
        return cycle;
    }

}