Last active
December 12, 2017 03:01
-
-
Save ncruces/eae7c3771c455914b2f457bb66c06903 to your computer and use it in GitHub Desktop.
CharacterIterator backed by a CharSequence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package io.github.ncruces.utils; | |
import java.text.CharacterIterator; | |
public final class CharSequenceCharacterIterator implements CharacterIterator { | |
private final CharSequence seq; | |
private int pos; | |
public CharSequenceCharacterIterator(CharSequence sequence) { | |
if (sequence == null) throw new NullPointerException(); | |
seq = sequence; | |
} | |
@Override | |
public char first() { | |
pos = 0; | |
return seq.length() > 0 ? seq.charAt(0) : DONE; | |
} | |
@Override | |
public char last() { | |
int len = seq.length(); | |
if (len > 0) return seq.charAt(pos = len - 1); | |
pos = 0; | |
return DONE; | |
} | |
@Override | |
public char current() { | |
if (pos >= seq.length()) return DONE; | |
return seq.charAt(pos); | |
} | |
@Override | |
public char next() { | |
int len = seq.length(); | |
if (pos < len - 1) { | |
return seq.charAt(++pos); | |
} | |
pos = len; | |
return DONE; | |
} | |
@Override | |
public char previous() { | |
if (pos > 0) { | |
return seq.charAt(--pos); | |
} | |
return DONE; | |
} | |
@Override | |
public char setIndex(int i) { | |
if ((i | seq.length() - i) < 0) throw new IllegalArgumentException(); | |
pos = i; | |
return current(); | |
} | |
@Override | |
public int getIndex() { | |
return pos; | |
} | |
@Override | |
public int getBeginIndex() { | |
return 0; | |
} | |
@Override | |
public int getEndIndex() { | |
return seq.length(); | |
} | |
@Override | |
public CharSequenceCharacterIterator clone() { | |
try { | |
return (CharSequenceCharacterIterator)super.clone(); | |
} catch (CloneNotSupportedException e) { | |
throw new InternalError(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment