make Struct expose a new parse method that takes a raw byte array

Test: TreeHugger
Flag: EXEMPT mainline
Signed-off-by: Maciej Żenczykowski <maze@google.com>
Change-Id: Ifdfc93e0c35df58a983beb30da546db7a0876398
This commit is contained in:
Maciej Żenczykowski 2025-07-29 13:30:43 -07:00
commit 724b2d27d4
2 changed files with 13 additions and 8 deletions

View file

@ -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<K extends Struct, V extends Struct> implements IBpfMap<K, V>
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<K extends Struct, V extends Struct> implements IBpfMap<K, V>
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 */

View file

@ -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> T parse(final Class<T> 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) {