[wpiutil] Add protobuf List pack/unpack for Java (#9042)

To aid in simplifying the packing/unpacking of Lists to protobuf, this
adds helper methods that put the iteration logic in `Protobuf.java`,
similar to arrays. This makes packing/unpacking a List a single line,
similar to other types. Useful for #8776 and #8172.
This commit is contained in:
Alan Everett
2026-07-01 23:03:06 -07:00
committed by GitHub
parent f494ff8c0d
commit 9dabcb99f3
2 changed files with 40 additions and 12 deletions

View File

@@ -5,6 +5,8 @@
package org.wpilib.util.protobuf;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import us.hebi.quickbuf.Descriptors.Descriptor;
@@ -180,6 +182,24 @@ public interface Protobuf<T, MessageType extends ProtoMessage<?>> {
return result;
}
/**
* Unpack a serialized protobuf array message to a list.
*
* @param <T> object type
* @param <MessageType> element type of the protobuf array
* @param msg protobuf array message
* @param proto protobuf implementation
* @return Deserialized list
*/
static <T, MessageType extends ProtoMessage<MessageType>> List<T> unpackList(
RepeatedMessage<MessageType> msg, Protobuf<T, MessageType> proto) {
ArrayList<T> result = new ArrayList<>(msg.length());
for (var item : msg) {
result.add(proto.unpack(item));
}
return result;
}
/**
* Pack a serialized protobuf array message.
*
@@ -209,4 +229,22 @@ public interface Protobuf<T, MessageType extends ProtoMessage<?>> {
msg.reserve(arr.length);
msg.addAll(arr);
}
/**
* Pack a serialized protobuf array message to a list.
*
* @param <T> object type
* @param <MessageType> element type of the protobuf array
* @param msg protobuf array message
* @param list list of objects
* @param proto protobuf implementation
*/
static <T, MessageType extends ProtoMessage<MessageType>> void packList(
RepeatedMessage<MessageType> msg, List<T> list, Protobuf<T, MessageType> proto) {
msg.clear();
msg.reserve(list.size());
for (var obj : list) {
proto.pack(msg.next(), obj);
}
}
}