@@ -242,6 +242,68 @@ public byte[] decode(byte[] encoded, int index, int length) {
242242 length + index );
243243 }
244244
245+ /**
246+ * Returns the digest length (in bytes) declared by the given multihash-encoded
247+ * value, starting at offset {@code 0}.
248+ *
249+ * <p>
250+ * This is a convenience method equivalent to {@link #digestLength(byte[], int)
251+ * hashLength(encoded, 0)}.
252+ * </p>
253+ *
254+ * @param encoded the multihash-encoded byte array
255+ * @return the declared digest length, in bytes
256+ *
257+ * @throws NullPointerException if {@code encoded} is {@code null}
258+ * @throws IllegalArgumentException if the input is shorter than
259+ * {@code codeVarint.length + 2} bytes, or if
260+ * the bytes at offset {@code 0} do not start
261+ * with this multihash's code
262+ */
263+ public long digestLength (byte [] encoded ) {
264+ return digestLength (encoded , 0 );
265+ }
266+
267+ /**
268+ * Returns the digest length (in bytes) declared by the given multihash-encoded
269+ * value.
270+ *
271+ * <p>
272+ * The method validates that the input begins at {@code index} with this
273+ * multihash's varint code, then decodes the varint length that immediately
274+ * follows the code.
275+ * </p>
276+ *
277+ * @param encoded the multihash-encoded byte array
278+ * @param index the starting offset within {@code encoded} at which the
279+ * multihash begins
280+ * @return the declared digest length, in bytes
281+ *
282+ * @throws NullPointerException if {@code encoded} is {@code null}
283+ * @throws IllegalArgumentException if the input is shorter than
284+ * {@code codeVarint.length + 2} bytes, or if
285+ * the bytes at {@code index} do not start
286+ * with this multihash's code
287+ * @throws IndexOutOfBoundsException if {@code index} is negative or exceeds the
288+ * available range
289+ */
290+ public long digestLength (byte [] encoded , int index ) {
291+ Objects .requireNonNull (encoded );
292+
293+ if (encoded .length < (codeVarint .length + 2 )) {
294+ throw new IllegalArgumentException (
295+ "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." );
297+ }
298+
299+ if (!IntStream .range (0 , codeVarint .length ).allMatch (i -> codeVarint [i ] == encoded [i + index ])) {
300+ throw new IllegalArgumentException (
301+ "The provided value is not encoded with this multihash: " + toString () + "." );
302+ }
303+
304+ return UVarInt .decode (encoded , index + codeVarint .length );
305+ }
306+
245307 @ Override
246308 public String toString () {
247309 return "Multihash [name=" + name + ", tag=" + tag + ", code=" + code + "]" ;
0 commit comments