MessageLite
的定义
对于MessageLite
的定义,目前找到了几个地方:
C++
版MessageLite
C++
版MessageLite
的代码定义
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Authors: wink@google.com (Wink Saville),
// kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// Defines MessageLite, the abstract interface implemented by all (lite
// and non-lite) protocol message objects.
#ifndef GOOGLE_PROTOBUF_MESSAGE_LITE_H__
#define GOOGLE_PROTOBUF_MESSAGE_LITE_H__
#include <climits>
#include <string>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/logging.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/port.h>
#include <google/protobuf/stubs/strutil.h>
#include <google/protobuf/explicitly_constructed.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/stubs/hash.h> // TODO(b/211442718): cleanup
// clang-format off
#include <google/protobuf/port_def.inc>
// clang-format on
#ifdef SWIG
#error "You cannot SWIG proto headers"
#endif
namespace google {
namespace protobuf {
template <typename T>
class RepeatedPtrField;
class FastReflectionMessageMutator;
class FastReflectionStringSetter;
class Reflection;
namespace io {
class CodedInputStream;
class CodedOutputStream;
class ZeroCopyInputStream;
class ZeroCopyOutputStream;
} // namespace io
namespace internal {
class SwapFieldHelper;
// See parse_context.h for explanation
class ParseContext;
class ExtensionSet;
class LazyField;
class RepeatedPtrFieldBase;
class TcParser;
class WireFormatLite;
class WeakFieldMap;
template <typename Type>
class GenericTypeHandler; // defined in repeated_field.h
// We compute sizes as size_t but cache them as int. This function converts a
// computed size to a cached size. Since we don't proceed with serialization
// if the total size was > INT_MAX, it is not important what this function
// returns for inputs > INT_MAX. However this case should not error or
// GOOGLE_CHECK-fail, because the full size_t resolution is still returned from
// ByteSizeLong() and checked against INT_MAX; we can catch the overflow
// there.
inline int ToCachedSize(size_t size) { return static_cast<int>(size); }
// We mainly calculate sizes in terms of size_t, but some functions that
// compute sizes return "int". These int sizes are expected to always be
// positive. This function is more efficient than casting an int to size_t
// directly on 64-bit platforms because it avoids making the compiler emit a
// sign extending instruction, which we don't want and don't want to pay for.
inline size_t FromIntSize(int size) {
// Convert to unsigned before widening so sign extension is not necessary.
return static_cast<unsigned int>(size);
}
// For cases where a legacy function returns an integer size. We GOOGLE_DCHECK()
// that the conversion will fit within an integer; if this is false then we
// are losing information.
inline int ToIntSize(size_t size) {
GOOGLE_DCHECK_LE(size, static_cast<size_t>(INT_MAX));
return static_cast<int>(size);
}
// Default empty string object. Don't use this directly. Instead, call
// GetEmptyString() to get the reference. This empty string is aligned with a
// minimum alignment of 8 bytes to match the requirement of ArenaStringPtr.
PROTOBUF_EXPORT extern ExplicitlyConstructedArenaString
fixed_address_empty_string;
PROTOBUF_EXPORT constexpr const std::string& GetEmptyStringAlreadyInited() {
return fixed_address_empty_string.get();
}
PROTOBUF_EXPORT size_t StringSpaceUsedExcludingSelfLong(const std::string& str);
} // namespace internal
// Interface to light weight protocol messages.
//
// This interface is implemented by all protocol message objects. Non-lite
// messages additionally implement the Message interface, which is a
// subclass of MessageLite. Use MessageLite instead when you only need
// the subset of features which it supports -- namely, nothing that uses
// descriptors or reflection. You can instruct the protocol compiler
// to generate classes which implement only MessageLite, not the full
// Message interface, by adding the following line to the .proto file:
//
// option optimize_for = LITE_RUNTIME;
//
// This is particularly useful on resource-constrained systems where
// the full protocol buffers runtime library is too big.
//
// Note that on non-constrained systems (e.g. servers) when you need
// to link in lots of protocol definitions, a better way to reduce
// total code footprint is to use optimize_for = CODE_SIZE. This
// will make the generated code smaller while still supporting all the
// same features (at the expense of speed). optimize_for = LITE_RUNTIME
// is best when you only have a small number of message types linked
// into your binary, in which case the size of the protocol buffers
// runtime itself is the biggest problem.
//
// Users must not derive from this class. Only the protocol compiler and
// the internal library are allowed to create subclasses.
class PROTOBUF_EXPORT MessageLite {
public:
constexpr MessageLite() {}
virtual ~MessageLite() = default;
// Basic Operations ------------------------------------------------
// Get the name of this message type, e.g. "foo.bar.BazProto".
virtual std::string GetTypeName() const = 0;
// Construct a new instance of the same type. Ownership is passed to the
// caller.
MessageLite* New() const { return New(nullptr); }
// Construct a new instance on the arena. Ownership is passed to the caller
// if arena is a nullptr.
virtual MessageLite* New(Arena* arena) const = 0;
// Returns user-owned arena; nullptr if it's message owned.
Arena* GetArena() const { return _internal_metadata_.user_arena(); }
// Clear all fields of the message and set them to their default values.
// Clear() avoids freeing memory, assuming that any memory allocated
// to hold parts of the message will be needed again to hold the next
// message. If you actually want to free the memory used by a Message,
// you must delete it.
virtual void Clear() = 0;
// Quickly check if all required fields have values set.
virtual bool IsInitialized() const = 0;
// This is not implemented for Lite messages -- it just returns "(cannot
// determine missing fields for lite message)". However, it is implemented
// for full messages. See message.h.
virtual std::string InitializationErrorString() const;
// If |other| is the exact same class as this, calls MergeFrom(). Otherwise,
// results are undefined (probably crash).
virtual void CheckTypeAndMergeFrom(const MessageLite& other) = 0;
// These methods return a human-readable summary of the message. Note that
// since the MessageLite interface does not support reflection, there is very
// little information that these methods can provide. They are shadowed by
// methods of the same name on the Message interface which provide much more
// information. The methods here are intended primarily to facilitate code
// reuse for logic that needs to interoperate with both full and lite protos.
//
// The format of the returned string is subject to change, so please do not
// assume it will remain stable over time.
std::string DebugString() const;
std::string ShortDebugString() const { return DebugString(); }
// MessageLite::DebugString is already Utf8 Safe. This is to add compatibility
// with Message.
std::string Utf8DebugString() const { return DebugString(); }
// Parsing ---------------------------------------------------------
// Methods for parsing in protocol buffer format. Most of these are
// just simple wrappers around MergeFromCodedStream(). Clear() will be
// called before merging the input.
// Fill the message with a protocol buffer parsed from the given input
// stream. Returns false on a read error or if the input is in the wrong
// format. A successful return does not indicate the entire input is
// consumed, ensure you call ConsumedEntireMessage() to check that if
// applicable.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromCodedStream(
io::CodedInputStream* input);
// Like ParseFromCodedStream(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCodedStream(
io::CodedInputStream* input);
// Read a protocol buffer from the given zero-copy input stream. If
// successful, the entire input will be consumed.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromZeroCopyStream(
io::ZeroCopyInputStream* input);
// Like ParseFromZeroCopyStream(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromZeroCopyStream(
io::ZeroCopyInputStream* input);
// Parse a protocol buffer from a file descriptor. If successful, the entire
// input will be consumed.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromFileDescriptor(
int file_descriptor);
// Like ParseFromFileDescriptor(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromFileDescriptor(
int file_descriptor);
// Parse a protocol buffer from a C++ istream. If successful, the entire
// input will be consumed.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromIstream(std::istream* input);
// Like ParseFromIstream(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromIstream(
std::istream* input);
// Read a protocol buffer from the given zero-copy input stream, expecting
// the message to be exactly "size" bytes long. If successful, exactly
// this many bytes will have been consumed from the input.
bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input,
int size);
// Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
// missing required fields.
bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream* input, int size);
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromBoundedZeroCopyStream(
io::ZeroCopyInputStream* input, int size);
// Like ParseFromBoundedZeroCopyStream(), but accepts messages that are
// missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromBoundedZeroCopyStream(
io::ZeroCopyInputStream* input, int size);
// Parses a protocol buffer contained in a string. Returns true on success.
// This function takes a string in the (non-human-readable) binary wire
// format, matching the encoding output by MessageLite::SerializeToString().
// If you'd like to convert a human-readable string into a protocol buffer
// object, see google::protobuf::TextFormat::ParseFromString().
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromString(ConstStringParam data);
// Like ParseFromString(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(
ConstStringParam data);
// Parse a protocol buffer contained in an array of bytes.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromArray(const void* data,
int size);
// Like ParseFromArray(), but accepts messages that are missing
// required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromArray(const void* data,
int size);
// Reads a protocol buffer from the stream and merges it into this
// Message. Singular fields read from the what is
// already in the Message and repeated fields are appended to those
// already present.
//
// It is the responsibility of the caller to call input->LastTagWas()
// (for groups) or input->ConsumedEntireMessage() (for non-groups) after
// this returns to verify that the message's end was delimited correctly.
//
// ParseFromCodedStream() is implemented as Clear() followed by
// MergeFromCodedStream().
bool MergeFromCodedStream(io::CodedInputStream* input);
// Like MergeFromCodedStream(), but succeeds even if required fields are
// missing in the input.
//
// MergeFromCodedStream() is just implemented as MergePartialFromCodedStream()
// followed by IsInitialized().
bool MergePartialFromCodedStream(io::CodedInputStream* input);
// Merge a protocol buffer contained in a string.
bool MergeFromString(ConstStringParam data);
// Serialization ---------------------------------------------------
// Methods for serializing in protocol buffer format. Most of these
// are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
// Write a protocol buffer of this message to the given output. Returns
// false on a write error. If the message is missing required fields,
// this may GOOGLE_CHECK-fail.
bool SerializeToCodedStream(io::CodedOutputStream* output) const;
// Like SerializeToCodedStream(), but allows missing required fields.
bool SerializePartialToCodedStream(io::CodedOutputStream* output) const;
// Write the message to the given zero-copy output stream. All required
// fields must be set.
bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
// Like SerializeToZeroCopyStream(), but allows missing required fields.
bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream* output) const;
// Serialize the message and store it in the given string. All required
// fields must be set.
bool SerializeToString(std::string* output) const;
// Like SerializeToString(), but allows missing required fields.
bool SerializePartialToString(std::string* output) const;
// Serialize the message and store it in the given byte array. All required
// fields must be set.
bool SerializeToArray(void* data, int size) const;
// Like SerializeToArray(), but allows missing required fields.
bool SerializePartialToArray(void* data, int size) const;
// Make a string encoding the message. Is equivalent to calling
// SerializeToString() on a string and using that. Returns the empty
// string if SerializeToString() would have returned an error.
// Note: If you intend to generate many such strings, you may
// reduce heap fragmentation by instead re-using the same string
// object with calls to SerializeToString().
std::string SerializeAsString() const;
// Like SerializeAsString(), but allows missing required fields.
std::string SerializePartialAsString() const;
// Serialize the message and write it to the given file descriptor. All
// required fields must be set.
bool SerializeToFileDescriptor(int file_descriptor) const;
// Like SerializeToFileDescriptor(), but allows missing required fields.
bool SerializePartialToFileDescriptor(int file_descriptor) const;
// Serialize the message and write it to the given C++ ostream. All
// required fields must be set.
bool SerializeToOstream(std::ostream* output) const;
// Like SerializeToOstream(), but allows missing required fields.
bool SerializePartialToOstream(std::ostream* output) const;
// Like SerializeToString(), but appends to the data to the string's
// existing contents. All required fields must be set.
bool AppendToString(std::string* output) const;
// Like AppendToString(), but allows missing required fields.
bool AppendPartialToString(std::string* output) const;
// Computes the serialized size of the message. This recursively calls
// ByteSizeLong() on all embedded messages.
//
// ByteSizeLong() is generally linear in the number of fields defined for the
// proto.
virtual size_t ByteSizeLong() const = 0;
// Legacy ByteSize() API.
PROTOBUF_DEPRECATED_MSG("Please use ByteSizeLong() instead")
int ByteSize() const { return internal::ToIntSize(ByteSizeLong()); }
// Serializes the message without recomputing the size. The message must not
// have changed since the last call to ByteSize(), and the value returned by
// ByteSize must be non-negative. Otherwise the results are undefined.
void SerializeWithCachedSizes(io::CodedOutputStream* output) const {
output->SetCur(_InternalSerialize(output->Cur(), output->EpsCopy()));
}
// Functions below here are not part of the public interface. It isn't
// enforced, but they should be treated as private, and will be private
// at some future time. Unfortunately the implementation of the "friend"
// keyword in GCC is broken at the moment, but we expect it will be fixed.
// Like SerializeWithCachedSizes, but writes directly to *target, returning
// a pointer to the byte immediately after the last byte written. "target"
// must point at a byte array of at least ByteSize() bytes. Whether to use
// deterministic serialization, e.g., maps in sorted order, is determined by
// CodedOutputStream::IsDefaultSerializationDeterministic().
uint8_t* SerializeWithCachedSizesToArray(uint8_t* target) const;
// Returns the result of the last call to ByteSize(). An embedded message's
// size is needed both to serialize it (because embedded messages are
// length-delimited) and to compute the outer message's size. Caching
// the size avoids computing it multiple times.
//
// ByteSize() does not automatically use the cached size when available
// because this would require invalidating it every time the message was
// modified, which would be too hard and expensive. (E.g. if a deeply-nested
// sub-message is changed, all of its parents' cached sizes would need to be
// invalidated, which is too much work for an otherwise inlined setter
// method.)
virtual int GetCachedSize() const = 0;
virtual const char* _InternalParse(const char* /*ptr*/,
internal::ParseContext* /*ctx*/) {
return nullptr;
}
virtual void OnDemandRegisterArenaDtor(Arena* /*arena*/) {}
protected:
template <typename T>
static T* CreateMaybeMessage(Arena* arena) {
return Arena::CreateMaybeMessage<T>(arena);
}
inline explicit MessageLite(Arena* arena, bool is_message_owned = false)
: _internal_metadata_(arena, is_message_owned) {}
// Returns the arena, if any, that directly owns this message and its internal
// memory (Arena::Own is different in that the arena doesn't directly own the
// internal memory). This method is used in proto's implementation for
// swapping, moving and setting allocated, for deciding whether the ownership
// of this message or its internal memory could be changed.
Arena* GetOwningArena() const { return _internal_metadata_.owning_arena(); }
// Returns the arena, used for allocating internal objects(e.g., child
// messages, etc), or owning incoming objects (e.g., set allocated).
Arena* GetArenaForAllocation() const { return _internal_metadata_.arena(); }
internal::InternalMetadata _internal_metadata_;
public:
enum ParseFlags {
kMerge = 0,
kParse = 1,
kMergePartial = 2,
kParsePartial = 3,
kMergeWithAliasing = 4,
kParseWithAliasing = 5,
kMergePartialWithAliasing = 6,
kParsePartialWithAliasing = 7
};
template <ParseFlags flags, typename T>
bool ParseFrom(const T& input);
// Fast path when conditions match (ie. non-deterministic)
// uint8_t* _InternalSerialize(uint8_t* ptr) const;
virtual uint8_t* _InternalSerialize(
uint8_t* ptr, io::EpsCopyOutputStream* stream) const = 0;
// Identical to IsInitialized() except that it logs an error message.
bool IsInitializedWithErrors() const {
if (IsInitialized()) return true;
LogInitializationErrorMessage();
return false;
}
private:
friend class FastReflectionMessageMutator;
friend class FastReflectionStringSetter;
friend class Message;
friend class Reflection;
friend class internal::ExtensionSet;
friend class internal::LazyField;
friend class internal::SwapFieldHelper;
friend class internal::TcParser;
friend class internal::WeakFieldMap;
friend class internal::WireFormatLite;
template <typename Type>
friend class Arena::InternalHelper;
template <typename Type>
friend class internal::GenericTypeHandler;
void LogInitializationErrorMessage() const;
bool MergeFromImpl(io::CodedInputStream* input, ParseFlags parse_flags);
GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageLite);
};
namespace internal {
template <bool alias>
bool MergeFromImpl(StringPiece input, MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<false>(StringPiece input,
MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<true>(StringPiece input,
MessageLite* msg,
MessageLite::ParseFlags parse_flags);
template <bool alias>
bool MergeFromImpl(io::ZeroCopyInputStream* input, MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<false>(io::ZeroCopyInputStream* input,
MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<true>(io::ZeroCopyInputStream* input,
MessageLite* msg,
MessageLite::ParseFlags parse_flags);
struct BoundedZCIS {
io::ZeroCopyInputStream* zcis;
int limit;
};
template <bool alias>
bool MergeFromImpl(BoundedZCIS input, MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<false>(BoundedZCIS input, MessageLite* msg,
MessageLite::ParseFlags parse_flags);
extern template bool MergeFromImpl<true>(BoundedZCIS input, MessageLite* msg,
MessageLite::ParseFlags parse_flags);
template <typename T>
struct SourceWrapper;
template <bool alias, typename T>
bool MergeFromImpl(const SourceWrapper<T>& input, MessageLite* msg,
MessageLite::ParseFlags parse_flags) {
return input.template MergeInto<alias>(msg, parse_flags);
}
} // namespace internal
template <MessageLite::ParseFlags flags, typename T>
bool MessageLite::ParseFrom(const T& input) {
if (flags & kParse) Clear();
constexpr bool alias = (flags & kMergeWithAliasing) != 0;
return internal::MergeFromImpl<alias>(input, this, flags);
}
// ===================================================================
// Shutdown support.
// Shut down the entire protocol buffers library, deleting all static-duration
// objects allocated by the library or by generated .pb.cc files.
//
// There are two reasons you might want to call this:
// * You use a draconian definition of "memory leak" in which you expect
// every single malloc() to have a corresponding free(), even for objects
// which live until program exit.
// * You are writing a dynamically-loaded library which needs to clean up
// after itself when the library is unloaded.
//
// It is safe to call this multiple times. However, it is not safe to use
// any other part of the protocol buffers library after
// ShutdownProtobufLibrary() has been called. Furthermore this call is not
// thread safe, user needs to synchronize multiple calls.
PROTOBUF_EXPORT void ShutdownProtobufLibrary();
namespace internal {
// Register a function to be called when ShutdownProtocolBuffers() is called.
PROTOBUF_EXPORT void OnShutdown(void (*func)());
// Run an arbitrary function on an arg
PROTOBUF_EXPORT void OnShutdownRun(void (*f)(const void*), const void* arg);
template <typename T>
T* OnShutdownDelete(T* p) {
OnShutdownRun([](const void* pp) { delete static_cast<const T*>(pp); }, p);
return p;
}
} // namespace internal
} // namespace protobuf
} // namespace google
#include <google/protobuf/port_undef.inc>
#endif // GOOGLE_PROTOBUF_MESSAGE_LITE_H__
C++
版MessageLite
的文档说明
message_lite.h
bookmark_border
#include <google/protobuf/message_lite.h>
namespace google::protobuf
Defines MessageLite, the abstract interface implemented by all (lite and non-lite) protocol message objects.
Classes in this file
MessageLite
Interface to light weight protocol messages.
File Members
These definitions are not part of any class.
void ShutdownProtobufLibrary()
Shut down the entire protocol buffers library, deleting all static-duration objects allocated by the library or by generated .pb.cc files. more...
void protobuf::ShutdownProtobufLibrary()
Shut down the entire protocol buffers library, deleting all static-duration objects allocated by the library or by generated .pb.cc files.
There are two reasons you might want to call this:
You use a draconian definition of "memory leak" in which you expect every single malloc() to have a corresponding free(), even for objects which live until program exit.
You are writing a dynamically-loaded library which needs to clean up after itself when the library is unloaded.
It is safe to call this multiple times. However, it is not safe to use any other part of the protocol buffers library after ShutdownProtobufLibrary() has been called. Furthermore this call is not thread safe, user needs to synchronize multiple calls.
class MessageLite
#include <google/protobuf/message_lite.h>
namespace google::protobuf
Interface to light weight protocol messages.
This interface is implemented by all protocol message objects. Non-lite messages additionally implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when you only need the subset of features which it supports – namely, nothing that uses descriptors or reflection. You can instruct the protocol compiler to generate classes which implement only MessageLite, not the full Message interface, by adding the following line to the .proto file:
option optimize_for = LITE_RUNTIME;
This is particularly useful on resource-constrained systems where the full protocol buffers runtime library is too big.
Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol definitions, a better way to reduce total code footprint is to use optimize_for = CODE_SIZE. This will make the generated code smaller while still supporting all the same features (at the expense of speed). optimize_for = LITE_RUNTIME is best when you only have a small number of message types linked into your binary, in which case the size of the protocol buffers runtime itself is the biggest problem.
Users must not derive from this class. Only the protocol compiler and the internal library are allowed to create subclasses.
Known subclasses:
Message
Members
enum ParseFlags
more...
protected internal::InternalMetadata _internal_metadata_
constexpr MessageLite()
virtual ~MessageLite()
template bool ParseFrom(const T & input)
virtual uint8 * _InternalSerialize(uint8 * ptr, io::EpsCopyOutputStream * stream) const = 0
Fast path when conditions match (ie. more...
bool IsInitializedWithErrors() const
Identical to IsInitialized() except that it logs an error message.
protected template static T * CreateMaybeMessage(Arena * arena)
protected explicit MessageLite(Arena * arena)
protected Arena * GetOwningArena() const
Returns the arena, if any, that directly owns this message and its internal memory (Arena::Own is different in that the arena doesn't directly own the internal memory). more...
protected Arena * GetArenaForAllocation() const
Returns the arena, used for allocating internal objects(e.g., child messages, etc), or owning incoming objects (e.g., set allocated).
Basic Operations
virtual std::string GetTypeName() const = 0
Get the name of this message type, e.g. "foo.bar.BazProto".
virtual MessageLite * New() const = 0
Construct a new instance of the same type. more...
virtual MessageLite * New(Arena * arena) const
Construct a new instance on the arena. more...
Arena * GetArena() const
Same as GetOwningArena.
void * GetMaybeArenaPointer() const
Get a pointer that may be equal to this message's arena, or may not be. more...
virtual void Clear() = 0
Clear all fields of the message and set them to their default values. more...
virtual bool IsInitialized() const = 0
Quickly check if all required fields have values set.
virtual std::string InitializationErrorString() const
This is not implemented for Lite messages – it just returns "(cannot determine missing fields for lite message)". more...
virtual void CheckTypeAndMergeFrom(const MessageLite & other) = 0
If |other| is the exact same class as this, calls MergeFrom(). more...
std::string DebugString() const
These methods return a human-readable summary of the message. more...
std::string ShortDebugString() const
std::string Utf8DebugString() const
MessageLite::DebugString is already Utf8 Safe. more...
Parsing
Methods for parsing in protocol buffer format.
Most of these are just simple wrappers around MergeFromCodedStream(). Clear() will be called before merging the input.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromCodedStream(io::CodedInputStream * input)
Fill the message with a protocol buffer parsed from the given input stream. more...
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromCodedStream(io::CodedInputStream * input)
Like ParseFromCodedStream(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromZeroCopyStream(io::ZeroCopyInputStream * input)
Read a protocol buffer from the given zero-copy input stream. more...
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromZeroCopyStream(io::ZeroCopyInputStream * input)
Like ParseFromZeroCopyStream(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromFileDescriptor(int file_descriptor)
Parse a protocol buffer from a file descriptor. more...
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromFileDescriptor(int file_descriptor)
Like ParseFromFileDescriptor(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromIstream(std::istream * input)
Parse a protocol buffer from a C++ istream. more...
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromIstream(std::istream * input)
Like ParseFromIstream(), but accepts messages that are missing required fields.
bool MergePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input, int size)
Read a protocol buffer from the given zero-copy input stream, expecting the message to be exactly "size" bytes long. more...
bool MergeFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input, int size)
Like ParseFromBoundedZeroCopyStream(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input, int size)
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromBoundedZeroCopyStream(io::ZeroCopyInputStream * input, int size)
Like ParseFromBoundedZeroCopyStream(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromString(ConstStringParam data)
Parses a protocol buffer contained in a string. more...
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromString(ConstStringParam data)
Like ParseFromString(), but accepts messages that are missing required fields.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParseFromArray(const void * data, int size)
Parse a protocol buffer contained in an array of bytes.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool ParsePartialFromArray(const void * data, int size)
Like ParseFromArray(), but accepts messages that are missing required fields.
bool MergeFromCodedStream(io::CodedInputStream * input)
Reads a protocol buffer from the stream and merges it into this Message. more...
bool MergePartialFromCodedStream(io::CodedInputStream * input)
Like MergeFromCodedStream(), but succeeds even if required fields are missing in the input. more...
bool MergeFromString(ConstStringParam data)
Merge a protocol buffer contained in a string.
Serialization
Methods for serializing in protocol buffer format.
Most of these are just simple wrappers around ByteSize() and SerializeWithCachedSizes().
bool SerializeToCodedStream(io::CodedOutputStream * output) const
Write a protocol buffer of this message to the given output. more...
bool SerializePartialToCodedStream(io::CodedOutputStream * output) const
Like SerializeToCodedStream(), but allows missing required fields.
bool SerializeToZeroCopyStream(io::ZeroCopyOutputStream * output) const
Write the message to the given zero-copy output stream. more...
bool SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream * output) const
Like SerializeToZeroCopyStream(), but allows missing required fields.
bool SerializeToString(std::string * output) const
Serialize the message and store it in the given string. more...
bool SerializePartialToString(std::string * output) const
Like SerializeToString(), but allows missing required fields.
bool SerializeToArray(void * data, int size) const
Serialize the message and store it in the given byte array. more...
bool SerializePartialToArray(void * data, int size) const
Like SerializeToArray(), but allows missing required fields.
std::string SerializeAsString() const
Make a string encoding the message. more...
std::string SerializePartialAsString() const
Like SerializeAsString(), but allows missing required fields.
bool SerializeToFileDescriptor(int file_descriptor) const
Serialize the message and write it to the given file descriptor. more...
bool SerializePartialToFileDescriptor(int file_descriptor) const
Like SerializeToFileDescriptor(), but allows missing required fields.
bool SerializeToOstream(std::ostream * output) const
Serialize the message and write it to the given C++ ostream. more...
bool SerializePartialToOstream(std::ostream * output) const
Like SerializeToOstream(), but allows missing required fields.
bool AppendToString(std::string * output) const
Like SerializeToString(), but appends to the data to the string's existing contents. more...
bool AppendPartialToString(std::string * output) const
Like AppendToString(), but allows missing required fields.
virtual size_t ByteSizeLong() const = 0
Computes the serialized size of the message. more...
int ByteSize() const
Legacy ByteSize() API.
void SerializeWithCachedSizes(io::CodedOutputStream * output) const
Serializes the message without recomputing the size. more...
uint8 * SerializeWithCachedSizesToArray(uint8 * target) const
Like SerializeWithCachedSizes, but writes directly to *target, returning a pointer to the byte immediately after the last byte written. more...
virtual int GetCachedSize() const = 0
Returns the result of the last call to ByteSize(). more...
virtual const char * _InternalParse(const char * , internal::ParseContext * )
enum MessageLite::ParseFlags {
kMerge = = 0,
kParse = = 1,
kMergePartial = = 2,
kParsePartial = = 3,
kMergeWithAliasing = = 4,
kParseWithAliasing = = 5,
kMergePartialWithAliasing = = 6,
kParsePartialWithAliasing = = 7
}
kMerge kParse kMergePartial kParsePartial kMergeWithAliasing kParseWithAliasing kMergePartialWithAliasing kParsePartialWithAliasing virtual uint8 * MessageLite::_InternalSerialize(
uint8 * ptr,
io::EpsCopyOutputStream * stream) const = 0
Fast path when conditions match (ie.
non-deterministic) uint8* _InternalSerialize(uint8* ptr) const;
protected Arena * MessageLite::GetOwningArena() const
Returns the arena, if any, that directly owns this message and its internal memory (Arena::Own is different in that the arena doesn't directly own the internal memory).
This method is used in proto's implementation for swapping, moving and setting allocated, for deciding whether the ownership of this message or its internal memory could be changed.
virtual MessageLite * MessageLite::New() const = 0
Construct a new instance of the same type.
Ownership is passed to the caller.
virtual MessageLite * MessageLite::New(
Arena * arena) const
Construct a new instance on the arena.
Ownership is passed to the caller if arena is a NULL. Default implementation for backwards compatibility.
void * MessageLite::GetMaybeArenaPointer() const
Get a pointer that may be equal to this message's arena, or may not be.
If the value returned by this method is equal to some arena pointer, then this message is on that arena; however, if this message is on some arena, this method may or may not return that arena's pointer. As a tradeoff, this method may be more efficient than GetArena(). The intent is to allow underlying representations that use e.g. tagged pointers to sometimes store the arena pointer directly, and sometimes in a more indirect way, and allow a fastpath comparison against the arena pointer when it's easy to obtain.
virtual void MessageLite::Clear() = 0
Clear all fields of the message and set them to their default values.
Clear() avoids freeing memory, assuming that any memory allocated to hold parts of the message will be needed again to hold the next message. If you actually want to free the memory used by a Message, you must delete it.
virtual std::string MessageLite::InitializationErrorString() const
This is not implemented for Lite messages – it just returns "(cannot determine missing fields for lite message)".
However, it is implemented for full messages. See message.h.
virtual void MessageLite::CheckTypeAndMergeFrom(
const MessageLite & other) = 0
If |other| is the exact same class as this, calls MergeFrom().
Otherwise, results are undefined (probably crash).
std::string MessageLite::DebugString() const
These methods return a human-readable summary of the message.
Note that since the MessageLite interface does not support reflection, there is very little information that these methods can provide. They are shadowed by methods of the same name on the Message interface which provide much more information. The methods here are intended primarily to facilitate code reuse for logic that needs to interoperate with both full and lite protos.
The format of the returned string is subject to change, so please do not assume it will remain stable over time.
std::string MessageLite::Utf8DebugString() const
MessageLite::DebugString is already Utf8 Safe.
This is to add compatibility with Message.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool
MessageLite::ParseFromCodedStream(
io::CodedInputStream * input)
Fill the message with a protocol buffer parsed from the given input stream.
Returns false on a read error or if the input is in the wrong format. A successful return does not indicate the entire input is consumed, ensure you call ConsumedEntireMessage() to check that if applicable.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool
MessageLite::ParseFromZeroCopyStream(
io::ZeroCopyInputStream * input)
Read a protocol buffer from the given zero-copy input stream.
If successful, the entire input will be consumed.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool
MessageLite::ParseFromFileDescriptor(
int file_descriptor)
Parse a protocol buffer from a file descriptor.
If successful, the entire input will be consumed.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool
MessageLite::ParseFromIstream(
std::istream * input)
Parse a protocol buffer from a C++ istream.
If successful, the entire input will be consumed.
bool MessageLite::MergePartialFromBoundedZeroCopyStream(
io::ZeroCopyInputStream * input,
int size)
Read a protocol buffer from the given zero-copy input stream, expecting the message to be exactly "size" bytes long.
If successful, exactly this many bytes will have been consumed from the input.
PROTOBUF_ATTRIBUTE_REINITIALIZES bool
MessageLite::ParseFromString(
ConstStringParam data)
Parses a protocol buffer contained in a string.
Returns true on success. This function takes a string in the (non-human-readable) binary wire format, matching the encoding output by MessageLite::SerializeToString(). If you'd like to convert a human-readable string into a protocol buffer object, see google::protobuf::TextFormat::ParseFromString().
bool MessageLite::MergeFromCodedStream(
io::CodedInputStream * input)
Reads a protocol buffer from the stream and merges it into this Message.
Singular fields read from the what is already in the Message and repeated fields are appended to those already present.
It is the responsibility of the caller to call input->LastTagWas() (for groups) or input->ConsumedEntireMessage() (for non-groups) after this returns to verify that the message's end was delimited correctly.
ParseFromCodedStream() is implemented as Clear() followed by MergeFromCodedStream().
bool MessageLite::MergePartialFromCodedStream(
io::CodedInputStream * input)
Like MergeFromCodedStream(), but succeeds even if required fields are missing in the input.
MergeFromCodedStream() is just implemented as MergePartialFromCodedStream() followed by IsInitialized().
bool MessageLite::SerializeToCodedStream(
io::CodedOutputStream * output) const
Write a protocol buffer of this message to the given output.
Returns false on a write error. If the message is missing required fields, this may GOOGLE_CHECK-fail.
bool MessageLite::SerializeToZeroCopyStream(
io::ZeroCopyOutputStream * output) const
Write the message to the given zero-copy output stream.
All required fields must be set.
bool MessageLite::SerializeToString(
std::string * output) const
Serialize the message and store it in the given string.
All required fields must be set.
bool MessageLite::SerializeToArray(
void * data,
int size) const
Serialize the message and store it in the given byte array.
All required fields must be set.
std::string MessageLite::SerializeAsString() const
Make a string encoding the message.
Is equivalent to calling SerializeToString() on a string and using that. Returns the empty string if SerializeToString() would have returned an error. Note: If you intend to generate many such strings, you may reduce heap fragmentation by instead re-using the same string object with calls to SerializeToString().
bool MessageLite::SerializeToFileDescriptor(
int file_descriptor) const
Serialize the message and write it to the given file descriptor.
All required fields must be set.
bool MessageLite::SerializeToOstream(
std::ostream * output) const
Serialize the message and write it to the given C++ ostream.
All required fields must be set.
bool MessageLite::AppendToString(
std::string * output) const
Like SerializeToString(), but appends to the data to the string's existing contents.
All required fields must be set.
virtual size_t MessageLite::ByteSizeLong() const = 0
Computes the serialized size of the message.
This recursively calls ByteSizeLong() on all embedded messages.
ByteSizeLong() is generally linear in the number of fields defined for the proto.
void MessageLite::SerializeWithCachedSizes(
io::CodedOutputStream * output) const
Serializes the message without recomputing the size.
The message must not have changed since the last call to ByteSize(), and the value returned by ByteSize must be non-negative. Otherwise the results are undefined.
uint8 * MessageLite::SerializeWithCachedSizesToArray(
uint8 * target) const
Like SerializeWithCachedSizes, but writes directly to *target, returning a pointer to the byte immediately after the last byte written.
"target" must point at a byte array of at least ByteSize() bytes. Whether to use deterministic serialization, e.g., maps in sorted order, is determined by CodedOutputStream::IsDefaultSerializationDeterministic().
virtual int MessageLite::GetCachedSize() const = 0
Returns the result of the last call to ByteSize().
An embedded message's size is needed both to serialize it (because embedded messages are length-delimited) and to compute the outer message's size. Caching the size avoids computing it multiple times.
ByteSize() does not automatically use the cached size when available because this would require invalidating it every time the message was modified, which would be too hard and expensive. (E.g. if a deeply-nested sub-message is changed, all of its parents' cached sizes would need to be invalidated, which is too much work for an otherwise inlined setter method.)
其中可以看到有枚举定义:
enum MessageLite::ParseFlags {
kMerge = = 0,
kParse = = 1,
kMergePartial = = 2,
kParsePartial = = 3,
kMergeWithAliasing = = 4,
kParseWithAliasing = = 5,
kMergePartialWithAliasing = = 6,
kParsePartialWithAliasing = = 7
}
Java
版MessageLite
Java
版MessageLite
的代码定义
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// TODO(kenton): Use generics? E.g. Builder<BuilderType extends Builder>, then
// mergeFrom*() could return BuilderType for better type-safety.
package com.google.protobuf;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Abstract interface implemented by Protocol Message objects.
*
* <p>This interface is implemented by all protocol message objects. Non-lite messages additionally
* implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when
* you only need the subset of features which it supports -- namely, nothing that uses descriptors
* or reflection. You can instruct the protocol compiler to generate classes which implement only
* MessageLite, not the full Message interface, by adding the follow line to the .proto file:
*
* <pre>
* option optimize_for = LITE_RUNTIME;
* </pre>
*
* <p>This is particularly useful on resource-constrained systems where the full protocol buffers
* runtime library is too big.
*
* <p>Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol
* definitions, a better way to reduce total code footprint is to use {@code optimize_for =
* CODE_SIZE}. This will make the generated code smaller while still supporting all the same
* features (at the expense of speed). {@code optimize_for = LITE_RUNTIME} is best when you only
* have a small number of message types linked into your binary, in which case the size of the
* protocol buffers runtime itself is the biggest problem.
*
* @author kenton@google.com Kenton Varda
*/
public interface MessageLite extends MessageLiteOrBuilder {
/**
* Serializes the message and writes it to {@code output}. This does not flush or close the
* stream.
*/
void writeTo(CodedOutputStream output) throws IOException;
/**
* Get the number of bytes required to encode this message. The result is only computed on the
* first call and memoized after that.
*
* If this message requires more than Integer.MAX_VALUE bytes to encode, the return value will
* be smaller than the actual number of bytes required and might be negative.
*/
int getSerializedSize();
/** Gets the parser for a message of the same type as this message. */
Parser<? extends MessageLite> getParserForType();
// -----------------------------------------------------------------
// Convenience methods.
/**
* Serializes the message to a {@code ByteString} and returns it. This is just a trivial wrapper
* around {@link #writeTo(CodedOutputStream)}.
*
* If this message requires more than Integer.MAX_VALUE bytes to encode, the behavior is
* unpredictable. It may throw a runtime exception or truncate or slice the data.
*/
ByteString toByteString();
/**
* Serializes the message to a {@code byte} array and returns it. This is just a trivial wrapper
* around {@link #writeTo(CodedOutputStream)}.
*
* If this message requires more than Integer.MAX_VALUE bytes to encode, the behavior is
* unpredictable. It may throw a runtime exception or truncate or slice the data.
*/
byte[] toByteArray();
/**
* Serializes the message and writes it to {@code output}. This is just a trivial wrapper around
* {@link #writeTo(CodedOutputStream)}. This does not flush or close the stream.
*
* <p>NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write any more data to the
* stream after the message, you must somehow ensure that the parser on the receiving end does not
* interpret this as being part of the protocol message. This can be done e.g. by writing the size
* of the message before the data, then making sure to limit the input to that size on the
* receiving end (e.g. by wrapping the InputStream in one which limits the input). Alternatively,
* just use {@link #writeDelimitedTo(OutputStream)}.
*/
void writeTo(OutputStream output) throws IOException;
/**
* Like {@link #writeTo(OutputStream)}, but writes the size of the message as a varint before
* writing the data. This allows more data to be written to the stream after the message without
* the need to delimit the message data yourself. Use {@link
* Builder#mergeDelimitedFrom(InputStream)} (or the static method {@code
* YourMessageType.parseDelimitedFrom(InputStream)}) to parse messages written by this method.
*/
void writeDelimitedTo(OutputStream output) throws IOException;
// =================================================================
// Builders
/** Constructs a new builder for a message of the same type as this message. */
Builder newBuilderForType();
/**
* Constructs a builder initialized with the current message. Use this to derive a new message
* from the current one.
*/
Builder toBuilder();
/** Abstract interface implemented by Protocol Message builders. */
interface Builder extends MessageLiteOrBuilder, Cloneable {
/** Resets all fields to their default values. */
Builder clear();
/**
* Constructs the message based on the state of the Builder. Subsequent changes to the Builder
* will not affect the returned message.
*
* @throws UninitializedMessageException The message is missing one or more required fields
* (i.e. {@link #isInitialized()} returns false). Use {@link #buildPartial()} to bypass this
* check.
*/
MessageLite build();
/**
* Like {@link #build()}, but does not throw an exception if the message is missing required
* fields. Instead, a partial message is returned. Subsequent changes to the Builder will not
* affect the returned message.
*/
MessageLite buildPartial();
/**
* Clones the Builder.
*
* @see Object#clone()
*/
Builder clone();
/**
* Parses a message of this type from the input and merges it with this message.
*
* <p>Warning: This does not verify that all required fields are present in the input message.
* If you call {@link #build()} without setting all required fields, it will throw an {@link
* UninitializedMessageException}, which is a {@code RuntimeException} and thus might not be
* caught. There are a few good ways to deal with this:
*
* <ul>
* <li>Call {@link #isInitialized()} to verify that all required fields are set before
* building.
* <li>Use {@code buildPartial()} to build, which ignores missing required fields.
* </ul>
*
* <p>Note: The caller should call {@link CodedInputStream#checkLastTagWas(int)} after calling
* this to verify that the last tag seen was the appropriate end-group tag, or zero for EOF.
*/
Builder mergeFrom(CodedInputStream input) throws IOException;
/**
* Like {@link Builder#mergeFrom(CodedInputStream)}, but also parses extensions. The extensions
* that you want to be able to parse must be registered in {@code extensionRegistry}. Extensions
* not in the registry will be treated as unknown fields.
*/
Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
// ---------------------------------------------------------------
// Convenience methods.
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream)}.
*
* @return this
*/
Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parse {@code data} as a message of this type and merge it with the message being built. This
* is just a small wrapper around {@link #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry)
throws InvalidProtocolBufferException;
/**
* Parse a message of this type from {@code input} and merge it with the message being built.
* This is just a small wrapper around {@link #mergeFrom(CodedInputStream)}. Note that this
* method always reads the <i>entire</i> input (unless it throws an exception). If you want it
* to stop earlier, you will need to wrap your input in some wrapper stream that limits reading.
* Or, use {@link MessageLite#writeDelimitedTo(OutputStream)} to write your message and {@link
* #mergeDelimitedFrom(InputStream)} to read it.
*
* <p>Despite usually reading the entire input, this does not close the stream.
*
* @return this
*/
Builder mergeFrom(InputStream input) throws IOException;
/**
* Parse a message of this type from {@code input} and merge it with the message being built.
* This is just a small wrapper around {@link
* #mergeFrom(CodedInputStream,ExtensionRegistryLite)}.
*
* @return this
*/
Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
/**
* Merge {@code other} into the message being built. {@code other} must have the exact same type
* as {@code this} (i.e. {@code getClass().equals(getDefaultInstanceForType().getClass())}).
*
* <p>Merging occurs as follows. For each field:
* * For singular primitive fields, if the field is set in {@code other}, then {@code other}'s
* value overwrites the value in this message.
* * For singular message fields, if the field is set in {@code other}, it is merged into the
* corresponding sub-message of this message using the same merging rules.
* * For repeated fields, the elements in {@code other} are concatenated with the elements in
* this message. * For oneof groups, if the other message has one of the fields set, the group
* of this message is cleared and replaced by the field of the other message, so that the oneof
* constraint is preserved.
*
* <p>This is equivalent to the {@code Message::MergeFrom} method in C++.
*/
Builder mergeFrom(MessageLite other);
/**
* Like {@link #mergeFrom(InputStream)}, but does not read until EOF. Instead, the size of the
* message (encoded as a varint) is read first, then the message data. Use {@link
* MessageLite#writeDelimitedTo(OutputStream)} to write messages in this format.
*
* @return True if successful, or false if the stream is at EOF when the method starts. Any
* other error (including reaching EOF during parsing) will cause an exception to be thrown.
*/
boolean mergeDelimitedFrom(InputStream input) throws IOException;
/** Like {@link #mergeDelimitedFrom(InputStream)} but supporting extensions. */
boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry)
throws IOException;
}
}
-> 对应的函数定义:
public interface MessageLite extends MessageLiteOrBuilder
{void writeTo(CodedOutputStream output) throws IOException;
int getSerializedSize();
Parser<? extends MessageLite> getParserForType();
ByteString toByteString();
byte[] toByteArray();
void writeTo(OutputStream output) throws IOException;
void writeDelimitedTo(OutputStream output) throws IOException;
Builders
Builder newBuilderForType();
Builder toBuilder();
interface Builder extends MessageLiteOrBuilder, Cloneable {
Builder clear();
MessageLite build();
MessageLite buildPartial();
Builder clone();
Builder mergeFrom(CodedInputStream input) throws IOException;
Builder mergeFrom(CodedInputStream input, ExtensionRegistryLite extensionRegistry) throws IOException;
Builder mergeFrom(ByteString data) throws InvalidProtocolBufferException;
Builder mergeFrom(ByteString data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException;
Builder mergeFrom(byte[] data) throws InvalidProtocolBufferException;
Builder mergeFrom(byte[] data, int off, int len) throws InvalidProtocolBufferException;
Builder mergeFrom(byte[] data, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException;
Builder mergeFrom(byte[] data, int off, int len, ExtensionRegistryLite extensionRegistry) throws InvalidProtocolBufferException;
Builder mergeFrom(InputStream input) throws IOException;
Builder mergeFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException;
Builder mergeFrom(MessageLite other);
boolean mergeDelimitedFrom(InputStream input) throws IOException;
boolean mergeDelimitedFrom(InputStream input, ExtensionRegistryLite extensionRegistry) throws IOException;
Java
版MessageLite
的文档说明
- com.google.protobuf Interface MessageLite
com.google.protobuf
Interface MessageLite
All Superinterfaces:
MessageLiteOrBuilder
All Known Subinterfaces:
Message
All Known Implementing Classes:
AbstractMessage, AbstractMessageLite, Any, Api, BoolValue, BytesValue, DescriptorProtos.DescriptorProto, DescriptorProtos.DescriptorProto.ExtensionRange, DescriptorProtos.DescriptorProto.ReservedRange, DescriptorProtos.EnumDescriptorProto, DescriptorProtos.EnumDescriptorProto.EnumReservedRange, DescriptorProtos.EnumOptions, DescriptorProtos.EnumValueDescriptorProto, DescriptorProtos.EnumValueOptions, DescriptorProtos.ExtensionRangeOptions, DescriptorProtos.FieldDescriptorProto, DescriptorProtos.FieldOptions, DescriptorProtos.FileDescriptorProto, DescriptorProtos.FileDescriptorSet, DescriptorProtos.FileOptions, DescriptorProtos.GeneratedCodeInfo, DescriptorProtos.GeneratedCodeInfo.Annotation, DescriptorProtos.MessageOptions, DescriptorProtos.MethodDescriptorProto, DescriptorProtos.MethodOptions, DescriptorProtos.OneofDescriptorProto, DescriptorProtos.OneofOptions, DescriptorProtos.ServiceDescriptorProto, DescriptorProtos.ServiceOptions, DescriptorProtos.SourceCodeInfo, DescriptorProtos.SourceCodeInfo.Location, DescriptorProtos.UninterpretedOption, DescriptorProtos.UninterpretedOption.NamePart, DoubleValue, Duration, DynamicMessage, Empty, Enum, EnumValue, Field, FieldMask, FloatValue, com.google.protobuf.GeneratedMessageV3, com.google.protobuf.GeneratedMessageV3.ExtendableMessage, Int32Value, Int64Value, ListValue, Method, Mixin, Option, PluginProtos.CodeGeneratorRequest, PluginProtos.CodeGeneratorResponse, PluginProtos.CodeGeneratorResponse.File, PluginProtos.Version, SourceContext, StringValue, Struct, Timestamp, Type, UInt32Value, UInt64Value, Value
public interface MessageLite
extends MessageLiteOrBuilder
Abstract interface implemented by Protocol Message objects.
This interface is implemented by all protocol message objects. Non-lite messages additionally implement the Message interface, which is a subclass of MessageLite. Use MessageLite instead when you only need the subset of features which it supports -- namely, nothing that uses descriptors or reflection. You can instruct the protocol compiler to generate classes which implement only MessageLite, not the full Message interface, by adding the follow line to the .proto file:
option optimize_for = LITE_RUNTIME;
This is particularly useful on resource-constrained systems where the full protocol buffers runtime library is too big.
Note that on non-constrained systems (e.g. servers) when you need to link in lots of protocol definitions, a better way to reduce total code footprint is to use optimize_for = CODE_SIZE. This will make the generated code smaller while still supporting all the same features (at the expense of speed). optimize_for = LITE_RUNTIME is best when you only have a small number of message types linked into your binary, in which case the size of the protocol buffers runtime itself is the biggest problem.
Nested Class Summary
Nested Classes
Modifier and Type Interface and Description
static interface MessageLite.Builder
Abstract interface implemented by Protocol Message builders.
Method Summary
All MethodsInstance MethodsAbstract Methods
Modifier and Type Method and Description
Parser<? extends MessageLite> getParserForType()
Gets the parser for a message of the same type as this message.
int getSerializedSize()
Get the number of bytes required to encode this message.
MessageLite.Builder newBuilderForType()
Constructs a new builder for a message of the same type as this message.
MessageLite.Builder toBuilder()
Constructs a builder initialized with the current message.
byte[] toByteArray()
Serializes the message to a byte array and returns it.
ByteString toByteString()
Serializes the message to a ByteString and returns it.
void writeDelimitedTo(java.io.OutputStream output)
Like writeTo(OutputStream), but writes the size of the message as a varint before writing the data.
void writeTo(CodedOutputStream output)
Serializes the message and writes it to output.
void writeTo(java.io.OutputStream output)
Serializes the message and writes it to output.
Methods inherited from interface com.google.protobuf.MessageLiteOrBuilder
getDefaultInstanceForType, isInitialized
Method Detail
writeTo
void writeTo(CodedOutputStream output)
throws java.io.IOException
Serializes the message and writes it to output. This does not flush or close the stream.
Throws:
java.io.IOException
getSerializedSize
int getSerializedSize()
Get the number of bytes required to encode this message. The result is only computed on the first call and memoized after that.
getParserForType
Parser<? extends MessageLite> getParserForType()
Gets the parser for a message of the same type as this message.
toByteString
ByteString toByteString()
Serializes the message to a ByteString and returns it. This is just a trivial wrapper around writeTo(CodedOutputStream).
toByteArray
byte[] toByteArray()
Serializes the message to a byte array and returns it. This is just a trivial wrapper around writeTo(CodedOutputStream).
writeTo
void writeTo(java.io.OutputStream output)
throws java.io.IOException
Serializes the message and writes it to output. This is just a trivial wrapper around writeTo(CodedOutputStream). This does not flush or close the stream.
NOTE: Protocol Buffers are not self-delimiting. Therefore, if you write any more data to the stream after the message, you must somehow ensure that the parser on the receiving end does not interpret this as being part of the protocol message. This can be done e.g. by writing the size of the message before the data, then making sure to limit the input to that size on the receiving end (e.g. by wrapping the InputStream in one which limits the input). Alternatively, just use writeDelimitedTo(OutputStream).
Throws:
java.io.IOException
writeDelimitedTo
void writeDelimitedTo(java.io.OutputStream output)
throws java.io.IOException
Like writeTo(OutputStream), but writes the size of the message as a varint before writing the data. This allows more data to be written to the stream after the message without the need to delimit the message data yourself. Use MessageLite.Builder.mergeDelimitedFrom(InputStream) (or the static method YourMessageType.parseDelimitedFrom(InputStream)) to parse messages written by this method.
Throws:
java.io.IOException
newBuilderForType
MessageLite.Builder newBuilderForType()
Constructs a new builder for a message of the same type as this message.
toBuilder
MessageLite.Builder toBuilder()
Constructs a builder initialized with the current message. Use this to derive a new message from the current one.