|
25 | 25 | import org.junit.Test; |
26 | 26 |
|
27 | 27 | import java.math.BigInteger; |
| 28 | +import java.nio.charset.Charset; |
| 29 | +import java.nio.charset.StandardCharsets; |
28 | 30 | import java.util.Arrays; |
29 | 31 | import java.util.List; |
30 | 32 | import java.util.Random; |
@@ -299,4 +301,50 @@ public void testRightShiftAgainstRefImpl() { |
299 | 301 | } |
300 | 302 | } |
301 | 303 | } |
| 304 | + |
| 305 | + @Test |
| 306 | + public void testCharToByteArray() { |
| 307 | + Charset[] charsets = new Charset[]{StandardCharsets.UTF_8, StandardCharsets.US_ASCII, StandardCharsets.UTF_16}; |
| 308 | + for (Charset charset : charsets) { |
| 309 | + checkCharArrayToByteArray("".toCharArray(), charset); |
| 310 | + checkCharArrayToByteArray("A".toCharArray(), charset); |
| 311 | + checkCharArrayToByteArray("12".toCharArray(), charset); |
| 312 | + checkCharArrayToByteArray("XYZ".toCharArray(), charset); |
| 313 | + checkCharArrayToByteArray("abcdefg".toCharArray(), charset); |
| 314 | + checkCharArrayToByteArray("71oh872gdl2dhp81g".toCharArray(), charset); |
| 315 | + |
| 316 | + } |
| 317 | + |
| 318 | + checkCharArrayToByteArray("யe2ாமறிந்தиют убSîne klâwenasd1".toCharArray(), StandardCharsets.UTF_8); |
| 319 | + } |
| 320 | + |
| 321 | + private void checkCharArrayToByteArray(char[] subject, Charset charset) { |
| 322 | + for (int lenI = 1; lenI < subject.length + 1; lenI++) { |
| 323 | + for (int offsetI = 0; offsetI < subject.length; offsetI++) { |
| 324 | + if (offsetI + lenI > subject.length) break; |
| 325 | + byte[] bytes = Util.charToByteArray(subject, charset, offsetI, lenI); |
| 326 | + assertEquals(Bytes.wrap(bytes), Bytes.wrap(new String(subject).substring(offsetI, offsetI + lenI).getBytes(charset))); |
| 327 | + } |
| 328 | + } |
| 329 | + compareArrayToByteArrayWithoutOffset(subject, charset); |
| 330 | + } |
| 331 | + |
| 332 | + private void compareArrayToByteArrayWithoutOffset(char[] subject, Charset charset) { |
| 333 | + assertArrayEquals(Util.charToByteArray(subject, charset, 0, subject.length), new String(subject).getBytes(charset)); |
| 334 | + } |
| 335 | + |
| 336 | + @Test(expected = IllegalArgumentException.class) |
| 337 | + public void testCharToByteArrayIllegalOffset() { |
| 338 | + Util.charToByteArray("abcdef".toCharArray(), StandardCharsets.UTF_8, -1, 1); |
| 339 | + } |
| 340 | + |
| 341 | + @Test(expected = IllegalArgumentException.class) |
| 342 | + public void testCharToByteArrayIllegalLength() { |
| 343 | + Util.charToByteArray("abcdef".toCharArray(), StandardCharsets.UTF_8, 0, -1); |
| 344 | + } |
| 345 | + |
| 346 | + @Test(expected = IllegalArgumentException.class) |
| 347 | + public void testCharToByteArrayIllegalOffsetPlusLength() { |
| 348 | + Util.charToByteArray("abcdef".toCharArray(), StandardCharsets.UTF_8, 4, 3); |
| 349 | + } |
302 | 350 | } |
0 commit comments