blob: 50743befd1c9d668cb74db8c0002c24cc9c4f9e0 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2007, 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.input;
import org.eclipse.statet.jcommons.lang.NonNullByDefault;
/**
* Text parser input for string representing only a part of the source.
*/
@NonNullByDefault
public final class OffsetStringParserInput extends TextParserInput implements CharSequence {
private final String source;
private final int sourceOffset;
public OffsetStringParserInput(final String source, final int sourceOffset,
final int defaultBufferSize) {
super(defaultBufferSize);
this.source= source;
this.sourceOffset= sourceOffset;
}
public OffsetStringParserInput(final String source, final int sourceOffset) {
this(source, sourceOffset,
Math.min(source.length(), DEFAULT_BUFFER_SIZE) );
}
@Override
public OffsetStringParserInput init(final int startIndex, final int stopIndex) {
super.init(startIndex, stopIndex);
return this;
}
public OffsetStringParserInput initAtOffset() {
super.init(this.sourceOffset, Integer.MIN_VALUE);
return this;
}
@Override
protected int getSourceStartIndex() {
return this.sourceOffset;
}
@Override
protected int getSourceLength() {
return this.source.length();
}
@Override
protected String getSourceString() {
return this.source;
}
@Override
protected int getSourceStringIndex() {
return this.sourceOffset;
}
@Override
protected void doUpdateBuffer(final int index, final char[] buffer,
final int requiredLength, final int recommendLength) {
final int length= Math.min(recommendLength, getStopIndex() - index);
this.source.getChars(index - this.sourceOffset, index - this.sourceOffset + length, buffer, 0);
setBuffer(buffer, 0, length);
}
/*- CharSequence ---------------------------------------------------------------------------------*/
@Override
public int length() {
return this.sourceOffset + this.source.length();
}
@Override
public char charAt(final int index) {
return this.source.charAt(index - this.sourceOffset);
}
@Override
public String subSequence(final int start, final int end) {
return this.source.substring(this.sourceOffset + start, this.sourceOffset + end);
}
}