|
| 1 | +/* |
| 2 | + * Copyright 2026 Glavo |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.glavo.nbt.internal; |
| 17 | + |
| 18 | +import org.junit.jupiter.api.Test; |
| 19 | + |
| 20 | +import java.nio.charset.StandardCharsets; |
| 21 | +import java.util.ArrayList; |
| 22 | +import java.util.Arrays; |
| 23 | + |
| 24 | +import static org.junit.jupiter.api.Assertions.assertNull; |
| 25 | +import static org.junit.jupiter.api.Assertions.assertSame; |
| 26 | + |
| 27 | +public final class StringCacheTest { |
| 28 | + @Test |
| 29 | + public void test() { |
| 30 | + var strings = new ArrayList<String>(); |
| 31 | + for (int i = 0; i < 10000; i++) { |
| 32 | + strings.add("str" + i); |
| 33 | + } |
| 34 | + |
| 35 | + var cache = new StringCache(strings.toArray(new String[0])); |
| 36 | + |
| 37 | + for (String string : strings) { |
| 38 | + byte[] bytes = string.getBytes(StandardCharsets.UTF_8); |
| 39 | + |
| 40 | + assertSame(string, cache.get(bytes, 0, bytes.length)); |
| 41 | + |
| 42 | + assertNull(cache.get(bytes, 1, bytes.length - 1)); |
| 43 | + |
| 44 | + // Test with a different offset |
| 45 | + byte[] newBytes = new byte[bytes.length + 1]; |
| 46 | + System.arraycopy(bytes, 0, newBytes, 1, bytes.length); |
| 47 | + assertSame(string, cache.get(newBytes, 1, bytes.length)); |
| 48 | + |
| 49 | + // Test with leading zeros |
| 50 | + Arrays.fill(newBytes, (byte) 0); |
| 51 | + System.arraycopy(bytes, 0, newBytes, 0, bytes.length); |
| 52 | + assertSame(string, cache.get(newBytes, 0, bytes.length)); |
| 53 | + } |
| 54 | + |
| 55 | + assertNull(cache.get("ABC".getBytes(StandardCharsets.UTF_8))); |
| 56 | + |
| 57 | + // Test long strings |
| 58 | + assertNull(cache.get("A".repeat(20).getBytes(StandardCharsets.UTF_8))); |
| 59 | + |
| 60 | + // Test non-ASCII characters |
| 61 | + assertNull(cache.get("喵".getBytes(StandardCharsets.UTF_8))); |
| 62 | + } |
| 63 | +} |
0 commit comments