/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.util;

/**
 * This class holds begin and length pointers to a {@link String} object. This is useful when you want to process
 * a sub-string but do not necessarily want to perform a copy of the original string up-front. Methods are provided
 * to return the intersection.
 *
 * @author Alex Leigh
 */
public final class StringRun {
    private final int beginIndex;
    private final int endIndex;

    public StringRun(final int beginIndex, final int endIndex) {
        this.beginIndex = beginIndex;
        this.endIndex = endIndex;
    }

    public int getBeginIndex() {
        return beginIndex;
    }

    public int getEndIndex() {
        return endIndex;
    }


    public String subString(final String original) {
        final int len = original.length();
        if (len <= beginIndex) throw new IllegalArgumentException();

        if (len > endIndex)
            return original.substring(beginIndex, endIndex + 1);
        else
            return original.substring(beginIndex, len);

    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final StringRun stringRun = (StringRun) o;

        if (beginIndex != stringRun.beginIndex) return false;
        return endIndex == stringRun.endIndex;

    }

    @Override
    public int hashCode() {
        int result = beginIndex;
        result = 31 * result + endIndex;
        return result;
    }

    @Override
    public String toString() {
        return "StringRun{" +
                "beginIndex=" + beginIndex +
                ", endIndex=" + endIndex +
                "} " + super.toString();
    }
}
