1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * https://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package org.apache.bcel.classfile;
21
22 import static org.junit.jupiter.api.Assertions.assertArrayEquals;
23 import static org.junit.jupiter.api.Assertions.assertEquals;
24 import static org.junit.jupiter.api.Assertions.assertThrows;
25
26 import java.io.IOException;
27
28 import org.junit.jupiter.api.Test;
29
30 /**
31 * Tests {@link Utility}.
32 */
33 class UtilityEncodeDecodeTest {
34
35 @Test
36 void testDecodeRejectsMalformedEscapes() throws Exception {
37 // Second character of a hex escape was never validated: used to throw an undeclared NumberFormatException.
38 assertThrows(IOException.class, () -> Utility.decode("$0z", false));
39 // Escape characters above 255 used to throw an undeclared ArrayIndexOutOfBoundsException.
40 assertThrows(IOException.class, () -> Utility.decode("$\u0141", false));
41 // Unmapped escape characters used to silently alias to the "$A" encoding (byte 0).
42 assertThrows(IOException.class, () -> Utility.decode("$!", false));
43 // Sanity check: valid escapes still decode ('$A' is the special escape for byte 0, '$3a' is hex 0x3a).
44 assertEquals(0, Utility.decode("$A", false)[0]);
45 assertEquals(0x3a, Utility.decode("$3a", false)[0]);
46 }
47
48 @Test
49 void testEncodeDecodeRoundTrip() throws Exception {
50 final byte[] bytes = new byte[256];
51 for (int i = 0; i < bytes.length; i++) {
52 bytes[i] = (byte) i;
53 }
54 assertArrayEquals(bytes, Utility.decode(Utility.encode(bytes, false), false));
55 assertArrayEquals(bytes, Utility.decode(Utility.encode(bytes, true), true));
56 }
57
58 /**
59 * Zero-filled data compresses far better than the fixed 3:1 ratio the decode buffer used to assume; the encode/decode round trip must still hold.
60 */
61 @Test
62 void testEncodeDecodeRoundTripHighCompressionRatio() throws Exception {
63 final byte[] original = new byte[4096];
64 final String encoded = Utility.encode(original, true);
65 assertArrayEquals(original, Utility.decode(encoded, true));
66 }
67 }