Created ByteInput#readString() to handle dynamic length strings

This commit is contained in:
Collin Smith 2020-12-11 18:27:13 -08:00
parent c29d7bfd39
commit fd795892b0
2 changed files with 17 additions and 1 deletions

View File

@ -560,7 +560,7 @@ public class BitInput {
*
* @param maxLen maximum number of characters to read
* @param bits size of each character ({@code 7} or {@code 8})
* @param nullTerminated {@code true} to stop reading at {@code '\0}'
* @param nullTerminated {@code true} to stop reading at {@code '\0'}
*/
public String readString(int maxLen, int bits, boolean nullTerminated) {
if (maxLen < 0) throw new IllegalArgumentException("maxLen(" + maxLen + ") < " + 0);

View File

@ -536,4 +536,20 @@ public class ByteInput {
throw new EndOfInput(t);
}
}
/**
* Reads bytes until {@code '\0'} is encountered and constructs a string.
*/
public String readString() {
assert aligned() : "not aligned";
int length = buffer.bytesBefore((byte) '\0');
if (length == -1) {
throw new EndOfInput(new IndexOutOfBoundsException(
"Failed to find null-termination for string!"));
}
incrementBitsRead((long) length * Byte.SIZE);
CharSequence charSequence = buffer.readCharSequence(length, CharsetUtil.US_ASCII);
skipBytes(1);
return charSequence.toString();
}
}