1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.rng.examples.stress;
18
19 import org.junit.jupiter.api.Assertions;
20 import org.junit.jupiter.api.Test;
21
22 import java.util.Arrays;
23 import java.util.Locale;
24 import java.util.concurrent.ThreadLocalRandom;
25
26
27
28
29 class HexTest {
30
31 private static final char[] DIGITS = {
32 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
33 };
34
35
36
37
38
39
40
41 @Test
42 void testHexEncodeAndDecode() {
43
44 for (int size = 0; size < 10; size++) {
45 assertHexEncodeAndDecode(new byte[size]);
46 }
47
48 for (int size : new int[] {3, 4, 5, 8, 16, 31}) {
49 final byte[] bytes = new byte[size];
50 for (int i = 0; i < 5; i++) {
51 ThreadLocalRandom.current().nextBytes(bytes);
52 assertHexEncodeAndDecode(bytes);
53 }
54 }
55 }
56
57
58
59
60
61
62 private static void assertHexEncodeAndDecode(byte[] bytes) {
63
64 final StringBuilder sb = new StringBuilder();
65 sb.append(Hex.encodeHex(bytes));
66 final byte[] decoded = Hex.decodeHex(sb);
67 Assertions.assertArrayEquals(bytes, decoded);
68 }
69
70
71
72
73
74
75
76 @Test
77 void testHexDecodeAndEncode() {
78
79
80 for (int size = 0; size < 10; size++) {
81 final char[] chars = new char[size * 2];
82 Arrays.fill(chars, '0');
83 assertHexDecodeAndEncode(chars);
84 }
85
86 for (int size : new int[] {3, 4, 5, 8, 16, 31}) {
87 final char[] chars = new char[size * 2];
88 for (int i = 0; i < 5; i++) {
89
90 for (int j = 0; j < chars.length; j++) {
91 chars[j] = DIGITS[ThreadLocalRandom.current().nextInt(16)];
92 }
93 assertHexDecodeAndEncode(chars);
94 }
95 }
96 }
97
98
99
100
101
102
103 private static void assertHexDecodeAndEncode(char[] chars) {
104 final String text = String.valueOf(chars);
105 final byte[] decoded = Hex.decodeHex(text);
106
107 Assertions.assertArrayEquals(text.toLowerCase(Locale.US).toCharArray(), Hex.encodeHex(decoded));
108 }
109
110 @Test
111 void testHexThrowsWithOddNumberOfCharacters() {
112 Assertions.assertThrows(IllegalArgumentException.class, () -> Hex.decodeHex("0"));
113 }
114
115 @Test
116 void testHexThrowsWithIllegalHexCharacters() {
117 Assertions.assertThrows(IllegalArgumentException.class, () -> Hex.decodeHex("0g"));
118 }
119 }