Add arrayCopy

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2022-06-09 21:35:18 +02:00
parent 20dcf91f4a
commit 8789a6c1f0
3 changed files with 31 additions and 3 deletions

View File

@ -38,4 +38,6 @@ public sealed interface ObjectArray<T>
}
void trim();
@UnknownNullability T @NotNull [] arrayCopy(@NotNull Class<T> type);
}

View File

@ -1,5 +1,6 @@
package net.minestom.server.utils.collection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnknownNullability;
@ -36,6 +37,12 @@ final class ObjectArrayImpl {
public void trim() {
this.array = Arrays.copyOf(array, max + 1);
}
@Override
public @UnknownNullability T @NotNull [] arrayCopy(@NotNull Class<T> type) {
//noinspection unchecked,rawtypes
return (T[]) Arrays.<T, T>copyOf(array, max + 1, (Class) type.arrayType());
}
}
static final class Concurrent<T> implements ObjectArray<T> {
@ -68,5 +75,11 @@ final class ObjectArrayImpl {
public synchronized void trim() {
this.array = Arrays.copyOf(array, max + 1);
}
@Override
public @UnknownNullability T @NotNull [] arrayCopy(@NotNull Class<T> type) {
//noinspection unchecked,rawtypes
return (T[]) Arrays.<T, T>copyOf(array, max + 1, (Class) type.arrayType());
}
}
}

View File

@ -3,14 +3,13 @@ package net.minestom.server.utils.collection;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.*;
public class ObjectArrayTest {
@ParameterizedTest
@ValueSource(booleans = {false, true})
public void testArray(boolean concurrent) {
public void objectArray(boolean concurrent) {
ObjectArray<String> array = concurrent ? ObjectArray.concurrent() : ObjectArray.singleThread();
array.set(50, "Hey");
@ -35,4 +34,18 @@ public class ObjectArrayTest {
assertNull(array.get(251));
assertNull(array.get(Integer.MAX_VALUE));
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
public void arrayCopy(boolean concurrent) {
ObjectArray<String> array = concurrent ? ObjectArray.concurrent() : ObjectArray.singleThread();
array.set(1, "Hey");
String[] copyCache = array.arrayCopy(String.class);
assertArrayEquals(new String[]{null, "Hey"}, copyCache);
array.set(2, "Hey2");
assertArrayEquals(new String[]{null, "Hey", "Hey2"}, array.arrayCopy(String.class));
assertArrayEquals(new String[]{null, "Hey"}, copyCache, "The copy cache should not be modified");
}
}