mirror of
https://github.com/wpilibsuite/allwpilib
synced 2026-07-06 03:31:43 +00:00
[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:
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user