RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
ProtobufBuffer.java
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5package org.wpilib.util.protobuf;
6
7import java.io.IOException;
8import java.nio.ByteBuffer;
9import us.hebi.quickbuf.ProtoMessage;
10import us.hebi.quickbuf.ProtoSink;
11import us.hebi.quickbuf.ProtoSource;
12
19public final class ProtobufBuffer<T, MessageType extends ProtoMessage<?>> {
20 private ProtobufBuffer(Protobuf<T, MessageType> proto) {
21 m_buf = ByteBuffer.allocateDirect(1024);
22 m_sink = ProtoSink.newDirectSink();
23 m_sink.setOutput(m_buf);
24 m_source = ProtoSource.newDirectSource();
25 m_msg = proto.createMessage();
26 m_proto = proto;
27 }
28
37 public static <T, MessageType extends ProtoMessage<?>> ProtobufBuffer<T, MessageType> create(
39 return new ProtobufBuffer<>(proto);
40 }
41
48 return m_proto;
49 }
50
56 public String getTypeString() {
57 return m_proto.getTypeString();
58 }
59
68 public ByteBuffer write(T value) throws IOException {
69 m_msg.clearQuick();
70 m_proto.pack(m_msg, value);
71 int size = m_msg.getSerializedSize();
72 if (size > m_buf.capacity()) {
73 m_buf = ByteBuffer.allocateDirect(size * 2);
74 m_sink.setOutput(m_buf);
75 }
76 m_sink.reset();
77 m_msg.writeTo(m_sink);
78 m_buf.position(m_sink.getTotalBytesWritten());
79 return m_buf;
80 }
81
91 public T read(byte[] buf, int start, int len) throws IOException {
92 m_msg.clearQuick();
93 m_source.setInput(buf, start, len);
94 m_msg.mergeFrom(m_source);
95 return m_proto.unpack(m_msg);
96 }
97
105 public T read(byte[] buf) throws IOException {
106 return read(buf, 0, buf.length);
107 }
108
116 public T read(ByteBuffer buf) throws IOException {
117 m_msg.clearQuick();
118 m_source.setInput(buf);
119 m_msg.mergeFrom(m_source);
120 return m_proto.unpack(m_msg);
121 }
122
133 public void readInto(T out, byte[] buf, int start, int len) throws IOException {
134 m_msg.clearQuick();
135 m_source.setInput(buf, start, len);
136 m_msg.mergeFrom(m_source);
137 m_proto.unpackInto(out, m_msg);
138 }
139
148 public void readInto(T out, byte[] buf) throws IOException {
149 readInto(out, buf, 0, buf.length);
150 }
151
160 public void readInto(T out, ByteBuffer buf) throws IOException {
161 m_msg.clearQuick();
162 m_source.setInput(buf);
163 m_msg.mergeFrom(m_source);
164 m_proto.unpackInto(out, m_msg);
165 }
166
167 private ByteBuffer m_buf;
168 private final ProtoSink m_sink;
169 private final ProtoSource m_source;
170 private final MessageType m_msg;
171 private final Protobuf<T, MessageType> m_proto;
172}
void readInto(T out, byte[] buf, int start, int len)
T read(byte[] buf, int start, int len)
static< T, MessageType extends ProtoMessage<?> ProtobufBuffer< T, MessageType > create(Protobuf< T, MessageType > proto)
Protobuf< T, MessageType > getProto()