Matthias Andreas Benkard | 4e8423d | 2021-12-19 22:56:09 +0100 | [diff] [blame] | 1 | package eu.mulk.jgvariant.ostree; |
| 2 | |
| 3 | import eu.mulk.jgvariant.core.Decoder; |
| 4 | import java.util.Arrays; |
| 5 | import java.util.HexFormat; |
| 6 | |
| 7 | /** |
| 8 | * A wrapper for a {@code byte[]} that implements {@link #equals(Object)}, {@link #hashCode()}, and |
| 9 | * {@link #toString()} according to value semantics. |
| 10 | */ |
| 11 | public record ByteString(byte[] bytes) { |
| 12 | |
| 13 | private static final Decoder<ByteString> DECODER = Decoder.ofByteArray().map(ByteString::new); |
| 14 | |
| 15 | public static Decoder<ByteString> decoder() { |
| 16 | return DECODER; |
| 17 | } |
| 18 | |
| 19 | @Override |
| 20 | public boolean equals(Object o) { |
| 21 | return (o instanceof ByteString byteString) && Arrays.equals(bytes, byteString.bytes); |
| 22 | } |
| 23 | |
| 24 | @Override |
| 25 | public int hashCode() { |
| 26 | return Arrays.hashCode(bytes); |
| 27 | } |
| 28 | |
| 29 | @Override |
| 30 | public String toString() { |
| 31 | return "ByteString{hex=\"%s\"}".formatted(hex()); |
| 32 | } |
| 33 | |
| 34 | public String hex() { |
| 35 | return HexFormat.of().formatHex(bytes); |
| 36 | } |
| 37 | |
| 38 | public static ByteString ofHex(String hex) { |
| 39 | return new ByteString(HexFormat.of().parseHex(hex)); |
| 40 | } |
| 41 | } |