001: // Copyright (c) 2001, 2002, 2003 Per M.A. Bothner and Brainfood Inc.
002: // This is free software; for terms and warranty disclaimer see ./COPYING.
003:
004: package gnu.lists;
005:
006: /** A sequence consisting of a sub-range of the elements of a base sequence.
007: * The start and end positions are positions triples (on the same sequence).
008: */
009:
010: public class SubSequence extends AbstractSequence implements Sequence {
011: /** Normally the Sequence this a sub-sequence of.
012: * Actually the sequence that provides context for the
013: * start and end position pairs. */
014: AbstractSequence base;
015:
016: /** Integer part of start position. */
017: int ipos0;
018:
019: /** Integer part of end position. */
020: int ipos1;
021:
022: public SubSequence() {
023: }
024:
025: public SubSequence(AbstractSequence base, int startPos, int endPos) {
026: this .base = base;
027: this .ipos0 = startPos;
028: this .ipos1 = endPos;
029: }
030:
031: public SubSequence(AbstractSequence base) {
032: this .base = base;
033: }
034:
035: public Object get(int index) {
036: if (index < 0 || index >= size())
037: throw new IndexOutOfBoundsException();
038: int start = base.nextIndex(ipos0);
039: return base.get(start + index);
040: }
041:
042: public int size() {
043: return base.getIndexDifference(ipos1, ipos0);
044: }
045:
046: public void removePosRange(int istart, int iend) {
047: base
048: .removePosRange(istart == 0 ? ipos0
049: : istart == -1 ? ipos1 : istart,
050: iend == -1 ? ipos1 : iend == 0 ? ipos0 : iend);
051: }
052:
053: protected boolean isAfterPos(int ipos) {
054: return base.isAfterPos(ipos);
055: }
056:
057: public int createPos(int offset, boolean isAfter) {
058: return base.createRelativePos(ipos0, offset, isAfter);
059: }
060:
061: public int createRelativePos(int pos, int offset, boolean isAfter) {
062: return base.createRelativePos(pos, offset, isAfter);
063: }
064:
065: protected int getIndexDifference(int ipos1, int ipos0) {
066: return base.getIndexDifference(ipos1, ipos0);
067: }
068:
069: public void releasePos(int ipos) {
070: base.releasePos(ipos);
071: }
072:
073: protected int nextIndex(int ipos) {
074: return getIndexDifference(ipos, ipos0);
075: }
076:
077: public int compare(int ipos1, int ipos2) {
078: return base.compare(ipos1, ipos2);
079: }
080:
081: public Object getPosNext(int ipos) {
082: if (base.compare(ipos, ipos1) >= 0)
083: return eofValue;
084: return base.getPosNext(ipos);
085: }
086:
087: public int getNextKind(int ipos) {
088: if (base.compare(ipos, ipos1) >= 0)
089: return EOF_VALUE;
090: return base.getNextKind(ipos);
091: }
092:
093: public Object getPosPrevious(int ipos) {
094: if (base.compare(ipos, ipos0) <= 0)
095: return eofValue;
096: return base.getPosPrevious(ipos);
097: }
098:
099: public void clear() {
100: removePosRange(ipos0, ipos1);
101: }
102:
103: public void finalize() {
104: base.releasePos(ipos0);
105: base.releasePos(ipos1);
106: }
107: }
|