Skip to content

Commit c29f742

Browse files
committed
Extend isEncoded(byte[]) of optional index+length parameters. Fix #120
1 parent 60f8f3f commit c29f742

1 file changed

Lines changed: 29 additions & 3 deletions

File tree

src/main/java/com/apicatalog/multicodec/Multicodec.java

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,34 @@ public byte[] encode(final byte[] value, int index, int length) {
177177
* prefix, {@code false} otherwise
178178
*/
179179
public boolean isEncoded(final byte[] encoded) {
180+
return isEncoded(encoded, 0, encoded.length);
181+
}
182+
183+
/**
184+
* Checks if the given encoded byte array starts with this codec's varint code.
185+
*
186+
* @param encoded the byte array to test
187+
* @param index the starting index (inclusive)
188+
* @return {@code true} if {@code encoded} starts with this codec's varint
189+
* prefix, {@code false} otherwise
190+
*/
191+
public boolean isEncoded(final byte[] encoded, final int index) {
192+
return isEncoded(encoded, index, encoded.length - index);
193+
}
194+
195+
/**
196+
* Checks if the given encoded byte array starts with this codec's varint code.
197+
*
198+
* @param encoded the byte array to test
199+
* @param index the starting index (inclusive)
200+
* @param length the number of bytes to read from {@code index}
201+
* @return {@code true} if {@code encoded} starts with this codec's varint
202+
* prefix, {@code false} otherwise
203+
*/
204+
public boolean isEncoded(final byte[] encoded, final int index, final int length) {
180205
return encoded != null
181-
&& encoded.length >= codeVarint.length
182-
&& IntStream.range(0, codeVarint.length).allMatch(i -> codeVarint[i] == encoded[i]);
206+
&& length >= codeVarint.length
207+
&& IntStream.range(0, codeVarint.length).allMatch(i -> codeVarint[i] == encoded[i + index]);
183208
}
184209

185210
/**
@@ -228,7 +253,8 @@ public byte[] decode(final byte[] encoded, final int index, final int length) {
228253

229254
if (length > (encoded.length - index)) {
230255
throw new IllegalArgumentException(
231-
"The requested decode length (" + length + ") is greater than the available bytes (" + (encoded.length - index) + ").");
256+
"The requested decode length (" + length + ") is greater than the available bytes ("
257+
+ (encoded.length - index) + ").");
232258
}
233259

234260
if (length < (codeVarint.length + 1)) {

0 commit comments

Comments
 (0)