Skip to content

Commit d5ccb59

Browse files
committed
Improve Multihash.digestLength() implementation
1 parent 5b23196 commit d5ccb59

1 file changed

Lines changed: 9 additions & 17 deletions

File tree

src/main/java/com/apicatalog/multihash/Multihash.java

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -214,20 +214,8 @@ public byte[] decode(byte[] encoded, int index, int length) {
214214
throw new IllegalArgumentException(
215215
"The requested decode length (" + length + ") is greater than the available bytes (" + (encoded.length - index) + ").");
216216
}
217-
218-
if (length < (codeVarint.length + 2)) {
219-
throw new IllegalArgumentException(
220-
"The value to decode must be a non-empty byte array with a minimum length of "
221-
+ (codeVarint.length + 2) + " bytes, but the actual length is " + length + " bytes.");
222-
}
223-
224-
if (!IntStream.range(0, codeVarint.length).allMatch(i -> codeVarint[i] == encoded[i + index])) {
225-
throw new IllegalArgumentException(
226-
"The provided value is not encoded with this multihash: " + toString() + ".");
227-
}
228-
229-
// Get digest size
230-
long size = UVarInt.decode(encoded, index + codeVarint.length);
217+
218+
long size = digestLength(encoded, index, length);
231219
int sizeVarintLength = UVarInt.byteLength(size);
232220

233221
if (size != (length - codeVarint.length - sizeVarintLength)) {
@@ -261,7 +249,7 @@ public byte[] decode(byte[] encoded, int index, int length) {
261249
* with this multihash's code
262250
*/
263251
public long digestLength(byte[] encoded) {
264-
return digestLength(encoded, 0);
252+
return digestLength(encoded, 0, encoded.length);
265253
}
266254

267255
/**
@@ -288,12 +276,16 @@ public long digestLength(byte[] encoded) {
288276
* available range
289277
*/
290278
public long digestLength(byte[] encoded, int index) {
279+
return digestLength(encoded, index, encoded.length - index);
280+
}
281+
282+
protected long digestLength(byte[] encoded, int index, int length) {
291283
Objects.requireNonNull(encoded);
292284

293-
if (encoded.length < (codeVarint.length + 2)) {
285+
if (length < (codeVarint.length + 2)) {
294286
throw new IllegalArgumentException(
295287
"The value to decode must be a non-empty byte array with a minimum length of "
296-
+ (codeVarint.length + 2) + " bytes, but the actual length is " + encoded.length + " bytes.");
288+
+ (codeVarint.length + 2) + " bytes, but the actual length is " + length + " bytes.");
297289
}
298290

299291
if (!IntStream.range(0, codeVarint.length).allMatch(i -> codeVarint[i] == encoded[i + index])) {

0 commit comments

Comments
 (0)