33
33
import java.io.OutputStream;
34
34
import java.io.IOException;
35
35
import java.io.UnsupportedEncodingException;
36
import java.io.InputStream;
38
39
* Encodes and writes protocol message fields.
382
383
/** Write a {@code bytes} field to the stream. */
383
384
public void writeBytesNoTag(final ByteString value) throws IOException {
384
final byte[] bytes = value.toByteArray();
385
writeRawVarint32(bytes.length);
386
writeRawBytes(bytes);
385
writeRawVarint32(value.size());
386
writeRawBytes(value);
389
389
/** Write a {@code uint32} field to the stream. */
870
870
writeRawByte((byte) value);
873
/** Write a byte string. */
874
public void writeRawBytes(final ByteString value) throws IOException {
875
writeRawBytes(value, 0, value.size());
873
878
/** Write an array of bytes. */
874
879
public void writeRawBytes(final byte[] value) throws IOException {
875
880
writeRawBytes(value, 0, value.length);
914
/** Write part of a byte string. */
915
public void writeRawBytes(final ByteString value, int offset, int length)
917
if (limit - position >= length) {
918
// We have room in the current buffer.
919
value.copyTo(buffer, offset, position, length);
922
// Write extends past current buffer. Fill the rest of this buffer and
924
final int bytesWritten = limit - position;
925
value.copyTo(buffer, offset, position, bytesWritten);
926
offset += bytesWritten;
927
length -= bytesWritten;
931
// Now deal with the rest.
932
// Since we have an output stream, this is our buffer
933
// and buffer offset == 0
934
if (length <= limit) {
935
// Fits in new buffer.
936
value.copyTo(buffer, offset, 0, length);
939
// Write is very big, but we can't do it all at once without allocating
940
// an a copy of the byte array since ByteString does not give us access
941
// to the underlying bytes. Use the InputStream interface on the
942
// ByteString and our buffer to copy between the two.
943
InputStream inputStreamFrom = value.newInput();
944
if (offset != inputStreamFrom.skip(offset)) {
945
throw new IllegalStateException("Skip failed? Should never happen.");
947
// Use the buffer as the temporary buffer to avoid allocating memory.
949
int bytesToRead = Math.min(length, limit);
950
int bytesRead = inputStreamFrom.read(buffer, 0, bytesToRead);
951
if (bytesRead != bytesToRead) {
952
throw new IllegalStateException("Read failed? Should never happen");
954
output.write(buffer, 0, bytesRead);
909
961
/** Encode and write a tag. */
910
962
public void writeTag(final int fieldNumber, final int wireType)
911
963
throws IOException {