Skip to content

Commit 5d8615a

Browse files
committed
Add isValid method to Multibase class
Starting point of #38, generated by GitHub Copilot Workspace AI.
1 parent 6cb4cc0 commit 5d8615a

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Simply clone this repo.
1717
byte[] data = ...
1818
String encoded = Multibase.encode(Multibase.Base.Base58BTC, data);
1919
byte[] decoded = Multibase.decode(encoded);
20+
boolean isValid = Multibase.isValid(encoded);
2021
```
2122

2223
## Dependency

src/main/java/io/ipfs/multibase/Multibase.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,4 +154,13 @@ private static String safeSubstringFromIndexOne(String data) {
154154
int charIndex = data.offsetByCodePoints(0, 1);
155155
return data.substring(charIndex);
156156
}
157+
158+
public static boolean isValid(String data) {
159+
try {
160+
decode(data);
161+
return true;
162+
} catch (IllegalArgumentException | UnsupportedOperationException e) {
163+
return false;
164+
}
165+
}
157166
}

src/test/java/io/ipfs/multibase/MultibaseTest.java

100755100644
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
import static org.junit.jupiter.api.Assertions.assertEquals;
1010
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
11+
import static org.junit.jupiter.api.Assertions.assertTrue;
12+
import static org.junit.jupiter.api.Assertions.assertFalse;
1113

1214
public class MultibaseTest {
1315

@@ -67,6 +69,29 @@ public void testDecode(Multibase.Base base, byte[] raw, String encoded) {
6769
assertArrayEquals(raw, output, String.format("Expected %s, but got %s", bytesToHex(raw), bytesToHex(output)));
6870
}
6971

72+
@MethodSource("data")
73+
@ParameterizedTest(name = "{index}: {0}, {2}")
74+
public void testIsValid(Multibase.Base base, byte[] raw, String encoded) {
75+
assertTrue(Multibase.isValid(encoded));
76+
}
77+
78+
public static Collection<String> invalidData() {
79+
return Arrays.asList(
80+
"f012", // Hex string of odd length, not allowed in Base16
81+
"f0g", // 'g' char is not allowed in Base16
82+
"zt1Zv2yaI", // 'I' char is not allowed in Base58
83+
"2", // '2' is not a valid encoding marker
84+
"", // Empty string is not a valid multibase
85+
"🚀🫕" // This Emoji (Swiss Fondue) is not part of the Base256Emoji table
86+
);
87+
}
88+
89+
@MethodSource("invalidData")
90+
@ParameterizedTest(name = "{index}: \"{0}\"")
91+
public void testIsInvalid(String input) {
92+
assertFalse(Multibase.isValid(input));
93+
}
94+
7095
//Copied from https://stackoverflow.com/a/140861
7196
private static byte[] hexToBytes(String s) {
7297
int len = s.length();

0 commit comments

Comments
 (0)