Last active
September 12, 2021 10:54
-
-
Save ncruces/ca9f91d89630d27ff05e35410a89022b to your computer and use it in GitHub Desktop.
CharSequence backed by a char[]
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; | |
public final class CharArraySequence implements CharSequence { | |
private final char[] buf; | |
private final int off, len; | |
public CharArraySequence(char[] value) { | |
buf = value; | |
off = 0; | |
len = value.length; | |
} | |
public CharArraySequence(char[] value, int offset, int length) { | |
if ((offset | length | offset + length | value.length - (offset + length)) < 0) { | |
throw new IndexOutOfBoundsException(); | |
} | |
buf = value; | |
off = offset; | |
len = length; | |
} | |
@Override | |
public int length() { return len; } | |
@Override | |
public String toString() { return String.valueOf(buf, off, len); } | |
@Override | |
public char charAt(int index) { | |
if ((index | len - index - 1) < 0) { | |
throw new IndexOutOfBoundsException(); | |
} | |
return buf[off + index]; | |
} | |
@Override | |
public CharSequence subSequence(int start, int end) { | |
if ((start | end | end - start | len - end) < 0) { | |
throw new IndexOutOfBoundsException(); | |
} | |
if ((start | len - end) == 0) { | |
return this; | |
} | |
return new CharArraySequence(off + start, end - start, buf); | |
} | |
private CharArraySequence(int offset, int length, char[] value) { | |
off = offset; | |
len = length; | |
buf = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment