Class CodedInputStream
- Direct Known Subclasses:
CodedInputStream.ArrayDecoder,CodedInputStream.IterableDirectByteBufferDecoder,CodedInputStream.StreamDecoder,CodedInputStream.UnsafeDirectNioDecoder
This class contains two kinds of methods: methods that read specific protocol message
constructs and field types (e.g. readTag() and readInt32()) and methods that
read low-level values (e.g. readRawVarint32() and readRawBytes(int)). If you are
reading encoded protocol messages, you should use the former methods, but if you are reading some
other format of your own design, use the latter.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static final classACodedInputStreamimplementation that uses a backing array as the input.private static final classImplementation ofCodedInputStreamthat uses anas the data source.private static final classImplementation ofCodedInputStreamthat uses anInputStreamas the data source.private static final classACodedInputStreamimplementation that uses a backing direct ByteBuffer as the input. -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate static final intprivate static final intprivate static int(package private) intVisible for subclasses.(package private) intprivate boolean(package private) intVisible for subclasses.(package private) CodedInputStreamReaderUsed to adapt to the experimentalReaderinterface. -
Constructor Summary
ConstructorsModifierConstructorDescriptionprivateDisable construction/inheritance outside of this class. -
Method Summary
Modifier and TypeMethodDescriptionabstract voidcheckLastTagWas(int value) Verifies that the last call to readTag() returned the given tag value.voidstatic intdecodeZigZag32(int n) Decode a ZigZag-encoded 32-bit value.static longdecodeZigZag64(long n) Decode a ZigZag-encoded 64-bit value.(package private) final voidSets thisCodedInputStreamto discard unknown fields.abstract voidenableAliasing(boolean enabled) EnablesByteStringaliasing of the underlying buffer, trading off on buffer pinning for data copies.abstract intReturns the number of bytes to be read before the current limit.abstract intabstract intThe total bytes read up to the current position.abstract booleanisAtEnd()Returns true if the stream has reached the end of the input.static CodedInputStreamnewInstance(byte[] buf) Create a new CodedInputStream wrapping the given byte array.static CodedInputStreamnewInstance(byte[] buf, int off, int len) Create a new CodedInputStream wrapping the given byte array slice.(package private) static CodedInputStreamnewInstance(byte[] buf, int off, int len, boolean bufferIsImmutable) Create a new CodedInputStream wrapping the given byte array slice.static CodedInputStreamnewInstance(InputStream input) Create a new CodedInputStream wrapping the given InputStream.static CodedInputStreamnewInstance(InputStream input, int bufferSize) Create a new CodedInputStream wrapping the given InputStream, with a specified buffer size.static CodedInputStreamnewInstance(Iterable<ByteBuffer> input) Create a new CodedInputStream wrapping the givenIterable <ByteBuffer>.(package private) static CodedInputStreamnewInstance(Iterable<ByteBuffer> bufs, boolean bufferIsImmutable) Create a new CodedInputStream wrapping the givenIterable <ByteBuffer>.static CodedInputStreamnewInstance(ByteBuffer buf) Create a new CodedInputStream wrapping the given ByteBuffer.(package private) static CodedInputStreamnewInstance(ByteBuffer buf, boolean bufferIsImmutable) Create a new CodedInputStream wrapping the given buffer.abstract voidpopLimit(int oldLimit) Discards the current limit, returning to the previous limit.abstract intpushLimit(int byteLimit) SetscurrentLimitto (current position) +byteLimit.abstract booleanreadBool()Read aboolfield value from the stream.abstract byte[]Read abytesfield value from the stream.abstract ByteBufferRead abytesfield value from the stream.abstract ByteStringRead abytesfield value from the stream.abstract doubleRead adoublefield value from the stream.abstract intreadEnum()Read an enum field value from the stream.abstract intRead afixed32field value from the stream.abstract longRead afixed64field value from the stream.abstract floatRead afloatfield value from the stream.abstract voidreadGroup(int fieldNumber, MessageLite.Builder builder, ExtensionRegistryLite extensionRegistry) Read agroupfield value from the stream.abstract <T extends MessageLite>
TreadGroup(int fieldNumber, Parser<T> parser, ExtensionRegistryLite extensionRegistry) Read agroupfield value from the stream.abstract intRead anint32field value from the stream.abstract longRead anint64field value from the stream.abstract voidreadMessage(MessageLite.Builder builder, ExtensionRegistryLite extensionRegistry) Read an embedded message field value from the stream.abstract <T extends MessageLite>
TreadMessage(Parser<T> parser, ExtensionRegistryLite extensionRegistry) Read an embedded message field value from the stream.abstract byteRead one byte from the input.abstract byte[]readRawBytes(int size) Read a fixed size of bytes from the input.abstract intRead a 32-bit little-endian integer from the stream.abstract longRead a 64-bit little-endian integer from the stream.abstract intRead a raw Varint from the stream.static intreadRawVarint32(int firstByte, InputStream input) LikereadRawVarint32(InputStream), but expects that the caller has already read one byte.(package private) static intreadRawVarint32(InputStream input) Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint.abstract longRead a raw Varint from the stream.(package private) abstract longVariant of readRawVarint64 for when uncomfortably close to the limit.abstract intRead ansfixed32field value from the stream.abstract longRead ansfixed64field value from the stream.abstract intRead ansint32field value from the stream.abstract longRead ansint64field value from the stream.abstract StringRead astringfield value from the stream.abstract StringRead astringfield value from the stream.abstract intreadTag()Attempt to read a field tag, returning zero if we have reached EOF.abstract intRead auint32field value from the stream.abstract longRead auint64field value from the stream.abstract voidreadUnknownGroup(int fieldNumber, MessageLite.Builder builder) Deprecated.abstract voidResets the current size counter to zero (seesetSizeLimit(int)).final intsetRecursionLimit(int limit) Set the maximum message recursion depth.final intsetSizeLimit(int limit) Only valid forInputStream-backed streams.(package private) final booleanWhether unknown fields in this input stream should be discarded during parsing into full runtime messages.abstract booleanskipField(int tag) Reads and discards a single field, given its tag value.abstract booleanskipField(int tag, CodedOutputStream output) Deprecated.useUnknownFieldSetorUnknownFieldSetLiteto skip to an output stream.abstract voidReads and discards an entire message.abstract voidskipMessage(CodedOutputStream output) Reads an entire message and writes it to output in wire format.abstract voidskipRawBytes(int size) Reads and discardssizebytes.(package private) final voidReverts the unknown fields preservation behavior for Proto2 and Proto3 full runtime to their default.
-
Field Details
-
DEFAULT_BUFFER_SIZE
private static final int DEFAULT_BUFFER_SIZE- See Also:
-
DEFAULT_SIZE_LIMIT
private static final int DEFAULT_SIZE_LIMIT- See Also:
-
defaultRecursionLimit
private static volatile int defaultRecursionLimit -
recursionDepth
int recursionDepthVisible for subclasses. See setRecursionLimit() -
recursionLimit
int recursionLimit -
sizeLimit
int sizeLimitVisible for subclasses. See setSizeLimit() -
wrapper
CodedInputStreamReader wrapperUsed to adapt to the experimentalReaderinterface. -
shouldDiscardUnknownFields
private boolean shouldDiscardUnknownFields
-
-
Constructor Details
-
CodedInputStream
private CodedInputStream()Disable construction/inheritance outside of this class.
-
-
Method Details
-
newInstance
Create a new CodedInputStream wrapping the given InputStream. -
newInstance
Create a new CodedInputStream wrapping the given InputStream, with a specified buffer size. -
newInstance
Create a new CodedInputStream wrapping the givenIterable <ByteBuffer>. -
newInstance
Create a new CodedInputStream wrapping the givenIterable <ByteBuffer>. -
newInstance
Create a new CodedInputStream wrapping the given byte array. -
newInstance
Create a new CodedInputStream wrapping the given byte array slice. -
newInstance
Create a new CodedInputStream wrapping the given byte array slice. -
newInstance
Create a new CodedInputStream wrapping the given ByteBuffer. The data starting from the ByteBuffer's current position to its limit will be read. The returned CodedInputStream may or may not share the underlying data in the ByteBuffer, therefore the ByteBuffer cannot be changed while the CodedInputStream is in use. Note that the ByteBuffer's position won't be changed by this function. Concurrent calls with the same ByteBuffer object are safe if no other thread is trying to alter the ByteBuffer's status. -
newInstance
Create a new CodedInputStream wrapping the given buffer. -
checkRecursionLimit
- Throws:
InvalidProtocolBufferException
-
readTag
Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number.- Throws:
IOException
-
checkLastTagWas
Verifies that the last call to readTag() returned the given tag value. This is used to verify that a nested group ended with the correct end tag.- Throws:
InvalidProtocolBufferException-valuedoes not match the last tag.
-
getLastTag
public abstract int getLastTag() -
skipField
Reads and discards a single field, given its tag value.- Returns:
falseif the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returnstrue.- Throws:
IOException
-
skipField
Deprecated.useUnknownFieldSetorUnknownFieldSetLiteto skip to an output stream.Reads a single field and writes it to output in wire format, given its tag value.- Returns:
falseif the tag is an endgroup tag, in which case nothing is skipped. Otherwise, returnstrue.- Throws:
IOException
-
skipMessage
Reads and discards an entire message. This will read either until EOF or until an endgroup tag, whichever comes first.- Throws:
IOException
-
skipMessage
Reads an entire message and writes it to output in wire format. This will read either until EOF or until an endgroup tag, whichever comes first.- Throws:
IOException
-
readDouble
Read adoublefield value from the stream.- Throws:
IOException
-
readFloat
Read afloatfield value from the stream.- Throws:
IOException
-
readUInt64
Read auint64field value from the stream.- Throws:
IOException
-
readInt64
Read anint64field value from the stream.- Throws:
IOException
-
readInt32
Read anint32field value from the stream.- Throws:
IOException
-
readFixed64
Read afixed64field value from the stream.- Throws:
IOException
-
readFixed32
Read afixed32field value from the stream.- Throws:
IOException
-
readBool
Read aboolfield value from the stream.- Throws:
IOException
-
readString
Read astringfield value from the stream. If the stream contains malformed UTF-8, replace the offending bytes with the standard UTF-8 replacement character.- Throws:
IOException
-
readStringRequireUtf8
Read astringfield value from the stream. If the stream contains malformed UTF-8, throw exceptionInvalidProtocolBufferException.- Throws:
IOException
-
readGroup
public abstract void readGroup(int fieldNumber, MessageLite.Builder builder, ExtensionRegistryLite extensionRegistry) throws IOException Read agroupfield value from the stream.- Throws:
IOException
-
readGroup
public abstract <T extends MessageLite> T readGroup(int fieldNumber, Parser<T> parser, ExtensionRegistryLite extensionRegistry) throws IOException Read agroupfield value from the stream.- Throws:
IOException
-
readUnknownGroup
@Deprecated public abstract void readUnknownGroup(int fieldNumber, MessageLite.Builder builder) throws IOException Deprecated.UnknownFieldSet.Builder now implements MessageLite.Builder, so you can just callreadGroup(int, com.google.protobuf.MessageLite.Builder, com.google.protobuf.ExtensionRegistryLite).Reads agroupfield value from the stream and merges it into the givenUnknownFieldSet.- Throws:
IOException
-
readMessage
public abstract void readMessage(MessageLite.Builder builder, ExtensionRegistryLite extensionRegistry) throws IOException Read an embedded message field value from the stream.- Throws:
IOException
-
readMessage
public abstract <T extends MessageLite> T readMessage(Parser<T> parser, ExtensionRegistryLite extensionRegistry) throws IOException Read an embedded message field value from the stream.- Throws:
IOException
-
readBytes
Read abytesfield value from the stream.- Throws:
IOException
-
readByteArray
Read abytesfield value from the stream.- Throws:
IOException
-
readByteBuffer
Read abytesfield value from the stream.- Throws:
IOException
-
readUInt32
Read auint32field value from the stream.- Throws:
IOException
-
readEnum
Read an enum field value from the stream. Caller is responsible for converting the numeric value to an actual enum.- Throws:
IOException
-
readSFixed32
Read ansfixed32field value from the stream.- Throws:
IOException
-
readSFixed64
Read ansfixed64field value from the stream.- Throws:
IOException
-
readSInt32
Read ansint32field value from the stream.- Throws:
IOException
-
readSInt64
Read ansint64field value from the stream.- Throws:
IOException
-
readRawVarint32
Read a raw Varint from the stream. If larger than 32 bits, discard the upper bits.- Throws:
IOException
-
readRawVarint64
Read a raw Varint from the stream.- Throws:
IOException
-
readRawVarint64SlowPath
Variant of readRawVarint64 for when uncomfortably close to the limit.- Throws:
IOException
-
readRawLittleEndian32
Read a 32-bit little-endian integer from the stream.- Throws:
IOException
-
readRawLittleEndian64
Read a 64-bit little-endian integer from the stream.- Throws:
IOException
-
enableAliasing
public abstract void enableAliasing(boolean enabled) EnablesByteStringaliasing of the underlying buffer, trading off on buffer pinning for data copies. Only valid for buffer-backed streams. -
setRecursionLimit
public final int setRecursionLimit(int limit) Set the maximum message recursion depth. In order to prevent malicious messages from causing stack overflows,CodedInputStreamlimits how deeply messages may be nested. The default limit is 100.- Returns:
- the old limit.
-
setSizeLimit
public final int setSizeLimit(int limit) Only valid forInputStream-backed streams.Set the maximum message size. In order to prevent malicious messages from exhausting memory or causing integer overflows,
CodedInputStreamlimits how large a message may be. The default limit isInteger.MAX_VALUE. You should set this limit as small as you can without harming your app's functionality. Note that size limits only apply when reading from anInputStream, not when constructed around a raw byte array.If you want to read several messages from a single CodedInputStream, you could call
resetSizeCounter()after each one to avoid hitting the size limit.- Returns:
- the old limit.
-
discardUnknownFields
final void discardUnknownFields()Sets thisCodedInputStreamto discard unknown fields. Only applies to full runtime messages; lite messages will always preserve unknowns.Note calling this function alone will have NO immediate effect on the underlying input data. The unknown fields will be discarded during parsing. This affects both Proto2 and Proto3 full runtime.
-
unsetDiscardUnknownFields
final void unsetDiscardUnknownFields()Reverts the unknown fields preservation behavior for Proto2 and Proto3 full runtime to their default. -
shouldDiscardUnknownFields
final boolean shouldDiscardUnknownFields()Whether unknown fields in this input stream should be discarded during parsing into full runtime messages. -
resetSizeCounter
public abstract void resetSizeCounter()Resets the current size counter to zero (seesetSizeLimit(int)). Only valid forInputStream-backed streams. -
pushLimit
SetscurrentLimitto (current position) +byteLimit. This is called when descending into a length-delimited embedded message.Note that
pushLimit()does NOT affect how many bytes theCodedInputStreamreads from an underlyingInputStreamwhen refreshing its buffer. If you need to prevent reading past a certain point in the underlyingInputStream(e.g. because you expect it to contain more data after the end of the message which you need to handle differently) then you must place a wrapper around yourInputStreamwhich limits the amount of data that can be read from it.- Returns:
- the old limit.
- Throws:
InvalidProtocolBufferException
-
popLimit
public abstract void popLimit(int oldLimit) Discards the current limit, returning to the previous limit.- Parameters:
oldLimit- The old limit, as returned bypushLimit.
-
getBytesUntilLimit
public abstract int getBytesUntilLimit()Returns the number of bytes to be read before the current limit. If no limit is set, returns -1. -
isAtEnd
Returns true if the stream has reached the end of the input. This is the case if either the end of the underlying input source has been reached or if the stream has reached a limit created usingpushLimit(int). This function may get blocked when using StreamDecoder as it invokesCodedInputStream.StreamDecoder.tryRefillBuffer(int)in this function which will try to read bytes from input.- Throws:
IOException
-
getTotalBytesRead
public abstract int getTotalBytesRead()The total bytes read up to the current position. CallingresetSizeCounter()resets this value to zero. -
readRawByte
Read one byte from the input.- Throws:
InvalidProtocolBufferException- The end of the stream or the current limit was reached.IOException
-
readRawBytes
Read a fixed size of bytes from the input.- Throws:
InvalidProtocolBufferException- The end of the stream or the current limit was reached.IOException
-
skipRawBytes
Reads and discardssizebytes.- Throws:
InvalidProtocolBufferException- The end of the stream or the current limit was reached.IOException
-
decodeZigZag32
public static int decodeZigZag32(int n) Decode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers into values that can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)- Parameters:
n- An unsigned 32-bit integer, stored in a signed int because Java has no explicit unsigned support.- Returns:
- A signed 32-bit integer.
-
decodeZigZag64
public static long decodeZigZag64(long n) Decode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers into values that can be efficiently encoded with varint. (Otherwise, negative values must be sign-extended to 64 bits to be varint encoded, thus always taking 10 bytes on the wire.)- Parameters:
n- An unsigned 64-bit integer, stored in a signed int because Java has no explicit unsigned support.- Returns:
- A signed 64-bit integer.
-
readRawVarint32
LikereadRawVarint32(InputStream), but expects that the caller has already read one byte. This allows the caller to determine if EOF has been reached before attempting to read.- Throws:
IOException
-
readRawVarint32
Reads a varint from the input one byte at a time, so that it does not read any bytes after the end of the varint. If you simply wrapped the stream in a CodedInputStream and usedreadRawVarint32(InputStream)then you would probably end up reading past the end of the varint since CodedInputStream buffers its input.- Throws:
IOException
-
readGroup(int, com.google.protobuf.MessageLite.Builder, com.google.protobuf.ExtensionRegistryLite).