Skip to content

Instantly share code, notes, and snippets.

@ncruces
Last active September 12, 2021 10:54
Show Gist options
  • Save ncruces/ca9f91d89630d27ff05e35410a89022b to your computer and use it in GitHub Desktop.
Save ncruces/ca9f91d89630d27ff05e35410a89022b to your computer and use it in GitHub Desktop.
CharSequence backed by a char[]
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