From e9f547f7baa3e6b10ed27ab621d5137eef17b21a Mon Sep 17 00:00:00 2001 From: Nassim Jahnke Date: Mon, 17 Jun 2024 11:48:21 +0200 Subject: [PATCH] Add ArrayUtil --- .../rewriter/EntityPacketRewriter1_21.java | 3 +- .../viaversion/viaversion/util/ArrayUtil.java | 50 +++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 common/src/main/java/com/viaversion/viaversion/util/ArrayUtil.java diff --git a/common/src/main/java/com/viaversion/viaversion/protocols/v1_20_5to1_21/rewriter/EntityPacketRewriter1_21.java b/common/src/main/java/com/viaversion/viaversion/protocols/v1_20_5to1_21/rewriter/EntityPacketRewriter1_21.java index 4b1be423a..0ef1e667b 100644 --- a/common/src/main/java/com/viaversion/viaversion/protocols/v1_20_5to1_21/rewriter/EntityPacketRewriter1_21.java +++ b/common/src/main/java/com/viaversion/viaversion/protocols/v1_20_5to1_21/rewriter/EntityPacketRewriter1_21.java @@ -37,6 +37,7 @@ import com.viaversion.viaversion.protocols.v1_20_5to1_21.Protocol1_20_5To1_21; import com.viaversion.viaversion.protocols.v1_20_5to1_21.data.Paintings1_20_5; import com.viaversion.viaversion.protocols.v1_20_5to1_21.storage.EfficiencyAttributeStorage; import com.viaversion.viaversion.rewriter.EntityRewriter; +import com.viaversion.viaversion.util.ArrayUtil; import com.viaversion.viaversion.util.Key; public final class EntityPacketRewriter1_21 extends EntityRewriter { @@ -60,7 +61,7 @@ public final class EntityPacketRewriter1_21 extends EntityRewriter. + */ +package com.viaversion.viaversion.util; + +import java.util.Arrays; + +/** + * For type safety and effort reasons, buffer types use arrays instead of lists. + *

+ * This class includes simple methods to work with these arrays in case they need to be modified + * (obviously being more expensive due to the required array copies for every modification). + */ +public final class ArrayUtil { + + public static T[] add(final T[] array, final T element) { + final int length = array.length; + final T[] newArray = Arrays.copyOf(array, length + 1); + newArray[length] = element; + return newArray; + } + + @SafeVarargs + public static T[] add(final T[] array, final T... elements) { + final int length = array.length; + final T[] newArray = Arrays.copyOf(array, length + elements.length); + System.arraycopy(elements, 0, newArray, length, elements.length); + return newArray; + } + + public static T[] remove(final T[] array, final int index) { + final T[] newArray = Arrays.copyOf(array, array.length - 1); + System.arraycopy(array, index + 1, newArray, index, newArray.length - index); + return newArray; + } +}