blob: 77e222b693b1f5c74612b5dbf77400044b8075cb [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2018, 2021 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.jcommons.text.core;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
import org.eclipse.statet.jcommons.lang.Nullable;
@NonNullByDefault
public class BasicTextRegion implements TextRegion {
private final int startOffset;
private final int endOffset;
/**
* @param startOffset the starting offset, inclusive
* @param endOffset the ending offset, exclusive
*/
public BasicTextRegion(final int startOffset, final int endOffset) {
if (startOffset > endOffset) {
throw new IllegalArgumentException("startOffset > endOffset: startOffset= " + startOffset + ", endOffset= " + endOffset); //$NON-NLS-1$ //$NON-NLS-2$
}
this.startOffset= startOffset;
this.endOffset= endOffset;
}
public BasicTextRegion(final int offset) {
this.startOffset= offset;
this.endOffset= offset;
}
public BasicTextRegion(final TextRegion region) {
this(region.getStartOffset(), region.getEndOffset());
}
@Override
public final int getStartOffset() {
return this.startOffset;
}
@Override
public final int getEndOffset() {
return this.endOffset;
}
@Override
public final int getLength() {
return this.endOffset - this.startOffset;
}
@Override
public int hashCode() {
return (this.startOffset << 24) | (getLength() << 16);
}
protected boolean equalsByOffsets(final TextRegion other) {
return (this.startOffset == other.getStartOffset()
&& this.endOffset == other.getEndOffset() );
}
@Override
public boolean equals(final @Nullable Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof TextRegion) {
return equalsByOffsets((TextRegion) obj);
}
return false;
}
protected final void appendIntervalString(final StringBuilder sb) {
sb.append('[');
sb.append(this.startOffset);
sb.append(',');
sb.append(this.endOffset);
sb.append(')');
}
@Override
public String toString() {
final StringBuilder sb= new StringBuilder();
appendIntervalString(sb);
return sb.toString();
}
}