Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/test/jdk/java/util/HexFormat/HexFormatTest.java
41149 views
1
/*
2
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import org.testng.annotations.DataProvider;
25
import org.testng.annotations.Test;
26
import org.testng.SkipException;
27
28
import java.io.CharArrayWriter;
29
import java.io.IOException;
30
import java.io.UncheckedIOException;
31
import java.nio.CharBuffer;
32
import java.util.Arrays;
33
import java.util.HexFormat;
34
import java.util.Locale;
35
36
import static org.testng.Assert.assertEquals;
37
import static org.testng.Assert.assertFalse;
38
import static org.testng.Assert.assertSame;
39
import static org.testng.Assert.assertThrows;
40
import static org.testng.Assert.assertTrue;
41
import static org.testng.Assert.expectThrows;
42
43
/*
44
* @test
45
* @summary Check HexFormat formatting and parsing
46
* @run testng/othervm HexFormatTest
47
*/
48
49
@Test
50
public class HexFormatTest {
51
static final Class<NullPointerException> NPE = NullPointerException.class;
52
53
@DataProvider(name = "HexFormattersParsers")
54
Object[][] hexFormattersParsers() {
55
return new Object[][]{
56
{"", "", "", true,
57
HexFormat.of().withUpperCase()},
58
{", ", "#", "L", false,
59
HexFormat.ofDelimiter(", ").withPrefix("#").withSuffix("L")},
60
{"", "", "", false,
61
HexFormat.of().withPrefix("").withSuffix("")},
62
{".", "", "", false,
63
HexFormat.ofDelimiter(".").withPrefix("").withSuffix("")},
64
{", ", "0x", "", true,
65
HexFormat.ofDelimiter(", ").withUpperCase().withPrefix("0x")},
66
{"\u0202", "\u0203", "\u0204", false,
67
HexFormat.ofDelimiter("\u0202").withPrefix("\u0203").withSuffix("\u0204")},
68
{"\u0202", "", "", false,
69
HexFormat.ofDelimiter("\u0202")},
70
71
};
72
}
73
74
@DataProvider(name = "HexStringsThrowing")
75
Object[][] HexStringsThrowing() {
76
return new Object[][]{
77
{"0", ":", "", ""}, // wrong string length
78
{"01:", ":", "", ""}, // wrong string length
79
{"01:0", ":", "", ""}, // wrong string length
80
{"0", ",", "", ""}, // wrong length and separator
81
{"01:", ",", "", ""}, // wrong length and separator
82
{"01:0", ",", "", ""}, // wrong length and separator
83
{"01:00", ",", "", ""}, // wrong separator
84
{"00]", ",", "[", "]"}, // missing prefix
85
{"[00", ",", "[", "]"}, // missing suffix
86
{"]", ",", "[", "]"}, // missing prefix
87
{"[", ",", "[", "]"}, // missing suffix
88
{"00", ",", "abc", ""}, // Prefix longer than string
89
{"01", ",", "", "def"}, // Suffix longer than string
90
{"abc00,", ",", "abc", ""}, // Prefix and delim but not another value
91
{"01def,", ",", "", "def"}, // Suffix and delim but not another value
92
};
93
}
94
95
@DataProvider(name = "BadBytesThrowing")
96
Object[][] badBytesThrowing() {
97
return new Object[][]{
98
{new byte[1], 0, 2}, // bad toIndex
99
{new byte[1], 1, 2}, // bad fromIndex + toIndex
100
{new byte[1], -1, 2}, // bad fromIndex
101
{new byte[1], -1, 1}, // bad fromIndex
102
{new byte[1], 0, -1}, // bad toIndex
103
{new byte[1], 1, -1}, // bad toIndex
104
};
105
}
106
107
@DataProvider(name = "BadParseHexThrowing")
108
Object[][] badParseHexThrowing() {
109
return new Object[][]{
110
{"a", 0, 2, IndexOutOfBoundsException.class}, // bad toIndex
111
{"b", 1, 2, IndexOutOfBoundsException.class}, // bad toIndex
112
{"a", -1, 2, IndexOutOfBoundsException.class}, // bad fromIndex
113
{"b", -1, 1, IndexOutOfBoundsException.class}, // bad fromIndex
114
{"a", 0, -1, IndexOutOfBoundsException.class}, // bad toIndex
115
{"b", 1, -1, IndexOutOfBoundsException.class}, // bad fromIndex + toIndex
116
{"76543210", 0, 7, IllegalArgumentException.class}, // odd number of digits
117
{"zz00", 0, 4, IllegalArgumentException.class}, // non-hex digits
118
{"00zz", 0, 4, IllegalArgumentException.class}, // non-hex digits
119
};
120
}
121
122
@DataProvider(name = "BadFromHexDigitsThrowing")
123
Object[][] badHexDigitsThrowing() {
124
return new Object[][]{
125
{"a", 0, 2, IndexOutOfBoundsException.class}, // bad toIndex
126
{"b", 1, 2, IndexOutOfBoundsException.class}, // bad fromIndex + toIndex
127
{"a", -1, 2, IndexOutOfBoundsException.class}, // bad toIndex
128
{"b", -1, 1, IndexOutOfBoundsException.class}, // bad fromIndex + toIndex
129
{"a", 0, -1, IndexOutOfBoundsException.class}, // bad toIndex
130
{"b", 1, -1, IndexOutOfBoundsException.class}, // bad fromIndex + toIndex
131
};
132
}
133
134
static byte[] genBytes(int origin, int len) {
135
byte[] bytes = new byte[len];
136
for (int i = 0; i < len; i++)
137
bytes[i] = (byte) (origin + i);
138
return bytes;
139
}
140
141
@Test
142
static void testToHex() {
143
HexFormat hex = HexFormat.of();
144
for (int i = 0; i < 32; i++) {
145
char c = hex.toLowHexDigit((byte)i);
146
String expected = Integer.toHexString(i & 0xf);
147
assertEquals(c, expected.charAt(0), "toHex formatting");
148
}
149
}
150
151
@Test
152
static void testToHexDigits() {
153
HexFormat hex = HexFormat.of();
154
for (int i = 0; i < 256; i++) {
155
String actual = hex.toHexDigits((byte)i);
156
int expected = HexFormat.fromHexDigits(actual);
157
assertEquals(expected, i, "fromHexDigits");
158
assertEquals(actual.charAt(0), hex.toHighHexDigit((byte)i),
159
"first char mismatch");
160
assertEquals(actual.charAt(1), hex.toLowHexDigit((byte)i),
161
"second char mismatch");
162
}
163
}
164
165
@Test
166
static void testIsHexDigit() {
167
for (int i = 0; i < 0x3ff; i++) {
168
boolean actual = HexFormat.isHexDigit(i);
169
boolean expected = Character.digit(i, 16) >= 0;
170
assertEquals(actual, expected, "isHexDigit: " + i);
171
}
172
}
173
174
@Test
175
static void testFromHexDigit() {
176
String chars = "0123456789ABCDEF0123456789abcdef";
177
for (int i = 0; i < chars.length(); i++) {
178
int v = HexFormat.fromHexDigit(chars.charAt(i));
179
assertEquals(v, i & 0xf, "fromHex decode");
180
}
181
}
182
183
@Test
184
static void testFromHexInvalid() {
185
for (int i = 0; i < 65536; i++) {
186
char ch = (char)i;
187
if (ch > 0xff || Character.digit(ch, 16) < 0) {
188
assertFalse(HexFormat.isHexDigit(ch), "isHexDigit incorrect for '" + ch + "' = " + i);
189
expectThrows(NumberFormatException.class,
190
() -> HexFormat.fromHexDigit(ch));
191
192
}
193
}
194
}
195
196
@Test
197
static void testAppendHexByteWithStringBuilder() {
198
HexFormat hex = HexFormat.of();
199
StringBuilder sb = new StringBuilder();
200
for (int i = 0; i < 256; i++) {
201
sb.setLength(0);
202
StringBuilder sb1 = hex.toHexDigits(sb, (byte)i);
203
assertSame(sb1, sb, "toHexDigits returned different StringBuilder");
204
assertEquals(sb.length(), 2, "wrong length after append: " + i);
205
assertEquals(sb.charAt(0), hex.toHighHexDigit((byte)i), "MSB converted wrong");
206
assertEquals(sb.charAt(1), hex.toLowHexDigit((byte)i), "LSB converted wrong");
207
208
assertEquals(HexFormat.fromHexDigits(sb), i, "hex.format(sb, byte) wrong");
209
}
210
}
211
212
@Test
213
static void testAppendHexByteWithCharBuffer() {
214
HexFormat hex = HexFormat.of();
215
CharBuffer cb = CharBuffer.allocate(256);
216
for (int i = 1; i <= 128; i++) {
217
CharBuffer cb1 = hex.toHexDigits(cb, (byte)i);
218
assertTrue(cb1 == cb);
219
assertEquals(cb.position(), i * 2);
220
}
221
assertEquals(cb.remaining(), 0);
222
}
223
224
@Test
225
static void testAppendHexByteWithCharArrayWriter() {
226
HexFormat hex = HexFormat.of();
227
CharArrayWriter caw = new CharArrayWriter();
228
for (int i = 1; i <= 128; i++) {
229
CharArrayWriter caw1 = hex.toHexDigits(caw, (byte)i);
230
assertTrue(caw1 == caw);
231
assertEquals(caw.size(), i * 2);
232
}
233
}
234
235
@Test
236
static void testFromHexPairInvalid() {
237
HexFormat hex = HexFormat.of();
238
239
// An assortment of invalid characters
240
String chars = "-0--0-";
241
for (int i = 0; i < chars.length(); i += 2) {
242
final int ndx = i;
243
Throwable ex = expectThrows(NumberFormatException.class,
244
() -> HexFormat.fromHexDigits(chars.subSequence(ndx, ndx+2)));
245
System.out.println(ex);
246
}
247
}
248
249
@Test(dataProvider = "HexStringsThrowing")
250
static void testToBytesThrowing(String value, String sep, String prefix, String suffix) {
251
HexFormat hex = HexFormat.ofDelimiter(sep).withPrefix(prefix).withSuffix(suffix);
252
Throwable ex = expectThrows(IllegalArgumentException.class,
253
() -> {
254
byte[] v = hex.parseHex(value);
255
System.out.println("str: " + value + ", actual: " + v + ", bytes: " +
256
Arrays.toString(v));
257
});
258
System.out.println("ex: " + ex);
259
}
260
261
@Test
262
static void testFactoryNPE() {
263
assertThrows(NPE, () -> HexFormat.ofDelimiter(null));
264
assertThrows(NPE, () -> HexFormat.of().withDelimiter(null));
265
assertThrows(NPE, () -> HexFormat.of().withPrefix(null));
266
assertThrows(NPE, () -> HexFormat.of().withSuffix(null));
267
}
268
269
@Test
270
static void testFormatHexNPE() {
271
assertThrows(NPE, () -> HexFormat.of().formatHex(null));
272
assertThrows(NPE, () -> HexFormat.of().formatHex(null, 0, 1));
273
assertThrows(NPE, () -> HexFormat.of().formatHex(null, null));
274
assertThrows(NPE, () -> HexFormat.of().formatHex(null, null, 0, 0));
275
StringBuilder sb = new StringBuilder();
276
assertThrows(NPE, () -> HexFormat.of().formatHex(sb, null));
277
assertThrows(NPE, () -> HexFormat.of().formatHex(sb, null, 0, 1));
278
}
279
280
@Test
281
static void testParseHexNPE() {
282
assertThrows(NPE, () -> HexFormat.of().parseHex(null));
283
assertThrows(NPE, () -> HexFormat.of().parseHex((String)null, 0, 0));
284
assertThrows(NPE, () -> HexFormat.of().parseHex((char[])null, 0, 0));
285
}
286
287
@Test
288
static void testFromHexNPE() {
289
assertThrows(NPE, () -> HexFormat.fromHexDigits(null));
290
assertThrows(NPE, () -> HexFormat.fromHexDigits(null, 0, 0));
291
assertThrows(NPE, () -> HexFormat.fromHexDigitsToLong(null));
292
assertThrows(NPE, () -> HexFormat.fromHexDigitsToLong(null, 0, 0));
293
}
294
295
@Test
296
static void testToHexDigitsNPE() {
297
assertThrows(NPE, () -> HexFormat.of().toHexDigits(null, (byte)0));
298
}
299
300
@Test(dataProvider = "BadParseHexThrowing")
301
static void badParseHex(String string, int offset, int length,
302
Class<? extends Throwable> exClass) {
303
assertThrows(exClass,
304
() -> HexFormat.of().parseHex(string, offset, length));
305
char[] chars = string.toCharArray();
306
assertThrows(exClass,
307
() -> HexFormat.of().parseHex(chars, offset, length));
308
}
309
310
@Test(dataProvider = "BadFromHexDigitsThrowing")
311
static void badFromHexDigits(String string, int fromIndex, int toIndex,
312
Class<? extends Throwable> exClass) {
313
assertThrows(exClass,
314
() -> HexFormat.fromHexDigits(string, fromIndex, toIndex));
315
assertThrows(exClass,
316
() -> HexFormat.fromHexDigitsToLong(string, fromIndex, toIndex));
317
}
318
319
// Verify IAE for strings that are too long for the target primitive type
320
// or the number of requested digits is too large.
321
@Test
322
static void wrongNumberDigits() {
323
assertThrows(IllegalArgumentException.class,
324
() -> HexFormat.fromHexDigits("9876543210"));
325
assertThrows(IllegalArgumentException.class,
326
() -> HexFormat.fromHexDigits("9876543210", 0, 9));
327
assertThrows(IllegalArgumentException.class,
328
() -> HexFormat.fromHexDigitsToLong("98765432109876543210"));
329
assertThrows(IllegalArgumentException.class,
330
() -> HexFormat.fromHexDigitsToLong("98765432109876543210", 0, 17));
331
}
332
333
@Test(dataProvider="HexFormattersParsers")
334
static void testFormatter(String delimiter, String prefix, String suffix,
335
boolean uppercase,
336
HexFormat hex) {
337
byte[] expected = genBytes('A', 15);
338
String res = hex.formatHex(expected);
339
assertTrue(res.startsWith(prefix), "Prefix not found");
340
assertTrue(res.endsWith(suffix), "Suffix not found");
341
int expectedLen = expected.length * (2 + prefix.length() +
342
delimiter.length() + suffix.length()) - delimiter.length();
343
assertEquals(res.length(), expectedLen, "String length");
344
345
if (expected.length > 1) {
346
// check prefix and suffix is present for each hex pair
347
for (int i = 0; i < expected.length; i++) {
348
int valueChars = prefix.length() + 2 + suffix.length();
349
int offset = i * (valueChars + delimiter.length());
350
String value = res.substring(offset, offset + valueChars);
351
assertTrue(value.startsWith(prefix), "wrong prefix");
352
assertTrue(value.endsWith(suffix), "wrong suffix");
353
354
// Check case of digits
355
String cc = value.substring(prefix.length(), prefix.length() + 2);
356
assertEquals(cc,
357
(uppercase) ? cc.toUpperCase(Locale.ROOT) : cc.toLowerCase(Locale.ROOT),
358
"Case mismatch");
359
if (i < expected.length - 1 && !delimiter.isEmpty()) {
360
// Check the delimiter is present for each pair except the last
361
assertEquals(res.substring(offset + valueChars,
362
offset + valueChars + delimiter.length()), delimiter);
363
}
364
}
365
}
366
}
367
368
@Test(dataProvider="HexFormattersParsers")
369
static void testFormatHexString(String unused1, String unused2, String unused3,
370
boolean unused4, HexFormat hex) {
371
byte[] expected = genBytes('A', 15);
372
String s = hex.formatHex(expected);
373
System.out.println(" formatted: " + s);
374
375
byte[] actual = hex.parseHex(s);
376
System.out.println(" parsed as: " + Arrays.toString(actual));
377
int mismatch = Arrays.mismatch(expected, actual);
378
assertEquals(actual, expected, "format/parse cycle failed, mismatch: " + mismatch);
379
}
380
381
@Test(dataProvider="HexFormattersParsers")
382
static void testParseHexStringRange(String delimiter, String prefix, String suffix,
383
boolean unused4, HexFormat hex) {
384
byte[] expected = genBytes('A', 15);
385
String s = hex.formatHex(expected);
386
387
// Parse values 2, 3, 4 from the generated string
388
int low = 2;
389
int high = 5;
390
int stride = prefix.length() + 2 + suffix.length() + delimiter.length();
391
System.out.println(" formatted subrange: " +
392
s.substring(low * stride, high * stride - delimiter.length()));
393
byte[] actual = hex.parseHex(s, low * stride,
394
high * stride - delimiter.length());
395
System.out.println(" parsed as: " + Arrays.toString(actual));
396
397
assertEquals(actual.length, (high - low), "array length");
398
int mismatch = Arrays.mismatch(expected, low, high, actual, 0, high - low);
399
assertEquals(mismatch, -1, "format/parse cycle failed, mismatch: " + mismatch);
400
}
401
402
@Test(dataProvider="HexFormattersParsers")
403
static void testParseHexEmptyString(String delimiter, String prefix, String suffix,
404
boolean unused4, HexFormat hex) {
405
byte[] actual = hex.parseHex("");
406
assertEquals(actual.length, 0, "empty string parse");
407
actual = hex.parseHex("abc", 0, 0);
408
assertEquals(actual.length, 0, "empty string range parse");
409
actual = hex.parseHex(new char[1], 0, 0);
410
assertEquals(actual.length, 0, "empty char array subrange empty parse");
411
}
412
413
@Test(dataProvider="HexFormattersParsers")
414
static void testFormatHexRangeString(String unused1, String unused2, String unused3,
415
boolean unused4, HexFormat hex) {
416
byte[] expected = genBytes('A', 15);
417
int low = 1;
418
int high = expected.length - 2;
419
String s = hex.formatHex(expected, low, high);
420
System.out.println(" formatted: " + s);
421
422
byte[] actual = hex.parseHex(s);
423
System.out.println(" parsed as: " + Arrays.toString(actual));
424
int mismatch = Arrays.mismatch(expected, low, high, actual, 0, high - low);
425
assertEquals(mismatch, -1, "format/parse cycle failed, mismatch: " + mismatch);
426
}
427
428
@Test(dataProvider="HexFormattersParsers")
429
static void testFormatHexAppendable(String unused1, String unused2, String unused3,
430
boolean unused4, HexFormat hex) {
431
byte[] expected = genBytes('A', 15);
432
StringBuilder sb = new StringBuilder();
433
StringBuilder s = hex.formatHex(sb, expected);
434
assertEquals(s, sb, "formatHex returned unknown StringBuilder");
435
System.out.println(" formatted: " + s);
436
437
byte[] actual = hex.parseHex(s.toString());
438
System.out.println(" parsed as: " + Arrays.toString(actual));
439
int mismatch = Arrays.mismatch(expected, actual);
440
assertEquals(actual, expected, "format/parse cycle failed, mismatch: " + mismatch);
441
}
442
443
@Test(dataProvider="HexFormattersParsers")
444
static void testFormatHexRangeAppendable(String unused1, String unused2, String unused3,
445
boolean unused4, HexFormat hex) {
446
byte[] expected = genBytes('A', 15);
447
int low = 1;
448
int high = expected.length - 2;
449
StringBuilder sb = new StringBuilder();
450
StringBuilder s = hex.formatHex(sb, expected, low, high);
451
assertEquals(s, sb, "formatHex returned unknown StringBuilder");
452
System.out.println(" formatted: " + s);
453
454
byte[] actual = hex.parseHex(s.toString());
455
System.out.println(" parsed as: " + Arrays.toString(actual));
456
byte[] sub = Arrays.copyOfRange(expected, low, high);
457
System.out.println("actual: " + Arrays.toString(actual));
458
System.out.println("sub : " + Arrays.toString(sub));
459
int mismatch = Arrays.mismatch(expected, low, high, actual, 0, high - low);
460
461
assertEquals(actual, sub, "format/parse cycle failed, mismatch: " + mismatch);
462
assertEquals(mismatch, -1, "format/parse cycle failed, mismatch: " + mismatch);
463
}
464
465
@Test(dataProvider="HexFormattersParsers")
466
static void testFormatHexCharArray(String unused1, String unused2, String unused3,
467
boolean unused4, HexFormat hex) {
468
byte[] expected = genBytes('A', 15);
469
String s = hex.formatHex(expected);
470
System.out.println(" formatted: " + s);
471
472
char[] chars = s.toCharArray();
473
byte[] actual = hex.parseHex(chars, 0, chars.length);
474
System.out.println(" parsed as: " + Arrays.toString(actual));
475
int mismatch = Arrays.mismatch(expected, actual);
476
assertEquals(actual, expected, "format/parse cycle failed, mismatch: " + mismatch);
477
}
478
479
@Test(dataProvider="HexFormattersParsers")
480
static void testFormatHexCharArrayIndexed(String delimiter, String prefix, String suffix,
481
boolean unused4, HexFormat hex) {
482
byte[] expected = genBytes('A', 15);
483
String s = hex.formatHex(expected);
484
System.out.println(" formatted: " + s);
485
486
487
// Parse values 2, 3, 4 from the generated string
488
int low = 2;
489
int high = 5;
490
int stride = prefix.length() + 2 + suffix.length() + delimiter.length();
491
System.out.println(" formatted subrange: " +
492
s.substring(low * stride, high * stride - delimiter.length()));
493
char[] chars = s.toCharArray();
494
byte[] actual = hex.parseHex(chars, low * stride,
495
high * stride - delimiter.length());
496
System.out.println(" parsed as: " + Arrays.toString(actual));
497
498
assertEquals(actual.length, (high - low), "array length");
499
int mismatch = Arrays.mismatch(expected, low, high, actual, 0, high - low);
500
assertEquals(mismatch, -1, "format/parse cycle failed, mismatch: " + mismatch);
501
}
502
503
@Test(dataProvider="HexFormattersParsers")
504
static void testFormatterToString(String delimiter, String prefix, String suffix,
505
boolean uppercase,
506
HexFormat hex) {
507
String actual = String.format(
508
"uppercase: %s, delimiter: \"%s\", prefix: \"%s\", suffix: \"%s\"",
509
uppercase, escapeNL(delimiter), escapeNL(prefix), escapeNL(suffix));
510
System.out.println(" hex: " + actual);
511
assertEquals(actual, hex.toString(), "Formatter toString mismatch");
512
}
513
514
@Test(dataProvider="HexFormattersParsers")
515
static void testFormatterParameterMethods(String delimiter, String prefix, String suffix,
516
boolean uppercase,
517
HexFormat hex) {
518
assertEquals(hex.delimiter(), delimiter);
519
assertEquals(hex.prefix(), prefix);
520
assertEquals(hex.suffix(), suffix);
521
assertEquals(hex.isUpperCase(), uppercase);
522
}
523
524
@Test(dataProvider="HexFormattersParsers")
525
static void testFormatterTestEquals(String delimiter, String prefix, String suffix,
526
boolean uppercase,
527
HexFormat expected) {
528
HexFormat actual = HexFormat.of()
529
.withDelimiter(delimiter)
530
.withPrefix(prefix)
531
.withSuffix(suffix);
532
actual = uppercase ? actual.withUpperCase() : actual.withLowerCase();
533
534
assertEquals(actual.delimiter(), delimiter, "delimiter");
535
assertEquals(actual.prefix(), prefix, "prefix");
536
assertEquals(actual.suffix(), suffix, "suffix");
537
assertEquals(actual.isUpperCase(), uppercase, "uppercase");
538
assertTrue(actual.equals(expected), "equals method");
539
assertEquals(actual.hashCode(), expected.hashCode(), "hashCode");
540
541
assertTrue(actual.equals(actual)); // equals self
542
assertFalse(actual.equals(null)); // never equals null
543
}
544
545
@Test(dataProvider="HexFormattersParsers")
546
static void testZeroLength(String delimiter, String prefix, String suffix, boolean uppercase,
547
HexFormat hex) {
548
// Test formatting of zero length byte arrays, should produce no output
549
StringBuilder sb = new StringBuilder();
550
assertEquals(hex.formatHex(new byte[0]), "", "Zero length");
551
assertEquals(hex.formatHex(new byte[0], 0, 0), "", "Zero length");
552
553
hex.formatHex(sb, new byte[0]);
554
assertEquals(sb.length(), 0, "length should not change");
555
hex.formatHex(sb, new byte[0], 0, 0);
556
assertEquals(sb.length(), 0, "length should not change");
557
558
}
559
private static String escapeNL(String string) {
560
return string.replace("\n", "\\n")
561
.replace("\r", "\\r");
562
}
563
564
@Test
565
static void testfromHexDigitsToInt() {
566
HexFormat hex = HexFormat.of();
567
568
String allHex = "76543210";
569
final int orig = 0x76543210;
570
for (int digits = 0; digits <= 8; digits++) {
571
String s = hex.toHexDigits(orig, digits);
572
long actual = HexFormat.fromHexDigits(s, 0, digits);
573
System.out.printf(" digits: %2d, formatted: \"%s\", parsed as: 0x%08x%n",
574
digits, s, actual);
575
assertEquals(s, allHex.substring(8 - digits, 8));
576
long expected = (digits < 8) ? orig & ~(0xffffffff << (4 * digits)) : orig;
577
assertEquals(actual, expected);
578
}
579
}
580
581
@Test
582
static void testfromHexDigitsToLong() {
583
HexFormat hex = HexFormat.of();
584
585
String allHex = "fedcba9876543210";
586
final long orig = 0xfedcba9876543210L;
587
for (int digits = 0; digits <= 16; digits++) {
588
String s = hex.toHexDigits(orig, digits);
589
long actual = HexFormat.fromHexDigitsToLong(s, 0, digits);
590
System.out.printf(" digits: %2d, formatted: \"%s\", parsed as: 0x%016xL%n",
591
digits, s, actual);
592
assertEquals(s, allHex.substring(16 - digits, 16));
593
long expected = (digits < 16) ? orig & ~(0xffffffffffffffffL << (4 * digits)) : orig;
594
assertEquals(actual, expected);
595
}
596
}
597
598
@Test
599
static void testToHexDigitsLong() {
600
HexFormat hex = HexFormat.of();
601
602
String allHex = "fedcba9876543210";
603
final long expected = 0xfedcba9876543210L;
604
String s = hex.toHexDigits(expected);
605
long actual = HexFormat.fromHexDigitsToLong(s);
606
System.out.printf(" formatted: \"%s\", parsed as: 0x%016xL%n", s, actual);
607
assertEquals(s, allHex);
608
assertEquals(actual, expected);
609
}
610
611
@Test(dataProvider="HexFormattersParsers")
612
static void testIOException(String delimiter, String prefix, String suffix, boolean uppercase,
613
HexFormat hex) {
614
Appendable throwingAppendable = new ThrowingAppendable();
615
assertThrows(UncheckedIOException.class,
616
() -> hex.formatHex(throwingAppendable, new byte[1]));
617
assertThrows(UncheckedIOException.class,
618
() -> hex.formatHex(throwingAppendable, new byte[1], 0, 1));
619
assertThrows(UncheckedIOException.class,
620
() -> hex.toHexDigits(throwingAppendable, (byte)1));
621
}
622
623
@Test(dataProvider="HexFormattersParsers")
624
static void testOOME(String delimiter, String prefix, String suffix, boolean uppercase,
625
HexFormat hex) {
626
// compute the size of byte array that will exceed the buffer
627
long valueChars = prefix.length() + 2 + suffix.length();
628
long stride = valueChars + delimiter.length();
629
long max = Integer.MAX_VALUE & 0xFFFFFFFFL;
630
long len = max / stride;
631
long remainder = max - ((len - 1) * stride);
632
if (remainder > valueChars) {
633
len++;
634
remainder -= valueChars;
635
}
636
try {
637
byte[] bytes = new byte[(int) len];
638
Throwable ex = expectThrows(OutOfMemoryError.class,
639
() -> hex.formatHex(bytes));
640
System.out.println("ex: " + ex);
641
} catch (OutOfMemoryError oome) {
642
System.out.printf("OOME: total mem: %08x, free mem: %08x, max mem: %08x%n",
643
Runtime.getRuntime().totalMemory(),
644
Runtime.getRuntime().freeMemory(),
645
Runtime.getRuntime().maxMemory());
646
throw new SkipException("Insufficient Memory to test OOME");
647
}
648
649
}
650
651
/**
652
* Example code from the HexFormat javadoc.
653
* Showing simple usage of the API using "assert" to express the correct results
654
* when shown in the javadoc.
655
* The additional TestNG asserts verify the correctness of the same code.
656
*/
657
@Test
658
private static void samples() {
659
{
660
// Primitive formatting and parsing.
661
HexFormat hex = HexFormat.of();
662
663
byte b = 127;
664
String byteStr = hex.toHexDigits(b);
665
System.out.println(" " + byteStr);
666
667
byte byteVal = (byte) HexFormat.fromHexDigits(byteStr);
668
assert(byteStr.equals("7f"));
669
assert(b == byteVal);
670
assertTrue(byteStr.equals("7f"));
671
assertTrue(b == byteVal);
672
673
674
char c = 'A';
675
String charStr = hex.toHexDigits(c);
676
System.out.println(" " + charStr);
677
int charVal = HexFormat.fromHexDigits(charStr);
678
assert(c == charVal);
679
assertTrue(c == charVal);
680
681
int i = 12345;
682
String intStr = hex.toHexDigits(i);
683
System.out.println(" " + intStr);
684
int intVal = HexFormat.fromHexDigits(intStr);
685
assert(i == intVal);
686
assertTrue(i == intVal);
687
688
long l = Long.MAX_VALUE;
689
String longStr = hex.toHexDigits(l, 16);
690
long longVal = HexFormat.fromHexDigitsToLong(longStr, 0, 16);
691
System.out.println(" " + longStr + ", " + longVal);
692
assert(l == longVal);
693
assertTrue(l == longVal);
694
}
695
696
{
697
// RFC 4752 Fingerprint
698
HexFormat formatFingerprint = HexFormat.ofDelimiter(":").withUpperCase();
699
byte[] bytes = {0, 1, 2, 3, 124, 125, 126, 127};
700
String str = formatFingerprint.formatHex(bytes);
701
System.out.println(" Formatted: " + str);
702
703
byte[] parsed = formatFingerprint.parseHex(str);
704
System.out.println(" Parsed: " + Arrays.toString(parsed));
705
assert(Arrays.equals(bytes, parsed));
706
assertTrue(Arrays.equals(bytes, parsed));
707
}
708
709
{
710
// Comma separated formatting
711
HexFormat commaFormat = HexFormat.ofDelimiter(",");
712
byte[] bytes = {0, 1, 2, 3, 124, 125, 126, 127};
713
String str = commaFormat.formatHex(bytes);
714
System.out.println(" Formatted: " + str);
715
716
byte[] parsed = commaFormat.parseHex(str);
717
System.out.println(" Parsed: " + Arrays.toString(parsed));
718
assert(Arrays.equals(bytes, parsed));
719
assertTrue(Arrays.equals(bytes, parsed));
720
}
721
{
722
// Text formatting
723
HexFormat commaFormat = HexFormat.ofDelimiter(", ").withPrefix("#");
724
byte[] bytes = {0, 1, 2, 3, 124, 125, 126, 127};
725
String str = commaFormat.formatHex(bytes);
726
System.out.println(" Formatted: " + str);
727
728
byte[] parsed = commaFormat.parseHex(str);
729
System.out.println(" Parsed: " + Arrays.toString(parsed));
730
assert(Arrays.equals(bytes, parsed));
731
assertTrue(Arrays.equals(bytes, parsed));
732
}
733
}
734
735
/**
736
* A test implementation of Appendable that throws IOException on all methods.
737
*/
738
static class ThrowingAppendable implements Appendable {
739
@Override
740
public Appendable append(CharSequence csq) throws IOException {
741
throw new IOException(".append(CharSequence) always throws");
742
}
743
744
@Override
745
public Appendable append(CharSequence csq, int start, int end) throws IOException {
746
throw new IOException(".append(CharSequence, start, end) always throws");
747
}
748
749
@Override
750
public Appendable append(char c) throws IOException {
751
throw new IOException(".append(char) always throws");
752
}
753
}
754
}
755
756