|
1 | 1 | package io.ipfs.multibase; |
2 | 2 |
|
3 | 3 | import java.util.Map; |
| 4 | +import java.util.Optional; |
4 | 5 | import java.util.TreeMap; |
5 | 6 |
|
6 | 7 | import io.ipfs.multibase.binary.Base32; |
@@ -45,14 +46,21 @@ public enum Base { |
45 | 46 | lookup.put(b.prefix, b); |
46 | 47 | } |
47 | 48 |
|
48 | | - public static Base lookup(String data) { |
| 49 | + private static Optional<Base> lookupOptional(String data) { |
| 50 | + if (data == null || data.isEmpty()) |
| 51 | + return Optional.empty(); |
49 | 52 | String p = Character.toString(data.codePointAt(0)); |
50 | 53 | Base base = lookup.get(p); |
51 | 54 | if (base != null) |
52 | | - return base; |
| 55 | + return Optional.of(base); |
53 | 56 | if (data.startsWith(Base256Emoji.prefix)) |
54 | | - return Base256Emoji; |
55 | | - throw new IllegalArgumentException("Unknown Multibase type: " + p); |
| 57 | + return Optional.of(Base256Emoji); |
| 58 | + return Optional.empty(); |
| 59 | + } |
| 60 | + |
| 61 | + public static Base lookup(String data) { |
| 62 | + return lookupOptional(data) |
| 63 | + .orElseThrow(() -> new IllegalArgumentException("Unknown Multibase type: " + data)); |
56 | 64 | } |
57 | 65 | } |
58 | 66 |
|
@@ -154,4 +162,22 @@ private static String safeSubstringFromIndexOne(String data) { |
154 | 162 | int charIndex = data.offsetByCodePoints(0, 1); |
155 | 163 | return data.substring(charIndex); |
156 | 164 | } |
| 165 | + |
| 166 | + /** |
| 167 | + * Check if the given data has a valid multibase prefix. |
| 168 | + * |
| 169 | + * <p> |
| 170 | + * Please note that "having a valid prefix" is NOT the same as "being an |
| 171 | + * entirely valid multibase string"; even if <tt>true</tt>, it's still entirely |
| 172 | + * possible for {@link #decode(String)} to throw an |
| 173 | + * <tt>IllegalArgumentException</tt>, if prefix is valid, but the following |
| 174 | + * data is not. |
| 175 | + * |
| 176 | + * @param data Multibase string to check. |
| 177 | + * @return true if the data has a valid multibase prefix, false otherwise; but |
| 178 | + * see above. |
| 179 | + */ |
| 180 | + public static boolean hasValidPrefix(String data) { |
| 181 | + return Base.lookupOptional(data).isPresent(); |
| 182 | + } |
157 | 183 | } |
0 commit comments