blob: cf6e99ac17d912e743b0093a3e635baa6aed4ccc [file] [log] [blame]
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +01001package eu.mulk.jgvariant.ostree;
2
3import eu.mulk.jgvariant.core.Decoder;
4import java.util.Arrays;
5import java.util.HexFormat;
Matthias Andreas Benkard05114642021-12-29 21:51:29 +01006import java.util.stream.IntStream;
7import java.util.stream.Stream;
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +01008
9/**
10 * A wrapper for a {@code byte[]} that implements {@link #equals(Object)}, {@link #hashCode()}, and
11 * {@link #toString()} according to value semantics.
Matthias Andreas Benkard05114642021-12-29 21:51:29 +010012 *
13 * @param bytes the byte array that this ByteString wraps.
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +010014 */
15public record ByteString(byte[] bytes) {
16
17 private static final Decoder<ByteString> DECODER = Decoder.ofByteArray().map(ByteString::new);
18
Matthias Andreas Benkard05114642021-12-29 21:51:29 +010019 /**
20 * Returns a decoder for a {@code byte[]} that wraps the result in {@link ByteString}.
21 *
22 * @return a possibly shared {@link Decoder}.
23 */
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +010024 public static Decoder<ByteString> decoder() {
25 return DECODER;
26 }
27
28 @Override
29 public boolean equals(Object o) {
30 return (o instanceof ByteString byteString) && Arrays.equals(bytes, byteString.bytes);
31 }
32
33 @Override
34 public int hashCode() {
35 return Arrays.hashCode(bytes);
36 }
37
38 @Override
39 public String toString() {
40 return "ByteString{hex=\"%s\"}".formatted(hex());
41 }
42
Matthias Andreas Benkard05114642021-12-29 21:51:29 +010043 /**
44 * Converts the contained byte array into a hex string.
45 *
46 * <p>Useful for printing.
47 *
48 * @return a hex string representation of this byte string.
49 */
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +010050 public String hex() {
51 return HexFormat.of().formatHex(bytes);
52 }
53
Matthias Andreas Benkard05114642021-12-29 21:51:29 +010054 /**
55 * Parses a hex string into a {@link ByteString}.
56 *
57 * @param hex a hex string.
58 * @return a {@link ByteString} corresponding to the given hex string.
59 */
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +010060 public static ByteString ofHex(String hex) {
61 return new ByteString(HexFormat.of().parseHex(hex));
62 }
Matthias Andreas Benkard05114642021-12-29 21:51:29 +010063
64 /**
65 * Returns the number of bytes in the byte string.
66 *
67 * @return the number of bytes in the byte string.
68 */
69 public int size() {
70 return bytes.length;
71 }
72
73 /**
74 * Returns a {@link Stream} of all the bytes in the byte string.
75 *
76 * @return a new {@link Stream}.
77 */
78 Stream<Byte> stream() {
79 return IntStream.range(0, bytes.length).mapToObj(i -> bytes[i]);
80 }
Matthias Andreas Benkard4e8423d2021-12-19 22:56:09 +010081}