From 724b2d27d49da23cf4cd9b5de921421eb4cc5de2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maciej=20=C5=BBenczykowski?= Date: Tue, 29 Jul 2025 13:30:43 -0700 Subject: [PATCH] make Struct expose a new parse method that takes a raw byte array MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Test: TreeHugger Flag: EXEMPT mainline Signed-off-by: Maciej Żenczykowski Change-Id: Ifdfc93e0c35df58a983beb30da546db7a0876398 --- .../device/com/android/net/module/util/BpfMap.java | 10 ++-------- .../device/com/android/net/module/util/Struct.java | 11 +++++++++++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/staticlibs/device/com/android/net/module/util/BpfMap.java b/staticlibs/device/com/android/net/module/util/BpfMap.java index 0fbc25de7b..7dd09e00e6 100644 --- a/staticlibs/device/com/android/net/module/util/BpfMap.java +++ b/staticlibs/device/com/android/net/module/util/BpfMap.java @@ -28,8 +28,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; import java.util.NoSuchElementException; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -217,9 +215,7 @@ public class BpfMap implements IBpfMap key == null ? null : key.writeToBytes(), rawKey)) return null; - final ByteBuffer buffer = ByteBuffer.wrap(rawKey); - buffer.order(ByteOrder.nativeOrder()); - return Struct.parse(mKeyClass, buffer); + return Struct.parse(mKeyClass, rawKey); } /** @@ -257,9 +253,7 @@ public class BpfMap implements IBpfMap byte[] rawValue = new byte[mValueSize]; if (!nativeFindMapEntry(mMapFd.getFd(), key.writeToBytes(), rawValue)) return null; - final ByteBuffer buffer = ByteBuffer.wrap(rawValue); - buffer.order(ByteOrder.nativeOrder()); - return Struct.parse(mValueClass, buffer); + return Struct.parse(mValueClass, rawValue); } /** Synchronize Kernel RCU */ diff --git a/staticlibs/device/com/android/net/module/util/Struct.java b/staticlibs/device/com/android/net/module/util/Struct.java index 006642b26f..ccf3957e88 100644 --- a/staticlibs/device/com/android/net/module/util/Struct.java +++ b/staticlibs/device/com/android/net/module/util/Struct.java @@ -654,6 +654,17 @@ public class Struct { } } + /** + * Parse raw data from a byte array according to the pre-defined annotation rule and return + * the type-variable object which is subclass of Struct class. + * This assumes the raw data has the same byte order as the native order. + */ + public static T parse(final Class clazz, final byte[] bytes) { + final ByteBuffer buf = ByteBuffer.wrap(bytes); + buf.order(ByteOrder.nativeOrder()); + return parse(clazz, buf); + } + private static int getSizeInternal(final FieldInfo[] fieldInfos) { int size = 0; for (FieldInfo fi : fieldInfos) {