Not found
Oops! This page doesn't exist. Try going back to the home page.
diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml deleted file mode 100644 index 5b5e5fecb..000000000 --- a/.github/workflows/gh-pages.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: github pages -on: - push: - branches: - - main # Set a branch to deploy - pull_request: - branches: - - main - workflow_dispatch: - -jobs: - deploy: - permissions: - contents: write - runs-on: ubuntu-22.04 - steps: - - uses: actions/checkout@v3 - with: - submodules: true # Fetch Hugo themes (true OR recursive) - fetch-depth: 0 # Fetch all history for .GitInfo and .Lastmod - - - name: Setup Hugo - uses: peaceiris/actions-hugo@v2 - with: - hugo-version: 0.121.2 - extended: true - - - name: Install Dependencies - run: npm install autoprefixer postcss postcss-cli - - - name: Build - run: hugo --minify - - - name: Deploy - uses: peaceiris/actions-gh-pages@v3 - if: github.ref == 'refs/heads/main' - with: - github_token: ${{ secrets.GITHUB_TOKEN }} - publish_dir: ./public - cname: protobuf.dev \ No newline at end of file diff --git a/content/reference/php/api-docs/opensearch.xml b/.nojekyll similarity index 100% rename from content/reference/php/api-docs/opensearch.xml rename to .nojekyll diff --git a/404.html b/404.html new file mode 100644 index 000000000..551fdf665 --- /dev/null +++ b/404.html @@ -0,0 +1,4 @@ +
Oops! This page doesn't exist. Try going back to the home page.
The “1-1-1” best practice advocates structuring definitions with one top-level
+entity (message, enum, or extension) per .proto file, corresponding to a
+single proto_library build rule. This approach promotes small, modular proto
+definitions. Key benefits include simplified refactoring, potentially improved
+build times, and smaller binary sizes due to minimized transitive dependencies.
The 1-1-1 best practice is to keep every proto_library and .proto file as small +as is reasonable, with the ideal being:
proto_library build rule.proto fileHaving the fewest number of message, enum, extension, and services as you +reasonably can makes refactoring easier. Moving files when they’re separated is +much easier than extracting messages from a file with other messages.
Following this practice can help build times and binary size by reducing the +size of your transitive dependencies in practice: when some code only needs to +use one enum, under a 1-1-1 design it can depend just on the .proto file that +defines that enum and avoid incidentally pulling in a large set of transitive +dependencies that may only be used by another message defined in the same file.
There are cases where the 1-1-1 ideal is not possible (circular dependencies), +not ideal (extremely conceptually coupled messages which have readability +benefits by being co-located), or where some of the downsides don’t apply (when +a .proto file has no imports, then there are no technical concerns about the +size of transitive dependencies). As with any best practice, use good judgment +for when to diverge from the guideline.
One place that modularity of proto schema files is important is when creating +gRPC +definitions. The following set of proto files shows modular structure.
student_id.proto
edition = "2023";
+
+package my.package;
+
+message StudentId {
+ string value = 1;
+}
+full_name.proto
edition = "2023";
+
+package my.package;
+
+message FullName {
+ string family_name = 1;
+ string given_name = 2;
+}
+student.proto
edition = "2023";
+
+package my.package;
+
+import "student_id.proto";
+import "full_name.proto";
+
+message Student {
+ StudentId id = 1;
+ FullName name = 2;
+}
+create_student_request.proto
edition = "2023";
+
+package my.package;
+
+import "full_name.proto";
+
+message CreateStudentRequest {
+ FullName name = 1;
+}
+create_student_response.proto
edition = "2023";
+
+package my.package;
+
+import "student.proto";
+
+message CreateStudentResponse {
+ Student student = 1;
+}
+get_student_request.proto
edition = "2023";
+
+package my.package;
+
+import "student_id.proto";
+
+message GetStudentRequest {
+ StudentId id = 1;
+}
+get_student_response.proto
edition = "2023";
+
+package my.package;
+
+import "student.proto";
+
+message GetStudentResponse {
+ Student student = 1;
+}
+student_service.proto
edition = "2023";
+
+package my.package;
+
+import "create_student_request.proto";
+import "create_student_response.proto";
+import "get_student_request.proto";
+import "get_student_response.proto";
+
+service StudentService {
+ rpc CreateStudent(CreateStudentRequest) returns (CreateStudentResponse);
+ rpc GetStudent(GetStudentRequest) returns (GetStudentResponse);
+}
+The service definition and each of the message definitions are each in their own +file, and you use includes to give access to the messages from other schema +files.
In this example, Student, StudentId, and FullName are domain types that
+are reusable across requests and responses. The top-level request and response
+protos are unique to each service+method.
If you later need to add a middle_name field to the FullName message, you
+won’t need to update every individual top-level message with that new field.
+Likewise, if you need to update Student with more information, all the
+requests and responses get the update. Further, StudentId might update to be a
+multi-part ID.
Lastly, having even simple types like StudentId wrapped as a message means
+that you have created a type that has semantics and consolidated documentation.
+For something like FullName you’ll need to be careful with where this PII gets
+logged; this is another advantage of not repeating these fields in multiple
+top-level messages. You can tag those fields in one place as sensitive
+and exclude them from logging.
Clients and servers are never updated at exactly the same time - even when you +try to update them at the same time. One or the +other may get rolled back. Don’t assume that you can make a breaking change and +it’ll be okay because the client and server are in sync.
Never re-use a tag number. It messes up deserialization. Even if you think no +one is using the field, don’t re-use a tag number. If the change was live ever, +there could be serialized versions of your proto in a log +somewhere. Or there could be old code in another server that will break.
When you delete a field that’s no longer used, reserve its tag number so that no
+one accidentally re-uses it in the future. Just reserved 2, 3; is enough. No
+type required (lets you trim dependencies!). You can also reserve names to avoid
+recycling now-deleted field names: reserved foo, bar;. See the docs on
+reserved field numbers
+and
+reserved field names.
When you delete an enum value that’s no longer used, reserve its number so that
+no one accidentally re-uses it in the future. Just reserved 2, 3; is enough.
+You can also reserve names to avoid recycling now-deleted value names: reserved FOO, BAR;. See also
+enum reserved values
When you add a new enum alias, put the new name last to give +services time to pick it up.
To safely remove the original name (if it’s being used for interchange, which it +shouldn’t), you must do the following:
Add the new name below the old name and deprecate the old one (serializers +will continue to use the old name)
After every parser has the schema rolled out, swap the order of the two +names (serializers will begin using the new name, parsers accept both)
After every serializer has that version of the schema, you can delete the +deprecated name.
Note: While in theory clients shouldn’t be using the old name for +interchange, it’s still polite to follow the above steps, especially for +widely-used enum names.
Almost never change the type of a field; it’ll mess up deserialization, same as
+re-using a tag number. The
+protobuf docs
+outline a small number of cases that are okay (for example, going between
+int32, uint32, int64 and bool). However, changing a field’s message type
+will break unless the new message is a superset of the old one.
Never add a required field, instead add // required to document the API
+contract. Required fields are considered harmful by so many they were
+removed from proto3 completely. Make all fields
+optional or repeated. You never know how long a message type is going to last
+and whether someone will be forced to fill in your required field with an empty
+string or zero in four years when it’s no longer logically required but the
+proto still says it is.
For proto3 there are no required fields, so this advice does not apply.
Don’t make a message with “lots” (think: hundreds) of fields. In C++ every field +adds roughly 65 bits to the in-memory object size whether it’s populated or not +(8 bytes for the pointer and, if the field is declared as optional, another bit +in a bitfield that keeps track of whether the field is set). When your proto +grows too large, the generated code may not even compile (for example, in Java +there is a hard limit on the size of a method +).
Enums should include a default FOO_UNSPECIFIED value as the first value in the
+declaration.
+When new values are added to an enum, old clients will see the field as unset
+and the getter will return the default value or the first-declared value if no
+default exists . For consistent behavior with proto enums,
+the first declared enum value should be a default FOO_UNSPECIFIED value and
+should use tag 0. It may be tempting to declare this default as a semantically
+meaningful value but as a general rule, do not, to aid in the evolution of your
+protocol as new enum values are added over time. All enum values declared under
+a container message are in the same C++ namespace, so prefix the unspecified
+value with the enum’s name to avoid compilation errors. If you’ll never need
+cross-language constants, an int32 will preserve unknown values and generates
+less code. Note that proto enums require the first value to be
+zero and can round-trip (deserialize, serialize) an unknown enum value.
Using words that have already been defined by the C++ language - specifically,
+in its headers such as math.h, may cause compilation errors if the #include
+statement for one of those headers appears before the one for .proto.h. Avoid
+using macro constants such as “NULL,” “NAN,” and “DOMAIN” as enum values.
Any where possibleIf you plan to use Any, first double-check if extensions can satisfy the use
+case instead. If yes, prefer using extensions.
Any was created in Proto3 to replace extensions. However, it has a number of
+design flaws. For most use cases, prefer using extensions.
The main use case that Any fulfills is the uncommon scenario in which
+horizontal infrastructure needs to propagate completely arbitrary messages, and
+declaring an extension for each possible legal types would be infeasible.
In the future, Protobuf may introduce a new concept that would satisfy the Any
+use cases without the design flaws, but we have no concrete plans at this time.
Using the following common, shared types is strongly encouraged. E.g., do not
+use int32 timestamp_seconds_since_epoch or int64 timeout_millis in your code
+when a perfectly suitable common type already exists!
duration
+is a signed, fixed-length span of time (for example, 42s).timestamp
+is a point in time independent of any time zone or calendar (for example,
+2017-01-15T01:30:15.01Z).interval
+is a time interval independent of time zone or calendar (for example,
+2017-01-15T01:30:15.01Z - 2017-01-16T02:30:15.01Z).date
+is a whole calendar date (for example, 2005-09-19).month
+is a month of year (for example, April).dayofweek
+is a day of week (for example, Monday).timeofday
+is a time of day (for example, 10:42:23).field_mask
+is a set of symbolic field paths (for example, f.b.d).postal_address
+is a postal address (for example, 1600 Amphitheatre Parkway Mountain View,
+CA 94043 USA).money
+is an amount of money with its currency type (for example, 42 USD).latlng
+is a latitude/longitude pair (for example, 37.386051 latitude and
+-122.083855 longitude).color
+is a color in the RGBA color space.Note: While the “Well-Known Types” (such as Duration and Timestamp) are
+included with the Protocol Buffers compiler, the “Common Types” (such as Date
+and Money) are not. To use the Common Types, you may need to add a dependency
+on the googleapis repository.
When defining a proto schema, you should have a single message, enum, extension, +service, or group of cyclic dependencies per file. This makes refactoring +easier. Moving files when they’re separated is much easier than extracting +messages from a file with other messages. Following this practice also helps to +keep the proto schema files smaller, which enhances maintainability.
If they will be widely used outside of your project, consider putting them in +their own file with no dependencies. Then it’s easy for anyone to use those +types without introducing the transitive dependencies in your other proto files.
For more on this topic, see +1-1-1 Rule.
Almost never change the default value of a proto field. This causes version skew +between clients and servers. A client reading an unset value will see a +different result than a server reading the same unset value when their builds +straddle the proto change. Proto3 removed the ability to +set default values.
Although it won’t cause crashes, you’ll lose data. For JSON, a mismatch in
+repeatedness will lose the whole message. For numeric proto3 fields and proto2
+packed fields, going from repeated to scalar will lose all data in that
+field. For non-numeric proto3 fields and un-annotated proto2 fields, going
+from repeated to scalar will result in the last deserialized value “winning.”
Going from scalar to repeated is OK in proto2 and in proto3 with
+[packed=false] because for binary serialization the scalar value becomes a
+one-element list.
Proto generated code is referred to in normal code. Ensure that options in
+.proto file do not result in generation of code which violate the style guide.
+For example:
java_outer_classname should follow
+https://google.github.io/styleguide/javaguide.html#s5.2.2-class-names
java_package and java_alt_package should follow
+https://google.github.io/styleguide/javaguide.html#s5.2.1-package-names
package, although used for Java when java_package is not present, always
+directly corresponds to C++ namespace and thus should follow
+https://google.github.io/styleguide/cppguide.html#Namespace_Names.
+If these style guides conflict, use java_package for Java.
ruby_package should be in the form Foo::Bar::Baz rather than
+Foo.Bar.Baz.
Text-based serialization formats like text format and +JSON represent fields and enum values as strings. As a result, deserialization +of protocol buffers in these formats using old code will fail when a field or +enum value is renamed, or when a new field or enum value or extension is added. +Use binary serialization when possible for data interchange, and use text format +for human editing and debugging only.
If you use protos converted to JSON in your API or for storing data, you may not +be able to safely rename fields or enums at all.
The stability of proto serialization is not guaranteed across binaries or across +builds of the same binary. Do not rely on it when, for example, building cache +keys.
Generate Java proto sources into a separate package from your hand-written Java
+sources. The package, java_package and java_alt_api_package options
+control
+where the generated Java sources are emitted.
+Make sure hand-written Java source code does not also live in that same package.
+A common practice is to generate your protos into a proto subpackage in your
+project that only contains those protos (that is, no hand-written source
+code).
Setting the java_package can introduce fully-qualified name collisions in
+generated code that did not exist in the .proto semantics. For example, these
+two files may create collisions in the generated code despite the
+fully-qualified names not colliding in the original schema:
package x;
+option java_package = "com.example.proto";
+message Abc {}
+package y;
+option java_package = "com.example.proto";
+message Abc {}
+To avoid these problems, you should never set the same java_package in two
+files that have different .proto packages set.
The best practice is to establish a local naming pattern where the package name
+is derived from the .proto package. For example, a best practice file with
+package y might consistently set option java_package = "com.example.proto.y".
This guidance also applies to any other language-specific options where package +overrides are possible.
If the name of a message, field, enum, or enum value is a keyword in the +language that reads from/writes to that field, then protobuf may change the +field name, and may have different ways to access them than normal fields. For +example, see +this warning about Python.
You should also avoid using keywords in your file paths, as this can also cause +problems.
Reusing the same messages for APIs and long-term storage may seem convenient, +reducing boilerplate and overhead of conversion between messages.
However, the needs of long-term storage and live RPC services tend to later +diverge. Using separate types even if they are largely duplicative initially +gives freedom to change your storage format without impacting your external +clients. Layer your code so that modules deal either with client protos, storage +protos, or translation.
There is a cost in maintaining the translation layer, but it quickly pays off +once you have clients and have to do your first storage changes.
If you are using boolean for a field, make sure that the field is indeed +describing just two possible states (for all time, not just now and the near +future). The future flexibility of using an enum is often worth it, even if it +only has two values when it is first introduced.
message Photo {
+ // Bad: True if it's a GIF.
+ optional bool gif;
+
+ // Good: File format of the referenced photo (for example, GIF, WebP, PNG).
+ optional PhotoType type;
+}
+Every proto schema definition file should set option java_outer_classname to
+the .proto file name converted to TitleCase with the ‘.’ removed. For example,
+the file student_record_request.proto should set:
option java_outer_classname = "StudentRecordRequestProto";
+The default behavior of Edition 2024 files has been aligned with this +recommendation, so no option should be set when using Edition 2024 or later.
Best practices content for defining and using protos exists in the following +topics:
Do not +cargo cult +settings in proto files. If you are creating a new proto file based on existing +schema definitions, don’t apply option settings except for those that you +understand the need for.
Avoid applying editions features
+except when they’re actually necessary. Features in .proto files signal the
+use of either experimental future behaviors or deprecated past behaviors. Best
+practices for the latest edition will always be the default. New proto schema
+definition content should remain feature-free, except if you want to early-adopt
+a feature for future behavior that’s being rolled out.
Copying-forward feature settings without understanding why they are set can lead +to unexpected behaviors in your code.
| Proto Type | -Notes | -
|---|---|
| double | -- |
| float | -- |
| int32 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint32 - instead. | -
| int64 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint64 - instead. | -
| uint32 | -Uses variable-length encoding. | -
| uint64 | -Uses variable-length encoding. | -
| sint32 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int32s. | -
| sint64 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int64s. | -
| fixed32 | -Always four bytes. More efficient than uint32 if values are often - greater than 228. | -
| fixed64 | -Always eight bytes. More efficient than uint64 if values are often - greater than 256. | -
| sfixed32 | -Always four bytes. | -
| sfixed64 | -Always eight bytes. | -
| bool | -- |
| string | -A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot - be longer than 232. | -
| bytes | -May contain any arbitrary sequence of bytes no longer than 232. | -
| Proto Type | -C++ Type | -Java/Kotlin Type[1] | -Python Type[3] | -Go Type | -Ruby Type | -C# Type | -PHP Type | -Dart Type | -Rust Type | -
|---|---|---|---|---|---|---|---|---|---|
| double | -double | -double | -float | -float64 | -Float | -double | -float | -double | -f64 | -
| float | -float | -float | -float | -float32 | -Float | -float | -float | -double | -f32 | -
| int32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| int64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| uint32 | -uint32_t | -int[2] | -int/long[4] | -uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| uint64 | -uint64_t | -long[2] | -int/long[4] | -uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sint32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| sint64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| fixed32 | -uint32_t | -int[2] | -int/long[4] | -uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| fixed64 | -uint64_t | -long[2] | -int/long[4] | -uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sfixed32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| sfixed64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| bool | -bool | -boolean | -bool | -bool | -TrueClass/FalseClass | -bool | -boolean | -bool | -bool | -
| string | -string | -String | -str/unicode[5] | -string | -String (UTF-8) | -string | -string | -String | -ProtoString | -
| bytes | -string | -ByteString | -str (Python 2), bytes (Python 3) | -[]byte | -String (ASCII-8BIT) | -ByteString | -string | -List |
- ProtoBytes | -
| Protobuf type | -JSON | -JSON example | -Notes | -||||||
|---|---|---|---|---|---|---|---|---|---|
| message | -object | -{"fooBar": v, "g": null, ...} |
- Generates JSON objects.
- - Keys are serialized as lowerCamelCase of field name. See - Field Names for more special cases regarding mapping of field names - to object keys. - - Well-known types have special representations, as described in the Well-known types table. -
- |
- ||||||
| enum | -string | -"FOO_BAR" |
- The name of the enum value as specified in proto is used. Parsers - accept both enum names and integer values. - | -||||||
| map<K,V> | -object | -{"k": v, ...} |
- All keys are converted to strings (object keys in JSON can only be strings). | -||||||
| repeated V | -array | -[v, ...] |
- - | ||||||
| bool | -true, false | -true, false |
- - | ||||||
| string | -string | -"Hello World!" |
- - | ||||||
| bytes | -base64 string | -"YWJjMTIzIT8kKiYoKSctPUB+" |
- JSON value will be the data encoded as a string using standard base64 - encoding with paddings. Either standard or URL-safe base64 encoding - with/without paddings are accepted. - | -||||||
| int32, fixed32, uint32 | -number | -1, -10, 0 |
- JSON value will be a number. Either numbers or strings are
- accepted. Empty strings are invalid. Exponent notation (such as 1e2) is
- accepted in both quoted and unquoted forms.
- |
- ||||||
| int64, fixed64, uint64 | -string | -"1", "-10" |
- JSON value will be a decimal string. Either numbers or strings are
- accepted. Empty strings are invalid. Exponent notation (such as 1e2) is
- accepted in both quoted and unquoted forms. See Strings for int64s
- for the explanation why strings are used for int64s.
- |
- ||||||
| float, double | -number | -1.1, -10.0, 0, "NaN", "Infinity" |
- JSON value will be a number or one of the special string values "NaN", - "Infinity", and "-Infinity". Either numbers or strings are accepted. - Empty strings are invalid. Exponent notation is also accepted. - | -||||||
| Message type | -JSON | -JSON example | -Notes | -
|---|---|---|---|
| Any | -object |
- {"@type": "url", "f": v, ... } |
- See Any | -
| Timestamp | -string | -"1972-01-01T10:00:20.021Z" |
- Uses RFC 3339 (see clarification). Generated output will always be Z-normalized - with 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are - also accepted. - | -
| Duration | -string | -"1.000340012s", "1s" |
- Generated output always contains 0, 3, 6, or 9 fractional digits, - depending on required precision, followed by the suffix "s". Accepted - are any fractional digits (also none) as long as they fit into - nanoseconds precision and the suffix "s" is required. This is not RFC 3339 - 'duration' format (see Durations for clarification). - | -
| Struct | -object |
- { ... } |
- Any JSON object. See struct.proto. |
-
| Wrapper types | -various types | -2, "2", "foo", true, "true", null, 0, ... |
- Wrappers use the same representation in JSON as the wrapped primitive
- type, except that null is allowed and preserved during data
- conversion and transfer.
- |
-
| FieldMask | -string | -"f.fooBar,h" |
- See field_mask.proto. |
-
| ListValue | -array | -[foo, bar, ...] |
- - |
| Value | -value | -- | Any JSON value. Check - google.protobuf.Value - for details. - | -
| NullValue | -null | -- | JSON null. Special case of the null parsing behavior. | -
| Empty | -object | -{} (not special cased) |
- An empty JSON object | -
| Proto Type | -Notes | -
|---|---|
| double | -- |
| float | -- |
| int32 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint32 - instead. | -
| int64 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint64 - instead. | -
| uint32 | -Uses variable-length encoding. | -
| uint64 | -Uses variable-length encoding. | -
| sint32 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int32s. | -
| sint64 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int64s. | -
| fixed32 | -Always four bytes. More efficient than uint32 if values are often - greater than 228. | -
| fixed64 | -Always eight bytes. More efficient than uint64 if values are often - greater than 256. | -
| sfixed32 | -Always four bytes. | -
| sfixed64 | -Always eight bytes. | -
| bool | -- |
| string | -A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot - be longer than 232. | -
| bytes | -May contain any arbitrary sequence of bytes no longer than 232. | -
| Proto Type | -C++ Type | -Java/Kotlin Type[1] | -Python Type[3] | -Go Type | -Ruby Type | -C# Type | -PHP Type | -Dart Type | -Rust Type | -
|---|---|---|---|---|---|---|---|---|---|
| double | -double | -double | -float | -*float64 | -Float | -double | -float | -double | -f64 | -
| float | -float | -float | -float | -*float32 | -Float | -float | -float | -double | -f32 | -
| int32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -*int32 | -i32 | -
| int64 | -int64_t | -long | -int/long[4] | -*int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| uint32 | -uint32_t | -int[2] | -int/long[4] | -*uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| uint64 | -uint64_t | -long[2] | -int/long[4] | -*uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sint32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -*int32 | -i32 | -
| sint64 | -int64_t | -long | -int/long[4] | -*int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| fixed32 | -uint32_t | -int[2] | -int/long[4] | -*uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| fixed64 | -uint64_t | -long[2] | -int/long[4] | -*uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sfixed32 | -int32_t | -int | -int | -*int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| sfixed64 | -int64_t | -long | -int/long[4] | -*int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| bool | -bool | -boolean | -bool | -*bool | -TrueClass/FalseClass | -bool | -boolean | -bool | -bool | -
| string | -string | -String | -unicode (Python 2), str (Python 3) | -*string | -String (UTF-8) | -string | -string | -String | -ProtoString | -
| bytes | -string | -ByteString | -bytes | -[]byte | -String (ASCII-8BIT) | -ByteString | -string | -List |
- ProtoBytes | -
| Proto Type | -Notes | -
|---|---|
| double | -- Uses IEEE 754 - double-precision format. - | -
| float | -- Uses IEEE 754 - single-precision format. - | -
| int32 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint32 - instead. | -
| int64 | -Uses variable-length encoding. Inefficient for encoding negative - numbers – if your field is likely to have negative values, use sint64 - instead. | -
| uint32 | -Uses variable-length encoding. | -
| uint64 | -Uses variable-length encoding. | -
| sint32 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int32s. | -
| sint64 | -Uses variable-length encoding. Signed int value. These more - efficiently encode negative numbers than regular int64s. | -
| fixed32 | -Always four bytes. More efficient than uint32 if values are often - greater than 228. | -
| fixed64 | -Always eight bytes. More efficient than uint64 if values are often - greater than 256. | -
| sfixed32 | -Always four bytes. | -
| sfixed64 | -Always eight bytes. | -
| bool | -- |
| string | -A string must always contain UTF-8 encoded or 7-bit ASCII text, and cannot - be longer than 232. | -
| bytes | -May contain any arbitrary sequence of bytes no longer than 232. | -
| Proto Type | -C++ Type | -Java/Kotlin Type[1] | -Python Type[3] | -Go Type | -Ruby Type | -C# Type | -PHP Type | -Dart Type | -Rust Type | -
|---|---|---|---|---|---|---|---|---|---|
| double | -double | -double | -float | -float64 | -Float | -double | -float | -double | -f64 | -
| float | -float | -float | -float | -float32 | -Float | -float | -float | -double | -f32 | -
| int32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| int64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| uint32 | -uint32_t | -int[2] | -int/long[4] | -uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| uint64 | -uint64_t | -long[2] | -int/long[4] | -uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sint32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| sint64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| fixed32 | -uint32_t | -int[2] | -int/long[4] | -uint32 | -Fixnum or Bignum (as required) | -uint | -integer | -int | -u32 | -
| fixed64 | -uint64_t | -long[2] | -int/long[4] | -uint64 | -Bignum | -ulong | -integer/string[6] | -Int64 | -u64 | -
| sfixed32 | -int32_t | -int | -int | -int32 | -Fixnum or Bignum (as required) | -int | -integer | -int | -i32 | -
| sfixed64 | -int64_t | -long | -int/long[4] | -int64 | -Bignum | -long | -integer/string[6] | -Int64 | -i64 | -
| bool | -bool | -boolean | -bool | -bool | -TrueClass/FalseClass | -bool | -boolean | -bool | -bool | -
| string | -std::string | -String | -str/unicode[5] | -string | -String (UTF-8) | -string | -string | -String | -ProtoString | -
| bytes | -std::string | -ByteString | -str (Python 2), bytes (Python 3) | -[]byte | -String (ASCII-8BIT) | -ByteString | -string | -List |
- ProtoBytes | -
Packages | |
|---|---|
Auxiliary classes used for I/O. | |
Utility classes. | |
Implementation of the Protocol Buffer compiler. | |
Files | |
|---|---|
This file defines an Arena allocator for better allocation performance. | |
This file contains classes which describe a type of protocol message. | |
Protocol buffer representations of descriptors. | |
Interface for manipulating databases of descriptors. | |
Defines an implementation of Message which can emulate types which are not known at compile-time. | |
This file defines the map container and its helpers to support protobuf maps. | |
Defines Message, the abstract interface implemented by non-lite protocol message objects. | |
Defines MessageLite, the abstract interface implemented by all (lite and non-lite) protocol message objects. | |
RepeatedField and RepeatedPtrField are used by generated protocol message classes to manipulate repeated fields. | |
DEPRECATED: This module declares the abstract interfaces underlying proto2 RPC services. | |
Utilities for printing and parsing protocol messages in a human-readable, text-based format. | |
Contains classes used to keep track of unrecognized fields seen while parsing a protocol message. | |
Auxiliary classes used for I/O.
The Protocol Buffer library uses the classes in this package to deal with I/O and encoding/decoding raw bytes. Most users will not need to deal with this package. However, users who want to adapt the system to work with their own I/O abstractions – e.g., to allow Protocol Buffers to be read from a different kind of input stream without the need for a temporary buffer – should take a closer look.
-Files | |
|---|---|
This file contains the CodedInputStream and CodedOutputStream classes, which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively, and allow you to read or write individual pieces of data in various formats. | |
Utility class for writing text to a ZeroCopyOutputStream. | |
Class for parsing tokenized text from a ZeroCopyInputStream. | |
This file contains the ZeroCopyInputStream and ZeroCopyOutputStream interfaces, which represent abstract I/O streams to and from which protocol buffers can be read and written. | |
This file contains common implementations of the interfaces defined in zero_copy_stream.h which are only included in the full (non-lite) protobuf library. | |
This file contains common implementations of the interfaces defined in zero_copy_stream.h which are included in the "lite" protobuf library. | |
Utility classes.
This package contains various utilities for message comparison, JSON conversion, well known types, etc.
-Files | |
|---|---|
Defines classes for field comparison. | |
Defines utilities for the FieldMask well known type. | |
Utility functions to convert between protobuf binary format and proto3 JSON format. | |
This file defines static methods and classes for comparing Protocol Messages. | |
Defines utilities for the Timestamp and Duration well known types. | |
Defines a TypeResolver for the Any message. | |
Defines utilities for the TypeResolver. | |
Implementation of the Protocol Buffer compiler.
This package contains code for parsing .proto files and generating code based on them. There are two reasons you might be interested in this package:
-Files | |
|---|---|
Defines the abstract interface implemented by each of the language-specific code generators. | |
Implements the Protocol Compiler front-end such that it may be reused by custom compilers written to support other languages. | |
This file is the public interface to the .proto file parser. | |
Implements parsing of .proto files to FileDescriptorProtos. | |
Front-end for protoc code generator plugins written in C++. | |
API for protoc plugins. | |
Generates C++ code for a given .proto file. | |
Generates C# code for a given .proto file. | |
Provides a mechanism for mapping a descriptor to the fully-qualified name of the corresponding C# class. | |
Generates Java code for a given .proto file. | |
Provides a mechanism for mapping a descriptor to the fully-qualified name of the corresponding Java class. | |
Generates JavaScript code for a given .proto file. | |
Generates ObjectiveC code for a given .proto file. | |
Helper functions for generating ObjectiveC code. | |
Generates Python code for a given .proto file. | |
Generates Ruby code for a given .proto file. | |
#include <google/protobuf/arena.h>
namespace google::protobuf
This file defines an Arena allocator for better allocation performance.
Classes in this file | |
|---|---|
ArenaOptions provides optional additional parameters to arena construction that control its block-allocation behavior. | |
Arena allocator. | |
Helper typetraits that indicates support for arenas in a type T at compile time. | |
#include <google/protobuf/arena.h>
namespace google::protobuf
ArenaOptions provides optional additional parameters to arena construction that control its block-allocation behavior.
Members | |
|---|---|
size_t | start_block_sizeThis defines the size of the first block requested from the system malloc. more... |
size_t | max_block_sizeThis defines the maximum block size requested from system malloc (unless an individual arena allocation request occurs with a size larger than this maximum). more... |
char * | initial_blockAn initial block of memory for the arena to use, or NULL for none. more... |
size_t | initial_block_sizeThe size of the initial block, if provided. |
void *(* | block_allocA function pointer to an alloc method that returns memory blocks of size requested. more... |
void(* | block_deallocA function pointer to a dealloc method that takes ownership of the blocks from the arena. more... |
| ArenaOptions() |
size_t ArenaOptions::start_block_sizeThis defines the size of the first block requested from the system malloc.
Subsequent block sizes will increase in a geometric series up to a maximum.
-size_t ArenaOptions::max_block_sizeThis defines the maximum block size requested from system malloc (unless an individual arena allocation request occurs with a size larger than this maximum).
Requested block sizes increase up to this value, then remain here.
-char * ArenaOptions::initial_blockAn initial block of memory for the arena to use, or NULL for none.
If provided, the block must live at least as long as the arena itself. The creator of the Arena retains ownership of the block after the Arena is destroyed.
-void *(* ArenaOptions::block_allocA function pointer to an alloc method that returns memory blocks of size requested.
By default, it contains a ptr to the malloc function.
- -NOTE: block_alloc and dealloc functions are expected to behave like malloc and free, including Asan poisoning.
-void(* ArenaOptions::block_deallocA function pointer to a dealloc method that takes ownership of the blocks from the arena.
By default, it contains a ptr to a wrapper function that calls free.
-#include <google/protobuf/arena.h>
namespace google::protobuf
Arena allocator.
Arena allocation replaces ordinary (heap-based) allocation with new/delete, and improves performance by aggregating allocations into larger blocks and freeing allocations all at once. Protocol messages are allocated on an arena by using Arena::CreateMessage<T>(Arena*), below, and are automatically freed when the arena is destroyed.
- -This is a thread-safe implementation: multiple threads may allocate from the arena concurrently. Destruction is not thread-safe and the destructing thread must synchronize with users of the arena first.
- -An arena provides two allocation interfaces: CreateMessage<T>, which works for arena-enabled proto2 message types as well as other types that satisfy the appropriate protocol (described below), and Create<T>, which works for any arbitrary type T. CreateMessage<T> is better when the type T supports it, because this interface (i) passes the arena pointer to the created object so that its sub-objects and internal allocations can use the arena too, and (ii) elides the object's destructor call when possible. Create<T> does not place any special requirements on the type T, and will invoke the object's destructor when the arena is destroyed.
- -The arena message allocation protocol, required by CreateMessage<T>(Arena* arena, Args&&... args), is as follows:
- -args (without arena), called when a T is allocated on the heap; and a constructor callable with Arena* arena, Args&&... args, called when a T is allocated on an arena. If the second constructor is called with a NULL arena pointer, it must be equivalent to invoking the first (args-only) constructor.This protocol is implemented by all arena-enabled proto2 message classes as well as protobuf container types like RepeatedPtrField and Map. The protocol is internal to protobuf and is not guaranteed to be stable. Non-proto types should not rely on this protocol.
- -Members | |
|---|---|
const size_t | kBlockOverhead = =
- internal::ThreadSafeArena::kBlockHeaderSize +
- internal::ThreadSafeArena::kSerialArenaSizeBlock overhead. more... |
| Arena()Default constructor with sensible default options, tuned for average use-cases. |
| Arena(char * initial_block, size_t initial_block_size)Construct an arena with default options, except for the supplied initial block. more... |
explicit | Arena(const ArenaOptions & options) |
| ~Arena() |
void | Init(const ArenaOptions & ) |
uint64 | SpaceAllocated() constThe following are routines are for monitoring. more... |
uint64 | SpaceUsed() constReturns the total space used by the arena. more... |
uint64 | Reset()Frees all storage allocated by this arena after calling destructors registered with OwnDestructor() and freeing objects registered with Own(). more... |
template void | Own(T * object)Adds |object| to a list of heap-allocated objects to be freed with |delete| when the arena is destroyed or reset. |
template void | OwnDestructor(T * object)Adds |object| to a list of objects whose destructors will be manually called when the arena is destroyed or reset. more... |
void | OwnCustomDestructor(void * object, void(*)(void *) destruct)Adds a custom member function on an object to the list of destructors that will be manually called when the arena is destroyed or reset. more... |
template static T * | CreateMessage(Arena * arena, Args &&... args)API to create proto2 message objects on the arena. more... |
template static PROTOBUF_NDEBUG_INLINE T * | Create(Arena * arena, Args &&... args)API to create any objects on the arena. more... |
template static PROTOBUF_NDEBUG_INLINE T * | CreateArray(Arena * arena, size_t num_elements)Create an array of object type T on the arena without invoking the constructor of T. more... |
template static Arena * | GetArena(const T * value)Retrieves the arena associated with |value| if |value| is an arena-capable message, or NULL otherwise. more... |
const size_t Arena::kBlockOverhead = =
- internal::ThreadSafeArena::kBlockHeaderSize +
- internal::ThreadSafeArena::kSerialArenaSizeBlock overhead.
Use this as a guide for how much to over-allocate the initial block if you want an allocation of size N to fit inside it.
-WARNING: if you allocate multiple objects, it is difficult to guarantee that a series of allocations will fit in the initial block, especially if Arena changes its alignment guarantees in the future!
- Arena::Arena(
char * initial_block,
size_t initial_block_size)Construct an arena with default options, except for the supplied initial block.
It is more efficient to use this constructor instead of passing ArenaOptions if the only configuration needed by the caller is supplying an initial block.
-explicit Arena::Arena(
const ArenaOptions & options)Arena constructor taking custom options.
See ArenaOptions above for descriptions of the options available.
-uint64 Arena::SpaceAllocated() constThe following are routines are for monitoring.
They will approximate the total sum allocated and used memory, but the exact value is an implementation deal. For instance allocated space depends on growth policies. Do not use these in unit tests. Returns the total space allocated by the arena, which is the sum of the sizes of the underlying blocks.
-uint64 Arena::SpaceUsed() constReturns the total space used by the arena.
Similar to SpaceAllocated but does not include free space and block overhead. The total space returned may not include space used by other threads executing concurrently with the call to this method.
-uint64 Arena::Reset()Frees all storage allocated by this arena after calling destructors registered with OwnDestructor() and freeing objects registered with Own().
Any objects allocated on this arena are unusable after this call. It also returns the total space used by the arena which is the sums of the sizes of the allocated blocks. This method is not thread-safe.
-template void Arena::OwnDestructor(
T * object)Adds |object| to a list of objects whose destructors will be manually called when the arena is destroyed or reset.
This differs from Own() in that it does not free the underlying memory with |delete|; hence, it is normally only used for objects that are placement-newed into arena-allocated memory.
-void Arena::OwnCustomDestructor(
void * object,
void(*)(void *) destruct)Adds a custom member function on an object to the list of destructors that will be manually called when the arena is destroyed or reset.
This differs from OwnDestructor() in that any member function may be specified, not only the class destructor.
-template static T * Arena::CreateMessage(
Arena * arena,
Args &&... args)API to create proto2 message objects on the arena.
If the arena passed in is NULL, then a heap allocated object is returned. Type T must be a message defined in a .proto file with cc_enable_arenas set to true, otherwise a compilation error will occur.
-RepeatedField and RepeatedPtrField may also be instantiated directly on an arena with this method.
-This function also accepts any type T that satisfies the arena message allocation protocol, documented above.
-template static PROTOBUF_NDEBUG_INLINE T *
Arena::Create(
Arena * arena,
Args &&... args)API to create any objects on the arena.
Note that only the object will be created on the arena; the underlying ptrs (in case of a proto2 message) will be still heap allocated. Proto messages should usually be allocated with CreateMessage<T>() instead.
-Note that even if T satisfies the arena message construction protocol (InternalArenaConstructable_ trait and optional DestructorSkippable_ trait), as described above, this function does not follow the protocol; instead, it treats T as a black-box type, just as if it did not have these traits. Specifically, T's constructor arguments will always be only those passed to Create<T>() – no additional arena pointer is implicitly added. Furthermore, the destructor will always be called at arena destruction time (unless the destructor is trivial). Hence, from T's point of view, it is as if the object were allocated on the heap (except that the underlying memory is obtained from the arena).
-template static PROTOBUF_NDEBUG_INLINE T *
Arena::CreateArray(
Arena * arena,
size_t num_elements)Create an array of object type T on the arena without invoking the constructor of T.
If arena is null, then the return value should be freed with delete[] x; (or ::operator delete[](x);). To ensure safe uses, this function checks at compile time (when compiled as C++11) that T is trivially default-constructible and trivially destructible.
template static Arena * Arena::GetArena(
const T * value)Retrieves the arena associated with |value| if |value| is an arena-capable message, or NULL otherwise.
If possible, the call resolves at compile time. Note that we can often devirtualize calls to value->GetArena() so usually calling this method is unnecessary.
#include <google/protobuf/arena.h>
namespace google::protobuf
template <typename >
Members | |
|---|---|
static Arena * | GetOwningArena(const T * p)Provides access to protected GetOwningArena to generated messages. |
static Arena * | GetArenaForAllocation(const T * p)Provides access to protected GetArenaForAllocation to generated messages. |
#include <google/protobuf/arena.h>
namespace google::protobuf
template <typename >
Helper typetraits that indicates support for arenas in a type T at compile time.
This is public only to allow construction of higher-level templated utilities.
-is_arena_constructable<T>::value is true if the message type T has arena support enabled, and false otherwise.
-is_destructor_skippable<T>::value is true if the message type T has told the arena that it is safe to skip the destructor, and false otherwise.
-This is inside Arena because only Arena has the friend relationships necessary to see the underlying generated code traits.
-Members |
|---|
#include <google/protobuf/arena.h>
namespace google::protobuf
template <typename >
Members |
|---|
#include <google/protobuf/stubs/common.h>
namespace google::protobuf
Contains basic types and utilities used by the rest of the library.
Classes in this file |
|---|
#include <google/protobuf/compiler/code_generator.h>
namespace google::protobuf::compiler
Defines the abstract interface implemented by each of the language-specific code generators.
Classes in this file | |
|---|---|
The abstract interface to a class which generates code implementing a particular proto file in a particular language. | |
CodeGenerators generate one or more files in a given directory. | |
File MembersThese definitions are not part of any class. | |
|---|---|
typedef | GeneratorContext OutputDirectoryThe type GeneratorContext was once called OutputDirectory. more... |
void | ParseGeneratorParameter(const std::string & , std::vector< std::pair< std::string, std::string > > * )Several code generators treat the parameter argument as holding a list of options separated by commas. more... |
std::string | StripProto(const std::string & filename)Strips ".proto" or ".protodevel" from the end of a filename. |
typedef compiler::OutputDirectoryThe type GeneratorContext was once called OutputDirectory.
This typedef provides backward compatibility.
-void compiler::ParseGeneratorParameter(
const std::string & ,
std::vector< std::pair< std::string, std::string > > * )Several code generators treat the parameter argument as holding a list of options separated by commas.
This helper function parses a set of comma-delimited name/value pairs: e.g., "foo=bar,baz,qux=corge" parses to the pairs:
- -("foo", "bar"), ("baz", ""), ("qux", "corge")
-
-#include <google/protobuf/compiler/code_generator.h>
namespace google::protobuf::compiler
The abstract interface to a class which generates code implementing a particular proto file in a particular language.
A number of these may be registered with CommandLineInterface to support various languages.
-Known subclasses:
Members | |
|---|---|
enum | FeatureSync with plugin.proto. more... |
| CodeGenerator() |
virtual | ~CodeGenerator() |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) const = 0Generates code for the given proto file, generating one or more files in the given output directory. more... |
virtual bool | GenerateAll(const std::vector< const FileDescriptor * > & files, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for all given proto files. more... |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual bool | HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library. more... |
enum CodeGenerator::Feature {
FEATURE_PROTO3_OPTIONAL = = 1
}Sync with plugin.proto.
| FEATURE_PROTO3_OPTIONAL |
virtual bool CodeGenerator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) const = 0Generates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual bool CodeGenerator::GenerateAll(
const std::vector< const FileDescriptor * > & files,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for all given proto files.
WARNING: The canonical code generator design produces one or two output files per input .proto file, and we do not wish to encourage alternate designs.
-A parameter is given as passed on the command line, as in |Generate()| above.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64_t CodeGenerator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-virtual bool CodeGenerator::HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library.
When protobufs does a api breaking change, the method can be removed.
-#include <google/protobuf/compiler/code_generator.h>
namespace google::protobuf::compiler
CodeGenerators generate one or more files in a given directory.
This abstract interface represents the directory to which the CodeGenerator is to write and other information about the context in which the Generator runs.
-Members | |
|---|---|
| GeneratorContext() |
virtual | ~GeneratorContext() |
virtual io::ZeroCopyOutputStream * | Open(const std::string & filename) = 0Opens the given file, truncating it if it exists, and returns a ZeroCopyOutputStream that writes to the file. more... |
virtual io::ZeroCopyOutputStream * | OpenForAppend(const std::string & filename)Similar to Open() but the output will be appended to the file if exists. |
virtual io::ZeroCopyOutputStream * | OpenForInsert(const std::string & filename, const std::string & insertion_point)Creates a ZeroCopyOutputStream which will insert code into the given file at the given insertion point. more... |
virtual io::ZeroCopyOutputStream * | OpenForInsertWithGeneratedCodeInfo(const std::string & filename, const std::string & insertion_point, const google::protobuf::GeneratedCodeInfo & info)Similar to OpenForInsert, but if info is non-empty, will open (or create) filename.pb.meta and insert info at the appropriate place with the necessary shifts. more... |
virtual void | ListParsedFiles(std::vector< const FileDescriptor * > * output)Returns a vector of FileDescriptors for all the files being compiled in this run. more... |
virtual void | GetCompilerVersion(Version * version) constRetrieves the version number of the protocol compiler associated with this GeneratorContext. |
virtual io::ZeroCopyOutputStream *
GeneratorContext::Open(
const std::string & filename) = 0Opens the given file, truncating it if it exists, and returns a ZeroCopyOutputStream that writes to the file.
The caller takes ownership of the returned object. This method never fails (a dummy stream will be returned instead).
-The filename given should be relative to the root of the source tree. E.g. the C++ generator, when generating code for "foo/bar.proto", will generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that "foo/" is included in these filenames. The filename is not allowed to contain "." or ".." components.
-virtual io::ZeroCopyOutputStream *
GeneratorContext::OpenForInsert(
const std::string & filename,
const std::string & insertion_point)Creates a ZeroCopyOutputStream which will insert code into the given file at the given insertion point.
See plugin.proto (plugin.pb.h) for more information on insertion points. The default implementation assert-fails – it exists only for backwards-compatibility.
-WARNING: This feature is currently EXPERIMENTAL and is subject to change.
-virtual io::ZeroCopyOutputStream *
GeneratorContext::OpenForInsertWithGeneratedCodeInfo(
const std::string & filename,
const std::string & insertion_point,
const google::protobuf::GeneratedCodeInfo & info)Similar to OpenForInsert, but if info is non-empty, will open (or create) filename.pb.meta and insert info at the appropriate place with the necessary shifts.
The default implementation ignores info.
WARNING: This feature will be REMOVED in the near future.
-virtual void GeneratorContext::ListParsedFiles(
std::vector< const FileDescriptor * > * output)Returns a vector of FileDescriptors for all the files being compiled in this run.
Useful for languages, such as Go, that treat files differently when compiled as a set rather than individually.
-#include <google/protobuf/compiler/command_line_interface.h>
namespace google::protobuf::compiler
Implements the Protocol Compiler front-end such that it may be reused by custom compilers written to support other languages.
Classes in this file | |
|---|---|
This class implements the command-line interface to the protocol compiler. | |
#include <google/protobuf/compiler/command_line_interface.h>
namespace google::protobuf::compiler
This class implements the command-line interface to the protocol compiler.
It is designed to make it very easy to create a custom protocol compiler supporting the languages of your choice. For example, if you wanted to create a custom protocol compiler binary which includes both the regular C++ support plus support for your own custom output "Foo", you would write a class "FooGenerator" which implements the CodeGenerator interface, then write a main() procedure like this:
- -int main(int argc, char* argv[]) {
- google::protobuf::compiler::CommandLineInterface cli;
-
- // Support generation of C++ source and headers.
- google::protobuf::compiler::cpp::CppGenerator cpp_generator;
- cli.RegisterGenerator("--cpp_out", &cpp_generator,
- "Generate C++ source and header.");
-
- // Support generation of Foo code.
- FooGenerator foo_generator;
- cli.RegisterGenerator("--foo_out", &foo_generator,
- "Generate Foo file.");
-
- return cli.Run(argc, argv);
-}
-
-The compiler is invoked with syntax like:
- -protoc --cpp_out=outdir --foo_out=outdir --proto_path=src src/foo.proto- -
The .proto file to compile can be specified on the command line using either its physical file path, or a virtual path relative to a directory specified in –proto_path. For example, for src/foo.proto, the following two protoc invocations work the same way:
- -1. protoc --proto_path=src src/foo.proto (physical file path) -2. protoc --proto_path=src foo.proto (virtual path relative to src)- -
If a file path can be interpreted both as a physical file path and as a relative virtual path, the physical file path takes precedence.
- -For a full description of the command-line syntax, invoke it with –help.
- -Members | |
|---|---|
const char *const | kPathSeparator |
| CommandLineInterface() |
| ~CommandLineInterface() |
void | RegisterGenerator(const std::string & flag_name, CodeGenerator * generator, const std::string & help_text)Register a code generator for a language. more... |
void | RegisterGenerator(const std::string & flag_name, const std::string & option_flag_name, CodeGenerator * generator, const std::string & help_text)Register a code generator for a language. more... |
void | AllowPlugins(const std::string & exe_name_prefix)Enables "plugins". more... |
int | Run(int argc, const char *const argv)Run the Protocol Compiler with the given command-line parameters. more... |
void | SetInputsAreProtoPathRelative(bool )DEPRECATED. more... |
void | SetVersionInfo(const std::string & text)Provides some text which will be printed when the –version flag is used. more... |
void CommandLineInterface::RegisterGenerator(
const std::string & flag_name,
CodeGenerator * generator,
const std::string & help_text)Register a code generator for a language.
Parameters:
-Some generators accept extra parameters. You can specify this parameter on the command-line by placing it before the output directory, separated by a colon:
-protoc --foo_out=enable_bar:outdir-
The text before the colon is passed to CodeGenerator::Generate() as the "parameter".
-void CommandLineInterface::RegisterGenerator(
const std::string & flag_name,
const std::string & option_flag_name,
CodeGenerator * generator,
const std::string & help_text)Register a code generator for a language.
Besides flag_name you can specify another option_flag_name that could be used to pass extra parameters to the registered code generator. Suppose you have registered a generator by calling:
-command_line_interface.RegisterGenerator("--foo_out", "--foo_opt", ...)
-Then you could invoke the compiler with a command like:
-protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz-
This will pass "enable_bar,enable_baz" as the parameter to the generator.
-void CommandLineInterface::AllowPlugins(
const std::string & exe_name_prefix)Enables "plugins".
In this mode, if a command-line flag ends with "_out" but does not match any registered generator, the compiler will attempt to find a "plugin" to implement the generator. Plugins are just executables. They should live somewhere in the PATH.
-The compiler determines the executable name to search for by concatenating exe_name_prefix with the unrecognized flag name, removing "_out". So, for example, if exe_name_prefix is "protoc-" and you pass the flag –foo_out, the compiler will try to run the program "protoc-gen-foo".
-The plugin program should implement the following usage:
-plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS-
–out indicates the output directory (as passed to the –foo_out parameter); if omitted, the current directory should be used. –parameter gives the generator parameter, if any was provided (see below). The PROTO_FILES list the .proto files which were given on the compiler command-line; these are the files for which the plugin is expected to generate output code. Finally, DESCRIPTORS is an encoded FileDescriptorSet (as defined in descriptor.proto). This is piped to the plugin's stdin. The set will include descriptors for all the files listed in PROTO_FILES as well as all files that they import. The plugin MUST NOT attempt to read the PROTO_FILES directly – it must use the FileDescriptorSet.
-The plugin should generate whatever files are necessary, as code generators normally do. It should write the names of all files it generates to stdout. The names should be relative to the output directory, NOT absolute names or relative to the current directory. If any errors occur, error messages should be written to stderr. If an error is fatal, the plugin should exit with a non-zero exit code.
-Plugins can have generator parameters similar to normal built-in generators. Extra generator parameters can be passed in via a matching "_opt" parameter. For example:
-protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz-
This will pass "enable_bar,enable_baz" as the parameter to the plugin.
-int CommandLineInterface::Run(
int argc,
const char *const argv)Run the Protocol Compiler with the given command-line parameters.
Returns the error code which should be returned by main().
-It may not be safe to call Run() in a multi-threaded environment because it calls strerror(). I'm not sure why you'd want to do this anyway.
-void CommandLineInterface::SetInputsAreProtoPathRelative(
bool )DEPRECATED.
Calling this method has no effect. Protocol compiler now always try to find the .proto file relative to the current directory first and if the file is not found, it will then treat the input path as a virtual path.
-void CommandLineInterface::SetVersionInfo(
const std::string & text)Provides some text which will be printed when the –version flag is used.
The version of libprotoc will also be printed on the next line after this text.
-#include <google/protobuf/compiler/cpp/cpp_generator.h>
namespace google::protobuf::compiler::cpp
Generates C++ code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates a C++ source file and header. | |
#include <google/protobuf/compiler/cpp/cpp_generator.h>
namespace google::protobuf::compiler::cpp
CodeGenerator implementation which generates a C++ source file and header.
If you create your own protocol compiler binary and you want it to support C++ output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
enum | Runtime |
| CppGenerator() |
| ~CppGenerator() |
void | set_opensource_runtime(bool opensource) |
void | set_runtime_include_base(const std::string & base)If set to a non-empty string, generated code will do: more... |
implements CodeGenerator | |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
enum CppGenerator::Runtime {
kGoogle3,
kOpensource,
kOpensourceGoogle3
}| kGoogle3 | Use the internal google3 runtime. |
| kOpensource | Use the open-source runtime. |
| kOpensourceGoogle3 | Use the open-source runtime with google3 #include paths. We make these absolute to avoid ambiguity, so the runtime will be #included like: - - |
void CppGenerator::set_runtime_include_base(
const std::string & base)If set to a non-empty string, generated code will do:
/google/protobuf/message.h"-
instead of:
- -This has no effect if opensource_runtime = false.
-virtual bool CppGenerator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64_t CppGenerator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/csharp/csharp_generator.h>
namespace google::protobuf::compiler::csharp
Generates C# code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates a C# source file and header. | |
#include <google/protobuf/compiler/csharp/csharp_generator.h>
namespace google::protobuf::compiler::csharp
CodeGenerator implementation which generates a C# source file and header.
If you create your own protocol compiler binary and you want it to support C# output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| Generator() |
| ~Generator() |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual bool Generator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64_t Generator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/csharp/csharp_names.h>
namespace google::protobuf::compiler::csharp
Provides a mechanism for mapping a descriptor to the fully-qualified name of the corresponding C# class.
Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
std::string | GetFileNamespace(const FileDescriptor * descriptor)Requires: more... |
std::string | GetClassName(const Descriptor * descriptor)Requires: more... |
std::string | GetReflectionClassName(const FileDescriptor * descriptor)Requires: more... |
std::string | GetOutputFile(const FileDescriptor * descriptor, const std::string file_extension, const bool generate_directories, const std::string base_namespace, std::string * error)Generates output file name for given file descriptor. more... |
std::string csharp::GetFileNamespace(
const FileDescriptor * descriptor)Requires:
descriptor != NULL-
Returns:
- -The namespace to use for given file descriptor.-
std::string csharp::GetClassName(
const Descriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -The fully-qualified C# class name.-
std::string csharp::GetReflectionClassName(
const FileDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -The fully-qualified name of the C# class that provides -access to the file descriptor. Proto compiler generates -such class for each .proto file processed.-
std::string csharp::GetOutputFile(
const FileDescriptor * descriptor,
const std::string file_extension,
const bool generate_directories,
const std::string base_namespace,
std::string * error)Generates output file name for given file descriptor.
If generate_directories is true, the output file will be put under directory corresponding to file's namespace. base_namespace can be used to strip some of the top level directories. E.g. for file with namespace "Bar.Foo" and base_namespace="Bar", the resulting file will be put under directory "Foo" (and not "Bar/Foo").
-Requires:
-descriptor != NULL -error != NULL- -
Returns:
- -The file name to use as output file for given file descriptor. In case -of failure, this function will return empty string and error parameter -will contain the error message.- -
#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
This file is the public interface to the .proto file parser.
Classes in this file | |
|---|---|
An implementation of DescriptorDatabase which loads files from a SourceTree and parses them. | |
Simple interface for parsing .proto files. | |
If the importer encounters problems while trying to import the proto files, it reports them to a MultiFileErrorCollector. | |
Abstract interface which represents a directory tree containing proto files. | |
An implementation of SourceTree which loads files from locations on disk. | |
#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
An implementation of DescriptorDatabase which loads files from a SourceTree and parses them.
Note: This class is not thread-safe since it maintains a table of source code locations for error reporting. However, when a DescriptorPool wraps a DescriptorDatabase, it uses mutex locking to make sure only one method of the database is called at a time, even if the DescriptorPool is used from multiple threads. Therefore, there is only a problem if you create multiple DescriptorPools wrapping the same SourceTreeDescriptorDatabase and use them from multiple threads.
- -Note: This class does not implement FindFileContainingSymbol() or FindFileContainingExtension(); these will always return false.
- -Members | |
|---|---|
| SourceTreeDescriptorDatabase(SourceTree * source_tree) |
| SourceTreeDescriptorDatabase(SourceTree * source_tree, DescriptorDatabase * fallback_database)If non-NULL, fallback_database will be checked if a file doesn't exist in the specified source_tree. |
| ~SourceTreeDescriptorDatabase() |
void | RecordErrorsTo(MultiFileErrorCollector * error_collector)Instructs the SourceTreeDescriptorDatabase to report any parse errors to the given MultiFileErrorCollector. more... |
DescriptorPool::ErrorCollector * | GetValidationErrorCollector()Gets a DescriptorPool::ErrorCollector which records errors to the MultiFileErrorCollector specified with RecordErrorsTo(). more... |
implements DescriptorDatabase | |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output)Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number. more... |
void SourceTreeDescriptorDatabase::RecordErrorsTo(
MultiFileErrorCollector * error_collector)Instructs the SourceTreeDescriptorDatabase to report any parse errors to the given MultiFileErrorCollector.
This should be called before parsing. error_collector must remain valid until either this method is called again or the SourceTreeDescriptorDatabase is destroyed.
-DescriptorPool::ErrorCollector *
SourceTreeDescriptorDatabase::GetValidationErrorCollector()Gets a DescriptorPool::ErrorCollector which records errors to the MultiFileErrorCollector specified with RecordErrorsTo().
This collector has the ability to determine exact line and column numbers of errors from the information given to it by the DescriptorPool.
-virtual bool SourceTreeDescriptorDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output)Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool SourceTreeDescriptorDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool SourceTreeDescriptorDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
Simple interface for parsing .proto files.
This wraps the process of opening the file, parsing it with a Parser, recursively parsing all its imports, and then cross-linking the results to produce a FileDescriptor.
-This is really just a thin wrapper around SourceTreeDescriptorDatabase. You may find that SourceTreeDescriptorDatabase is more flexible.
-Members | |
|---|---|
| Importer(SourceTree * source_tree, MultiFileErrorCollector * error_collector) |
| ~Importer() |
const FileDescriptor * | Import(const std::string & filename)Import the given file and build a FileDescriptor representing it. more... |
const DescriptorPool * | pool() constThe DescriptorPool in which all imported FileDescriptors and their contents are stored. |
void | AddUnusedImportTrackFile(const std::string & file_name, bool is_error = false) |
void | ClearUnusedImportTrackFiles() |
const FileDescriptor *
Importer::Import(
const std::string & filename)Import the given file and build a FileDescriptor representing it.
If the file is already in the DescriptorPool, the existing FileDescriptor will be returned. The FileDescriptor is property of the DescriptorPool, and will remain valid until it is destroyed. If any errors occur, they will be reported using the error collector and Import() will return NULL.
-A particular Importer object will only report errors for a particular file once. All future attempts to import the same file will return NULL without reporting any errors. The idea is that you might want to import a lot of files without seeing the same errors over and over again. If you want to see errors for the same files repeatedly, you can use a separate Importer object to import each one (but use the same DescriptorPool so that they can be cross-linked).
-#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
If the importer encounters problems while trying to import the proto files, it reports them to a MultiFileErrorCollector.
Members | |
|---|---|
| MultiFileErrorCollector() |
virtual | ~MultiFileErrorCollector() |
virtual void | AddError(const std::string & filename, int line, int column, const std::string & message) = 0Line and column numbers are zero-based. more... |
virtual void | AddWarning(const std::string & , int , int , const std::string & ) |
virtual void MultiFileErrorCollector::AddError(
const std::string & filename,
int line,
int column,
const std::string & message) = 0Line and column numbers are zero-based.
A line number of -1 indicates an error with the entire file (e.g. "not found").
-#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
Abstract interface which represents a directory tree containing proto files.
Used by the default implementation of Importer to resolve import statements Most users will probably want to use the DiskSourceTree implementation, below.
-Known subclasses:
Members | |
|---|---|
| SourceTree() |
virtual | ~SourceTree() |
virtual io::ZeroCopyInputStream * | Open(const std::string & filename) = 0Open the given file and return a stream that reads it, or NULL if not found. more... |
virtual std::string | GetLastErrorMessage() |
virtual io::ZeroCopyInputStream *
SourceTree::Open(
const std::string & filename) = 0Open the given file and return a stream that reads it, or NULL if not found.
The caller takes ownership of the returned object. The filename must be a path relative to the root of the source tree and must not contain "." or ".." components.
-virtual std::string SourceTree::GetLastErrorMessage()If Open() returns NULL, calling this method immediately will return an description of the error.
Subclasses should implement this method and return a meaningful value for better error reporting.
-#include <google/protobuf/compiler/importer.h>
namespace google::protobuf::compiler
An implementation of SourceTree which loads files from locations on disk.
Multiple mappings can be set up to map locations in the DiskSourceTree to locations in the physical filesystem.
-Members | |
|---|---|
enum | DiskFileToVirtualFileResultReturn type for DiskFileToVirtualFile(). more... |
| DiskSourceTree() |
| ~DiskSourceTree() |
void | MapPath(const std::string & virtual_path, const std::string & disk_path) |
DiskFileToVirtualFileResult | DiskFileToVirtualFile(const std::string & disk_file, std::string * virtual_file, std::string * shadowing_disk_file)Given a path to a file on disk, find a virtual path mapping to that file. more... |
bool | VirtualFileToDiskFile(const std::string & virtual_file, std::string * disk_file)Given a virtual path, find the path to the file on disk. more... |
implements SourceTree | |
virtual io::ZeroCopyInputStream * | Open(const std::string & filename)Open the given file and return a stream that reads it, or NULL if not found. more... |
virtual std::string | GetLastErrorMessage() |
enum DiskSourceTree::DiskFileToVirtualFileResult {
SUCCESS,
SHADOWED,
CANNOT_OPEN,
NO_MAPPING
}Return type for DiskFileToVirtualFile().
| SUCCESS | |
| SHADOWED | |
| CANNOT_OPEN | |
| NO_MAPPING |
void DiskSourceTree::MapPath(
const std::string & virtual_path,
const std::string & disk_path)Map a path on disk to a location in the SourceTree.
The path may be either a file or a directory. If it is a directory, the entire tree under it will be mapped to the given virtual location. To map a directory to the root of the source tree, pass an empty string for virtual_path.
-If multiple mapped paths apply when opening a file, they will be searched in order. For example, if you do:
-MapPath("bar", "foo/bar");
-MapPath("", "baz");
-and then you do:
-Open("bar/qux");
-the DiskSourceTree will first try to open foo/bar/qux, then baz/bar/qux, returning the first one that opens successfully.
-disk_path may be an absolute path or relative to the current directory, just like a path you'd pass to open().
-DiskFileToVirtualFileResult
DiskSourceTree::DiskFileToVirtualFile(
const std::string & disk_file,
std::string * virtual_file,
std::string * shadowing_disk_file)Given a path to a file on disk, find a virtual path mapping to that file.
The first mapping created with MapPath() whose disk_path contains the filename is used. However, that virtual path may not actually be usable to open the given file. Possible return values are:
-bool DiskSourceTree::VirtualFileToDiskFile(
const std::string & virtual_file,
std::string * disk_file)Given a virtual path, find the path to the file on disk.
Return true and update disk_file with the on-disk path if the file exists. Return false and leave disk_file untouched if the file doesn't exist.
-virtual io::ZeroCopyInputStream *
DiskSourceTree::Open(
const std::string & filename)Open the given file and return a stream that reads it, or NULL if not found.
The caller takes ownership of the returned object. The filename must be a path relative to the root of the source tree and must not contain "." or ".." components.
-virtual std::string DiskSourceTree::GetLastErrorMessage()If Open() returns NULL, calling this method immediately will return an description of the error.
Subclasses should implement this method and return a meaningful value for better error reporting.
-#include <google/protobuf/compiler/java/java_generator.h>
namespace google::protobuf::compiler::java
Generates Java code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates Java code. | |
#include <google/protobuf/compiler/java/java_generator.h>
namespace google::protobuf::compiler::java
CodeGenerator implementation which generates Java code.
If you create your own protocol compiler binary and you want it to support Java output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| JavaGenerator() |
| ~JavaGenerator() |
implements CodeGenerator | |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual bool JavaGenerator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64_t JavaGenerator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/java/java_names.h>
namespace google::protobuf::compiler::java
Provides a mechanism for mapping a descriptor to the fully-qualified name of the corresponding Java class.
Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
std::string | ClassName(const Descriptor * descriptor)Requires: more... |
std::string | ClassName(const EnumDescriptor * descriptor)Requires: more... |
std::string | ClassName(const FileDescriptor * descriptor)Requires: more... |
std::string | ClassName(const ServiceDescriptor * descriptor)Requires: more... |
std::string | FileJavaPackage(const FileDescriptor * descriptor)Requires: more... |
std::string | CapitalizedFieldName(const FieldDescriptor * descriptor)Requires: more... |
std::string java::ClassName(
const Descriptor * descriptor)Requires:
descriptor != NULL-
Returns:
- -The fully-qualified Java class name.-
std::string java::ClassName(
const EnumDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -The fully-qualified Java class name.-
std::string java::ClassName(
const FileDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -The fully-qualified Java class name.-
std::string java::ClassName(
const ServiceDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -The fully-qualified Java class name.-
std::string java::FileJavaPackage(
const FileDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -Java package name.-
std::string java::CapitalizedFieldName(
const FieldDescriptor * descriptor)Requires:
descriptor != NULL- -
Returns:
- -Capitalized camel case name field name.- -
#include <google/protobuf/compiler/javanano/javanano_generator.h>
namespace google::protobuf::compiler::javanano
Generates Java nano code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates Java nano code. | |
#include <google/protobuf/compiler/javanano/javanano_generator.h>
namespace google::protobuf::compiler::javanano
CodeGenerator implementation which generates Java nano code.
If you create your own protocol compiler binary and you want it to support Java output for the nano runtime, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| JavaNanoGenerator() |
| ~JavaNanoGenerator() |
implements CodeGenerator | |
virtual bool | Generate(const FileDescriptor * file, const string & parameter, GeneratorContext * generator_context, string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual bool JavaNanoGenerator::Generate(
const FileDescriptor * file,
const string & parameter,
GeneratorContext * generator_context,
string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-#include <google/protobuf/compiler/js/js_generator.h>
namespace google::protobuf::compiler::js
Generates JavaScript code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates a JavaScript source file and header. | |
#include <google/protobuf/compiler/js/js_generator.h>
namespace google::protobuf::compiler::js
Members | |
|---|---|
enum | ImportStyleWhat style of imports should be used. more... |
enum | OutputMode |
std::string | output_dirOutput path. |
std::string | namespace_prefixNamespace prefix. |
bool | binaryEnable binary-format support? |
enum google::protobuf::compiler::js::GeneratorOptions::ImportStyle | import_style |
bool | add_require_for_enumsAdd a goog.requires() call for each enum type used. more... |
bool | testonlySet this as a test-only module via goog.setTestOnly();. |
std::string | libraryCreate a library with name <name>_lib.js rather than a separate .js file per type? |
bool | error_on_name_conflictError if there are two types that would generate the same output file? |
std::string | extensionThe extension to use for output file names. |
bool | one_output_file_per_input_fileCreate a separate output file for each input file? |
bool | annotate_codeIf true, we should append annotations as comments on the last line for generated .js file. more... |
| GeneratorOptions() |
bool | ParseFromOptions(const std::vector< std::pair< std::string, std::string > > & options, std::string * error) |
std::string | GetFileNameExtension() constReturns the file name extension to use for generated code. |
OutputMode | output_mode() constIndicates how to output the generated code based on the provided options. |
enum GeneratorOptions::ImportStyle {
kImportClosure,
kImportCommonJs,
kImportCommonJsStrict,
kImportBrowser,
kImportEs6
}What style of imports should be used.
| kImportClosure | goog.require() |
| kImportCommonJs | require() |
| kImportCommonJsStrict | require() with no global export |
| kImportBrowser | no import statements |
| kImportEs6 | import { member } from '' |
enum GeneratorOptions::OutputMode {
kOneOutputFilePerInputFile,
kOneOutputFilePerSCC,
kEverythingInOneFile
}| kOneOutputFilePerInputFile | Create an output file for each input .proto file. |
| kOneOutputFilePerSCC | Create an output file for each type. |
| kEverythingInOneFile | Put everything in a single file named by the library option. |
bool GeneratorOptions::add_require_for_enumsAdd a goog.requires() call for each enum type used.
If not set, a forward declaration with goog.forwardDeclare is produced instead.
bool GeneratorOptions::annotate_codeIf true, we should append annotations as comments on the last line for generated .js file.
Annotations used by tools like to provide cross-references between .js and .proto files. Annotations are encoded as base64 proto of GeneratedCodeInfo message (see descriptor.proto).
-#include <google/protobuf/compiler/js/js_generator.h>
namespace google::protobuf::compiler::js
CodeGenerator implementation which generates a JavaScript source file and header.
If you create your own protocol compiler binary and you want it to support JavaScript output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| Generator() |
virtual | ~Generator() |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual bool | HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library. more... |
virtual bool | GenerateAll(const std::vector< const FileDescriptor * > & files, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for all given proto files. more... |
virtual uint64 | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual bool Generator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual bool Generator::HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library.
When protobufs does a api breaking change, the method can be removed.
-virtual bool Generator::GenerateAll(
const std::vector< const FileDescriptor * > & files,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for all given proto files.
WARNING: The canonical code generator design produces one or two output files per input .proto file, and we do not wish to encourage alternate designs.
-A parameter is given as passed on the command line, as in |Generate()| above.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64 Generator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/objectivec/objectivec_generator.h>
namespace google::protobuf::compiler::objectivec
Generates ObjectiveC code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation which generates a ObjectiveC source file and header. | |
#include <google/protobuf/compiler/objectivec/objectivec_generator.h>
namespace google::protobuf::compiler::objectivec
CodeGenerator implementation which generates a ObjectiveC source file and header.
If you create your own protocol compiler binary and you want it to support ObjectiveC output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| ObjectiveCGenerator() |
| ~ObjectiveCGenerator() |
| ObjectiveCGenerator(const ObjectiveCGenerator & ) |
ObjectiveCGenerator & | operator=(const ObjectiveCGenerator & ) |
implements CodeGenerator | |
virtual bool | HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library. more... |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory. more... |
virtual bool | GenerateAll(const std::vector< const FileDescriptor * > & files, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constGenerates code for all given proto files. more... |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual bool ObjectiveCGenerator::HasGenerateAll() constThis is no longer used, but this class is part of the opensource protobuf library, so it has to remain to keep vtables the same for the current version of the library.
When protobufs does a api breaking change, the method can be removed.
-virtual bool ObjectiveCGenerator::Generate(
const FileDescriptor * file,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for the given proto file, generating one or more files in the given output directory.
A parameter to be passed to the generator can be specified on the command line. This is intended to be used to pass generator specific parameters. It is empty if no parameter was given. ParseGeneratorParameter (below), can be used to accept multiple parameters within the single parameter command line flag.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual bool ObjectiveCGenerator::GenerateAll(
const std::vector< const FileDescriptor * > & files,
const std::string & parameter,
GeneratorContext * generator_context,
std::string * error) constGenerates code for all given proto files.
WARNING: The canonical code generator design produces one or two output files per input .proto file, and we do not wish to encourage alternate designs.
-A parameter is given as passed on the command line, as in |Generate()| above.
-Returns true if successful. Otherwise, sets *error to a description of the problem (e.g. "invalid parameter") and returns false.
-virtual uint64_t ObjectiveCGenerator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
namespace google::protobuf::compiler::objectivec
Helper functions for generating ObjectiveC code.
Classes in this file | |
|---|---|
Generator options (see objectivec_generator.cc for a description of each): | |
Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform the input into the expected output. | |
Helper for parsing simple files. | |
Helper class for parsing framework import mappings and generating import statements. | |
File MembersThese definitions are not part of any class. | |
|---|---|
enum | ObjectiveCType |
enum | FlagType |
const char *const | ProtobufLibraryFrameworkNameThe name the commonly used by the library when built as a framework. more... |
std::string | EscapeTrigraphs(const std::string & to_escape)Escape C++ trigraphs by escaping question marks to "\?". |
void | TrimWhitespace(StringPiece * input)Remove white space from either end of a StringPiece. |
bool | IsRetainedName(const std::string & name)Returns true if the name requires a ns_returns_not_retained attribute applied to it. |
bool | IsInitName(const std::string & name)Returns true if the name starts with "init" and will need to have special handling under ARC. |
std::string | FileClassPrefix(const FileDescriptor * file)Gets the objc_class_prefix. |
std::string | FilePath(const FileDescriptor * file)Gets the path of the file we're going to generate (sans the .pb.h extension). more... |
std::string | FilePathBasename(const FileDescriptor * file)Just like FilePath(), but without the directory part. |
std::string | FileClassName(const FileDescriptor * file)Gets the name of the root class we'll generate in the file. more... |
std::string | ClassName(const Descriptor * descriptor)These return the fully-qualified class name corresponding to the given descriptor. |
std::string | ClassName(const Descriptor * descriptor, std::string * out_suffix_added) |
std::string | EnumName(const EnumDescriptor * descriptor) |
std::string | EnumValueName(const EnumValueDescriptor * descriptor)Returns the fully-qualified name of the enum value corresponding to the the descriptor. |
std::string | EnumValueShortName(const EnumValueDescriptor * descriptor)Returns the name of the enum value corresponding to the descriptor. |
std::string | UnCamelCaseEnumShortName(const std::string & name)Reverse what an enum does. |
std::string | ExtensionMethodName(const FieldDescriptor * descriptor)Returns the name to use for the extension (used as the method off the file's Root class). |
std::string | FieldName(const FieldDescriptor * field)Returns the transformed field name. |
std::string | FieldNameCapitalized(const FieldDescriptor * field) |
std::string | OneofEnumName(const OneofDescriptor * descriptor)Returns the transformed oneof name. |
std::string | OneofName(const OneofDescriptor * descriptor) |
std::string | OneofNameCapitalized(const OneofDescriptor * descriptor) |
std::string | ObjCClass(const std::string & class_name)Returns a symbol that can be used in C code to refer to an Objective C class without initializing the class. |
std::string | ObjCClassDeclaration(const std::string & class_name)Declares an Objective C class without initializing the class so that it can be refrerred to by ObjCClass. |
bool | HasPreservingUnknownEnumSemantics(const FileDescriptor * file) |
bool | IsMapEntryMessage(const Descriptor * descriptor) |
std::string | UnCamelCaseFieldName(const std::string & name, const FieldDescriptor * field)Reverse of the above. |
template std::string | GetOptionalDeprecatedAttribute(const TDescriptor * descriptor, const FileDescriptor * file = NULL, bool preSpace = true, bool postNewline = false) |
std::string | GetCapitalizedType(const FieldDescriptor * field) |
ObjectiveCType | GetObjectiveCType(FieldDescriptor::Type field_type) |
ObjectiveCType | GetObjectiveCType(const FieldDescriptor * field) |
bool | IsPrimitiveType(const FieldDescriptor * field) |
bool | IsReferenceType(const FieldDescriptor * field) |
std::string | GPBGenericValueFieldName(const FieldDescriptor * field) |
std::string | DefaultValue(const FieldDescriptor * field) |
bool | HasNonZeroDefaultValue(const FieldDescriptor * field) |
std::string | BuildFlagsString(const FlagType type, const std::vector< std::string > & strings) |
std::string | BuildCommentsString(const SourceLocation & location, bool prefer_single_line)Builds HeaderDoc/appledoc style comments out of the comments in the .proto file. |
std::string | ProtobufFrameworkImportSymbol(const std::string & framework_name)Returns the CPP symbol name to use as the gate for framework style imports for the given framework name to use. |
bool | IsProtobufLibraryBundledProtoFile(const FileDescriptor * file)Checks if the file is one of the proto's bundled with the library. |
bool | ValidateObjCClassPrefixes(const std::vector< const FileDescriptor * > & files, const Options & generation_options, std::string * out_error)Checks the prefix for the given files and outputs any warnings as needed. more... |
bool | ParseSimpleFile(const std::string & path, LineConsumer * line_consumer, std::string * out_error) |
enum objectivec::ObjectiveCType {
OBJECTIVECTYPE_INT32,
OBJECTIVECTYPE_UINT32,
OBJECTIVECTYPE_INT64,
OBJECTIVECTYPE_UINT64,
OBJECTIVECTYPE_FLOAT,
OBJECTIVECTYPE_DOUBLE,
OBJECTIVECTYPE_BOOLEAN,
OBJECTIVECTYPE_STRING,
OBJECTIVECTYPE_DATA,
OBJECTIVECTYPE_ENUM,
OBJECTIVECTYPE_MESSAGE
}| OBJECTIVECTYPE_INT32 | |
| OBJECTIVECTYPE_UINT32 | |
| OBJECTIVECTYPE_INT64 | |
| OBJECTIVECTYPE_UINT64 | |
| OBJECTIVECTYPE_FLOAT | |
| OBJECTIVECTYPE_DOUBLE | |
| OBJECTIVECTYPE_BOOLEAN | |
| OBJECTIVECTYPE_STRING | |
| OBJECTIVECTYPE_DATA | |
| OBJECTIVECTYPE_ENUM | |
| OBJECTIVECTYPE_MESSAGE |
enum objectivec::FlagType {
FLAGTYPE_DESCRIPTOR_INITIALIZATION,
FLAGTYPE_EXTENSION,
FLAGTYPE_FIELD
}| FLAGTYPE_DESCRIPTOR_INITIALIZATION | |
| FLAGTYPE_EXTENSION | |
| FLAGTYPE_FIELD |
const char *const objectivec::ProtobufLibraryFrameworkNameThe name the commonly used by the library when built as a framework.
This lines up to the name used in the CocoaPod.
- -std::string objectivec::FilePath(
const FileDescriptor * file)Gets the path of the file we're going to generate (sans the .pb.h extension).
The path will be dependent on the objectivec package declared in the proto package.
-std::string objectivec::FileClassName(
const FileDescriptor * file)Gets the name of the root class we'll generate in the file.
This class is not meant for external consumption, but instead contains helpers that the rest of the classes need
-bool objectivec::ValidateObjCClassPrefixes(
const std::vector< const FileDescriptor * > & files,
const Options & generation_options,
std::string * out_error)Checks the prefix for the given files and outputs any warnings as needed.
If there are flat out errors, then out_error is filled in with the first error and the result is false.
-#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
namespace google::protobuf::compiler::objectivec
Generator options (see objectivec_generator.cc for a description of each):
Members | |
|---|---|
std::string | expected_prefixes_path |
std::vector< std::string > | expected_prefixes_suppressions |
std::string | generate_for_named_framework |
std::string | named_framework_to_proto_path_mappings_path |
std::string | runtime_import_prefix |
| Options() |
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
namespace google::protobuf::compiler::objectivec
Generate decode data needed for ObjC's GPBDecodeTextFormatName() to transform the input into the expected output.
Members | |
|---|---|
| TextFormatDecodeData() |
| ~TextFormatDecodeData() |
| TextFormatDecodeData(const TextFormatDecodeData & ) |
TextFormatDecodeData & | operator=(const TextFormatDecodeData & ) |
void | AddString(int32 key, const std::string & input_for_decode, const std::string & desired_output) |
size_t | num_entries() const |
std::string | Data() const |
static std::string | DecodeDataForString(const std::string & input_for_decode, const std::string & desired_output) |
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
namespace google::protobuf::compiler::objectivec
Helper for parsing simple files.
Members | |
|---|---|
| LineConsumer() |
virtual | ~LineConsumer() |
virtual bool | ConsumeLine(const StringPiece & line, std::string * out_error) = 0 |
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
namespace google::protobuf::compiler::objectivec
Helper class for parsing framework import mappings and generating import statements.
Members | |
|---|---|
| ImportWriter(const std::string & generate_for_named_framework, const std::string & named_framework_to_proto_path_mappings_path, const std::string & runtime_import_prefix, bool include_wkt_imports) |
| ~ImportWriter() |
void | AddFile(const FileDescriptor * file, const std::string & header_extension) |
void | Print(io::Printer * printer) const |
static void | PrintRuntimeImports(io::Printer * printer, const std::vector< std::string > & header_to_import, const std::string & runtime_import_prefix, bool default_cpp_symbol = false) |
#include <google/protobuf/compiler/parser.h>
namespace google::protobuf::compiler
Implements parsing of .proto files to FileDescriptorProtos.
Classes in this file | |
|---|---|
Implements parsing of protocol definitions (such as .proto files). | |
A table mapping (descriptor, ErrorLocation) pairs – as reported by DescriptorPool when validating descriptors – to line and column numbers within the original source code. | |
#include <google/protobuf/compiler/parser.h>
namespace google::protobuf::compiler
Implements parsing of protocol definitions (such as .proto files).
Note that most users will be more interested in the Importer class. Parser is a lower-level class which simply converts a single .proto file to a FileDescriptorProto. It does not resolve import directives or perform many other kinds of validation needed to construct a complete FileDescriptor.
- -Members | |
|---|---|
| Parser() |
| ~Parser() |
bool | Parse(io::Tokenizer * input, FileDescriptorProto * file)Parse the entire input and construct a FileDescriptorProto representing it. more... |
void | RecordSourceLocationsTo(SourceLocationTable * location_table)DEPRECATED: New code should use the SourceCodeInfo embedded in the FileDescriptorProto. more... |
void | RecordErrorsTo(io::ErrorCollector * error_collector)Requests that errors be recorded to the given ErrorCollector while parsing. more... |
const std::string & | GetSyntaxIdentifier()Returns the identifier used in the "syntax = " declaration, if one was seen during the last call to Parse(), or the empty string otherwise. |
void | SetRequireSyntaxIdentifier(bool value)If set true, input files will be required to begin with a syntax identifier. more... |
void | SetStopAfterSyntaxIdentifier(bool value)Call SetStopAfterSyntaxIdentifier(true) to tell the parser to stop parsing as soon as it has seen the syntax identifier, or lack thereof. more... |
bool Parser::Parse(
io::Tokenizer * input,
FileDescriptorProto * file)Parse the entire input and construct a FileDescriptorProto representing it.
Returns true if no errors occurred, false otherwise.
-void Parser::RecordSourceLocationsTo(
SourceLocationTable * location_table)DEPRECATED: New code should use the SourceCodeInfo embedded in the FileDescriptorProto.
Requests that locations of certain definitions be recorded to the given SourceLocationTable while parsing. This can be used to look up exact line and column numbers for errors reported by DescriptorPool during validation. Set to NULL (the default) to discard source location information.
-void Parser::RecordErrorsTo(
io::ErrorCollector * error_collector)Requests that errors be recorded to the given ErrorCollector while parsing.
Set to NULL (the default) to discard error messages.
-void Parser::SetRequireSyntaxIdentifier(
bool value)If set true, input files will be required to begin with a syntax identifier.
Otherwise, files may omit this. If a syntax identifier is provided, it must be 'syntax = "proto2";' and must appear at the top of this file regardless of whether or not it was required.
-void Parser::SetStopAfterSyntaxIdentifier(
bool value)Call SetStopAfterSyntaxIdentifier(true) to tell the parser to stop parsing as soon as it has seen the syntax identifier, or lack thereof.
This is useful for quickly identifying the syntax of the file without parsing the whole thing. If this is enabled, no error will be recorded if the syntax identifier is something other than "proto2" (since presumably the caller intends to deal with that), but other kinds of errors (e.g. parse errors) will still be reported. When this is enabled, you may pass a NULL FileDescriptorProto to Parse().
-#include <google/protobuf/compiler/parser.h>
namespace google::protobuf::compiler
A table mapping (descriptor, ErrorLocation) pairs – as reported by DescriptorPool when validating descriptors – to line and column numbers within the original source code.
This is semi-obsolete: FileDescriptorProto.source_code_info now contains far more complete information about source locations. However, as of this writing you still need to use SourceLocationTable when integrating with DescriptorPool.
-Members | |
|---|---|
| SourceLocationTable() |
| ~SourceLocationTable() |
bool | Find(const Message * descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, int * line, int * column) constFinds the precise location of the given error and fills in *line and *column with the line and column numbers. more... |
bool | FindImport(const Message * descriptor, const std::string & name, int * line, int * column) const |
void | Add(const Message * descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, int line, int column)Adds a location to the table. |
void | AddImport(const Message * descriptor, const std::string & name, int line, int column) |
void | Clear()Clears the contents of the table. |
bool SourceLocationTable::Find(
const Message * descriptor,
DescriptorPool::ErrorCollector::ErrorLocation location,
int * line,
int * column) constFinds the precise location of the given error and fills in *line and *column with the line and column numbers.
If not found, sets *line to -1 and *column to 0 (since line = -1 is used to mean "error has no exact -location" in the ErrorCollector interface). Returns true if found, false otherwise.
-#include <google/protobuf/compiler/plugin.h>
namespace google::protobuf::compiler
Front-end for protoc code generator plugins written in C++.
To implement a protoc plugin in C++, simply write an implementation of CodeGenerator, then create a main() function like:
- -int main(int argc, char* argv[]) {
- MyCodeGenerator generator;
- return google::protobuf::compiler::PluginMain(argc, argv, &generator);
-}
-
-You must link your plugin against libprotobuf and libprotoc.
- -The core part of PluginMain is to invoke the given CodeGenerator on a CodeGeneratorRequest to generate a CodeGeneratorResponse. This part is abstracted out and made into function GenerateCode so that it can be reused, for example, to implement a variant of PluginMain that does some preprocessing on the input CodeGeneratorRequest before feeding the request to the given code generator.
- -To get protoc to use the plugin, do one of the following:
- -Place the plugin binary anywhere, with any name, and pass the –plugin parameter to protoc to direct it to your plugin like so:
-protoc --plugin=protoc-gen-NAME=path/to/mybinary --NAME_out=OUT_DIR-
On Windows, make sure to include the .exe suffix:
-protoc --plugin=protoc-gen-NAME=path/to/mybinary.exe --NAME_out=OUT_DIR-
Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
int | PluginMain(int argc, char * argv, const CodeGenerator * generator)Implements main() for a protoc plugin exposing the given code generator. |
bool | GenerateCode(const CodeGeneratorRequest & request, const CodeGenerator & generator, CodeGeneratorResponse * response, std::string * error_msg)Generates code using the given code generator. more... |
bool compiler::GenerateCode(
const CodeGeneratorRequest & request,
const CodeGenerator & generator,
CodeGeneratorResponse * response,
std::string * error_msg)Generates code using the given code generator.
Returns true if the code generation is successful. If the code generation fails, error_msg may be populated to describe the failure cause.
-#include <google/protobuf/compiler/plugin.pb.h>
namespace google::protobuf::compiler
API for protoc plugins.
This file defines a set of protocol message classes which make up the API to protoc code generator plugins. Plugins written in C++ should probably build on the API in plugin.h instead of dealing with the protobuf-level API, but plugins in other languages will need to deal with the raw messages as defined below.
The protocol compiler currently doesn't support auto-generated documentation, hence this page contains no descriptions. This file was generated by the protocol compiler from plugin.proto, whose contents are as follows:
// 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.
-
-// Author: kenton@google.com (Kenton Varda)
-//
-// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
-// change.
-//
-// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
-// just a program that reads a CodeGeneratorRequest from stdin and writes a
-// CodeGeneratorResponse to stdout.
-//
-// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
-// of dealing with the raw protocol defined here.
-//
-// A plugin executable needs only to be placed somewhere in the path. The
-// plugin should be named "protoc-gen-$NAME", and will then be used when the
-// flag "--${NAME}_out" is passed to protoc.
-
-syntax = "proto2";
-
-package google.protobuf.compiler;
-option java_package = "com.google.protobuf.compiler";
-option java_outer_classname = "PluginProtos";
-
-option go_package = "google.golang.org/protobuf/types/pluginpb";
-
-import "google/protobuf/descriptor.proto";
-
-// The version number of protocol compiler.
-message Version {
- optional int32 major = 1;
- optional int32 minor = 2;
- optional int32 patch = 3;
- // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
- // be empty for mainline stable releases.
- optional string suffix = 4;
-}
-
-// An encoded CodeGeneratorRequest is written to the plugin's stdin.
-message CodeGeneratorRequest {
- // The .proto files that were explicitly listed on the command-line. The
- // code generator should generate code only for these files. Each file's
- // descriptor will be included in proto_file, below.
- repeated string file_to_generate = 1;
-
- // The generator parameter passed on the command-line.
- optional string parameter = 2;
-
- // FileDescriptorProtos for all files in files_to_generate and everything
- // they import. The files will appear in topological order, so each file
- // appears before any file that imports it.
- //
- // protoc guarantees that all proto_files will be written after
- // the fields above, even though this is not technically guaranteed by the
- // protobuf wire format. This theoretically could allow a plugin to stream
- // in the FileDescriptorProtos and handle them one by one rather than read
- // the entire set into memory at once. However, as of this writing, this
- // is not similarly optimized on protoc's end -- it will store all fields in
- // memory at once before sending them to the plugin.
- //
- // Type names of fields and extensions in the FileDescriptorProto are always
- // fully qualified.
- repeated FileDescriptorProto proto_file = 15;
-
- // The version number of protocol compiler.
- optional Version compiler_version = 3;
-
-}
-
-// The plugin writes an encoded CodeGeneratorResponse to stdout.
-message CodeGeneratorResponse {
- // Error message. If non-empty, code generation failed. The plugin process
- // should exit with status code zero even if it reports an error in this way.
- //
- // This should be used to indicate errors in .proto files which prevent the
- // code generator from generating correct code. Errors which indicate a
- // problem in protoc itself -- such as the input CodeGeneratorRequest being
- // unparseable -- should be reported by writing a message to stderr and
- // exiting with a non-zero status code.
- optional string error = 1;
-
- // A bitmask of supported features that the code generator supports.
- // This is a bitwise "or" of values from the Feature enum.
- optional uint64 supported_features = 2;
-
- // Sync with code_generator.h.
- enum Feature {
- FEATURE_NONE = 0;
- FEATURE_PROTO3_OPTIONAL = 1;
- }
-
- // Represents a single generated file.
- message File {
- // The file name, relative to the output directory. The name must not
- // contain "." or ".." components and must be relative, not be absolute (so,
- // the file cannot lie outside the output directory). "/" must be used as
- // the path separator, not "\".
- //
- // If the name is omitted, the content will be appended to the previous
- // file. This allows the generator to break large files into small chunks,
- // and allows the generated text to be streamed back to protoc so that large
- // files need not reside completely in memory at one time. Note that as of
- // this writing protoc does not optimize for this -- it will read the entire
- // CodeGeneratorResponse before writing files to disk.
- optional string name = 1;
-
-// If non-empty, indicates that the named file should already exist, and the
-// content here is to be inserted into that file at a defined insertion
-// point. This feature allows a code generator to extend the output
-// produced by another code generator. The original generator may provide
-// insertion points by placing special annotations in the file that look
-// like:
-// @@protoc_insertion_point(NAME)
-// The annotation can have arbitrary text before and after it on the line,
-// which allows it to be placed in a comment. NAME should be replaced with
-// an identifier naming the point -- this is what other generators will use
-// as the insertion_point. Code inserted at this point will be placed
-// immediately above the line containing the insertion point (thus multiple
-// insertions to the same point will come out in the order they were added).
-// The double-@ is intended to make it unlikely that the generated code
-// could contain things that look like insertion points by accident.
-//
-// For example, the C++ code generator places the following line in the
-// .pb.h files that it generates:
-// // @@protoc_insertion_point(namespace_scope)
-// This line appears within the scope of the file's package namespace, but
-// outside of any particular class. Another plugin can then specify the
-// insertion_point "namespace_scope" to generate additional classes or
-// other declarations that should be placed in this scope.
-//
-// Note that if the line containing the insertion point begins with
-// whitespace, the same whitespace will be added to every line of the
-// inserted text. This is useful for languages like Python, where
-// indentation matters. In these languages, the insertion point comment
-// should be indented the same amount as any inserted code will need to be
-// in order to work correctly in that context.
-//
-// The code generator that generates the initial file and the one which
-// inserts into it must both run as part of a single invocation of protoc.
-// Code generators are executed in the order in which they appear on the
-// command line.
-//
-// If |insertion_point| is present, |name| must also be present.
-optional string insertion_point = 2;
-
-// The file contents.
-optional string content = 15;
-
-// Information describing the file content being inserted. If an insertion
-// point is used, this information will be appropriately offset and inserted
-// into the code generation metadata for the generated files.
-optional GeneratedCodeInfo generated_code_info = 16;
-
- }
- repeated File file = 15;
-}
-Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
const ::protobuf::internal::DescriptorTable | descriptor_table_google_2fprotobuf_2fcompiler_2fplugin_2eproto |
PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN protobuf::compiler::CodeGeneratorRequest * | Arena::CreateMaybeMessage< protobuf::compiler::CodeGeneratorRequest >(Arena * ) |
protobuf::compiler::CodeGeneratorResponse * | Arena::CreateMaybeMessage< protobuf::compiler::CodeGeneratorResponse >(Arena * ) |
protobuf::compiler::CodeGeneratorResponse_File * | Arena::CreateMaybeMessage< protobuf::compiler::CodeGeneratorResponse_File >(Arena * ) |
protobuf::compiler::Version * | Arena::CreateMaybeMessage< protobuf::compiler::Version >(Arena * ) |
const EnumDescriptor * | GetEnumDescriptor< protobuf::compiler::CodeGeneratorResponse_Feature >() |
#include <google/protobuf/compiler/python/python_generator.h>
namespace google::protobuf::compiler::python
Generates Python code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation for generated Python protocol buffer classes. | |
#include <google/protobuf/compiler/python/python_generator.h>
namespace google::protobuf::compiler::python
CodeGenerator implementation for generated Python protocol buffer classes.
If you create your own protocol compiler binary and you want it to support Python output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members | |
|---|---|
| Generator() |
virtual | ~Generator() |
virtual bool | Generate(const FileDescriptor * file, const std::string & parameter, GeneratorContext * generator_context, std::string * error) constCodeGenerator methods. |
virtual uint64_t | GetSupportedFeatures() constImplement this to indicate what features this code generator supports. more... |
virtual uint64_t Generator::GetSupportedFeatures() constImplement this to indicate what features this code generator supports.
This should be a bitwise OR of features from the Features enum in plugin.proto.
-#include <google/protobuf/compiler/ruby/ruby_generator.h>
namespace google::protobuf::compiler::ruby
Generates Ruby code for a given .proto file.
Classes in this file | |
|---|---|
CodeGenerator implementation for generated Ruby protocol buffer classes. | |
#include <google/protobuf/compiler/ruby/ruby_generator.h>
namespace google::protobuf::compiler::ruby
CodeGenerator implementation for generated Ruby protocol buffer classes.
If you create your own protocol compiler binary and you want it to support Ruby output, you can do so by registering an instance of this CodeGenerator with the CommandLineInterface in your main() function.
- -Members |
|---|
#include <google/protobuf/descriptor.h>
namespace google::protobuf
This file contains classes which describe a type of protocol message.
You can use a message's descriptor to learn at runtime what fields it contains and what the types of those fields are. The Message interface also allows you to dynamically access and modify individual fields by passing the FieldDescriptor of the field you are interested in.
- -Most users will not care about descriptors, because they will write code specific to certain protocol types and will simply use the classes generated by the protocol compiler directly. Advanced users who want to operate on arbitrary types (not known at compile time) may want to read descriptors in order to learn about the contents of a message. A very small number of users will want to construct their own Descriptors, either because they are implementing Message manually or because they are writing something like the protocol compiler.
- -For an example of how you might use descriptors, see the code example at the top of message.h.
- -Classes in this file | |
|---|---|
NB, all indices are zero-based. | |
Options when generating machine-parsable output from a descriptor with DebugString(). | |
Describes a type of protocol message, or a particular group within a message. | |
A range of field numbers which are designated for third-party extensions. | |
A range of reserved field numbers. | |
Describes a single field of a message. | |
Describes a oneof defined in a message type. | |
Describes an enum type defined in a .proto file. | |
A range of reserved field numbers. | |
Describes an individual enum constant of a particular type. | |
Describes an RPC service. | |
Describes an individual service method. | |
Describes a whole .proto file. | |
Used to construct descriptors. | |
When converting a FileDescriptorProto to a FileDescriptor, various errors might be detected in the input. | |
#include <google/protobuf/descriptor.h>
namespace google::protobuf
NB, all indices are zero-based.
Members | |
|---|---|
int | start_line |
int | end_line |
int | start_column |
int | end_column |
std::string | leading_commentsDoc comments found at the source location. more... |
std::string | trailing_comments |
std::vector< std::string > | leading_detached_comments |
std::string SourceLocation::leading_commentsDoc comments found at the source location.
See the comments in SourceCodeInfo.Location (descriptor.proto) for details.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Options when generating machine-parsable output from a descriptor with DebugString().
Members | |
|---|---|
bool | include_commentsinclude original user comments as recorded in SourceLocation entries. more... |
bool | elide_group_bodyIf true, elide the braced body in the debug string. |
bool | elide_oneof_body |
| DebugStringOptions() |
bool DebugStringOptions::include_commentsinclude original user comments as recorded in SourceLocation entries.
N.B. that this must be |false| by default: several other pieces of code (for example, the C++ code generation for fields in the proto compiler) rely on DebugString() output being unobstructed by user comments.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes a type of protocol message, or a particular group within a message.
To obtain the Descriptor for a given message object, call Message::GetDescriptor(). Generated message classes also have a static method called descriptor() which returns the type's descriptor. Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
enum | WellKnownType |
typedef | DescriptorProto Proto |
const std::string & | name() constThe name of the message type, not including its scope. |
const std::string & | full_name() constThe fully-qualified name of the message type, scope delimited by periods. more... |
int | index() constIndex of this descriptor within the file or containing type's message type array. |
const FileDescriptor * | file() constThe .proto file in which this message type was defined. Never nullptr. |
const Descriptor * | containing_type() constIf this Descriptor describes a nested type, this returns the type in which it is nested. more... |
const MessageOptions & | options() constGet options for this message type. more... |
void | CopyTo(DescriptorProto * proto) constWrite the contents of this Descriptor into the given DescriptorProto. more... |
std::string | DebugString() constWrite the contents of this descriptor in a human-readable form. more... |
std::string | DebugStringWithOptions(const DebugStringOptions & options) constSimilar to DebugString(), but additionally takes options (e.g., include original user comments in output). |
bool | is_placeholder() constReturns true if this is a placeholder for an unknown type. more... |
WellKnownType | well_known_type() const |
Field stuff | |
int | field_count() constThe number of fields in this message type. |
const FieldDescriptor * | field(int index) constGets a field by index, where 0 <= index < field_count(). more... |
const FieldDescriptor * | FindFieldByNumber(int number) constLooks up a field by declared tag number. more... |
const FieldDescriptor * | FindFieldByName(ConstStringParam name) constLooks up a field by name. Returns nullptr if no such field exists. |
const FieldDescriptor * | FindFieldByLowercaseName(ConstStringParam lowercase_name) constLooks up a field by lowercased name (as returned by lowercase_name()). more... |
const FieldDescriptor * | FindFieldByCamelcaseName(ConstStringParam camelcase_name) constLooks up a field by camel-case name (as returned by camelcase_name()). more... |
int | oneof_decl_count() constThe number of oneofs in this message type. |
int | real_oneof_decl_count() constThe number of oneofs in this message type, excluding synthetic oneofs. more... |
const OneofDescriptor * | oneof_decl(int index) constGet a oneof by index, where 0 <= index < oneof_decl_count(). more... |
const OneofDescriptor * | FindOneofByName(ConstStringParam name) constLooks up a oneof by name. Returns nullptr if no such oneof exists. |
Nested type stuff | |
int | nested_type_count() constThe number of nested types in this message type. |
const Descriptor * | nested_type(int index) constGets a nested type by index, where 0 <= index < nested_type_count(). more... |
const Descriptor * | FindNestedTypeByName(ConstStringParam name) constLooks up a nested type by name. more... |
Enum stuff | |
int | enum_type_count() constThe number of enum types in this message type. |
const EnumDescriptor * | enum_type(int index) constGets an enum type by index, where 0 <= index < enum_type_count(). more... |
const EnumDescriptor * | FindEnumTypeByName(ConstStringParam name) constLooks up an enum type by name. more... |
const EnumValueDescriptor * | FindEnumValueByName(ConstStringParam name) constLooks up an enum value by name, among all enum types in this message. more... |
Extensions | |
int | extension_range_count() constThe number of extension ranges in this message type. |
const ExtensionRange * | extension_range(int index) constGets an extension range by index, where 0 <= index < extension_range_count(). more... |
bool | IsExtensionNumber(int number) constReturns true if the number is in one of the extension ranges. |
const ExtensionRange * | FindExtensionRangeContainingNumber(int number) constReturns nullptr if no extension range contains the given number. |
int | extension_count() constThe number of extensions defined nested within this message type's scope. more... |
const FieldDescriptor * | extension(int index) constGet an extension by index, where 0 <= index < extension_count(). more... |
const FieldDescriptor * | FindExtensionByName(ConstStringParam name) constLooks up a named extension (which extends some other message type) defined within this message type's scope. |
const FieldDescriptor * | FindExtensionByLowercaseName(ConstStringParam name) constSimilar to FindFieldByLowercaseName(), but finds extensions defined within this message type's scope. |
const FieldDescriptor * | FindExtensionByCamelcaseName(ConstStringParam name) constSimilar to FindFieldByCamelcaseName(), but finds extensions defined within this message type's scope. |
Reserved fields | |
int | reserved_range_count() constThe number of reserved ranges in this message type. |
const ReservedRange * | reserved_range(int index) constGets an reserved range by index, where 0 <= index < reserved_range_count(). more... |
bool | IsReservedNumber(int number) constReturns true if the number is in one of the reserved ranges. |
const ReservedRange * | FindReservedRangeContainingNumber(int number) constReturns nullptr if no reserved range contains the given number. |
int | reserved_name_count() constThe number of reserved field names in this message type. |
const std::string & | reserved_name(int index) constGets a reserved name by index, where 0 <= index < reserved_name_count(). more... |
bool | IsReservedName(ConstStringParam name) constReturns true if the field name is reserved. |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this message declaration. more... |
Maps | |
const FieldDescriptor * | map_key() constReturns the FieldDescriptor for the "key" field. more... |
const FieldDescriptor * | map_value() constReturns the FieldDescriptor for the "value" field. more... |
enum Descriptor::WellKnownType {
WELLKNOWNTYPE_UNSPECIFIED,
WELLKNOWNTYPE_DOUBLEVALUE,
WELLKNOWNTYPE_FLOATVALUE,
WELLKNOWNTYPE_INT64VALUE,
WELLKNOWNTYPE_UINT64VALUE,
WELLKNOWNTYPE_INT32VALUE,
WELLKNOWNTYPE_UINT32VALUE,
WELLKNOWNTYPE_STRINGVALUE,
WELLKNOWNTYPE_BYTESVALUE,
WELLKNOWNTYPE_BOOLVALUE,
WELLKNOWNTYPE_ANY,
WELLKNOWNTYPE_FIELDMASK,
WELLKNOWNTYPE_DURATION,
WELLKNOWNTYPE_TIMESTAMP,
WELLKNOWNTYPE_VALUE,
WELLKNOWNTYPE_LISTVALUE,
WELLKNOWNTYPE_STRUCT,
**WELLKNOWNTYPE**DO_NOT_USE__ADD_DEFAULT_INSTEAD__
}| WELLKNOWNTYPE_UNSPECIFIED | Not a well-known type. |
| WELLKNOWNTYPE_DOUBLEVALUE | Wrapper types. google.protobuf.DoubleValue |
| WELLKNOWNTYPE_FLOATVALUE | google.protobuf.FloatValue |
| WELLKNOWNTYPE_INT64VALUE | google.protobuf.Int64Value |
| WELLKNOWNTYPE_UINT64VALUE | google.protobuf.UInt64Value |
| WELLKNOWNTYPE_INT32VALUE | google.protobuf.Int32Value |
| WELLKNOWNTYPE_UINT32VALUE | google.protobuf.UInt32Value |
| WELLKNOWNTYPE_STRINGVALUE | google.protobuf.StringValue |
| WELLKNOWNTYPE_BYTESVALUE | google.protobuf.BytesValue |
| WELLKNOWNTYPE_BOOLVALUE | google.protobuf.BoolValue |
| WELLKNOWNTYPE_ANY | Other well known types. google.protobuf.Any |
| WELLKNOWNTYPE_FIELDMASK | google.protobuf.FieldMask |
| WELLKNOWNTYPE_DURATION | google.protobuf.Duration |
| WELLKNOWNTYPE_TIMESTAMP | google.protobuf.Timestamp |
| WELLKNOWNTYPE_VALUE | google.protobuf.Value |
| WELLKNOWNTYPE_LISTVALUE | google.protobuf.ListValue |
| WELLKNOWNTYPE_STRUCT | google.protobuf.Struct |
| **WELLKNOWNTYPE**DO_NOT_USE__ADD_DEFAULT_INSTEAD__ | New well-known types may be added in the future. Please make sure any switch() statements have a 'default' case. - |
const std::string &
Descriptor::full_name() constThe fully-qualified name of the message type, scope delimited by periods.
For example, message type "Foo" which is declared in package "bar" has full name "bar.Foo". If a type "Baz" is nested within Foo, Baz's full_name is "bar.Foo.Baz". To get only the part that comes after the last '.', use name().
-const Descriptor *
Descriptor::containing_type() constIf this Descriptor describes a nested type, this returns the type in which it is nested.
Otherwise, returns nullptr.
-const MessageOptions &
Descriptor::options() constGet options for this message type.
These are specified in the .proto file by placing lines like "option foo = 1234;" in the message definition. Allowed options are defined by MessageOptions in descriptor.proto, and any available extensions of that message.
-void Descriptor::CopyTo(
DescriptorProto * proto) constWrite the contents of this Descriptor into the given DescriptorProto.
The target DescriptorProto must be clear before calling this; if it isn't, the result may be garbage.
-std::string Descriptor::DebugString() constWrite the contents of this descriptor in a human-readable form.
Output will be suitable for re-parsing.
-bool Descriptor::is_placeholder() constReturns true if this is a placeholder for an unknown type.
This will only be the case if this descriptor comes from a DescriptorPool with AllowUnknownDependencies() set.
-const FieldDescriptor *
Descriptor::field(
int index) constGets a field by index, where 0 <= index < field_count().
These are returned in the order they were defined in the .proto file.
-const FieldDescriptor *
Descriptor::FindFieldByNumber(
int number) constLooks up a field by declared tag number.
Returns nullptr if no such field exists.
-const FieldDescriptor *
Descriptor::FindFieldByLowercaseName(
ConstStringParam lowercase_name) constLooks up a field by lowercased name (as returned by lowercase_name()).
This lookup may be ambiguous if multiple field names differ only by case, in which case the field returned is chosen arbitrarily from the matches.
-const FieldDescriptor *
Descriptor::FindFieldByCamelcaseName(
ConstStringParam camelcase_name) constLooks up a field by camel-case name (as returned by camelcase_name()).
This lookup may be ambiguous if multiple field names differ in a way that leads them to have identical camel-case names, in which case the field returned is chosen arbitrarily from the matches.
-int Descriptor::real_oneof_decl_count() constThe number of oneofs in this message type, excluding synthetic oneofs.
Real oneofs always come first, so iterating up to real_oneof_decl_cout() will yield all real oneofs.
-const OneofDescriptor *
Descriptor::oneof_decl(
int index) constGet a oneof by index, where 0 <= index < oneof_decl_count().
These are returned in the order they were defined in the .proto file.
-const Descriptor *
Descriptor::nested_type(
int index) constGets a nested type by index, where 0 <= index < nested_type_count().
These are returned in the order they were defined in the .proto file.
-const Descriptor *
Descriptor::FindNestedTypeByName(
ConstStringParam name) constLooks up a nested type by name.
Returns nullptr if no such nested type exists.
-const EnumDescriptor *
Descriptor::enum_type(
int index) constGets an enum type by index, where 0 <= index < enum_type_count().
These are returned in the order they were defined in the .proto file.
-const EnumDescriptor *
Descriptor::FindEnumTypeByName(
ConstStringParam name) constLooks up an enum type by name.
Returns nullptr if no such enum type exists.
-const EnumValueDescriptor *
Descriptor::FindEnumValueByName(
ConstStringParam name) constLooks up an enum value by name, among all enum types in this message.
Returns nullptr if no such value exists.
-const ExtensionRange *
Descriptor::extension_range(
int index) constGets an extension range by index, where 0 <= index < extension_range_count().
These are returned in the order they were defined in the .proto file.
-int Descriptor::extension_count() constThe number of extensions defined nested within this message type's scope.
See doc:
- will return "foo", even though "foo" is an extension of M1. To find all known extensions of a given message, instead use DescriptorPool::FindAllExtensions.
const FieldDescriptor *
Descriptor::extension(
int index) constGet an extension by index, where 0 <= index < extension_count().
These are returned in the order they were defined in the .proto file.
-const ReservedRange *
Descriptor::reserved_range(
int index) constGets an reserved range by index, where 0 <= index < reserved_range_count().
These are returned in the order they were defined in the .proto file.
-const std::string &
Descriptor::reserved_name(
int index) constGets a reserved name by index, where 0 <= index < reserved_name_count().
Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually an array of pointers rather than the usual array of objects.
-bool Descriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this message declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-const FieldDescriptor *
Descriptor::map_key() constReturns the FieldDescriptor for the "key" field.
If this isn't a map entry field, returns nullptr.
-const FieldDescriptor *
Descriptor::map_value() constReturns the FieldDescriptor for the "value" field.
If this isn't a map entry field, returns nullptr.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
A range of field numbers which are designated for third-party extensions.
Members | |
|---|---|
typedef | DescriptorProto_ExtensionRange Proto |
typedef | ExtensionRangeOptions OptionsType |
int | startinclusive |
int | endexclusive |
const ExtensionRangeOptions * | options_ |
void | CopyTo(DescriptorProto_ExtensionRange * proto) constSee Descriptor::CopyTo(). |
#include <google/protobuf/descriptor.h>
namespace google::protobuf
A range of reserved field numbers.
Members | |
|---|---|
int | startinclusive |
int | endexclusive |
#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes a single field of a message.
To get the descriptor for a given field, first get the Descriptor for the message in which it is defined, then call Descriptor::FindFieldByName(). To get a FieldDescriptor for an extension, do one of the following:
-Members | |
|---|---|
enum | TypeIdentifies a field type. more... |
enum | CppTypeSpecifies the C++ data type used to represent the field. more... |
enum | LabelIdentifies whether the field is optional, required, or repeated. more... |
typedef | FieldDescriptorProto Proto |
const int | kMaxNumber = = (1 << 29) - 1Valid field numbers are positive integers up to kMaxNumber. |
const int | kFirstReservedNumber = = 19000First field number reserved for the protocol buffer library implementation. more... |
const int | kLastReservedNumber = = 19999Last field number reserved for the protocol buffer library implementation. more... |
int32 | default_value_int32_ |
int64 | default_value_int64_ |
uint32 | default_value_uint32_ |
uint64 | default_value_uint64_ |
float | default_value_float_ |
double | default_value_double_ |
bool | default_value_bool_ |
const EnumValueDescriptor * | default_value_enum_ |
const std::string * | default_value_string_ |
std::atomic< const Message * > | default_generated_instance_ |
const std::string & | name() constName of this field within the message. |
const std::string & | full_name() constFully-qualified name of the field. |
const std::string & | json_name() constJSON name of this field. |
const FileDescriptor * | file() constFile in which this field was defined. |
bool | is_extension() constIs this an extension field? |
int | number() constDeclared tag number. |
const std::string & | lowercase_name() const |
const std::string & | camelcase_name() const |
Type | type() constDeclared type of this field. |
const char * | type_name() constName of the declared type. |
CppType | cpp_type() constC++ type of this field. |
const char * | cpp_type_name() constName of the C++ type. |
Label | label() constoptional/required/repeated |
bool | is_required() constshorthand for label() == LABEL_REQUIRED |
bool | is_optional() constshorthand for label() == LABEL_OPTIONAL |
bool | is_repeated() constshorthand for label() == LABEL_REPEATED |
bool | is_packable() constshorthand for is_repeated() && IsTypePackable(type()) |
bool | is_packed() constshorthand for is_packable() && options().packed() |
bool | is_map() const |
bool | has_optional_keyword() constReturns true if this field was syntactically written with "optional" in the .proto file. more... |
bool | has_presence() constReturns true if this field tracks presence, ie. more... |
int | index() constIndex of this field within the message's field array, or the file or extension scope's extensions array. |
bool | has_default_value() constDoes this field have an explicitly-declared default value? |
bool | has_json_name() constWhether the user has specified the json_name field option in the .proto file. |
int32 | default_value_int32() constGet the field default value if cpp_type() == CPPTYPE_INT32. more... |
int64 | default_value_int64() constGet the field default value if cpp_type() == CPPTYPE_INT64. more... |
uint32 | default_value_uint32() constGet the field default value if cpp_type() == CPPTYPE_UINT32. more... |
uint64 | default_value_uint64() constGet the field default value if cpp_type() == CPPTYPE_UINT64. more... |
float | default_value_float() constGet the field default value if cpp_type() == CPPTYPE_FLOAT. more... |
double | default_value_double() constGet the field default value if cpp_type() == CPPTYPE_DOUBLE. more... |
bool | default_value_bool() constGet the field default value if cpp_type() == CPPTYPE_BOOL. more... |
const EnumValueDescriptor * | default_value_enum() constGet the field default value if cpp_type() == CPPTYPE_ENUM. more... |
const std::string & | default_value_string() constGet the field default value if cpp_type() == CPPTYPE_STRING. more... |
const Descriptor * | containing_type() constThe Descriptor for the message of which this is a field. more... |
const OneofDescriptor * | containing_oneof() constIf the field is a member of a oneof, this is the one, otherwise this is nullptr. |
const OneofDescriptor * | real_containing_oneof() constIf the field is a member of a non-synthetic oneof, returns the descriptor for the oneof, otherwise returns nullptr. |
int | index_in_oneof() constIf the field is a member of a oneof, returns the index in that oneof. |
const Descriptor * | extension_scope() constAn extension may be declared within the scope of another message. more... |
const Descriptor * | message_type() constIf type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the message or the group type. more... |
const EnumDescriptor * | enum_type() constIf type is TYPE_ENUM, returns a descriptor for the enum. more... |
const FieldOptions & | options() constGet the FieldOptions for this field. more... |
void | CopyTo(FieldDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
const std::string & | PrintableNameForExtension() constReturns full_name() except if the field is a MessageSet extension, in which case it returns the full_name() of the containing message type for backwards compatibility with proto1. more... |
static CppType | TypeToCppType(Type type)Helper method to get the CppType for a particular Type. |
static const char * | TypeName(Type type)Helper method to get the name of a Type. |
static const char * | CppTypeName(CppType cpp_type)Helper method to get the name of a CppType. |
static bool | IsTypePackable(Type field_type)Return true iff [[]packed = true] is valid for fields of this type. |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this field declaration. more... |
enum FieldDescriptor::Type {
TYPE_DOUBLE = = 1,
TYPE_FLOAT = = 2,
TYPE_INT64 = = 3,
TYPE_UINT64 = = 4,
TYPE_INT32 = = 5,
TYPE_FIXED64 = = 6,
TYPE_FIXED32 = = 7,
TYPE_BOOL = = 8,
TYPE_STRING = = 9,
TYPE_GROUP = = 10,
TYPE_MESSAGE = = 11,
TYPE_BYTES = = 12,
TYPE_UINT32 = = 13,
TYPE_ENUM = = 14,
TYPE_SFIXED32 = = 15,
TYPE_SFIXED64 = = 16,
TYPE_SINT32 = = 17,
TYPE_SINT64 = = 18,
MAX_TYPE = = 18
}Identifies a field type.
0 is reserved for errors. The order is weird for historical reasons. Types 12 and up are new in proto2.
-| TYPE_DOUBLE | double, exactly eight bytes on the wire. |
| TYPE_FLOAT | float, exactly four bytes on the wire. |
| TYPE_INT64 | int64, varint on the wire. Negative numbers take 10 bytes. Use TYPE_SINT64 if negative values are likely. - |
| TYPE_UINT64 | uint64, varint on the wire. |
| TYPE_INT32 | int32, varint on the wire. Negative numbers take 10 bytes. Use TYPE_SINT32 if negative values are likely. - |
| TYPE_FIXED64 | uint64, exactly eight bytes on the wire. |
| TYPE_FIXED32 | uint32, exactly four bytes on the wire. |
| TYPE_BOOL | bool, varint on the wire. |
| TYPE_STRING | UTF-8 text. |
| TYPE_GROUP | Tag-delimited message. Deprecated. |
| TYPE_MESSAGE | Length-delimited message. |
| TYPE_BYTES | Arbitrary byte array. |
| TYPE_UINT32 | uint32, varint on the wire |
| TYPE_ENUM | Enum, varint on the wire. |
| TYPE_SFIXED32 | int32, exactly four bytes on the wire |
| TYPE_SFIXED64 | int64, exactly eight bytes on the wire |
| TYPE_SINT32 | int32, ZigZag-encoded varint on the wire |
| TYPE_SINT64 | int64, ZigZag-encoded varint on the wire |
| MAX_TYPE | Constant useful for defining lookup tables indexed by Type. |
enum FieldDescriptor::CppType {
CPPTYPE_INT32 = = 1,
CPPTYPE_INT64 = = 2,
CPPTYPE_UINT32 = = 3,
CPPTYPE_UINT64 = = 4,
CPPTYPE_DOUBLE = = 5,
CPPTYPE_FLOAT = = 6,
CPPTYPE_BOOL = = 7,
CPPTYPE_ENUM = = 8,
CPPTYPE_STRING = = 9,
CPPTYPE_MESSAGE = = 10,
MAX_CPPTYPE = = 10
}Specifies the C++ data type used to represent the field.
There is a fixed mapping from Type to CppType where each Type maps to exactly one CppType. 0 is reserved for errors.
-| CPPTYPE_INT32 | TYPE_INT32, TYPE_SINT32, TYPE_SFIXED32. |
| CPPTYPE_INT64 | TYPE_INT64, TYPE_SINT64, TYPE_SFIXED64. |
| CPPTYPE_UINT32 | TYPE_UINT32, TYPE_FIXED32. |
| CPPTYPE_UINT64 | TYPE_UINT64, TYPE_FIXED64. |
| CPPTYPE_DOUBLE | TYPE_DOUBLE. |
| CPPTYPE_FLOAT | TYPE_FLOAT. |
| CPPTYPE_BOOL | TYPE_BOOL. |
| CPPTYPE_ENUM | TYPE_ENUM. |
| CPPTYPE_STRING | TYPE_STRING, TYPE_BYTES. |
| CPPTYPE_MESSAGE | TYPE_MESSAGE, TYPE_GROUP. |
| MAX_CPPTYPE | Constant useful for defining lookup tables indexed by CppType. |
enum FieldDescriptor::Label {
LABEL_OPTIONAL = = 1,
LABEL_REQUIRED = = 2,
LABEL_REPEATED = = 3,
MAX_LABEL = = 3
}Identifies whether the field is optional, required, or repeated.
0 is reserved for errors.
-| LABEL_OPTIONAL | optional |
| LABEL_REQUIRED | required |
| LABEL_REPEATED | repeated |
| MAX_LABEL | Constant useful for defining lookup tables indexed by Label. |
const int FieldDescriptor::kFirstReservedNumber = = 19000First field number reserved for the protocol buffer library implementation.
Users may not declare fields that use reserved numbers.
-const int FieldDescriptor::kLastReservedNumber = = 19999Last field number reserved for the protocol buffer library implementation.
Users may not declare fields that use reserved numbers.
-const std::string &
FieldDescriptor::lowercase_name() constSame as name() except converted to lower-case.
This (and especially the FindFieldByLowercaseName() method) can be useful when parsing formats which prefer to use lowercase naming style. (Although, technically field names should be lowercased anyway according to the protobuf style guide, so this only makes a difference when dealing with old .proto files which do not follow the guide.)
-const std::string &
FieldDescriptor::camelcase_name() constSame as name() except converted to camel-case.
In this conversion, any time an underscore appears in the name, it is removed and the next letter is capitalized. Furthermore, the first letter of the name is lower-cased. Examples:
-FooBar -> fooBar -foo_bar -> fooBar -fooBar -> fooBar-
This (and especially the FindFieldByCamelcaseName() method) can be useful when parsing formats which prefer to use camel-case naming style.
-bool FieldDescriptor::has_optional_keyword() constReturns true if this field was syntactically written with "optional" in the .proto file.
Excludes singular proto3 fields that do not have a label.
-bool FieldDescriptor::has_presence() constReturns true if this field tracks presence, ie.
does the field distinguish between "unset" and "present with default value." This includes required, optional, and oneof fields. It excludes maps, repeated fields, and singular proto3 fields without "optional".
-For fields where has_presence() == true, the return value of Reflection::HasField() is semantically meaningful.
-int32 FieldDescriptor::default_value_int32() constGet the field default value if cpp_type() == CPPTYPE_INT32.
If no explicit default was defined, the default is 0.
-int64 FieldDescriptor::default_value_int64() constGet the field default value if cpp_type() == CPPTYPE_INT64.
If no explicit default was defined, the default is 0.
-uint32 FieldDescriptor::default_value_uint32() constGet the field default value if cpp_type() == CPPTYPE_UINT32.
If no explicit default was defined, the default is 0.
-uint64 FieldDescriptor::default_value_uint64() constGet the field default value if cpp_type() == CPPTYPE_UINT64.
If no explicit default was defined, the default is 0.
-float FieldDescriptor::default_value_float() constGet the field default value if cpp_type() == CPPTYPE_FLOAT.
If no explicit default was defined, the default is 0.0.
-double FieldDescriptor::default_value_double() constGet the field default value if cpp_type() == CPPTYPE_DOUBLE.
If no explicit default was defined, the default is 0.0.
-bool FieldDescriptor::default_value_bool() constGet the field default value if cpp_type() == CPPTYPE_BOOL.
If no explicit default was defined, the default is false.
-const EnumValueDescriptor *
FieldDescriptor::default_value_enum() constGet the field default value if cpp_type() == CPPTYPE_ENUM.
If no explicit default was defined, the default is the first value defined in the enum type (all enum types are required to have at least one value). This never returns nullptr.
-const std::string &
FieldDescriptor::default_value_string() constGet the field default value if cpp_type() == CPPTYPE_STRING.
If no explicit default was defined, the default is the empty string.
-const Descriptor *
FieldDescriptor::containing_type() constThe Descriptor for the message of which this is a field.
For extensions, this is the extended type. Never nullptr.
-const Descriptor *
FieldDescriptor::extension_scope() constAn extension may be declared within the scope of another message.
If this field is an extension (is_extension() is true), then extension_scope() returns that message, or nullptr if the extension was declared at global scope. If this is not an extension, extension_scope() is undefined (may assert-fail).
-const Descriptor *
FieldDescriptor::message_type() constIf type is TYPE_MESSAGE or TYPE_GROUP, returns a descriptor for the message or the group type.
Otherwise, returns null.
-const EnumDescriptor *
FieldDescriptor::enum_type() constIf type is TYPE_ENUM, returns a descriptor for the enum.
Otherwise, returns null.
-const FieldOptions &
FieldDescriptor::options() constGet the FieldOptions for this field.
This includes things listed in square brackets after the field definition. E.g., the field:
-optional string text = 1 [[]ctype=CORD];-
has the "ctype" option set. Allowed options are defined by FieldOptions in descriptor.proto, and any available extensions of that message.
-const std::string &
FieldDescriptor::PrintableNameForExtension() constReturns full_name() except if the field is a MessageSet extension, in which case it returns the full_name() of the containing message type for backwards compatibility with proto1.
A MessageSet extension is defined as an optional message extension whose containing type has the message_set_wire_format option set. This should be true of extensions of google.protobuf.bridge.MessageSet; by convention, such extensions are named "message_set_extension".
-The opposite operation (looking up an extension's FieldDescriptor given its printable name) can be accomplished with
-message->file()->pool()->FindExtensionByPrintableName(message, name)-
where the extension extends "message".
-bool FieldDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this field declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes a oneof defined in a message type.
Members | |
|---|---|
typedef | OneofDescriptorProto Proto |
const std::string & | name() constName of this oneof. |
const std::string & | full_name() constFully-qualified name of the oneof. |
int | index() constIndex of this oneof within the message's oneof array. |
bool | is_synthetic() constReturns whether this oneof was inserted by the compiler to wrap a proto3 optional field. more... |
const FileDescriptor * | file() constThe .proto file in which this oneof was defined. Never nullptr. |
const Descriptor * | containing_type() constThe Descriptor for the message containing this oneof. |
int | field_count() constThe number of (non-extension) fields which are members of this oneof. |
const FieldDescriptor * | field(int index) constGet a member of this oneof, in the order in which they were declared in the .proto file. more... |
const OneofOptions & | options() const |
void | CopyTo(OneofDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this oneof declaration. more... |
bool OneofDescriptor::is_synthetic() constReturns whether this oneof was inserted by the compiler to wrap a proto3 optional field.
If this returns true, code generators should not emit it.
-const FieldDescriptor *
OneofDescriptor::field(
int index) constGet a member of this oneof, in the order in which they were declared in the .proto file.
Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because fields_ is actually an array of pointers rather than the usual array of objects.
-Does not include extensions.
-bool OneofDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this oneof declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes an enum type defined in a .proto file.
To get the EnumDescriptor for a generated enum type, call TypeName_descriptor(). Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
typedef | EnumDescriptorProto Proto |
const std::string & | name() constThe name of this enum type in the containing scope. |
const std::string & | full_name() constThe fully-qualified name of the enum type, scope delimited by periods. |
int | index() constIndex of this enum within the file or containing message's enum array. |
const FileDescriptor * | file() constThe .proto file in which this enum type was defined. Never nullptr. |
int | value_count() constThe number of values for this EnumDescriptor. more... |
const EnumValueDescriptor * | value(int index) constGets a value by index, where 0 <= index < value_count(). more... |
const EnumValueDescriptor * | FindValueByName(ConstStringParam name) constLooks up a value by name. Returns nullptr if no such value exists. |
const EnumValueDescriptor * | FindValueByNumber(int number) constLooks up a value by number. more... |
const Descriptor * | containing_type() constIf this enum type is nested in a message type, this is that message type. more... |
const EnumOptions & | options() constGet options for this enum type. more... |
void | CopyTo(EnumDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
bool | is_placeholder() constReturns true if this is a placeholder for an unknown enum. more... |
Reserved fields | |
int | reserved_range_count() constThe number of reserved ranges in this message type. |
const EnumDescriptor::ReservedRange * | reserved_range(int index) constGets an reserved range by index, where 0 <= index < reserved_range_count(). more... |
bool | IsReservedNumber(int number) constReturns true if the number is in one of the reserved ranges. |
const EnumDescriptor::ReservedRange * | FindReservedRangeContainingNumber(int number) constReturns nullptr if no reserved range contains the given number. |
int | reserved_name_count() constThe number of reserved field names in this message type. |
const std::string & | reserved_name(int index) constGets a reserved name by index, where 0 <= index < reserved_name_count(). more... |
bool | IsReservedName(ConstStringParam name) constReturns true if the field name is reserved. |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this enum declaration. more... |
int EnumDescriptor::value_count() constThe number of values for this EnumDescriptor.
Guaranteed to be greater than zero.
-const EnumValueDescriptor *
EnumDescriptor::value(
int index) constGets a value by index, where 0 <= index < value_count().
These are returned in the order they were defined in the .proto file.
-const EnumValueDescriptor *
EnumDescriptor::FindValueByNumber(
int number) constLooks up a value by number.
Returns nullptr if no such value exists. If multiple values have this number, the first one defined is returned.
-const Descriptor *
EnumDescriptor::containing_type() constIf this enum type is nested in a message type, this is that message type.
Otherwise, nullptr.
-const EnumOptions &
EnumDescriptor::options() constGet options for this enum type.
These are specified in the .proto file by placing lines like "option foo = 1234;" in the enum definition. Allowed options are defined by EnumOptions in descriptor.proto, and any available extensions of that message.
-bool EnumDescriptor::is_placeholder() constReturns true if this is a placeholder for an unknown enum.
This will only be the case if this descriptor comes from a DescriptorPool with AllowUnknownDependencies() set.
-const EnumDescriptor::ReservedRange *
EnumDescriptor::reserved_range(
int index) constGets an reserved range by index, where 0 <= index < reserved_range_count().
These are returned in the order they were defined in the .proto file.
-const std::string &
EnumDescriptor::reserved_name(
int index) constGets a reserved name by index, where 0 <= index < reserved_name_count().
Can't use PROTOBUF_DEFINE_ARRAY_ACCESSOR because reserved_names_ is actually an array of pointers rather than the usual array of objects.
-bool EnumDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this enum declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
A range of reserved field numbers.
Members | |
|---|---|
int | startinclusive |
int | endinclusive |
#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes an individual enum constant of a particular type.
To get the EnumValueDescriptor for a given enum value, first get the EnumDescriptor for its type, then use EnumDescriptor::FindValueByName() or EnumDescriptor::FindValueByNumber(). Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
typedef | EnumValueDescriptorProto Proto |
const std::string & | name() constName of this enum constant. |
int | index() constIndex within the enums's Descriptor. |
int | number() constNumeric value of this enum constant. |
const std::string & | full_name() constThe full_name of an enum value is a sibling symbol of the enum type. more... |
const FileDescriptor * | file() constThe .proto file in which this value was defined. Never nullptr. |
const EnumDescriptor * | type() constThe type of this value. Never nullptr. |
const EnumValueOptions & | options() constGet options for this enum value. more... |
void | CopyTo(EnumValueDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this enum value declaration. more... |
const std::string &
EnumValueDescriptor::full_name() constThe full_name of an enum value is a sibling symbol of the enum type.
e.g. the full name of FieldDescriptorProto::TYPE_INT32 is actually "google.protobuf.FieldDescriptorProto.TYPE_INT32", NOT "google.protobuf.FieldDescriptorProto.Type.TYPE_INT32". This is to conform with C++ scoping rules for enums.
-const EnumValueOptions &
EnumValueDescriptor::options() constGet options for this enum value.
These are specified in the .proto file by adding text like "[[]foo = 1234]" after an enum value definition. Allowed options are defined by EnumValueOptions in descriptor.proto, and any available extensions of that message.
-bool EnumValueDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this enum value declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes an RPC service.
Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
typedef | ServiceDescriptorProto Proto |
const std::string & | name() constThe name of the service, not including its containing scope. |
const std::string & | full_name() constThe fully-qualified name of the service, scope delimited by periods. |
int | index() constIndex of this service within the file's services array. |
const FileDescriptor * | file() constThe .proto file in which this service was defined. Never nullptr. |
const ServiceOptions & | options() constGet options for this service type. more... |
int | method_count() constThe number of methods this service defines. |
const MethodDescriptor * | method(int index) const |
const MethodDescriptor * | FindMethodByName(ConstStringParam name) constLook up a MethodDescriptor by name. |
void | CopyTo(ServiceDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this service declaration. more... |
const ServiceOptions &
ServiceDescriptor::options() constGet options for this service type.
These are specified in the .proto file by placing lines like "option foo = 1234;" in the service definition. Allowed options are defined by ServiceOptions in descriptor.proto, and any available extensions of that message.
-const MethodDescriptor *
ServiceDescriptor::method(
int index) constGets a MethodDescriptor by index, where 0 <= index < method_count().
These are returned in the order they were defined in the .proto file.
-bool ServiceDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this service declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes an individual service method.
To obtain a MethodDescriptor given a service, first get its ServiceDescriptor, then call ServiceDescriptor::FindMethodByName(). Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
typedef | MethodDescriptorProto Proto |
const std::string & | name() constName of this method, not including containing scope. |
const std::string & | full_name() constThe fully-qualified name of the method, scope delimited by periods. |
int | index() constIndex within the service's Descriptor. |
const FileDescriptor * | file() constThe .proto file in which this method was defined. Never nullptr. |
const ServiceDescriptor * | service() constGets the service to which this method belongs. Never nullptr. |
const Descriptor * | input_type() constGets the type of protocol message which this method accepts as input. |
const Descriptor * | output_type() constGets the type of protocol message which this message produces as output. |
bool | client_streaming() constGets whether the client streams multiple requests. |
bool | server_streaming() constGets whether the server streams multiple responses. |
const MethodOptions & | options() constGet options for this method. more... |
void | CopyTo(MethodDescriptorProto * proto) constSee Descriptor::CopyTo(). |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
Source Location | |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this method declaration. more... |
const MethodOptions &
MethodDescriptor::options() constGet options for this method.
These are specified in the .proto file by placing lines like "option foo = 1234;" in curly-braces after a method declaration. Allowed options are defined by MethodOptions in descriptor.proto, and any available extensions of that message.
-bool MethodDescriptor::GetSourceLocation(
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this method declaration.
Returns false and leaves |*out_location| unchanged iff location information was not available.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Describes a whole .proto file.
To get the FileDescriptor for a compiled-in file, get the descriptor for something defined in that file and call descriptor->file(). Use DescriptorPool to construct your own descriptors.
-Members | |
|---|---|
enum | SyntaxSyntax of this file. more... |
typedef | FileDescriptorProto Proto |
const std::string & | name() constThe filename, relative to the source tree. more... |
const std::string & | package() constThe package, e.g. "google.protobuf.compiler". |
const DescriptorPool * | pool() const |
int | dependency_count() constThe number of files imported by this one. |
const FileDescriptor * | dependency(int index) constGets an imported file by index, where 0 <= index < dependency_count(). more... |
int | public_dependency_count() constThe number of files public imported by this one. more... |
const FileDescriptor * | public_dependency(int index) constGets a public imported file by index, where 0 <= index < public_dependency_count(). more... |
int | weak_dependency_count() constThe number of files that are imported for weak fields. more... |
const FileDescriptor * | weak_dependency(int index) constGets a weak imported file by index, where 0 <= index < weak_dependency_count(). more... |
int | message_type_count() constNumber of top-level message types defined in this file. more... |
const Descriptor * | message_type(int index) constGets a top-level message type, where 0 <= index < message_type_count(). more... |
int | enum_type_count() constNumber of top-level enum types defined in this file. more... |
const EnumDescriptor * | enum_type(int index) constGets a top-level enum type, where 0 <= index < enum_type_count(). more... |
int | service_count() constNumber of services defined in this file. |
const ServiceDescriptor * | service(int index) constGets a service, where 0 <= index < service_count(). more... |
int | extension_count() constNumber of extensions defined at file scope. more... |
const FieldDescriptor * | extension(int index) constGets an extension's descriptor, where 0 <= index < extension_count(). more... |
const FileOptions & | options() constGet options for this file. more... |
Syntax | syntax() const |
const Descriptor * | FindMessageTypeByName(ConstStringParam name) constFind a top-level message type by name (not full_name). more... |
const EnumDescriptor * | FindEnumTypeByName(ConstStringParam name) constFind a top-level enum type by name. Returns nullptr if not found. |
const EnumValueDescriptor * | FindEnumValueByName(ConstStringParam name) constFind an enum value defined in any top-level enum by name. more... |
const ServiceDescriptor * | FindServiceByName(ConstStringParam name) constFind a service definition by name. Returns nullptr if not found. |
const FieldDescriptor * | FindExtensionByName(ConstStringParam name) constFind a top-level extension definition by name. more... |
const FieldDescriptor * | FindExtensionByLowercaseName(ConstStringParam name) constSimilar to FindExtensionByName(), but searches by lowercased-name. more... |
const FieldDescriptor * | FindExtensionByCamelcaseName(ConstStringParam name) constSimilar to FindExtensionByName(), but searches by camelcased-name. more... |
void | CopyTo(FileDescriptorProto * proto) const |
void | CopySourceCodeInfoTo(FileDescriptorProto * proto) constWrite the source code information of this FileDescriptor into the given FileDescriptorProto. more... |
void | CopyJsonNameTo(FileDescriptorProto * proto) constFill the json_name field of FieldDescriptorProto for all fields. more... |
std::string | DebugString() const |
std::string | DebugStringWithOptions(const DebugStringOptions & options) const |
bool | is_placeholder() constReturns true if this is a placeholder for an unknown file. more... |
bool | GetSourceLocation(SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of this file declaration (namely, the empty path). |
bool | GetSourceLocation(const std::vector< int > & path, SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of the declaration or declaration-part denoted by |path|. more... |
static const char * | SyntaxName(Syntax syntax) |
enum FileDescriptor::Syntax {
SYNTAX_UNKNOWN = = 0,
SYNTAX_PROTO2 = = 2,
SYNTAX_PROTO3 = = 3
}Syntax of this file.
| SYNTAX_UNKNOWN | |
| SYNTAX_PROTO2 | |
| SYNTAX_PROTO3 |
const std::string &
FileDescriptor::name() constThe filename, relative to the source tree.
e.g. "foo/bar/baz.proto"
-const DescriptorPool *
FileDescriptor::pool() constThe DescriptorPool in which this FileDescriptor and all its contents were allocated.
Never nullptr.
-const FileDescriptor *
FileDescriptor::dependency(
int index) constGets an imported file by index, where 0 <= index < dependency_count().
These are returned in the order they were defined in the .proto file.
-int FileDescriptor::public_dependency_count() constThe number of files public imported by this one.
The public dependency list is a subset of the dependency list.
-const FileDescriptor *
FileDescriptor::public_dependency(
int index) constGets a public imported file by index, where 0 <= index < public_dependency_count().
These are returned in the order they were defined in the .proto file.
-int FileDescriptor::weak_dependency_count() constThe number of files that are imported for weak fields.
The weak dependency list is a subset of the dependency list.
-const FileDescriptor *
FileDescriptor::weak_dependency(
int index) constGets a weak imported file by index, where 0 <= index < weak_dependency_count().
These are returned in the order they were defined in the .proto file.
-int FileDescriptor::message_type_count() constNumber of top-level message types defined in this file.
(This does not include nested types.)
-const Descriptor *
FileDescriptor::message_type(
int index) constGets a top-level message type, where 0 <= index < message_type_count().
These are returned in the order they were defined in the .proto file.
-int FileDescriptor::enum_type_count() constNumber of top-level enum types defined in this file.
(This does not include nested types.)
-const EnumDescriptor *
FileDescriptor::enum_type(
int index) constGets a top-level enum type, where 0 <= index < enum_type_count().
These are returned in the order they were defined in the .proto file.
-const ServiceDescriptor *
FileDescriptor::service(
int index) constGets a service, where 0 <= index < service_count().
These are returned in the order they were defined in the .proto file.
-int FileDescriptor::extension_count() constNumber of extensions defined at file scope.
(This does not include extensions nested within message types.)
-const FieldDescriptor *
FileDescriptor::extension(
int index) constGets an extension's descriptor, where 0 <= index < extension_count().
These are returned in the order they were defined in the .proto file.
-const FileOptions &
FileDescriptor::options() constGet options for this file.
These are specified in the .proto file by placing lines like "option foo = 1234;" at the top level, outside of any other definitions. Allowed options are defined by FileOptions in descriptor.proto, and any available extensions of that message.
-const Descriptor *
FileDescriptor::FindMessageTypeByName(
ConstStringParam name) constFind a top-level message type by name (not full_name).
Returns nullptr if not found.
-const EnumValueDescriptor *
FileDescriptor::FindEnumValueByName(
ConstStringParam name) constFind an enum value defined in any top-level enum by name.
Returns nullptr if not found.
-const FieldDescriptor *
FileDescriptor::FindExtensionByName(
ConstStringParam name) constFind a top-level extension definition by name.
Returns nullptr if not found.
-const FieldDescriptor *
FileDescriptor::FindExtensionByLowercaseName(
ConstStringParam name) constSimilar to FindExtensionByName(), but searches by lowercased-name.
-const FieldDescriptor *
FileDescriptor::FindExtensionByCamelcaseName(
ConstStringParam name) constSimilar to FindExtensionByName(), but searches by camelcased-name.
-void FileDescriptor::CopyTo(
FileDescriptorProto * proto) constSee Descriptor::CopyTo().
Notes:
-void FileDescriptor::CopySourceCodeInfoTo(
FileDescriptorProto * proto) constWrite the source code information of this FileDescriptor into the given FileDescriptorProto.
See CopyTo() above.
-void FileDescriptor::CopyJsonNameTo(
FileDescriptorProto * proto) constFill the json_name field of FieldDescriptorProto for all fields.
Can only be called after CopyTo().
-bool FileDescriptor::is_placeholder() constReturns true if this is a placeholder for an unknown file.
This will only be the case if this descriptor comes from a DescriptorPool with AllowUnknownDependencies() set.
-bool FileDescriptor::GetSourceLocation(
const std::vector< int > & path,
SourceLocation * out_location) constUpdates |*out_location| to the source location of the complete extent of the declaration or declaration-part denoted by |path|.
Returns false and leaves |*out_location| unchanged iff location information was not available. (See SourceCodeInfo for description of path encoding.)
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
Used to construct descriptors.
Normally you won't want to build your own descriptors. Message classes constructed by the protocol compiler will provide them for you. However, if you are implementing Message on your own, or if you are writing a program which can operate on totally arbitrary types and needs to load them from some sort of database, you might need to.
-Since Descriptors are composed of a whole lot of cross-linked bits of data that would be a pain to put together manually, the DescriptorPool class is provided to make the process easier. It can take a FileDescriptorProto (defined in descriptor.proto), validate it, and convert it to a set of nicely cross-linked Descriptors.
-DescriptorPool also helps with memory management. Descriptors are composed of many objects containing static data and pointers to each other. In all likelihood, when it comes time to delete this data, you'll want to delete it all at once. In fact, it is not uncommon to have a whole pool of descriptors all cross-linked with each other which you wish to delete all at once. This class represents such a pool, and handles the memory management for you.
-You can also search for descriptors within a DescriptorPool by name, and extensions by number.
-Members | |
|---|---|
| DescriptorPool()Create a normal, empty DescriptorPool. |
explicit | DescriptorPool(DescriptorDatabase * fallback_database, ErrorCollector * error_collector = nullptr) |
| ~DescriptorPool() |
const FileDescriptor * | FindFileByName(ConstStringParam name) constFind a FileDescriptor in the pool by file name. more... |
const FileDescriptor * | FindFileContainingSymbol(ConstStringParam symbol_name) constFind the FileDescriptor in the pool which defines the given symbol. more... |
static const DescriptorPool * | generated_pool()Get a pointer to the generated pool. more... |
Looking up descriptorsThese find descriptors by fully-qualified name. These will find both top-level descriptors and nested descriptors. They return nullptr if not found. | |
const Descriptor * | FindMessageTypeByName(ConstStringParam name) const |
const FieldDescriptor * | FindFieldByName(ConstStringParam name) const |
const FieldDescriptor * | FindExtensionByName(ConstStringParam name) const |
const OneofDescriptor * | FindOneofByName(ConstStringParam name) const |
const EnumDescriptor * | FindEnumTypeByName(ConstStringParam name) const |
const EnumValueDescriptor * | FindEnumValueByName(ConstStringParam name) const |
const ServiceDescriptor * | FindServiceByName(ConstStringParam name) const |
const MethodDescriptor * | FindMethodByName(ConstStringParam name) const |
const FieldDescriptor * | FindExtensionByNumber(const Descriptor * extendee, int number) constFinds an extension of the given type by number. more... |
const FieldDescriptor * | FindExtensionByPrintableName(const Descriptor * extendee, ConstStringParam printable_name) constFinds an extension of the given type by its printable name. more... |
void | FindAllExtensions(const Descriptor * extendee, std::vector< const FieldDescriptor * > * out) constFinds extensions of extendee. more... |
Building descriptors | |
const FileDescriptor * | BuildFile(const FileDescriptorProto & proto)Convert the FileDescriptorProto to real descriptors and place them in this DescriptorPool. more... |
const FileDescriptor * | BuildFileCollectingErrors(const FileDescriptorProto & proto, ErrorCollector * error_collector)Same as BuildFile() except errors are sent to the given ErrorCollector. |
void | AllowUnknownDependencies()By default, it is an error if a FileDescriptorProto contains references to types or other files that are not found in the DescriptorPool (or its backing DescriptorDatabase, if any). more... |
void | EnforceWeakDependencies(bool enforce)By default, weak imports are allowed to be missing, in which case we will use a placeholder for the dependency and convert the field to be an Empty message field. more... |
Internal stuff
- These methods MUST NOT be called from outside the proto2 library. -These methods may contain hidden pitfalls and may be removed in a future library version. - | |
explicit | DescriptorPool(const DescriptorPool * underlay)Create a DescriptorPool which is overlaid on top of some other pool. more... |
void | DisallowEnforceUtf8()Disallow [[]enforce_utf8 = false] in .proto files. |
void | InternalDontEnforceDependencies()For internal use only: Changes the behavior of BuildFile() such that it allows the file to make reference to message types declared in other files which it did not officially declare as dependencies. |
void | InternalSetLazilyBuildDependencies()For internal use only: Enables lazy building of dependencies of a file. more... |
void | internal_set_underlay(const DescriptorPool * underlay)For internal use only. |
bool | InternalIsFileLoaded(ConstStringParam filename) constFor internal (unit test) use only: Returns true if a FileDescriptor has been constructed for the given file, false otherwise. more... |
void | AddUnusedImportTrackFile(ConstStringParam file_name, bool is_error = false)Add a file to unused_import_track_files_. more... |
void | ClearUnusedImportTrackFiles() |
static void | InternalAddGeneratedFile(const void * encoded_file_descriptor, int size)Called by generated classes at init time to add their descriptors to generated_pool. more... |
static DescriptorPool * | internal_generated_pool()For internal use only: Gets a non-const pointer to the generated pool. more... |
static DescriptorDatabase * | internal_generated_database()For internal use only: Gets a non-const pointer to the generated descriptor database. more... |
const FileDescriptor *
DescriptorPool::FindFileByName(
ConstStringParam name) constFind a FileDescriptor in the pool by file name.
Returns nullptr if not found.
-const FileDescriptor *
DescriptorPool::FindFileContainingSymbol(
ConstStringParam symbol_name) constFind the FileDescriptor in the pool which defines the given symbol.
If any of the Find*ByName() methods below would succeed, then this is equivalent to calling that method and calling the result's file() method. Otherwise this returns nullptr.
-static const DescriptorPool *
DescriptorPool::generated_pool()Get a pointer to the generated pool.
Generated protocol message classes which are compiled into the binary will allocate their descriptors in this pool. Do not add your own descriptors to this pool.
-const FieldDescriptor *
DescriptorPool::FindExtensionByNumber(
const Descriptor * extendee,
int number) constFinds an extension of the given type by number.
The extendee must be a member of this DescriptorPool or one of its underlays.
-const FieldDescriptor *
DescriptorPool::FindExtensionByPrintableName(
const Descriptor * extendee,
ConstStringParam printable_name) constFinds an extension of the given type by its printable name.
See comments above PrintableNameForExtension() for the definition of "printable name". The extendee must be a member of this DescriptorPool or one of its underlays. Returns nullptr if there is no known message extension with the given printable name.
-void DescriptorPool::FindAllExtensions(
const Descriptor * extendee,
std::vector< const FieldDescriptor * > * out) constFinds extensions of extendee.
The extensions will be appended to out in an undefined order. Only extensions defined directly in this DescriptorPool or one of its underlays are guaranteed to be found: extensions defined in the fallback database might not be found depending on the database implementation.
-const FileDescriptor *
DescriptorPool::BuildFile(
const FileDescriptorProto & proto)Convert the FileDescriptorProto to real descriptors and place them in this DescriptorPool.
All dependencies of the file must already be in the pool. Returns the resulting FileDescriptor, or nullptr if there were problems with the input (e.g. the message was invalid, or dependencies were missing). Details about the errors are written to GOOGLE_LOG(ERROR).
-void DescriptorPool::AllowUnknownDependencies()By default, it is an error if a FileDescriptorProto contains references to types or other files that are not found in the DescriptorPool (or its backing DescriptorDatabase, if any).
If you call AllowUnknownDependencies(), however, then unknown types and files will be replaced by placeholder descriptors (which can be identified by the is_placeholder() method). This can allow you to perform some useful operations with a .proto file even if you do not have access to other .proto files on which it depends. However, some heuristics must be used to fill in the gaps in information, and these can lead to descriptors which are inaccurate. For example, the DescriptorPool may be forced to guess whether an unknown type is a message or an enum, as well as what package it resides in. Furthermore, placeholder types will not be discoverable via FindMessageTypeByName() and similar methods, which could confuse some descriptor-based algorithms. Generally, the results of this option should be handled with extreme care.
-void DescriptorPool::EnforceWeakDependencies(
bool enforce)By default, weak imports are allowed to be missing, in which case we will use a placeholder for the dependency and convert the field to be an Empty message field.
If you call EnforceWeakDependencies(true), however, the DescriptorPool will report a import not found error.
-explicit DescriptorPool::DescriptorPool(
const DescriptorPool * underlay)Create a DescriptorPool which is overlaid on top of some other pool.
If you search for a descriptor in the overlay and it is not found, the underlay will be searched as a backup. If the underlay has its own underlay, that will be searched next, and so on. This also means that files built in the overlay will be cross-linked with the underlay's descriptors if necessary. The underlay remains property of the caller; it must remain valid for the lifetime of the newly-constructed pool.
-Example: Say you want to parse a .proto file at runtime in order to use its type with a DynamicMessage. Say this .proto file has dependencies, but you know that all the dependencies will be things that are already compiled into the binary. For ease of use, you'd like to load the types right out of generated_pool() rather than have to parse redundant copies of all these .protos and runtime. But, you don't want to add the parsed types directly into generated_pool(): this is not allowed, and would be bad design anyway. So, instead, you could use generated_pool() as an underlay for a new DescriptorPool in which you add only the new file.
-WARNING: Use of underlays can lead to many subtle gotchas. Instead, try to formulate what you want to do in terms of DescriptorDatabases.
-void DescriptorPool::InternalSetLazilyBuildDependencies()For internal use only: Enables lazy building of dependencies of a file.
Delay the building of dependencies of a file descriptor until absolutely necessary, like when message_type() is called on a field that is defined in that dependency's file. This will cause functional issues if a proto or one of its dependencies has errors. Should only be enabled for the generated_pool_ (because no descriptor build errors are guaranteed by the compilation generation process), testing, or if a lack of descriptor build errors can be guaranteed for a pool.
-bool DescriptorPool::InternalIsFileLoaded(
ConstStringParam filename) constFor internal (unit test) use only: Returns true if a FileDescriptor has been constructed for the given file, false otherwise.
Useful for testing lazy descriptor initialization behavior.
-void DescriptorPool::AddUnusedImportTrackFile(
ConstStringParam file_name,
bool is_error = false)Add a file to unused_import_track_files_.
DescriptorBuilder will log warnings or errors for those files if there is any unused import.
-static void DescriptorPool::InternalAddGeneratedFile(
const void * encoded_file_descriptor,
int size)Called by generated classes at init time to add their descriptors to generated_pool.
Do NOT call this in your own code! filename must be a permanent string (e.g. a string literal).
-static DescriptorPool * DescriptorPool::internal_generated_pool()For internal use only: Gets a non-const pointer to the generated pool.
This is called at static-initialization time only, so thread-safety is not a concern. If both an underlay and a fallback database are present, the underlay takes precedence.
-static DescriptorDatabase *
DescriptorPool::internal_generated_database()For internal use only: Gets a non-const pointer to the generated descriptor database.
Only used for testing.
-#include <google/protobuf/descriptor.h>
namespace google::protobuf
When converting a FileDescriptorProto to a FileDescriptor, various errors might be detected in the input.
The caller may handle these programmatically by implementing an ErrorCollector.
-Members | |
|---|---|
enum | ErrorLocationThese constants specify what exact part of the construct is broken. more... |
| ErrorCollector() |
virtual | ~ErrorCollector() |
virtual void | AddError(const std::string & filename, const std::string & element_name, const Message * descriptor, ErrorLocation location, const std::string & message) = 0Reports an error in the FileDescriptorProto. more... |
virtual void | AddWarning(const std::string & , const std::string & , const Message * , ErrorLocation , const std::string & )Reports a warning in the FileDescriptorProto. more... |
enum ErrorCollector::ErrorLocation {
NAME,
NUMBER,
TYPE,
EXTENDEE,
DEFAULT_VALUE,
INPUT_TYPE,
OUTPUT_TYPE,
OPTION_NAME,
OPTION_VALUE,
IMPORT,
OTHER
}These constants specify what exact part of the construct is broken.
This is useful e.g. for mapping the error back to an exact location in a .proto file.
-| NAME | the symbol name, or the package name for files |
| NUMBER | field or extension range number |
| TYPE | field type |
| EXTENDEE | field extendee |
| DEFAULT_VALUE | field default value |
| INPUT_TYPE | method input type |
| OUTPUT_TYPE | method output type |
| OPTION_NAME | name in assignment |
| OPTION_VALUE | value in option assignment |
| IMPORT | import error |
| OTHER | some other problem |
virtual void ErrorCollector::AddError(
const std::string & filename,
const std::string & element_name,
const Message * descriptor,
ErrorLocation location,
const std::string & message) = 0Reports an error in the FileDescriptorProto.
Use this function if the problem occurred should interrupt building the FileDescriptorProto.
-virtual void ErrorCollector::AddWarning(
const std::string & ,
const std::string & ,
const Message * ,
ErrorLocation ,
const std::string & )Reports a warning in the FileDescriptorProto.
Use this function if the problem occurred should NOT interrupt building the FileDescriptorProto.
-#include <google/protobuf/descriptor.pb.h>
namespace google::protobuf
Protocol buffer representations of descriptors.
This file defines a set of protocol message classes which represent the same information represented by the classes defined in descriptor.h. You can convert a FileDescriptorProto to a FileDescriptor using the DescriptorPool class. Thus, the classes in this file allow protocol type definitions to be communicated efficiently between processes.
- -The protocol compiler currently doesn't support auto-generated documentation, hence this page contains no descriptions. This file was generated by the protocol compiler from descriptor.proto, whose contents are as follows:
// 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.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// The messages in this file describe the definitions found in .proto files.
-// A valid .proto file can be translated directly to a FileDescriptorProto
-// without any other information (e.g. without reading its imports).
-
-syntax = "proto2";
-
-package google.protobuf;
-
-option go_package = "google.golang.org/protobuf/types/descriptorpb";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DescriptorProtos";
-option csharp_namespace = "Google.Protobuf.Reflection";
-option objc_class_prefix = "GPB";
-option cc_enable_arenas = true;
-
-// descriptor.proto must be optimized for speed because reflection-based
-// algorithms don't work during bootstrapping.
-option optimize_for = SPEED;
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-message FileDescriptorSet {
- repeated FileDescriptorProto file = 1;
-}
-
-// Describes a complete .proto file.
-message FileDescriptorProto {
- optional string name = 1; // file name, relative to root of source tree
- optional string package = 2; // e.g. "foo", "foo.bar", etc.
-
- // Names of files imported by this file.
- repeated string dependency = 3;
- // Indexes of the public imported files in the dependency list above.
- repeated int32 public_dependency = 10;
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- repeated int32 weak_dependency = 11;
-
- // All top-level definitions in this file.
- repeated DescriptorProto message_type = 4;
- repeated EnumDescriptorProto enum_type = 5;
- repeated ServiceDescriptorProto service = 6;
- repeated FieldDescriptorProto extension = 7;
-
- optional FileOptions options = 8;
-
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- optional SourceCodeInfo source_code_info = 9;
-
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- optional string syntax = 12;
-}
-
-// Describes a message type.
-message DescriptorProto {
- optional string name = 1;
-
- repeated FieldDescriptorProto field = 2;
- repeated FieldDescriptorProto extension = 6;
-
- repeated DescriptorProto nested_type = 3;
- repeated EnumDescriptorProto enum_type = 4;
-
- message ExtensionRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Exclusive.
-
-optional ExtensionRangeOptions options = 3;
-
- }
- repeated ExtensionRange extension_range = 5;
-
- repeated OneofDescriptorProto oneof_decl = 8;
-
- optional MessageOptions options = 7;
-
- // Range of reserved tag numbers. Reserved tag numbers may not be used by
- // fields or extension ranges in the same message. Reserved ranges may
- // not overlap.
- message ReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Exclusive.
- }
- repeated ReservedRange reserved_range = 9;
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- repeated string reserved_name = 10;
-}
-
-message ExtensionRangeOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-// Describes a field within a message.
-message FieldDescriptorProto {
- enum Type {
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- TYPE_DOUBLE = 1;
- TYPE_FLOAT = 2;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- TYPE_INT64 = 3;
- TYPE_UINT64 = 4;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- TYPE_INT32 = 5;
- TYPE_FIXED64 = 6;
- TYPE_FIXED32 = 7;
- TYPE_BOOL = 8;
- TYPE_STRING = 9;
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- TYPE_GROUP = 10;
- TYPE_MESSAGE = 11; // Length-delimited aggregate.
-
-// New in version 2.
-TYPE_BYTES = 12;
-TYPE_UINT32 = 13;
-TYPE_ENUM = 14;
-TYPE_SFIXED32 = 15;
-TYPE_SFIXED64 = 16;
-TYPE_SINT32 = 17; // Uses ZigZag encoding.
-TYPE_SINT64 = 18; // Uses ZigZag encoding.
-
- }
-
- enum Label {
- // 0 is reserved for errors
- LABEL_OPTIONAL = 1;
- LABEL_REQUIRED = 2;
- LABEL_REPEATED = 3;
- }
-
- optional string name = 1;
- optional int32 number = 3;
- optional Label label = 4;
-
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- optional Type type = 5;
-
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- optional string type_name = 6;
-
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- optional string extendee = 2;
-
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- optional string default_value = 7;
-
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- optional int32 oneof_index = 9;
-
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- optional string json_name = 10;
-
- optional FieldOptions options = 8;
-
- // If true, this is a proto3 "optional". When a proto3 field is optional, it
- // tracks presence regardless of field type.
- //
- // When proto3_optional is true, this field must be belong to a oneof to
- // signal to old proto3 clients that presence is tracked for this field. This
- // oneof is known as a "synthetic" oneof, and this field must be its sole
- // member (each proto3 optional field gets its own synthetic oneof). Synthetic
- // oneofs exist in the descriptor only, and do not generate any API. Synthetic
- // oneofs must be ordered after all "real" oneofs.
- //
- // For message fields, proto3_optional doesn't create any semantic change,
- // since non-repeated message fields always track presence. However it still
- // indicates the semantic detail of whether the user wrote "optional" or not.
- // This can be useful for round-tripping the .proto file. For consistency we
- // give message fields a synthetic oneof also, even though it is not required
- // to track presence. This is especially important because the parser can't
- // tell if a field is a message or an enum, so it must always create a
- // synthetic oneof.
- //
- // Proto2 optional fields do not set this flag, because they already indicate
- // optional with `LABEL_OPTIONAL`.
- optional bool proto3_optional = 17;
-}
-
-// Describes a oneof.
-message OneofDescriptorProto {
- optional string name = 1;
- optional OneofOptions options = 2;
-}
-
-// Describes an enum type.
-message EnumDescriptorProto {
- optional string name = 1;
-
- repeated EnumValueDescriptorProto value = 2;
-
- optional EnumOptions options = 3;
-
- // Range of reserved numeric values. Reserved values may not be used by
- // entries in the same enum. Reserved ranges may not overlap.
- //
- // Note that this is distinct from DescriptorProto.ReservedRange in that it
- // is inclusive such that it can appropriately represent the entire int32
- // domain.
- message EnumReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Inclusive.
- }
-
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- repeated EnumReservedRange reserved_range = 4;
-
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- repeated string reserved_name = 5;
-}
-
-// Describes a value within an enum.
-message EnumValueDescriptorProto {
- optional string name = 1;
- optional int32 number = 2;
-
- optional EnumValueOptions options = 3;
-}
-
-// Describes a service.
-message ServiceDescriptorProto {
- optional string name = 1;
- repeated MethodDescriptorProto method = 2;
-
- optional ServiceOptions options = 3;
-}
-
-// Describes a method of a service.
-message MethodDescriptorProto {
- optional string name = 1;
-
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- optional string input_type = 2;
- optional string output_type = 3;
-
- optional MethodOptions options = 4;
-
- // Identifies if client streams multiple client messages
- optional bool client_streaming = 5 [default = false];
- // Identifies if server streams multiple server messages
- optional bool server_streaming = 6 [default = false];
-}
-
-// ===================================================================
-// Options
-
-// Each of the definitions above may have "options" attached. These are
-// just annotations which may cause code to be generated slightly differently
-// or may contain hints for code that manipulates protocol messages.
-//
-// Clients may define custom options as extensions of the *Options messages.
-// These extensions may not yet be known at parsing time, so the parser cannot
-// store the values in them. Instead it stores them in a field in the *Options
-// message called uninterpreted_option. This field must have the same name
-// across all *Options messages. We then use this field to populate the
-// extensions when we build a descriptor, at which point all protos have been
-// parsed and so all extensions are known.
-//
-// Extension numbers for custom options may be chosen as follows:
-// * For options which will only be used within a single application or
-// organization, or for experimental options, use field numbers 50000
-// through 99999. It is up to you to ensure that you do not use the
-// same number for multiple options.
-// * For options which will be published and used publicly by multiple
-// independent entities, e-mail protobuf-global-extension-registry@google.com
-// to reserve extension numbers. Simply provide your project name (e.g.
-// Objective-C plugin) and your project website (if available) -- there's no
-// need to explain how you intend to use them. Usually you only need one
-// extension number. You can declare multiple options with only one extension
-// number by putting them in a sub-message. See the Custom Options section of
-// the docs for examples:
-// /programming-guides/proto#options
-// If this turns out to be popular, a web service will be set up
-// to automatically assign option numbers.
-
-message FileOptions {
-
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- optional string java_package = 1;
-
- // Controls the name of the wrapper Java class generated for the .proto file.
- // That class will always contain the .proto file's getDescriptor() method as
- // well as any top-level extensions defined in the .proto file.
- // If java_multiple_files is disabled, then all the other classes from the
- // .proto file will be nested inside the single wrapper outer class.
- optional string java_outer_classname = 8;
-
- // If enabled, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the wrapper class
- // named by java_outer_classname. However, the wrapper class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- optional bool java_multiple_files = 10 [default = false];
-
- // This option does nothing.
- optional bool java_generate_equals_and_hash = 20 [deprecated=true];
-
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- optional bool java_string_check_utf8 = 27 [default = false];
-
- // Generated classes can be optimized for speed or code size.
- enum OptimizeMode {
- SPEED = 1; // Generate complete code for parsing, serialization,
- // etc.
- CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
- LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
- }
- optional OptimizeMode optimize_for = 9 [default = SPEED];
-
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- optional string go_package = 11;
-
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- optional bool cc_generic_services = 16 [default = false];
- optional bool java_generic_services = 17 [default = false];
- optional bool py_generic_services = 18 [default = false];
- optional bool php_generic_services = 42 [default = false];
-
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- optional bool deprecated = 23 [default = false];
-
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- optional bool cc_enable_arenas = 31 [default = true];
-
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- optional string objc_class_prefix = 36;
-
- // Namespace for generated classes; defaults to the package.
- optional string csharp_namespace = 37;
-
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- optional string swift_prefix = 39;
-
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- optional string php_class_prefix = 40;
-
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- optional string php_namespace = 41;
-
- // Use this option to change the namespace of php generated metadata classes.
- // Default is empty. When this option is empty, the proto file name will be
- // used for determining the namespace.
- optional string php_metadata_namespace = 44;
-
- // Use this option to change the package of ruby generated classes. Default
- // is empty. When this option is not set, the package name will be used for
- // determining the ruby package.
- optional string ruby_package = 45;
-
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message.
- // See the documentation for the "Options" section above.
- extensions 1000 to max;
-
- reserved 38;
-}
-
-message MessageOptions {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- optional bool message_set_wire_format = 1 [default = false];
-
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- optional bool no_standard_descriptor_accessor = 2 [default = false];
-
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- optional bool deprecated = 3 [default = false];
-
- reserved 4, 5, 6;
-
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map<KeyType, ValueType> map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementations still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- optional bool map_entry = 7;
-
- reserved 8; // javalite_serializable
- reserved 9; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message FieldOptions {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- optional CType ctype = 1 [default = STRING];
- enum CType {
- // Default mode.
- STRING = 0;
-
-CORD = 1;
-
-STRING_PIECE = 2;
-
- }
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- optional bool packed = 2;
-
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- optional JSType jstype = 6 [default = JS_NORMAL];
- enum JSType {
- // Use the default type.
- JS_NORMAL = 0;
-
-// Use JavaScript strings.
-JS_STRING = 1;
-
-// Use JavaScript numbers.
-JS_NUMBER = 2;
-
- }
-
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- optional bool lazy = 5 [default = false];
-
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- optional bool deprecated = 3 [default = false];
-
- // For Google-internal migration only. Do not use.
- optional bool weak = 10 [default = false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-
- reserved 4; // removed jtype
-}
-
-message OneofOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumOptions {
-
- // Set this option to true to allow mapping different tag names to the same
- // value.
- optional bool allow_alias = 2;
-
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- optional bool deprecated = 3 [default = false];
-
- reserved 5; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumValueOptions {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- optional bool deprecated = 1 [default = false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message ServiceOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- optional bool deprecated = 33 [default = false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message MethodOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- optional bool deprecated = 33 [default = false];
-
- // Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
- // or neither? HTTP based RPC implementation may choose GET verb for safe
- // methods, and PUT verb for idempotent methods instead of the default POST.
- enum IdempotencyLevel {
- IDEMPOTENCY_UNKNOWN = 0;
- NO_SIDE_EFFECTS = 1; // implies idempotent
- IDEMPOTENT = 2; // idempotent, but may have side effects
- }
- optional IdempotencyLevel idempotency_level = 34
- [default = IDEMPOTENCY_UNKNOWN];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-message UninterpretedOption {
- // The name of the uninterpreted option. Each string represents a segment in
- // a dot-separated name. is_extension is true iff a segment represents an
- // extension (denoted with parentheses in options specs in .proto files).
- // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
- // "foo.(bar.baz).qux".
- message NamePart {
- required string name_part = 1;
- required bool is_extension = 2;
- }
- repeated NamePart name = 2;
-
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- optional string identifier_value = 3;
- optional uint64 positive_int_value = 4;
- optional int64 negative_int_value = 5;
- optional double double_value = 6;
- optional bytes string_value = 7;
- optional string aggregate_value = 8;
-}
-
-// ===================================================================
-// Optional source code info
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-message SourceCodeInfo {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendant. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- repeated Location location = 1;
- message Location {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- repeated int32 path = 1 [packed = true];
-
-// Always has exactly three or four elements: start line, start column,
-// end line (optional, otherwise assumed same as start line), end column.
-// These are packed into a single field for efficiency. Note that line
-// and column numbers are zero-based -- typically you will want to add
-// 1 to each before displaying to a user.
-repeated int32 span = 2 [packed = true];
-
-// If this SourceCodeInfo represents a complete declaration, these are any
-// comments appearing before and after the declaration which appear to be
-// attached to the declaration.
-//
-// A series of line comments appearing on consecutive lines, with no other
-// tokens appearing on those lines, will be treated as a single comment.
-//
-// leading_detached_comments will keep paragraphs of comments that appear
-// before (but not connected to) the current element. Each paragraph,
-// separated by empty lines, will be one comment element in the repeated
-// field.
-//
-// Only the comment content is provided; comment markers (e.g. //) are
-// stripped out. For block comments, leading whitespace and an asterisk
-// will be stripped from the beginning of each line other than the first.
-// Newlines are included in the output.
-//
-// Examples:
-//
-// optional int32 foo = 1; // Comment attached to foo.
-// // Comment attached to bar.
-// optional int32 bar = 2;
-//
-// optional string baz = 3;
-// // Comment attached to baz.
-// // Another line attached to baz.
-//
-// // Comment attached to qux.
-// //
-// // Another line attached to qux.
-// optional double qux = 4;
-//
-// // Detached comment for corge. This is not leading or trailing comments
-// // to qux or corge because there are blank lines separating it from
-// // both.
-//
-// // Detached comment for corge paragraph 2.
-//
-// optional string corge = 5;
-// /* Block comment attached
-// * to corge. Leading asterisks
-// * will be removed. */ // /* Block comment attached to
-// * grault. */
-// optional int32 grault = 6;
-//
-// // ignored detached comments.
-optional string leading_comments = 3;
-optional string trailing_comments = 4;
-repeated string leading_detached_comments = 6;
-
- }
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-message GeneratedCodeInfo {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- repeated Annotation annotation = 1;
- message Annotation {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- repeated int32 path = 1 [packed = true];
-
-// Identifies the filesystem path to the original source .proto.
-optional string source_file = 2;
-
-// Identifies the starting offset in bytes in the generated code
-// that relates to the identified object.
-optional int32 begin = 3;
-
-// Identifies the ending offset in bytes in the generated code that
-// relates to the identified offset. The end offset should be one past
-// the last relevant byte (so the length of the text = end - begin).
-optional int32 end = 4;
-
- }
-}
-Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
enum | FieldDescriptorProto_Type |
enum | FieldDescriptorProto_Label |
enum | FileOptions_OptimizeMode |
enum | FieldOptions_CType |
enum | FieldOptions_JSType |
enum | MethodOptions_IdempotencyLevel |
const ::protobuf::internal::DescriptorTable | descriptor_table_google_2fprotobuf_2fdescriptor_2eproto |
DescriptorProtoDefaultTypeInternal | _DescriptorProto_default_instance_ |
DescriptorProto_ExtensionRangeDefaultTypeInternal | _DescriptorProto_ExtensionRange_default_instance_ |
DescriptorProto_ReservedRangeDefaultTypeInternal | _DescriptorProto_ReservedRange_default_instance_ |
EnumDescriptorProtoDefaultTypeInternal | _EnumDescriptorProto_default_instance_ |
EnumDescriptorProto_EnumReservedRangeDefaultTypeInternal | _EnumDescriptorProto_EnumReservedRange_default_instance_ |
EnumOptionsDefaultTypeInternal | _EnumOptions_default_instance_ |
EnumValueDescriptorProtoDefaultTypeInternal | _EnumValueDescriptorProto_default_instance_ |
EnumValueOptionsDefaultTypeInternal | _EnumValueOptions_default_instance_ |
ExtensionRangeOptionsDefaultTypeInternal | _ExtensionRangeOptions_default_instance_ |
FieldDescriptorProtoDefaultTypeInternal | _FieldDescriptorProto_default_instance_ |
FieldOptionsDefaultTypeInternal | _FieldOptions_default_instance_ |
FileDescriptorProtoDefaultTypeInternal | _FileDescriptorProto_default_instance_ |
FileDescriptorSetDefaultTypeInternal | _FileDescriptorSet_default_instance_ |
FileOptionsDefaultTypeInternal | _FileOptions_default_instance_ |
GeneratedCodeInfoDefaultTypeInternal | _GeneratedCodeInfo_default_instance_ |
GeneratedCodeInfo_AnnotationDefaultTypeInternal | _GeneratedCodeInfo_Annotation_default_instance_ |
MessageOptionsDefaultTypeInternal | _MessageOptions_default_instance_ |
MethodDescriptorProtoDefaultTypeInternal | _MethodDescriptorProto_default_instance_ |
MethodOptionsDefaultTypeInternal | _MethodOptions_default_instance_ |
OneofDescriptorProtoDefaultTypeInternal | _OneofDescriptorProto_default_instance_ |
OneofOptionsDefaultTypeInternal | _OneofOptions_default_instance_ |
ServiceDescriptorProtoDefaultTypeInternal | _ServiceDescriptorProto_default_instance_ |
ServiceOptionsDefaultTypeInternal | _ServiceOptions_default_instance_ |
SourceCodeInfoDefaultTypeInternal | _SourceCodeInfo_default_instance_ |
SourceCodeInfo_LocationDefaultTypeInternal | _SourceCodeInfo_Location_default_instance_ |
UninterpretedOptionDefaultTypeInternal | _UninterpretedOption_default_instance_ |
UninterpretedOption_NamePartDefaultTypeInternal | _UninterpretedOption_NamePart_default_instance_ |
constexpr FieldDescriptorProto_Type | FieldDescriptorProto_Type_Type_MIN = = FieldDescriptorProto_Type_TYPE_DOUBLE |
constexpr FieldDescriptorProto_Type | FieldDescriptorProto_Type_Type_MAX = = FieldDescriptorProto_Type_TYPE_SINT64 |
constexpr int | FieldDescriptorProto_Type_Type_ARRAYSIZE = = FieldDescriptorProto_Type_Type_MAX + 1 |
constexpr FieldDescriptorProto_Label | FieldDescriptorProto_Label_Label_MIN = = FieldDescriptorProto_Label_LABEL_OPTIONAL |
constexpr FieldDescriptorProto_Label | FieldDescriptorProto_Label_Label_MAX = = FieldDescriptorProto_Label_LABEL_REPEATED |
constexpr int | FieldDescriptorProto_Label_Label_ARRAYSIZE = = FieldDescriptorProto_Label_Label_MAX + 1 |
constexpr FileOptions_OptimizeMode | FileOptions_OptimizeMode_OptimizeMode_MIN = = FileOptions_OptimizeMode_SPEED |
constexpr FileOptions_OptimizeMode | FileOptions_OptimizeMode_OptimizeMode_MAX = = FileOptions_OptimizeMode_LITE_RUNTIME |
constexpr int | FileOptions_OptimizeMode_OptimizeMode_ARRAYSIZE = = FileOptions_OptimizeMode_OptimizeMode_MAX + 1 |
constexpr FieldOptions_CType | FieldOptions_CType_CType_MIN = = FieldOptions_CType_STRING |
constexpr FieldOptions_CType | FieldOptions_CType_CType_MAX = = FieldOptions_CType_STRING_PIECE |
constexpr int | FieldOptions_CType_CType_ARRAYSIZE = = FieldOptions_CType_CType_MAX + 1 |
constexpr FieldOptions_JSType | FieldOptions_JSType_JSType_MIN = = FieldOptions_JSType_JS_NORMAL |
constexpr FieldOptions_JSType | FieldOptions_JSType_JSType_MAX = = FieldOptions_JSType_JS_NUMBER |
constexpr int | FieldOptions_JSType_JSType_ARRAYSIZE = = FieldOptions_JSType_JSType_MAX + 1 |
constexpr MethodOptions_IdempotencyLevel | MethodOptions_IdempotencyLevel_IdempotencyLevel_MIN = = MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN |
constexpr MethodOptions_IdempotencyLevel | MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX = = MethodOptions_IdempotencyLevel_IDEMPOTENT |
constexpr int | MethodOptions_IdempotencyLevel_IdempotencyLevel_ARRAYSIZE = = MethodOptions_IdempotencyLevel_IdempotencyLevel_MAX + 1 |
PROTOBUF_NAMESPACE_CLOSE PROTOBUF_NAMESPACE_OPEN protobuf::DescriptorProto * | Arena::CreateMaybeMessage< protobuf::DescriptorProto >(Arena * ) |
protobuf::DescriptorProto_ExtensionRange * | Arena::CreateMaybeMessage< protobuf::DescriptorProto_ExtensionRange >(Arena * ) |
protobuf::DescriptorProto_ReservedRange * | Arena::CreateMaybeMessage< protobuf::DescriptorProto_ReservedRange >(Arena * ) |
protobuf::EnumDescriptorProto * | Arena::CreateMaybeMessage< protobuf::EnumDescriptorProto >(Arena * ) |
protobuf::EnumDescriptorProto_EnumReservedRange * | Arena::CreateMaybeMessage< protobuf::EnumDescriptorProto_EnumReservedRange >(Arena * ) |
protobuf::EnumOptions * | Arena::CreateMaybeMessage< protobuf::EnumOptions >(Arena * ) |
protobuf::EnumValueDescriptorProto * | Arena::CreateMaybeMessage< protobuf::EnumValueDescriptorProto >(Arena * ) |
protobuf::EnumValueOptions * | Arena::CreateMaybeMessage< protobuf::EnumValueOptions >(Arena * ) |
protobuf::ExtensionRangeOptions * | Arena::CreateMaybeMessage< protobuf::ExtensionRangeOptions >(Arena * ) |
protobuf::FieldDescriptorProto * | Arena::CreateMaybeMessage< protobuf::FieldDescriptorProto >(Arena * ) |
protobuf::FieldOptions * | Arena::CreateMaybeMessage< protobuf::FieldOptions >(Arena * ) |
protobuf::FileDescriptorProto * | Arena::CreateMaybeMessage< protobuf::FileDescriptorProto >(Arena * ) |
protobuf::FileDescriptorSet * | Arena::CreateMaybeMessage< protobuf::FileDescriptorSet >(Arena * ) |
protobuf::FileOptions * | Arena::CreateMaybeMessage< protobuf::FileOptions >(Arena * ) |
protobuf::GeneratedCodeInfo * | Arena::CreateMaybeMessage< protobuf::GeneratedCodeInfo >(Arena * ) |
protobuf::GeneratedCodeInfo_Annotation * | Arena::CreateMaybeMessage< protobuf::GeneratedCodeInfo_Annotation >(Arena * ) |
protobuf::MessageOptions * | Arena::CreateMaybeMessage< protobuf::MessageOptions >(Arena * ) |
protobuf::MethodDescriptorProto * | Arena::CreateMaybeMessage< protobuf::MethodDescriptorProto >(Arena * ) |
protobuf::MethodOptions * | Arena::CreateMaybeMessage< protobuf::MethodOptions >(Arena * ) |
protobuf::OneofDescriptorProto * | Arena::CreateMaybeMessage< protobuf::OneofDescriptorProto >(Arena * ) |
protobuf::OneofOptions * | Arena::CreateMaybeMessage< protobuf::OneofOptions >(Arena * ) |
protobuf::ServiceDescriptorProto * | Arena::CreateMaybeMessage< protobuf::ServiceDescriptorProto >(Arena * ) |
protobuf::ServiceOptions * | Arena::CreateMaybeMessage< protobuf::ServiceOptions >(Arena * ) |
protobuf::SourceCodeInfo * | Arena::CreateMaybeMessage< protobuf::SourceCodeInfo >(Arena * ) |
protobuf::SourceCodeInfo_Location * | Arena::CreateMaybeMessage< protobuf::SourceCodeInfo_Location >(Arena * ) |
protobuf::UninterpretedOption * | Arena::CreateMaybeMessage< protobuf::UninterpretedOption >(Arena * ) |
protobuf::UninterpretedOption_NamePart * | Arena::CreateMaybeMessage< protobuf::UninterpretedOption_NamePart >(Arena * ) |
bool | FieldDescriptorProto_Type_IsValid(int value) |
const ::protobuf::EnumDescriptor * | FieldDescriptorProto_Type_descriptor() |
template const std::string & | FieldDescriptorProto_Type_Name(T enum_t_value) |
bool | FieldDescriptorProto_Type_Parse(::protobuf::ConstStringParam name, FieldDescriptorProto_Type * value) |
bool | FieldDescriptorProto_Label_IsValid(int value) |
const ::protobuf::EnumDescriptor * | FieldDescriptorProto_Label_descriptor() |
template const std::string & | FieldDescriptorProto_Label_Name(T enum_t_value) |
bool | FieldDescriptorProto_Label_Parse(::protobuf::ConstStringParam name, FieldDescriptorProto_Label * value) |
bool | FileOptions_OptimizeMode_IsValid(int value) |
const ::protobuf::EnumDescriptor * | FileOptions_OptimizeMode_descriptor() |
template const std::string & | FileOptions_OptimizeMode_Name(T enum_t_value) |
bool | FileOptions_OptimizeMode_Parse(::protobuf::ConstStringParam name, FileOptions_OptimizeMode * value) |
bool | FieldOptions_CType_IsValid(int value) |
const ::protobuf::EnumDescriptor * | FieldOptions_CType_descriptor() |
template const std::string & | FieldOptions_CType_Name(T enum_t_value) |
bool | FieldOptions_CType_Parse(::protobuf::ConstStringParam name, FieldOptions_CType * value) |
bool | FieldOptions_JSType_IsValid(int value) |
const ::protobuf::EnumDescriptor * | FieldOptions_JSType_descriptor() |
template const std::string & | FieldOptions_JSType_Name(T enum_t_value) |
bool | FieldOptions_JSType_Parse(::protobuf::ConstStringParam name, FieldOptions_JSType * value) |
bool | MethodOptions_IdempotencyLevel_IsValid(int value) |
const ::protobuf::EnumDescriptor * | MethodOptions_IdempotencyLevel_descriptor() |
template const std::string & | MethodOptions_IdempotencyLevel_Name(T enum_t_value) |
bool | MethodOptions_IdempotencyLevel_Parse(::protobuf::ConstStringParam name, MethodOptions_IdempotencyLevel * value) |
const EnumDescriptor * | GetEnumDescriptor< protobuf::FieldDescriptorProto_Type >() |
const EnumDescriptor * | GetEnumDescriptor< protobuf::FieldDescriptorProto_Label >() |
const EnumDescriptor * | GetEnumDescriptor< protobuf::FileOptions_OptimizeMode >() |
const EnumDescriptor * | GetEnumDescriptor< protobuf::FieldOptions_CType >() |
const EnumDescriptor * | GetEnumDescriptor< protobuf::FieldOptions_JSType >() |
const EnumDescriptor * | GetEnumDescriptor< protobuf::MethodOptions_IdempotencyLevel >() |
enum protobuf::FieldDescriptorProto_Type {
FieldDescriptorProto_Type_TYPE_DOUBLE = = 1,
FieldDescriptorProto_Type_TYPE_FLOAT = = 2,
FieldDescriptorProto_Type_TYPE_INT64 = = 3,
FieldDescriptorProto_Type_TYPE_UINT64 = = 4,
FieldDescriptorProto_Type_TYPE_INT32 = = 5,
FieldDescriptorProto_Type_TYPE_FIXED64 = = 6,
FieldDescriptorProto_Type_TYPE_FIXED32 = = 7,
FieldDescriptorProto_Type_TYPE_BOOL = = 8,
FieldDescriptorProto_Type_TYPE_STRING = = 9,
FieldDescriptorProto_Type_TYPE_GROUP = = 10,
FieldDescriptorProto_Type_TYPE_MESSAGE = = 11,
FieldDescriptorProto_Type_TYPE_BYTES = = 12,
FieldDescriptorProto_Type_TYPE_UINT32 = = 13,
FieldDescriptorProto_Type_TYPE_ENUM = = 14,
FieldDescriptorProto_Type_TYPE_SFIXED32 = = 15,
FieldDescriptorProto_Type_TYPE_SFIXED64 = = 16,
FieldDescriptorProto_Type_TYPE_SINT32 = = 17,
FieldDescriptorProto_Type_TYPE_SINT64 = = 18
}| FieldDescriptorProto_Type_TYPE_DOUBLE | |
| FieldDescriptorProto_Type_TYPE_FLOAT | |
| FieldDescriptorProto_Type_TYPE_INT64 | |
| FieldDescriptorProto_Type_TYPE_UINT64 | |
| FieldDescriptorProto_Type_TYPE_INT32 | |
| FieldDescriptorProto_Type_TYPE_FIXED64 | |
| FieldDescriptorProto_Type_TYPE_FIXED32 | |
| FieldDescriptorProto_Type_TYPE_BOOL | |
| FieldDescriptorProto_Type_TYPE_STRING | |
| FieldDescriptorProto_Type_TYPE_GROUP | |
| FieldDescriptorProto_Type_TYPE_MESSAGE | |
| FieldDescriptorProto_Type_TYPE_BYTES | |
| FieldDescriptorProto_Type_TYPE_UINT32 | |
| FieldDescriptorProto_Type_TYPE_ENUM | |
| FieldDescriptorProto_Type_TYPE_SFIXED32 | |
| FieldDescriptorProto_Type_TYPE_SFIXED64 | |
| FieldDescriptorProto_Type_TYPE_SINT32 | |
| FieldDescriptorProto_Type_TYPE_SINT64 |
enum protobuf::FieldDescriptorProto_Label {
FieldDescriptorProto_Label_LABEL_OPTIONAL = = 1,
FieldDescriptorProto_Label_LABEL_REQUIRED = = 2,
FieldDescriptorProto_Label_LABEL_REPEATED = = 3
}| FieldDescriptorProto_Label_LABEL_OPTIONAL | |
| FieldDescriptorProto_Label_LABEL_REQUIRED | |
| FieldDescriptorProto_Label_LABEL_REPEATED |
enum protobuf::FileOptions_OptimizeMode {
FileOptions_OptimizeMode_SPEED = = 1,
FileOptions_OptimizeMode_CODE_SIZE = = 2,
FileOptions_OptimizeMode_LITE_RUNTIME = = 3
}| FileOptions_OptimizeMode_SPEED | |
| FileOptions_OptimizeMode_CODE_SIZE | |
| FileOptions_OptimizeMode_LITE_RUNTIME |
enum protobuf::FieldOptions_CType {
FieldOptions_CType_STRING = = 0,
FieldOptions_CType_CORD = = 1,
FieldOptions_CType_STRING_PIECE = = 2
}| FieldOptions_CType_STRING | |
| FieldOptions_CType_CORD | |
| FieldOptions_CType_STRING_PIECE |
enum protobuf::FieldOptions_JSType {
FieldOptions_JSType_JS_NORMAL = = 0,
FieldOptions_JSType_JS_STRING = = 1,
FieldOptions_JSType_JS_NUMBER = = 2
}| FieldOptions_JSType_JS_NORMAL | |
| FieldOptions_JSType_JS_STRING | |
| FieldOptions_JSType_JS_NUMBER |
enum protobuf::MethodOptions_IdempotencyLevel {
MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN = = 0,
MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS = = 1,
MethodOptions_IdempotencyLevel_IDEMPOTENT = = 2
}| MethodOptions_IdempotencyLevel_IDEMPOTENCY_UNKNOWN | |
| MethodOptions_IdempotencyLevel_NO_SIDE_EFFECTS | |
| MethodOptions_IdempotencyLevel_IDEMPOTENT |
#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
Interface for manipulating databases of descriptors.
Classes in this file | |
|---|---|
Abstract interface for a database of descriptors. | |
A DescriptorDatabase into which you can insert files manually. | |
Very similar to SimpleDescriptorDatabase, but stores all the descriptors as raw bytes and generally tries to use as little memory as possible. | |
A DescriptorDatabase that fetches files from a given pool. | |
A DescriptorDatabase that wraps two or more others. | |
#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
Abstract interface for a database of descriptors.
This is useful if you want to create a DescriptorPool which loads descriptors on-demand from some sort of large database. If the database is large, it may be inefficient to enumerate every .proto file inside it calling DescriptorPool::BuildFile() for each one. Instead, a DescriptorPool can be created which wraps a DescriptorDatabase and only builds particular descriptors when they are needed.
- -Known subclasses:
DescriptorPoolDatabaseEncodedDescriptorDatabaseMergedDescriptorDatabaseSimpleDescriptorDatabaseSourceTreeDescriptorDatabaseMembers | |
|---|---|
| DescriptorDatabase() |
virtual | ~DescriptorDatabase() |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output) = 0Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output) = 0Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output) = 0Find the file which defines an extension extending the given message type with the given field number. more... |
virtual bool | FindAllExtensionNumbers(const std::string & , std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order. more... |
virtual bool | FindAllFileNames(std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order. more... |
bool | FindAllPackageNames(std::vector< std::string > * output)Finds the package names and appends them to the output in an undefined order. more... |
bool | FindAllMessageNames(std::vector< std::string > * output)Finds the message names and appends them to the output in an undefined order. more... |
virtual bool DescriptorDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output) = 0Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool DescriptorDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output) = 0Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool DescriptorDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output) = 0Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-virtual bool DescriptorDatabase::FindAllExtensionNumbers(
const std::string & ,
std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all extensions, and it's not guaranteed that FindFileContainingExtension will return true on all of the found numbers. Returns true if the search was successful, otherwise returns false and leaves output unchanged.
- -This method has a default implementation that always returns false.
-virtual bool DescriptorDatabase::FindAllFileNames(
std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all files. Returns true if the database supports searching all file names, otherwise returns false and leaves output unchanged.
- -This method has a default implementation that always returns false.
-bool DescriptorDatabase::FindAllPackageNames(
std::vector< std::string > * output)Finds the package names and appends them to the output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all packages. Returns true if the database supports searching all package names, otherwise returns false and leaves output unchanged.
-bool DescriptorDatabase::FindAllMessageNames(
std::vector< std::string > * output)Finds the message names and appends them to the output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all messages. Returns true if the database supports searching all message names, otherwise returns false and leaves output unchanged.
-#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
A DescriptorDatabase into which you can insert files manually.
FindFileContainingSymbol() is fully-implemented. When you add a file, its symbols will be indexed for this purpose. Note that the implementation may return false positives, but only if it isn't possible for the symbol to be defined in any other file. In particular, if a file defines a symbol "Foo", then searching for "Foo.[anything]" will match that file. This way, the database does not need to aggressively index all children of a symbol.
- -FindFileContainingExtension() is mostly-implemented. It works if and only if the original FieldDescriptorProto defining the extension has a fully-qualified type name in its "extendee" field (i.e. starts with a '.'). If the extendee is a relative name, SimpleDescriptorDatabase will not attempt to resolve the type, so it will not know what type the extension is extending. Therefore, calling FindFileContainingExtension() with the extension's containing type will never actually find that extension. Note that this is an unlikely problem, as all FileDescriptorProtos created by the protocol compiler (as well as ones created by calling FileDescriptor::CopyTo()) will always use fully-qualified names for all types. You only need to worry if you are constructing FileDescriptorProtos yourself, or are calling compiler::Parser directly.
- -Members | |
|---|---|
| SimpleDescriptorDatabase() |
| ~SimpleDescriptorDatabase() |
bool | Add(const FileDescriptorProto & file)Adds the FileDescriptorProto to the database, making a copy. more... |
bool | AddAndOwn(const FileDescriptorProto * file)Adds the FileDescriptorProto to the database and takes ownership of it. |
implements DescriptorDatabase | |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output)Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number. more... |
virtual bool | FindAllExtensionNumbers(const std::string & , std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order. more... |
virtual bool | FindAllFileNames(std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order. more... |
bool SimpleDescriptorDatabase::Add(
const FileDescriptorProto & file)Adds the FileDescriptorProto to the database, making a copy.
The object can be deleted after Add() returns. Returns false if the file conflicted with a file already in the database, in which case an error will have been written to GOOGLE_LOG(ERROR).
-virtual bool SimpleDescriptorDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output)Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool SimpleDescriptorDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool SimpleDescriptorDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-virtual bool SimpleDescriptorDatabase::FindAllExtensionNumbers(
const std::string & ,
std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all extensions, and it's not guaranteed that FindFileContainingExtension will return true on all of the found numbers. Returns true if the search was successful, otherwise returns false and leaves output unchanged.
-This method has a default implementation that always returns false.
-virtual bool SimpleDescriptorDatabase::FindAllFileNames(
std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all files. Returns true if the database supports searching all file names, otherwise returns false and leaves output unchanged.
-This method has a default implementation that always returns false.
-#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
Very similar to SimpleDescriptorDatabase, but stores all the descriptors as raw bytes and generally tries to use as little memory as possible.
The same caveats regarding FindFileContainingExtension() apply as with SimpleDescriptorDatabase.
-Members | |
|---|---|
| EncodedDescriptorDatabase() |
| ~EncodedDescriptorDatabase() |
bool | Add(const void * encoded_file_descriptor, int size)Adds the FileDescriptorProto to the database. more... |
bool | AddCopy(const void * encoded_file_descriptor, int size)Like Add(), but makes a copy of the data, so that the caller does not need to keep it around. |
bool | FindNameOfFileContainingSymbol(const std::string & symbol_name, std::string * output)Like FindFileContainingSymbol but returns only the name of the file. |
implements DescriptorDatabase | |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output)Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number. more... |
virtual bool | FindAllExtensionNumbers(const std::string & , std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order. more... |
virtual bool | FindAllFileNames(std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order. more... |
bool EncodedDescriptorDatabase::Add(
const void * encoded_file_descriptor,
int size)Adds the FileDescriptorProto to the database.
The descriptor is provided in encoded form. The database does not make a copy of the bytes, nor does it take ownership; it's up to the caller to make sure the bytes remain valid for the life of the database. Returns false and logs an error if the bytes are not a valid FileDescriptorProto or if the file conflicted with a file already in the database.
-virtual bool EncodedDescriptorDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output)Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool EncodedDescriptorDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool EncodedDescriptorDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-virtual bool EncodedDescriptorDatabase::FindAllExtensionNumbers(
const std::string & ,
std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all extensions, and it's not guaranteed that FindFileContainingExtension will return true on all of the found numbers. Returns true if the search was successful, otherwise returns false and leaves output unchanged.
-This method has a default implementation that always returns false.
-virtual bool EncodedDescriptorDatabase::FindAllFileNames(
std::vector< std::string > * )Finds the file names and appends them to the output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all files. Returns true if the database supports searching all file names, otherwise returns false and leaves output unchanged.
-This method has a default implementation that always returns false.
-#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
A DescriptorDatabase that fetches files from a given pool.
Members | |
|---|---|
explicit | DescriptorPoolDatabase(const DescriptorPool & pool) |
| ~DescriptorPoolDatabase() |
implements DescriptorDatabase | |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output)Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number. more... |
virtual bool | FindAllExtensionNumbers(const std::string & , std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order. more... |
virtual bool DescriptorPoolDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output)Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool DescriptorPoolDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool DescriptorPoolDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-virtual bool DescriptorPoolDatabase::FindAllExtensionNumbers(
const std::string & ,
std::vector< int > * )Finds the tag numbers used by all known extensions of extendee_type, and appends them to output in an undefined order.
This method is best-effort: it's not guaranteed that the database will find all extensions, and it's not guaranteed that FindFileContainingExtension will return true on all of the found numbers. Returns true if the search was successful, otherwise returns false and leaves output unchanged.
-This method has a default implementation that always returns false.
-#include <google/protobuf/descriptor_database.h>
namespace google::protobuf
A DescriptorDatabase that wraps two or more others.
It first searches the first database and, if that fails, tries the second, and so on.
-Members | |
|---|---|
| MergedDescriptorDatabase(DescriptorDatabase * source1, DescriptorDatabase * source2)Merge just two databases. The sources remain property of the caller. |
explicit | MergedDescriptorDatabase(const std::vector< DescriptorDatabase * > & sources)Merge more than two databases. more... |
| ~MergedDescriptorDatabase() |
implements DescriptorDatabase | |
virtual bool | FindFileByName(const std::string & filename, FileDescriptorProto * output)Find a file by file name. more... |
virtual bool | FindFileContainingSymbol(const std::string & symbol_name, FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name. more... |
virtual bool | FindFileContainingExtension(const std::string & containing_type, int field_number, FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number. more... |
virtual bool | FindAllExtensionNumbers(const std::string & extendee_type, std::vector< int > * output)Merges the results of calling all databases. more... |
explicit MergedDescriptorDatabase::MergedDescriptorDatabase(
const std::vector< DescriptorDatabase * > & sources)Merge more than two databases.
The sources remain property of the caller. The vector may be deleted after the constructor returns but the DescriptorDatabases need to stick around.
-virtual bool MergedDescriptorDatabase::FindFileByName(
const std::string & filename,
FileDescriptorProto * output)Find a file by file name.
Fills in in *output and returns true if found. Otherwise, returns false, leaving the contents of *output undefined.
-virtual bool MergedDescriptorDatabase::FindFileContainingSymbol(
const std::string & symbol_name,
FileDescriptorProto * output)Find the file that declares the given fully-qualified symbol name.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined.
-virtual bool MergedDescriptorDatabase::FindFileContainingExtension(
const std::string & containing_type,
int field_number,
FileDescriptorProto * output)Find the file which defines an extension extending the given message type with the given field number.
If found, fills in *output and returns true, otherwise returns false and leaves *output undefined. containing_type must be a fully-qualified type name.
-virtual bool MergedDescriptorDatabase::FindAllExtensionNumbers(
const std::string & extendee_type,
std::vector< int > * output)Merges the results of calling all databases.
Returns true iff any of the databases returned true.
-#include <google/protobuf/dynamic_message.h>
namespace google::protobuf
Defines an implementation of Message which can emulate types which are not known at compile-time.
Classes in this file | |
|---|---|
Constructs implementations of Message which can emulate types which are not known at compile-time. | |
Helper for computing a sorted list of map entries via reflection. | |
#include <google/protobuf/dynamic_message.h>
namespace google::protobuf
Constructs implementations of Message which can emulate types which are not known at compile-time.
Sometimes you want to be able to manipulate protocol types that you don't know about at compile time. It would be nice to be able to construct a Message object which implements the message type given by any arbitrary Descriptor. DynamicMessage provides this.
- -As it turns out, a DynamicMessage needs to construct extra information about its type in order to operate. Most of this information can be shared between all DynamicMessages of the same type. But, caching this information in some sort of global map would be a bad idea, since the cached information for a particular descriptor could outlive the descriptor itself. To avoid this problem, DynamicMessageFactory encapsulates this "cache". All DynamicMessages of the same type created from the same factory will share the same support data. Any Descriptors used with a particular factory must outlive the factory.
- -Members | |
|---|---|
| DynamicMessageFactory()Construct a DynamicMessageFactory that will search for extensions in the DescriptorPool in which the extendee is defined. |
| DynamicMessageFactory(const DescriptorPool * pool)Construct a DynamicMessageFactory that will search for extensions in the given DescriptorPool. more... |
| ~DynamicMessageFactory() |
void | SetDelegateToGeneratedFactory(bool enable) |
implements MessageFactory | |
virtual const Message * | GetPrototype(const Descriptor * type) |
DynamicMessageFactory::DynamicMessageFactory(
const DescriptorPool * pool)Construct a DynamicMessageFactory that will search for extensions in the given DescriptorPool.
DEPRECATED: Use CodedInputStream::SetExtensionRegistry() to tell the parser to look for extensions in an alternate pool. However, note that this is almost never what you want to do. Almost all users should use the zero-arg constructor.
-void DynamicMessageFactory::SetDelegateToGeneratedFactory(
bool enable)Call this to tell the DynamicMessageFactory that if it is given a Descriptor d for which:
d->file()->pool() == DescriptorPool::generated_pool(),-
then it should delegate to MessageFactory::generated_factory() instead of constructing a dynamic implementation of the message. In theory there is no down side to doing this, so it may become the default in the future.
-virtual const Message * DynamicMessageFactory::GetPrototype(
const Descriptor * type)Given a Descriptor, constructs the default (prototype) Message of that type.
You can then call that message's New() method to construct a mutable message of that type.
-Calling this method twice with the same Descriptor returns the same object. The returned object remains property of the factory and will be destroyed when the factory is destroyed. Also, any objects created by calling the prototype's New() method share some data with the prototype, so these must be destroyed before the DynamicMessageFactory is destroyed.
-The given descriptor must outlive the returned message, and hence must outlive the DynamicMessageFactory.
-The method is thread-safe.
-#include <google/protobuf/dynamic_message.h>
namespace google::protobuf
Helper for computing a sorted list of map entries via reflection.
Members | |
|---|---|
static std::vector< const Message * > | Sort(const Message & message, int map_size, const Reflection * reflection, const FieldDescriptor * field) |
#include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
This file contains the CodedInputStream and CodedOutputStream classes, which wrap a ZeroCopyInputStream or ZeroCopyOutputStream, respectively, and allow you to read or write individual pieces of data in various formats.
In particular, these implement the varint encoding for integers, a simple variable-length encoding in which smaller numbers take fewer bytes.
- -Typically these classes will only be used internally by the protocol buffer library in order to encode and decode protocol buffers. Clients of the library only need to know about this class if they wish to write custom message parsing or serialization procedures.
- -CodedOutputStream example:
- -// Write some data to "myfile". First we write a 4-byte "magic number"
-// to identify the file type, then write a length-delimited string. The
-// string is composed of a varint giving the length followed by the raw
-// bytes.
-int fd = open("myfile", O_CREAT | O_WRONLY);
-ZeroCopyOutputStream* raw_output = new FileOutputStream(fd);
-CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
-
-int magic_number = 1234;
-char text[] = "Hello world!";
-coded_output->WriteLittleEndian32(magic_number);
-coded_output->WriteVarint32(strlen(text));
-coded_output->WriteRaw(text, strlen(text));
-
-delete coded_output;
-delete raw_output;
-close(fd);
-
-CodedInputStream example:
- -// Read a file created by the above code.
-int fd = open("myfile", O_RDONLY);
-ZeroCopyInputStream* raw_input = new FileInputStream(fd);
-CodedInputStream* coded_input = new CodedInputStream(raw_input);
-
-coded_input->ReadLittleEndian32(&magic_number);
-if (magic_number != 1234) {
- cerr << "File not in expected format." << endl;
- return;
-}
-
-uint32 size;
-coded_input->ReadVarint32(&size);
-
-char* text = new char[size + 1];
-coded_input->ReadRaw(buffer, size);
-text[size] = '\0';
-
-delete coded_input;
-delete raw_input;
-close(fd);
-
-cout << "Text is: " << text << endl;
-delete [] text;
-
-For those who are interested, varint encoding is defined as follows:
- -The encoding operates on unsigned integers of up to 64 bits in length. Each byte of the encoded value has the format:
- -In theory, varint could be used to encode integers of any length. However, for practicality we set a limit at 64 bits. The maximum encoded length of a number is thus 10 bytes.
- -Classes in this file | |
|---|---|
Class which reads and decodes binary data which is composed of varint- encoded integers and fixed-width pieces. | |
EpsCopyOutputStream wraps a ZeroCopyOutputStream and exposes a new stream, which has the property you can write kSlopBytes (16 bytes) from the current position without bounds checks. | |
Class which encodes and writes binary data which is composed of varint- encoded integers and fixed-width pieces. | |
Compile-time equivalent of VarintSize32(). | |
#include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
Class which reads and decodes binary data which is composed of varint- encoded integers and fixed-width pieces.
Wraps a ZeroCopyInputStream. Most users will not need to deal with CodedInputStream.
-Most methods of CodedInputStream that return a bool return false if an underlying I/O error occurs or if the data is malformed. Once such a failure occurs, the CodedInputStream is broken and is no longer useful. After a failure, callers also should assume writes to "out" args may have occurred, though nothing useful can be determined from those writes.
-Members | |
|---|---|
explicit | CodedInputStream(ZeroCopyInputStream * input)Create a CodedInputStream that reads from the given ZeroCopyInputStream. |
explicit | CodedInputStream(const uint8 * buffer, int size)Create a CodedInputStream that reads from the given flat array. more... |
| ~CodedInputStream()Destroy the CodedInputStream and position the underlying ZeroCopyInputStream at the first unread byte. more... |
bool | IsFlat() constReturn true if this CodedInputStream reads from a flat array instead of a ZeroCopyInputStream. |
bool | Skip(int count)Skips a number of bytes. more... |
bool | GetDirectBufferPointer(const void ** data, int * size)Sets *data to point directly at the unread part of the CodedInputStream's underlying buffer, and *size to the size of that buffer, but does not advance the stream's current position. more... |
void | GetDirectBufferPointerInline(const void ** data, int * size)Like GetDirectBufferPointer, but this method is inlined, and does not attempt to Refresh() if the buffer is currently empty. |
bool | ReadRaw(void * buffer, int size)Read raw bytes, copying them into the given buffer. |
bool | ReadString(std::string * buffer, int size)Like ReadRaw, but reads into a string. |
bool | ReadLittleEndian32(uint32 * value)Read a 32-bit little-endian integer. |
bool | ReadLittleEndian64(uint64 * value)Read a 64-bit little-endian integer. |
bool | ReadVarint32(uint32 * value)Read an unsigned integer with Varint encoding, truncating to 32 bits. more... |
bool | ReadVarint64(uint64 * value)Read an unsigned integer with Varint encoding. |
bool | ReadVarintSizeAsInt(int * value)Reads a varint off the wire into an "int". more... |
uint32 | ReadTag()Read a tag. more... |
uint32 | ReadTagNoLastTag() |
std::pair< uint32, bool > | ReadTagWithCutoff(uint32 cutoff) |
std::pair< uint32, bool > | ReadTagWithCutoffNoLastTag(uint32 cutoff) |
bool | ExpectTag(uint32 expected)Usually returns true if calling ReadVarint32() now would produce the given value. more... |
bool | ExpectAtEnd()Usually returns true if no more bytes can be read. more... |
bool | LastTagWas(uint32 expected)If the last call to ReadTag() or ReadTagWithCutoff() returned the given value, returns true. more... |
void | SetLastTag(uint32 tag) |
bool | ConsumedEntireMessage()When parsing message (but NOT a group), this method must be called immediately after MergeFromCodedStream() returns (if it returns true) to further verify that the message ended in a legitimate way. more... |
void | SetConsumed() |
static const uint8 * | ReadLittleEndian32FromArray(const uint8 * buffer, uint32 * value)These methods read from an externally provided buffer. more... |
static const uint8 * | ReadLittleEndian64FromArray(const uint8 * buffer, uint64 * value)Read a 64-bit little-endian integer. more... |
static const uint8 * | ExpectTagFromArray(const uint8 * buffer, uint32 expected)Like above, except this reads from the specified buffer. more... |
LimitsLimits are used when parsing length-delimited embedded messages. After the message's length is read, PushLimit() is used to prevent the CodedInputStream from reading beyond that length. Once the embedded message has been parsed, PopLimit() is called to undo the limit. | |
typedef | int Limit |
Limit | PushLimit(int byte_limit)Places a limit on the number of bytes that the stream may read, starting from the current position. more... |
void | PopLimit(Limit limit)Pops the last limit pushed by PushLimit(). more... |
int | BytesUntilLimit() constReturns the number of bytes left until the nearest limit on the stack is hit, or -1 if no limits are in place. |
int | CurrentPosition() constReturns current position relative to the beginning of the input stream. |
Total Bytes LimitTo prevent malicious users from sending excessively large messages and causing memory exhaustion, CodedInputStream imposes a hard limit on the total number of bytes it will read. | |
| int = {
- SetTotalBytesLimit(total_bytes_limit) |
void | SetTotalBytesLimit(int total_bytes_limit)Sets the maximum number of bytes that this CodedInputStream will read before refusing to continue. more... |
| PROTOBUF_DEPRECATED_MSG("Please use the single parameter version of SetTotalBytesLimit(). The " "second parameter is ignored." ) |
int | BytesUntilTotalBytesLimit() constThe Total Bytes Limit minus the Current Position, or -1 if the total bytes limit is INT_MAX. |
Recursion Limit
- To prevent corrupt or malicious messages from causing stack overflows, we must keep track of the depth of recursion when parsing embedded messages and groups. -CodedInputStream keeps track of this because it is the only object that is passed down the stack during parsing. - | |
void | SetRecursionLimit(int limit)Sets the maximum recursion depth. The default is 100. |
int | RecursionBudget() |
bool | IncrementRecursionDepth()Increments the current recursion depth. more... |
void | DecrementRecursionDepth()Decrements the recursion depth if possible. |
void | UnsafeDecrementRecursionDepth()Decrements the recursion depth blindly. more... |
std::pair< CodedInputStream::Limit, int > | IncrementRecursionDepthAndPushLimit(int byte_limit)Shorthand for make_pair(PushLimit(byte_limit), –recursion_budget_). more... |
Limit | ReadLengthAndPushLimit()Shorthand for PushLimit(ReadVarint32(&length) ? length : 0). |
bool | DecrementRecursionDepthAndPopLimit(Limit limit)Helper that is equivalent to: { bool result = ConsumedEntireMessage(); PopLimit(limit); UnsafeDecrementRecursionDepth(); return result; } Using this can reduce code size and complexity in some cases. more... |
bool | CheckEntireMessageConsumedAndPopLimit(Limit limit)Helper that is equivalent to: { bool result = ConsumedEntireMessage(); PopLimit(limit); return result; } Using this can reduce code size and complexity in some cases. |
static int | GetDefaultRecursionLimit() |
Extension Registry
- ADVANCED USAGE: 99.9% of people can ignore this section. -By default, when parsing extensions, the parser looks for extension definitions in the pool which owns the outer message's Descriptor. However, you may call SetExtensionRegistry() to provide an alternative pool instead. This makes it possible, for example, to parse a message using a generated class, but represent some extensions using DynamicMessage. - | |
void | SetExtensionRegistry(const DescriptorPool * pool, MessageFactory * factory)Set the pool used to look up extensions. more... |
const DescriptorPool * | GetExtensionPool()Get the DescriptorPool set via SetExtensionRegistry(), or NULL if no pool has been provided. |
MessageFactory * | GetExtensionFactory()Get the MessageFactory set via SetExtensionRegistry(), or NULL if no factory has been provided. |
explicit CodedInputStream::CodedInputStream(
const uint8 * buffer,
int size)Create a CodedInputStream that reads from the given flat array.
This is faster than using an ArrayInputStream. PushLimit(size) is implied by this constructor.
-CodedInputStream::~CodedInputStream()Destroy the CodedInputStream and position the underlying ZeroCopyInputStream at the first unread byte.
If an error occurred while reading (causing a method to return false), then the exact position of the input stream may be anywhere between the last value that was read successfully and the stream's byte limit.
-bool CodedInputStream::Skip(
int count)Skips a number of bytes.
Returns false if an underlying read error occurs.
-bool CodedInputStream::GetDirectBufferPointer(
const void ** data,
int * size)Sets *data to point directly at the unread part of the CodedInputStream's underlying buffer, and *size to the size of that buffer, but does not advance the stream's current position.
This will always either produce a non-empty buffer or return false. If the caller consumes any of this data, it should then call Skip() to skip over the consumed bytes. This may be useful for implementing external fast parsing routines for types of data not covered by the CodedInputStream interface.
-bool CodedInputStream::ReadVarint32(
uint32 * value)Read an unsigned integer with Varint encoding, truncating to 32 bits.
Reading a 32-bit value is equivalent to reading a 64-bit one and casting it to uint32, but may be more efficient.
-bool CodedInputStream::ReadVarintSizeAsInt(
int * value)Reads a varint off the wire into an "int".
This should be used for reading sizes off the wire (sizes of strings, submessages, bytes fields, etc).
-The value from the wire is interpreted as unsigned. If its value exceeds the representable value of an integer on this platform, instead of truncating we return false. Truncating (as performed by ReadVarint32() above) is an acceptable approach for fields representing an integer, but when we are parsing a size from the wire, truncating the value would result in us misparsing the payload.
-uint32 CodedInputStream::ReadTag()Read a tag.
This calls ReadVarint32() and returns the result, or returns zero (which is not a valid tag) if ReadVarint32() fails. Also, ReadTag (but not ReadTagNoLastTag) updates the last tag value, which can be checked with LastTagWas().
-Always inline because this is only called in one place per parse loop but it is called for every iteration of said loop, so it should be fast. GCC doesn't want to inline this by default.
-std::pair< uint32, bool >
CodedInputStream::ReadTagWithCutoff(
uint32 cutoff)This usually a faster alternative to ReadTag() when cutoff is a manifest constant.
It does particularly well for cutoff >= 127. The first part of the return value is the tag that was read, though it can also be 0 in the cases where ReadTag() would return 0. If the second part is true then the tag is known to be in [0, cutoff]. If not, the tag either is above cutoff or is 0. (There's intentional wiggle room when tag is 0, because that can arise in several ways, and for best performance we want to avoid an extra "is tag == 0?" check here.)
-bool CodedInputStream::ExpectTag(
uint32 expected)Usually returns true if calling ReadVarint32() now would produce the given value.
Will always return false if ReadVarint32() would not return the given value. If ExpectTag() returns true, it also advances past the varint. For best performance, use a compile-time constant as the parameter. Always inline because this collapses to a small number of instructions when given a constant parameter, but GCC doesn't want to inline by default.
-bool CodedInputStream::ExpectAtEnd()Usually returns true if no more bytes can be read.
Always returns false if more bytes can be read. If ExpectAtEnd() returns true, a subsequent call to LastTagWas() will act as if ReadTag() had been called and returned zero, and ConsumedEntireMessage() will return true.
-bool CodedInputStream::LastTagWas(
uint32 expected)If the last call to ReadTag() or ReadTagWithCutoff() returned the given value, returns true.
Otherwise, returns false. ReadTagNoLastTag/ReadTagWithCutoffNoLastTag do not preserve the last returned value.
-This is needed because parsers for some types of embedded messages (with field type TYPE_GROUP) don't actually know that they've reached the end of a message until they see an ENDGROUP tag, which was actually part of the enclosing message. The enclosing message would like to check that tag to make sure it had the right number, so it calls LastTagWas() on return from the embedded parser to check.
-bool CodedInputStream::ConsumedEntireMessage()When parsing message (but NOT a group), this method must be called immediately after MergeFromCodedStream() returns (if it returns true) to further verify that the message ended in a legitimate way.
For example, this verifies that parsing did not end on an end-group tag. It also checks for some cases where, due to optimizations, MergeFromCodedStream() can incorrectly return true.
-static const uint8 * CodedInputStream::ReadLittleEndian32FromArray(
const uint8 * buffer,
uint32 * value)These methods read from an externally provided buffer.
static
-The caller is responsible for ensuring that the buffer has sufficient space. Read a 32-bit little-endian integer.
-static const uint8 * CodedInputStream::ReadLittleEndian64FromArray(
const uint8 * buffer,
uint64 * value)Read a 64-bit little-endian integer.
static
-static const uint8 * CodedInputStream::ExpectTagFromArray(
const uint8 * buffer,
uint32 expected)Like above, except this reads from the specified buffer.
The caller is responsible for ensuring that the buffer is large enough to read a varint of the expected size. For best performance, use a compile-time constant as the expected tag parameter.
-Returns a pointer beyond the expected tag if it was found, or NULL if it was not.
-typedef CodedInputStream::LimitOpaque type used with PushLimit() and PopLimit().
Do not modify values of this type yourself. The only reason that this isn't a struct with private internals is for efficiency.
-Limit CodedInputStream::PushLimit(
int byte_limit)Places a limit on the number of bytes that the stream may read, starting from the current position.
Once the stream hits this limit, it will act like the end of the input has been reached until PopLimit() is called.
-As the names imply, the stream conceptually has a stack of limits. The shortest limit on the stack is always enforced, even if it is not the top limit.
-The value returned by PushLimit() is opaque to the caller, and must be passed unchanged to the corresponding call to PopLimit().
-void CodedInputStream::PopLimit(
Limit limit)Pops the last limit pushed by PushLimit().
The input must be the value returned by that call to PushLimit().
-void CodedInputStream::SetTotalBytesLimit(
int total_bytes_limit)Sets the maximum number of bytes that this CodedInputStream will read before refusing to continue.
To prevent servers from allocating enormous amounts of memory to hold parsed messages, the maximum message length should be limited to the shortest length that will not harm usability. The default limit is INT_MAX (~2GB) and apps should set shorter limits if possible. An error will always be printed to stderr if the limit is reached.
-Note: setting a limit less than the current read position is interpreted as a limit on the current position.
-This is unrelated to PushLimit()/PopLimit().
-bool CodedInputStream::IncrementRecursionDepth()Increments the current recursion depth.
Returns true if the depth is under the limit, false if it has gone over.
-void CodedInputStream::UnsafeDecrementRecursionDepth()Decrements the recursion depth blindly.
This is faster than DecrementRecursionDepth(). It should be used only if all previous increments to recursion depth were successful.
-std::pair< CodedInputStream::Limit, int >
CodedInputStream::IncrementRecursionDepthAndPushLimit(
int byte_limit)Shorthand for make_pair(PushLimit(byte_limit), –recursion_budget_).
Using this can reduce code size and complexity in some cases. The caller is expected to check that the second part of the result is non-negative (to bail out if the depth of recursion is too high) and, if all is well, to later pass the first part of the result to PopLimit() or similar.
-bool CodedInputStream::DecrementRecursionDepthAndPopLimit(
Limit limit)Helper that is equivalent to: { bool result = ConsumedEntireMessage(); PopLimit(limit); UnsafeDecrementRecursionDepth(); return result; } Using this can reduce code size and complexity in some cases.
Do not use unless the current recursion depth is greater than zero.
-void CodedInputStream::SetExtensionRegistry(
const DescriptorPool * pool,
MessageFactory * factory)Set the pool used to look up extensions.
Most users do not need to call this as the correct pool will be chosen automatically.
-WARNING: It is very easy to misuse this. Carefully read the requirements below. Do not use this unless you are sure you need it. Almost no one does.
-Let's say you are parsing a message into message object m, and you want to take advantage of SetExtensionRegistry(). You must follow these requirements:
-The given DescriptorPool must contain m->GetDescriptor(). It is not sufficient for it to simply contain a descriptor that has the same name and content – it must be the exact object. In other words:
-assert(pool->FindMessageTypeByName(m->GetDescriptor()->full_name()) == - m->GetDescriptor());-
There are two ways to satisfy this requirement: 1) Use m->GetDescriptor()->pool() as the pool. This is generally useless
-because this is the pool that would be used anyway if you didn't call -SetExtensionRegistry() at all.-
2) Use a DescriptorPool which has m->GetDescriptor()->pool() as an
-"underlay". Read the documentation for DescriptorPool for more -information about underlays.-
You must also provide a MessageFactory. This factory will be used to construct Message objects representing extensions. The factory's GetPrototype() MUST return non-NULL for any Descriptor which can be found through the provided pool.
-If the provided factory might return instances of protocol-compiler- generated (i.e. compiled-in) types, or if the outer message object m is a generated type, then the given factory MUST have this property: If GetPrototype() is given a Descriptor which resides in DescriptorPool::generated_pool(), the factory MUST return the same prototype which MessageFactory::generated_factory() would return. That is, given a descriptor for a generated type, the factory must return an instance of the generated class (NOT DynamicMessage). However, when given a descriptor for a type that is NOT in generated_pool, the factory is free to return any implementation.
-The reason for this requirement is that generated sub-objects may be accessed via the standard (non-reflection) extension accessor methods, and these methods will down-cast the object to the generated class type. If the object is not actually of that type, the results would be undefined. On the other hand, if an extension is not compiled in, then there is no way the code could end up accessing it via the standard accessors – the only way to access the extension is via reflection. When using reflection, DynamicMessage and generated messages are indistinguishable, so it's fine if these objects are represented using DynamicMessage.
-Using DynamicMessageFactory on which you have called SetDelegateToGeneratedFactory(true) should be sufficient to satisfy the above requirement.
-If either pool or factory is NULL, both must be NULL.
-Note that this feature is ignored when parsing "lite" messages as they do not have descriptors.
-#include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
EpsCopyOutputStream wraps a ZeroCopyOutputStream and exposes a new stream, which has the property you can write kSlopBytes (16 bytes) from the current position without bounds checks.
The cursor into the stream is managed by the user of the class and is an explicit parameter in the methods. Careful use of this class, ie. keep ptr a local variable, eliminates the need to for the compiler to sync the ptr value between register and memory.
-Members | |
|---|---|
enum | @33 |
| EpsCopyOutputStream(ZeroCopyOutputStream * stream, bool deterministic, uint8 ** pp)Initialize from a stream. |
| EpsCopyOutputStream(void * data, int size, bool deterministic)Only for array serialization. more... |
| EpsCopyOutputStream(void * data, int size, ZeroCopyOutputStream * stream, bool deterministic, uint8 ** pp)Initialize from stream but with the first buffer already given (eager). |
uint8 * | Trim(uint8 * ptr)Flush everything that's written into the underlying ZeroCopyOutputStream and trims the underlying stream to the location of ptr. |
PROTOBUF_MUST_USE_RESULT uint8 * | EnsureSpace(uint8 * ptr)After this it's guaranteed you can safely write kSlopBytes to ptr. more... |
uint8 * | WriteRaw(const void * data, int size, uint8 * ptr) |
uint8 * | WriteRawMaybeAliased(const void * data, int size, uint8 * ptr)Writes the buffer specified by data, size to the stream. more... |
uint8 * | WriteStringMaybeAliased(uint32 num, const std::string & s, uint8 * ptr) |
uint8 * | WriteBytesMaybeAliased(uint32 num, const std::string & s, uint8 * ptr) |
template uint8 * | WriteString(uint32 num, const T & s, uint8 * ptr) |
template uint8 * | WriteBytes(uint32 num, const T & s, uint8 * ptr) |
template uint8 * | WriteInt32Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteUInt32Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteSInt32Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteInt64Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteUInt64Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteSInt64Packed(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteEnumPacked(int num, const T & r, int size, uint8 * ptr) |
template uint8 * | WriteFixedPacked(int num, const T & r, uint8 * ptr) |
bool | HadError() constReturns true if there was an underlying I/O error since this object was created. |
void | EnableAliasing(bool enabled)Instructs the EpsCopyOutputStream to allow the underlying ZeroCopyOutputStream to hold pointers to the original structure instead of copying, if it supports it (i.e. more... |
void | SetSerializationDeterministic(bool value)See documentation on CodedOutputStream::SetSerializationDeterministic. |
bool | IsSerializationDeterministic() constSee documentation on CodedOutputStream::IsSerializationDeterministic. |
int64 | ByteCount(uint8 * ptr) constThe number of bytes written to the stream at position ptr, relative to the stream's overall position. |
uint8 * | SetInitialBuffer(void * data, int size)These methods are for CodedOutputStream. more... |
enum EpsCopyOutputStream::@33 {
kSlopBytes = = 16
}| kSlopBytes |
EpsCopyOutputStream::EpsCopyOutputStream(
void * data,
int size,
bool deterministic)Only for array serialization.
No overflow protection, end_ will be the pointed to the end of the array. When using this the total size is already known, so no need to maintain the slop region.
-PROTOBUF_MUST_USE_RESULT uint8 *
EpsCopyOutputStream::EnsureSpace(
uint8 * ptr)After this it's guaranteed you can safely write kSlopBytes to ptr.
This will never fail! The underlying stream can produce an error. Use HadError to check for errors.
-uint8 * EpsCopyOutputStream::WriteRawMaybeAliased(
const void * data,
int size,
uint8 * ptr)Writes the buffer specified by data, size to the stream.
Possibly by aliasing the buffer (ie. not copying the data). The caller is responsible to make sure the buffer is alive for the duration of the ZeroCopyOutputStream.
-void EpsCopyOutputStream::EnableAliasing(
bool enabled)Instructs the EpsCopyOutputStream to allow the underlying ZeroCopyOutputStream to hold pointers to the original structure instead of copying, if it supports it (i.e.
output->AllowsAliasing() is true). If the underlying stream does not support aliasing, then enabling it has no affect. For now, this only affects the behavior of WriteRawMaybeAliased().
-NOTE: It is caller's responsibility to ensure that the chunk of memory remains live until all of the data has been consumed from the stream.
-uint8 * EpsCopyOutputStream::SetInitialBuffer(
void * data,
int size)These methods are for CodedOutputStream.
Ideally they should be private but to match current behavior of CodedOutputStream as close as possible we allow it some functionality.
-#include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
Class which encodes and writes binary data which is composed of varint- encoded integers and fixed-width pieces.
Wraps a ZeroCopyOutputStream. Most users will not need to deal with CodedOutputStream.
-Most methods of CodedOutputStream which return a bool return false if an underlying I/O error occurs. Once such a failure occurs, the CodedOutputStream is broken and is no longer useful. The Write* methods do not return the stream status, but will invalidate the stream if an error occurs. The client can probe HadError() to determine the status.
-Note that every method of CodedOutputStream which writes some data has a corresponding static "ToArray" version. These versions write directly to the provided buffer, returning a pointer past the last written byte. They require that the buffer has sufficient capacity for the encoded data. This allows an optimization where we check if an output stream has enough space for an entire message before we start writing and, if there is, we call only the ToArray methods to avoid doing bound checks for each individual value. i.e., in the example above:
-CodedOutputStream* coded_output = new CodedOutputStream(raw_output);
-int magic_number = 1234;
-char text[] = "Hello world!";
-
-int coded_size = sizeof(magic_number) +
- CodedOutputStream::VarintSize32(strlen(text)) +
- strlen(text);
-
-uint8* buffer =
- coded_output->GetDirectBufferForNBytesAndAdvance(coded_size);
-if (buffer != nullptr) {
- // The output stream has enough space in the buffer: write directly to
- // the array.
- buffer = CodedOutputStream::WriteLittleEndian32ToArray(magic_number,
- buffer);
- buffer = CodedOutputStream::WriteVarint32ToArray(strlen(text), buffer);
- buffer = CodedOutputStream::WriteRawToArray(text, strlen(text), buffer);
-} else {
- // Make bound-checked writes, which will ask the underlying stream for
- // more space as needed.
- coded_output->WriteLittleEndian32(magic_number);
- coded_output->WriteVarint32(strlen(text));
- coded_output->WriteRaw(text, strlen(text));
-}
-
-delete coded_output;
-Members | |
|---|---|
explicit | CodedOutputStream(ZeroCopyOutputStream * stream)Create an CodedOutputStream that writes to the given ZeroCopyOutputStream. |
| CodedOutputStream(ZeroCopyOutputStream * stream, bool do_eager_refresh) |
| ~CodedOutputStream()Destroy the CodedOutputStream and position the underlying ZeroCopyOutputStream immediately after the last byte written. |
bool | HadError()Returns true if there was an underlying I/O error since this object was created. more... |
void | Trim()Trims any unused space in the underlying buffer so that its size matches the number of bytes written by this stream. more... |
bool | Skip(int count)Skips a number of bytes, leaving the bytes unmodified in the underlying buffer. more... |
bool | GetDirectBufferPointer(void ** data, int * size)Sets *data to point directly at the unwritten part of the CodedOutputStream's underlying buffer, and *size to the size of that buffer, but does not advance the stream's current position. more... |
uint8 * | GetDirectBufferForNBytesAndAdvance(int size)If there are at least "size" bytes available in the current buffer, returns a pointer directly into the buffer and advances over these bytes. more... |
void | WriteRaw(const void * buffer, int size)Write raw bytes, copying them from the given buffer. |
void | WriteRawMaybeAliased(const void * data, int size)Like WriteRaw() but will try to write aliased data if aliasing is turned on. |
void | WriteString(const std::string & str)Equivalent to WriteRaw(str.data(), str.size()). |
void | WriteLittleEndian32(uint32 value)Write a 32-bit little-endian integer. |
void | WriteLittleEndian64(uint64 value)Write a 64-bit little-endian integer. |
void | WriteVarint32(uint32 value)Write an unsigned integer with Varint encoding. more... |
void | WriteVarint64(uint64 value)Write an unsigned integer with Varint encoding. |
void | WriteVarint32SignExtended(int32 value)Equivalent to WriteVarint32() except when the value is negative, in which case it must be sign-extended to a full 10 bytes. |
void | WriteTag(uint32 value)This is identical to WriteVarint32(), but optimized for writing tags. more... |
int | ByteCount() constReturns the total number of bytes written since this object was created. |
void | EnableAliasing(bool enabled)Instructs the CodedOutputStream to allow the underlying ZeroCopyOutputStream to hold pointers to the original structure instead of copying, if it supports it (i.e. more... |
void | SetSerializationDeterministic(bool value)Indicate to the serializer whether the user wants derministic serialization. more... |
bool | IsSerializationDeterministic() constReturn whether the user wants deterministic serialization. See above. |
template void | Serialize(const Func & func) |
uint8 * | Cur() const |
void | SetCur(uint8 * ptr) |
EpsCopyOutputStream * | EpsCopy() |
static uint8 * | WriteRawToArray(const void * buffer, int size, uint8 * target)Like WriteRaw() but writing directly to the target array. more... |
static uint8 * | WriteStringToArray(const std::string & str, uint8 * target)Like WriteString() but writing directly to the target array. |
static uint8 * | WriteStringWithSizeToArray(const std::string & str, uint8 * target)Write the varint-encoded size of str followed by str. |
static uint8 * | WriteLittleEndian32ToArray(uint32 value, uint8 * target)Like WriteLittleEndian32() but writing directly to the target array. |
static uint8 * | WriteLittleEndian64ToArray(uint64 value, uint8 * target)Like WriteLittleEndian64() but writing directly to the target array. |
static uint8 * | WriteVarint32ToArray(uint32 value, uint8 * target)Like WriteVarint32() but writing directly to the target array. |
static uint8 * | WriteVarint32ToArrayOutOfLine(uint32 value, uint8 * target)Like WriteVarint32() but writing directly to the target array, and with the less common-case paths being out of line rather than inlined. |
static uint8 * | WriteVarint64ToArray(uint64 value, uint8 * target)Like WriteVarint64() but writing directly to the target array. |
static uint8 * | WriteVarint32SignExtendedToArray(int32 value, uint8 * target)Like WriteVarint32SignExtended() but writing directly to the target array. |
static uint8 * | WriteTagToArray(uint32 value, uint8 * target)Like WriteTag() but writing directly to the target array. |
static size_t | VarintSize32(uint32 value)Returns the number of bytes needed to encode the given value as a varint. |
static size_t | VarintSize64(uint64 value)Returns the number of bytes needed to encode the given value as a varint. |
static size_t | VarintSize32SignExtended(int32 value)If negative, 10 bytes. Otherwise, same as VarintSize32(). |
static bool | IsDefaultSerializationDeterministic() |
bool CodedOutputStream::HadError()Returns true if there was an underlying I/O error since this object was created.
On should call Trim before this function in order to catch all errors.
-void CodedOutputStream::Trim()Trims any unused space in the underlying buffer so that its size matches the number of bytes written by this stream.
The underlying buffer will automatically be trimmed when this stream is destroyed; this call is only necessary if the underlying buffer is accessed before the stream is destroyed.
-bool CodedOutputStream::Skip(
int count)Skips a number of bytes, leaving the bytes unmodified in the underlying buffer.
Returns false if an underlying write error occurs. This is mainly useful with GetDirectBufferPointer(). Note of caution, the skipped bytes may contain uninitialized data. The caller must make sure that the skipped bytes are properly initialized, otherwise you might leak bytes from your heap.
-bool CodedOutputStream::GetDirectBufferPointer(
void ** data,
int * size)Sets *data to point directly at the unwritten part of the CodedOutputStream's underlying buffer, and *size to the size of that buffer, but does not advance the stream's current position.
This will always either produce a non-empty buffer or return false. If the caller writes any data to this buffer, it should then call Skip() to skip over the consumed bytes. This may be useful for implementing external fast serialization routines for types of data not covered by the CodedOutputStream interface.
-uint8 * CodedOutputStream::GetDirectBufferForNBytesAndAdvance(
int size)If there are at least "size" bytes available in the current buffer, returns a pointer directly into the buffer and advances over these bytes.
The caller may then write directly into this buffer (e.g. using the *ToArray static methods) rather than go through CodedOutputStream. If there are not enough bytes available, returns NULL. The return pointer is invalidated as soon as any other non-const method of CodedOutputStream is called.
-void CodedOutputStream::WriteVarint32(
uint32 value)Write an unsigned integer with Varint encoding.
Writing a 32-bit value is equivalent to casting it to uint64 and writing it as a 64-bit value, but may be more efficient.
-void CodedOutputStream::WriteTag(
uint32 value)This is identical to WriteVarint32(), but optimized for writing tags.
In particular, if the input is a compile-time constant, this method compiles down to a couple instructions. Always inline because otherwise the aforementioned optimization can't work, but GCC by default doesn't want to inline this.
-void CodedOutputStream::EnableAliasing(
bool enabled)Instructs the CodedOutputStream to allow the underlying ZeroCopyOutputStream to hold pointers to the original structure instead of copying, if it supports it (i.e.
output->AllowsAliasing() is true). If the underlying stream does not support aliasing, then enabling it has no affect. For now, this only affects the behavior of WriteRawMaybeAliased().
-NOTE: It is caller's responsibility to ensure that the chunk of memory remains live until all of the data has been consumed from the stream.
-void CodedOutputStream::SetSerializationDeterministic(
bool value)Indicate to the serializer whether the user wants derministic serialization.
The default when this is not called comes from the global default, controlled by SetDefaultSerializationDeterministic.
-What deterministic serialization means is entirely up to the driver of the serialization process (i.e. the caller of methods like WriteVarint32). In the case of serializing a proto buffer message using one of the methods of MessageLite, this means that for a given binary equal messages will always be serialized to the same bytes. This implies:
-Repeated serialization of a message will return the same bytes. - -Different processes running the same binary (including on different -machines) will serialize equal messages to the same bytes.-
Note that this is not canonical across languages. It is also unstable across different builds with intervening message definition changes, due to unknown fields. Users who need canonical serialization (e.g. persistent storage in a canonical form, fingerprinting) should define their own canonicalization specification and implement the serializer using reflection APIs rather than relying on this API.
-static uint8 * CodedOutputStream::WriteRawToArray(
const void * buffer,
int size,
uint8 * target)Like WriteRaw() but writing directly to the target array.
This is not inlined, as the compiler often optimizes memcpy into inline copy loops. Since this gets called by every field with string or bytes type, inlining may lead to a significant amount of code bloat, with only a minor performance gain.
-#include <google/protobuf/io/coded_stream.h>
namespace google::protobuf::io
template <typename Value>
Compile-time equivalent of VarintSize32().
Members | |
|---|---|
const size_t | value = = (Value < (1 << 7)) ? 1
- : (Value < (1 << 14)) ? 2
- : (Value < (1 << 21)) ? 3
- : (Value < (1 << 28)) ? 4
- : 5 |
#include <google/protobuf/io/gzip_stream.h>
namespace google::protobuf::io
This file contains the definition for classes GzipInputStream and GzipOutputStream.
GzipInputStream decompresses data from an underlying ZeroCopyInputStream and provides the decompressed data as a ZeroCopyInputStream.
- -GzipOutputStream is an ZeroCopyOutputStream that compresses data to an underlying ZeroCopyOutputStream.
- -Classes in this file | |
|---|---|
A ZeroCopyInputStream that reads compressed data through zlib. | |
#include <google/protobuf/io/gzip_stream.h>
namespace google::protobuf::io
A ZeroCopyInputStream that reads compressed data through zlib.
Members | |
|---|---|
enum | FormatFormat key for constructor. more... |
explicit | GzipInputStream(ZeroCopyInputStream * sub_stream, Format format = AUTO, int buffer_size = -1)buffer_size and format may be -1 for default of 64kB and GZIP format |
virtual | ~GzipInputStream() |
const char * | ZlibErrorMessage() constReturn last error message or NULL if no error. |
int | ZlibErrorCode() const |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64 | ByteCount() constReturns the total number of bytes read since this object was created. |
enum GzipInputStream::Format {
AUTO = = 0,
GZIP = = 1,
ZLIB = = 2
}Format key for constructor.
| AUTO | zlib will autodetect gzip header or deflate stream |
| GZIP | GZIP streams have some extra header data for file attributes. |
| ZLIB | Simpler zlib stream format. |
virtual bool GzipInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void GzipInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool GzipInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/gzip_stream.h>
namespace google::protobuf::io
Members | |
|---|---|
enum | FormatFormat key for constructor. more... |
explicit | GzipOutputStream(ZeroCopyOutputStream * sub_stream)Create a GzipOutputStream with default options. |
| GzipOutputStream(ZeroCopyOutputStream * sub_stream, const Options & options)Create a GzipOutputStream with the given options. |
virtual | ~GzipOutputStream() |
const char * | ZlibErrorMessage() constReturn last error message or NULL if no error. |
int | ZlibErrorCode() const |
bool | Flush()Flushes data written so far to zipped data in the underlying stream. more... |
bool | Close()Writes out all data and closes the gzip stream. more... |
implements ZeroCopyOutputStream | |
virtual bool | Next(void ** data, int * size)Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) |
virtual int64 | ByteCount() constReturns the total number of bytes written since this object was created. |
enum GzipOutputStream::Format {
GZIP = = 1,
ZLIB = = 2
}Format key for constructor.
| GZIP | GZIP streams have some extra header data for file attributes. |
| ZLIB | Simpler zlib stream format. |
bool GzipOutputStream::Flush()Flushes data written so far to zipped data in the underlying stream.
It is the caller's responsibility to flush the underlying stream if necessary. Compression may be less efficient stopping and starting around flushes. Returns true if no error.
-Please ensure that block size is > 6. Here is an excerpt from the zlib doc that explains why:
-In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that avail_out is greater than six to avoid repeated flush markers due to avail_out == 0 on return.
-bool GzipOutputStream::Close()Writes out all data and closes the gzip stream.
It is the caller's responsibility to close the underlying stream if necessary. Returns true if no error.
-virtual bool GzipOutputStream::Next(
void ** data,
int * size)Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void GzipOutputStream::BackUp(
int count)Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-#include <google/protobuf/io/gzip_stream.h>
namespace google::protobuf::io
Members | |
|---|---|
Format | formatDefaults to GZIP. |
int | buffer_sizeWhat size buffer to use internally. Defaults to 64kB. |
int | compression_levelA number between 0 and 9, where 0 is no compression and 9 is best compression. more... |
int | compression_strategyDefaults to Z_DEFAULT_STRATEGY. more... |
| Options()Initializes with default values. |
intOptions::compression_levelA number between 0 and 9, where 0 is no compression and 9 is best compression.
Defaults to Z_DEFAULT_COMPRESSION (see zlib.h).
-intOptions::compression_strategyDefaults to Z_DEFAULT_STRATEGY.
Can also be set to Z_FILTERED, Z_HUFFMAN_ONLY, or Z_RLE. See the documentation for deflateInit2 in zlib.h for definitions of these constants.
-#include <google/protobuf/io/printer.h>
namespace google::protobuf::io
Utility class for writing text to a ZeroCopyOutputStream.
Classes in this file | |
|---|---|
Records annotations about a Printer's output. | |
Records annotations about a Printer's output to the given protocol buffer, assuming that the buffer has an ::Annotation message exposing path, source_file, begin and end fields. | |
#include <google/protobuf/io/printer.h>
namespace google::protobuf::io
Records annotations about a Printer's output.
Known subclasses:
Members | |
|---|---|
typedef | std::pair< std::pair< size_t, size_t >, std::string > AnnotationAnnotation is a offset range and a payload pair. |
virtual void | AddAnnotation(size_t begin_offset, size_t end_offset, const std::string & file_path, const std::vector< int > & path) = 0Records that the bytes in file_path beginning with begin_offset and ending before end_offset are associated with the SourceCodeInfo-style path. |
virtual void | AddAnnotationNew(Annotation & ) |
virtual | ~AnnotationCollector() |
virtual void AnnotationCollector::AddAnnotationNew(
Annotation & )Just a vector of range, payload pairs stored in a context should suffice.
- -#include <google/protobuf/io/printer.h>
namespace google::protobuf::io
template <typename >
Records annotations about a Printer's output to the given protocol buffer, assuming that the buffer has an ::Annotation message exposing path, source_file, begin and end fields.
Members | |
|---|---|
explicit | AnnotationProtoCollector(AnnotationProto * annotation_proto)annotation_proto is the protocol buffer to which new Annotations should be added. more... |
virtual void | AddAnnotation(size_t begin_offset, size_t end_offset, const std::string & file_path, const std::vector< int > & path)Override for AnnotationCollector::AddAnnotation. |
virtual void | AddAnnotationNew(Annotation & a)Override for AnnotationCollector::AddAnnotation. |
explicit AnnotationProtoCollector::AnnotationProtoCollector(
AnnotationProto * annotation_proto)annotation_proto is the protocol buffer to which new Annotations should be added.
It is not owned by the AnnotationProtoCollector.
-#include <google/protobuf/io/printer.h>
namespace google::protobuf::io
Members | |
|---|---|
| Printer(ZeroCopyOutputStream * output, char variable_delimiter)Create a printer that writes text to the given output stream. more... |
| Printer(ZeroCopyOutputStream * output, char variable_delimiter, AnnotationCollector * annotation_collector)Create a printer that writes text to the given output stream. more... |
| ~Printer() |
template void | Annotate(const char * varname, const SomeDescriptor * descriptor)Link a substitution variable emitted by the last call to Print to the object described by descriptor. |
template void | Annotate(const char * begin_varname, const char * end_varname, const SomeDescriptor * descriptor)Link the output range defined by the substitution variables as emitted by the last call to Print to the object described by descriptor. more... |
void | Annotate(const char * varname, const std::string & file_name)Link a substitution variable emitted by the last call to Print to the file with path file_name. |
void | Annotate(const char * begin_varname, const char * end_varname, const std::string & file_name)Link the output range defined by the substitution variables as emitted by the last call to Print to the file with path file_name. more... |
void | Print(const std::map< std::string, std::string > & variables, const char * text)Print some text after applying variable substitutions. more... |
template void | Print(const char * text, const Args &... args)Like the first Print(), except the substitutions are given as parameters. |
void | Indent()Indent text by two spaces. more... |
void | Outdent()Reduces the current indent level by two spaces, or crashes if the indent level is zero. |
void | PrintRaw(const std::string & data)Write a string to the output buffer. more... |
void | PrintRaw(const char * data)Write a zero-delimited string to output buffer. more... |
void | WriteRaw(const char * data, int size)Write some bytes to the output buffer. more... |
void | FormatInternal(const std::vector< std::string > & args, const std::map< std::string, std::string > & vars, const char * format)FormatInternal is a helper function not meant to use directly, use compiler::cpp::Formatter instead. more... |
bool | failed() constTrue if any write to the underlying stream failed. more... |
Printer::Printer(
ZeroCopyOutputStream * output,
char variable_delimiter)Create a printer that writes text to the given output stream.
Use the given character as the delimiter for variables.
- Printer::Printer(
ZeroCopyOutputStream * output,
char variable_delimiter,
AnnotationCollector * annotation_collector)Create a printer that writes text to the given output stream.
Use the given character as the delimiter for variables. If annotation_collector is not null, Printer will provide it with annotations about code written to the stream. annotation_collector is not owned by Printer.
-template void Printer::Annotate(
const char * begin_varname,
const char * end_varname,
const SomeDescriptor * descriptor)Link the output range defined by the substitution variables as emitted by the last call to Print to the object described by descriptor.
The range begins at begin_varname's value and ends after the last character of the value substituted for end_varname.
-void Printer::Annotate(
const char * begin_varname,
const char * end_varname,
const std::string & file_name)Link the output range defined by the substitution variables as emitted by the last call to Print to the file with path file_name.
The range begins at begin_varname's value and ends after the last character of the value substituted for end_varname.
-void Printer::Print(
const std::map< std::string, std::string > & variables,
const char * text)Print some text after applying variable substitutions.
If a particular variable in the text is not defined, this will crash. Variables to be substituted are identified by their names surrounded by delimiter characters (as given to the constructor). The variable bindings are defined by the given map.
-void Printer::Indent()Indent text by two spaces.
After calling Indent(), two spaces will be inserted at the beginning of each line of text. Indent() may be called multiple times to produce deeper indents.
-void Printer::PrintRaw(
const std::string & data)Write a string to the output buffer.
This method does not look for newlines to add indentation.
-void Printer::PrintRaw(
const char * data)Write a zero-delimited string to output buffer.
This method does not look for newlines to add indentation.
-void Printer::WriteRaw(
const char * data,
int size)Write some bytes to the output buffer.
This method does not look for newlines to add indentation.
-void Printer::FormatInternal(
const std::vector< std::string > & args,
const std::map< std::string, std::string > & vars,
const char * format)FormatInternal is a helper function not meant to use directly, use compiler::cpp::Formatter instead.
This function is meant to support formatting text using named variables (eq. "$foo$) from a lookup map (vars) -and variables directly supplied by arguments (eq "$1$" meaning first argument which is the zero index element of args).
-bool Printer::failed() constTrue if any write to the underlying stream failed.
(We don't just crash in this case because this is an I/O failure, not a programming error.)
-#include <google/protobuf/io/tokenizer.h>
namespace google::protobuf::io
Class for parsing tokenized text from a ZeroCopyInputStream.
Classes in this file | |
|---|---|
Abstract interface for an object which collects the errors that occur during parsing. | |
This class converts a stream of raw text into a stream of tokens for the protocol definition parser to parse. | |
Structure representing a token read from the token stream. | |
File MembersThese definitions are not part of any class. | |
|---|---|
typedef | int ColumnNumberBy "column number", the proto compiler refers to a count of the number of bytes before a given byte, except that a tab character advances to the next multiple of 8 bytes. more... |
typedef io::ColumnNumberBy "column number", the proto compiler refers to a count of the number of bytes before a given byte, except that a tab character advances to the next multiple of 8 bytes.
Note in particular that column numbers are zero-based, while many user interfaces use one-based column numbers.
-#include <google/protobuf/io/tokenizer.h>
namespace google::protobuf::io
Abstract interface for an object which collects the errors that occur during parsing.
A typical implementation might simply print the errors to stdout.
- -Members | |
|---|---|
| ErrorCollector() |
virtual | ~ErrorCollector() |
virtual void | AddError(int line, ColumnNumber column, const std::string & message) = 0Indicates that there was an error in the input at the given line and column numbers. more... |
virtual void | AddWarning(int , ColumnNumber , const std::string & )Indicates that there was a warning in the input at the given line and column numbers. more... |
virtual void ErrorCollector::AddError(
int line,
ColumnNumber column,
const std::string & message) = 0Indicates that there was an error in the input at the given line and column numbers.
The numbers are zero-based, so you may want to add 1 to each before printing them.
-virtual void ErrorCollector::AddWarning(
int ,
ColumnNumber ,
const std::string & )Indicates that there was a warning in the input at the given line and column numbers.
The numbers are zero-based, so you may want to add 1 to each before printing them.
-#include <google/protobuf/io/tokenizer.h>
namespace google::protobuf::io
This class converts a stream of raw text into a stream of tokens for the protocol definition parser to parse.
The tokens recognized are similar to those that make up the C language; see the TokenType enum for precise descriptions. Whitespace and comments are skipped. By default, C- and C++-style comments are recognized, but other styles can be used by calling set_comment_style().
-Members | |
|---|---|
enum | TokenType |
| Tokenizer(ZeroCopyInputStream * input, ErrorCollector * error_collector) |
| ~Tokenizer() |
const Token & | current()Get the current token. more... |
const Token & | previous()Return the previous token – i.e. more... |
bool | Next()Advance to the next token. more... |
bool | NextWithComments(std::string * prev_trailing_comments, std::vector< std::string > * detached_comments, std::string * next_leading_comments) |
Options | |
enum | CommentStyleValid values for set_comment_style(). more... |
void | set_allow_f_after_float(bool value)Set true to allow floats to be suffixed with the letter 'f'. more... |
void | set_comment_style(CommentStyle style)Sets the comment style. |
void | set_require_space_after_number(bool require)Whether to require whitespace between a number and a field name. more... |
void | set_allow_multiline_strings(bool allow)Whether to allow string literals to span multiple lines. more... |
static bool | IsIdentifier(const std::string & text)External helper: validate an identifier. |
Parse helpers | |
static double | ParseFloat(const std::string & text)Parses a TYPE_FLOAT token. more... |
static void | ParseString(const std::string & text, std::string * output)Parses a TYPE_STRING token. more... |
static void | ParseStringAppend(const std::string & text, std::string * output)Identical to ParseString, but appends to output. |
static bool | ParseInteger(const std::string & text, uint64 max_value, uint64 * output)Parses a TYPE_INTEGER token. more... |
enum Tokenizer::TokenType {
TYPE_START,
TYPE_END,
TYPE_IDENTIFIER,
TYPE_INTEGER,
TYPE_FLOAT,
TYPE_STRING,
TYPE_SYMBOL
}| TYPE_START | Next() has not yet been called. |
| TYPE_END | End of input reached. "text" is empty. |
| TYPE_IDENTIFIER | A sequence of letters, digits, and underscores, not starting with a digit. It is an error for a number to be followed by an identifier with no space in between. - |
| TYPE_INTEGER | A sequence of digits representing an integer. Normally the digits are decimal, but a prefix of "0x" indicates a hex number and a leading zero indicates octal, just like with C numeric literals. A leading negative sign is NOT included in the token; it's up to the parser to interpret the unary minus operator on its own. - |
| TYPE_FLOAT | A floating point literal, with a fractional part and/or an exponent. Always in decimal. Again, never negative. - |
| TYPE_STRING | A quoted sequence of escaped characters. Either single or double quotes can be used, but they must match. A string literal cannot cross a line break. - |
| TYPE_SYMBOL | Any other printable character, like '!' or '+'. Symbols are always a single character, so "!+$%" is four tokens. - |
Tokenizer::Tokenizer(
ZeroCopyInputStream * input,
ErrorCollector * error_collector)Construct a Tokenizer that reads and tokenizes text from the given input stream and writes errors to the given error_collector.
The caller keeps ownership of input and error_collector.
-const Token & Tokenizer::current()Get the current token.
This is updated when Next() is called. Before the first call to Next(), current() has type TYPE_START and no contents.
-const Token & Tokenizer::previous()bool Tokenizer::Next()Advance to the next token.
Returns false if the end of the input is reached.
-bool Tokenizer::NextWithComments(
std::string * prev_trailing_comments,
std::vector< std::string > * detached_comments,
std::string * next_leading_comments)Like Next(), but also collects comments which appear between the previous and next tokens.
Comments which appear to be attached to the previous token are stored in *prev_tailing_comments. Comments which appear to be attached to the next token are stored in *next_leading_comments. Comments appearing in between which do not appear to be attached to either will be added to detached_comments. Any of these parameters can be NULL to simply discard the comments.
-A series of line comments appearing on consecutive lines, with no other tokens appearing on those lines, will be treated as a single comment.
-Only the comment content is returned; comment markers (e.g. //) are stripped out. For block comments, leading whitespace and an asterisk will be stripped from the beginning of each line other than the first. Newlines are included in the output.
-Examples:
-optional int32 foo = 1; // Comment attached to foo. -// Comment attached to bar. -optional int32 bar = 2; - -optional string baz = 3; -// Comment attached to baz. -// Another line attached to baz. - -// Comment attached to qux. -// -// Another line attached to qux. -optional double qux = 4; - -// Detached comment. This is not attached to qux or corge -// because there are blank lines separating it from both. - -optional string corge = 5; -/* Block comment attached - * to corge. Leading asterisks - * will be removed. * / -/* Block comment attached to - * grault. * / -optional int32 grault = 6; - *-
enum Tokenizer::CommentStyle {
CPP_COMMENT_STYLE,
SH_COMMENT_STYLE
}Valid values for set_comment_style().
| CPP_COMMENT_STYLE | Line comments begin with "//", block comments are delimited by "/*" and "* /". |
| SH_COMMENT_STYLE | Line comments begin with "#". No way to write block comments. |
void Tokenizer::set_allow_f_after_float(
bool value)Set true to allow floats to be suffixed with the letter 'f'.
Tokens which would otherwise be integers but which have the 'f' suffix will be forced to be interpreted as floats. For all other purposes, the 'f' is ignored.
-void Tokenizer::set_require_space_after_number(
bool require)Whether to require whitespace between a number and a field name.
Default is true. Do not use this; for Google-internal cleanup only.
-void Tokenizer::set_allow_multiline_strings(
bool allow)Whether to allow string literals to span multiple lines.
Default is false. Do not use this; for Google-internal cleanup only.
-static double Tokenizer::ParseFloat(
const std::string & text)Parses a TYPE_FLOAT token.
This never fails, so long as the text actually comes from a TYPE_FLOAT token parsed by Tokenizer. If it doesn't, the result is undefined (possibly an assert failure).
-static void Tokenizer::ParseString(
const std::string & text,
std::string * output)Parses a TYPE_STRING token.
This never fails, so long as the text actually comes from a TYPE_STRING token parsed by Tokenizer. If it doesn't, the result is undefined (possibly an assert failure).
-static bool Tokenizer::ParseInteger(
const std::string & text,
uint64 max_value,
uint64 * output)Parses a TYPE_INTEGER token.
Returns false if the result would be greater than max_value. Otherwise, returns true and sets *output to the result. If the text is not from a Token of type TYPE_INTEGER originally parsed by a Tokenizer, the result is undefined (possibly an assert failure).
-#include <google/protobuf/io/tokenizer.h>
namespace google::protobuf::io
Structure representing a token read from the token stream.
Members | |
|---|---|
TokenType | type |
std::string | textThe exact text of the token as it appeared in the input. more... |
int | line"line" and "column" specify the position of the first character of the token within the input stream. more... |
ColumnNumber | column |
ColumnNumber | end_column |
std::string Token::textThe exact text of the token as it appeared in the input.
e.g. tokens of TYPE_STRING will still be escaped and in quotes.
-int Token::line"line" and "column" specify the position of the first character of the token within the input stream.
They are zero-based.
-#include <google/protobuf/io/zero_copy_stream.h>
namespace google::protobuf::io
This file contains the ZeroCopyInputStream and ZeroCopyOutputStream interfaces, which represent abstract I/O streams to and from which protocol buffers can be read and written.
For a few simple implementations of these interfaces, see zero_copy_stream_impl.h.
- -These interfaces are different from classic I/O streams in that they try to minimize the amount of data copying that needs to be done. To accomplish this, responsibility for allocating buffers is moved to the stream object, rather than being the responsibility of the caller. So, the stream can return a buffer which actually points directly into the final data structure where the bytes are to be stored, and the caller can interact directly with that buffer, eliminating an intermediate copy operation.
- -As an example, consider the common case in which you are reading bytes from an array that is already in memory (or perhaps an mmap()ed file). With classic I/O streams, you would do something like:
- -char buffer[BUFFER_SIZE]; -input->Read(buffer, BUFFER_SIZE); -DoSomething(buffer, BUFFER_SIZE);- -
Then, the stream basically just calls memcpy() to copy the data from the array into your buffer. With a ZeroCopyInputStream, you would do this instead:
- -const void* buffer; -int size; -input->Next(&buffer, &size); -DoSomething(buffer, size);- -
Here, no copy is performed. The input stream returns a pointer directly into the backing array, and the caller ends up reading directly from it.
- -If you want to be able to read the old-fashion way, you can create a CodedInputStream or CodedOutputStream wrapping these objects and use their ReadRaw()/WriteRaw() methods. These will, of course, add a copy step, but Coded*Stream will handle buffering so at least it will be reasonably efficient.
- -ZeroCopyInputStream example:
- -// Read in a file and print its contents to stdout.
-int fd = open("myfile", O_RDONLY);
-ZeroCopyInputStream* input = new FileInputStream(fd);
-
-const void* buffer;
-int size;
-while (input->Next(&buffer, &size)) {
- cout.write(buffer, size);
-}
-
-delete input;
-close(fd);
-
-ZeroCopyOutputStream example:
- -// Copy the contents of "infile" to "outfile", using plain read() for
-// "infile" but a ZeroCopyOutputStream for "outfile".
-int infd = open("infile", O_RDONLY);
-int outfd = open("outfile", O_WRONLY);
-ZeroCopyOutputStream* output = new FileOutputStream(outfd);
-
-void* buffer;
-int size;
-while (output->Next(&buffer, &size)) {
- int bytes = read(infd, buffer, size);
- if (bytes < size) {
- // Reached EOF.
- output->BackUp(size - bytes);
- break;
- }
-}
-
-delete output;
-close(infd);
-close(outfd);
-
-Classes in this file | |
|---|---|
Abstract interface similar to an input stream but designed to minimize copying. | |
Abstract interface similar to an output stream but designed to minimize copying. | |
#include <google/protobuf/io/zero_copy_stream.h>
namespace google::protobuf::io
Abstract interface similar to an input stream but designed to minimize copying.
Known subclasses:
ArrayInputStreamConcatenatingInputStreamCopyingInputStreamAdaptorFileInputStreamIstreamInputStreamLimitingInputStreamMembers | |
|---|---|
| ZeroCopyInputStream() |
virtual | ~ZeroCopyInputStream() |
virtual bool | Next(const void ** data, int * size) = 0Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) = 0 |
virtual bool | Skip(int count) = 0Skips a number of bytes. more... |
virtual int64_t | ByteCount() const = 0Returns the total number of bytes read since this object was created. |
virtual bool ZeroCopyInputStream::Next(
const void ** data,
int * size) = 0Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void ZeroCopyInputStream::BackUp(
int count) = 0Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool ZeroCopyInputStream::Skip(
int count) = 0Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream.h>
namespace google::protobuf::io
Abstract interface similar to an output stream but designed to minimize copying.
Known subclasses:
Members | |
|---|---|
| ZeroCopyOutputStream() |
virtual | ~ZeroCopyOutputStream() |
virtual bool | Next(void ** data, int * size) = 0Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) = 0 |
virtual int64_t | ByteCount() const = 0Returns the total number of bytes written since this object was created. |
virtual bool | WriteAliasedRaw(const void * data, int size)Write a given chunk of data to the output. more... |
virtual bool | AllowsAliasing() const |
virtual bool ZeroCopyOutputStream::Next(
void ** data,
int * size) = 0Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void ZeroCopyOutputStream::BackUp(
int count) = 0Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-virtual bool ZeroCopyOutputStream::WriteAliasedRaw(
const void * data,
int size)Write a given chunk of data to the output.
Some output streams may implement this in a way that avoids copying. Check AllowsAliasing() before calling WriteAliasedRaw(). It will GOOGLE_CHECK fail if WriteAliasedRaw() is called on a stream that does not allow aliasing.
-NOTE: It is caller's responsibility to ensure that the chunk of memory remains live until all of the data has been consumed from the stream.
-#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
This file contains common implementations of the interfaces defined in zero_copy_stream.h which are only included in the full (non-lite) protobuf library.
These implementations include Unix file descriptors and C++ iostreams. See also: zero_copy_stream_impl_lite.h
- -Classes in this file | |
|---|---|
A ZeroCopyInputStream which reads from a file descriptor. | |
A ZeroCopyOutputStream which writes to a file descriptor. | |
A ZeroCopyInputStream which reads from a C++ istream. | |
A ZeroCopyOutputStream which writes to a C++ ostream. | |
A ZeroCopyInputStream which reads from several other streams in sequence. | |
#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
A ZeroCopyInputStream which reads from a file descriptor.
FileInputStream is preferred over using an ifstream with IstreamInputStream. The latter will introduce an extra layer of buffering, harming performance. Also, it's conceivable that FileInputStream could someday be enhanced to use zero-copy file descriptors on OSs which support them.
-Members | |
|---|---|
explicit | FileInputStream(int file_descriptor, int block_size = -1)Creates a stream that reads from the given Unix file descriptor. more... |
bool | Close()Flushes any buffers and closes the underlying file. more... |
void | SetCloseOnDelete(bool value)By default, the file descriptor is not closed when the stream is destroyed. more... |
int | GetErrno() constIf an I/O error has occurred on this file descriptor, this is the errno from that error. more... |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
explicit FileInputStream::FileInputStream(
int file_descriptor,
int block_size = -1)Creates a stream that reads from the given Unix file descriptor.
If a block_size is given, it specifies the number of bytes that should be read and returned with each call to Next(). Otherwise, a reasonable default is used.
-bool FileInputStream::Close()Flushes any buffers and closes the underlying file.
Returns false if an error occurs during the process; use GetErrno() to examine the error. Even if an error occurs, the file descriptor is closed when this returns.
-void FileInputStream::SetCloseOnDelete(
bool value)By default, the file descriptor is not closed when the stream is destroyed.
Call SetCloseOnDelete(true) to change that. WARNING: This leaves no way for the caller to detect if close() fails. If detecting close() errors is important to you, you should arrange to close the descriptor yourself.
-int FileInputStream::GetErrno() constIf an I/O error has occurred on this file descriptor, this is the errno from that error.
Otherwise, this is zero. Once an error occurs, the stream is broken and all subsequent operations will fail.
-virtual bool FileInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void FileInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool FileInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
A ZeroCopyOutputStream which writes to a file descriptor.
FileOutputStream is preferred over using an ofstream with OstreamOutputStream. The latter will introduce an extra layer of buffering, harming performance. Also, it's conceivable that FileOutputStream could someday be enhanced to use zero-copy file descriptors on OSs which support them.
-Members | |
|---|---|
explicit | FileOutputStream(int file_descriptor, int block_size = -1)Creates a stream that writes to the given Unix file descriptor. more... |
| ~FileOutputStream() |
bool | Close()Flushes any buffers and closes the underlying file. more... |
void | SetCloseOnDelete(bool value)By default, the file descriptor is not closed when the stream is destroyed. more... |
int | GetErrno() constIf an I/O error has occurred on this file descriptor, this is the errno from that error. more... |
explicit FileOutputStream::FileOutputStream(
int file_descriptor,
int block_size = -1)Creates a stream that writes to the given Unix file descriptor.
If a block_size is given, it specifies the size of the buffers that should be returned by Next(). Otherwise, a reasonable default is used.
-bool FileOutputStream::Close()Flushes any buffers and closes the underlying file.
Returns false if an error occurs during the process; use GetErrno() to examine the error. Even if an error occurs, the file descriptor is closed when this returns.
-void FileOutputStream::SetCloseOnDelete(
bool value)By default, the file descriptor is not closed when the stream is destroyed.
Call SetCloseOnDelete(true) to change that. WARNING: This leaves no way for the caller to detect if close() fails. If detecting close() errors is important to you, you should arrange to close the descriptor yourself.
-int FileOutputStream::GetErrno() constIf an I/O error has occurred on this file descriptor, this is the errno from that error.
Otherwise, this is zero. Once an error occurs, the stream is broken and all subsequent operations will fail.
-#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
A ZeroCopyInputStream which reads from a C++ istream.
Note that for reading files (or anything represented by a file descriptor), FileInputStream is more efficient.
-Members | |
|---|---|
explicit | IstreamInputStream(std::istream * stream, int block_size = -1)Creates a stream that reads from the given C++ istream. more... |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
explicit IstreamInputStream::IstreamInputStream(
std::istream * stream,
int block_size = -1)Creates a stream that reads from the given C++ istream.
If a block_size is given, it specifies the number of bytes that should be read and returned with each call to Next(). Otherwise, a reasonable default is used.
-virtual bool IstreamInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void IstreamInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool IstreamInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
A ZeroCopyOutputStream which writes to a C++ ostream.
Note that for writing files (or anything represented by a file descriptor), FileOutputStream is more efficient.
-Members | |
|---|---|
explicit | OstreamOutputStream(std::ostream * stream, int block_size = -1)Creates a stream that writes to the given C++ ostream. more... |
| ~OstreamOutputStream() |
implements ZeroCopyOutputStream | |
virtual bool | Next(void ** data, int * size)Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) |
virtual int64_t | ByteCount() constReturns the total number of bytes written since this object was created. |
explicit OstreamOutputStream::OstreamOutputStream(
std::ostream * stream,
int block_size = -1)Creates a stream that writes to the given C++ ostream.
If a block_size is given, it specifies the size of the buffers that should be returned by Next(). Otherwise, a reasonable default is used.
-virtual bool OstreamOutputStream::Next(
void ** data,
int * size)Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void OstreamOutputStream::BackUp(
int count)Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-#include <google/protobuf/io/zero_copy_stream_impl.h>
namespace google::protobuf::io
A ZeroCopyInputStream which reads from several other streams in sequence.
ConcatenatingInputStream is unable to distinguish between end-of-stream and read errors in the underlying streams, so it assumes any errors mean end-of-stream. So, if the underlying streams fail for any other reason, ConcatenatingInputStream may do odd things. It is suggested that you do not use ConcatenatingInputStream on streams that might produce read errors other than end-of-stream.
-Members | |
|---|---|
| ConcatenatingInputStream(ZeroCopyInputStream *const streams, int count)All streams passed in as well as the array itself must remain valid until the ConcatenatingInputStream is destroyed. |
| ~ConcatenatingInputStream() |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
virtual bool ConcatenatingInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void ConcatenatingInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool ConcatenatingInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
This file contains common implementations of the interfaces defined in zero_copy_stream.h which are included in the "lite" protobuf library.
These implementations cover I/O on raw arrays and strings, as well as adaptors which make it easy to implement streams based on traditional streams. Of course, many users will probably want to write their own implementations of these interfaces specific to the particular I/O abstractions they prefer to use, but these should cover the most common cases.
- -Classes in this file | |
|---|---|
A ZeroCopyInputStream backed by an in-memory array of bytes. | |
A ZeroCopyOutputStream backed by an in-memory array of bytes. | |
A ZeroCopyOutputStream which appends bytes to a string. | |
A generic traditional input stream interface. | |
A ZeroCopyInputStream which reads from a CopyingInputStream. | |
A generic traditional output stream interface. | |
A ZeroCopyOutputStream which writes to a CopyingOutputStream. | |
A ZeroCopyInputStream which wraps some other stream and limits it to a particular byte count. | |
File MembersThese definitions are not part of any class. | |
|---|---|
char * | mutable_string_data(std::string * s)Return a pointer to mutable characters underlying the given string. more... |
std::pair< char *, bool > | as_string_data(std::string * s)as_string_data(s) is equivalent to ({ char* p = mutable_string_data(s); make_pair(p, p != NULL); }) Sometimes it's faster: in some scenarios p cannot be NULL, and then the code can avoid that check. |
char * io::mutable_string_data(
std::string * s)Return a pointer to mutable characters underlying the given string.
The return value is valid until the next time the string is resized. We trust the caller to treat the return value as an array of length s->size().
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyInputStream backed by an in-memory array of bytes.
Members | |
|---|---|
| ArrayInputStream(const void * data, int size, int block_size = -1)Create an InputStream that returns the bytes pointed to by "data". more... |
| ~ArrayInputStream() |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
ArrayInputStream::ArrayInputStream(
const void * data,
int size,
int block_size = -1)Create an InputStream that returns the bytes pointed to by "data".
"data" remains the property of the caller but must remain valid until the stream is destroyed. If a block_size is given, calls to Next() will return data blocks no larger than the given size. Otherwise, the first call to Next() returns the entire array. block_size is mainly useful for testing; in production you would probably never want to set it.
-virtual bool ArrayInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void ArrayInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool ArrayInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyOutputStream backed by an in-memory array of bytes.
Members | |
|---|---|
| ArrayOutputStream(void * data, int size, int block_size = -1)Create an OutputStream that writes to the bytes pointed to by "data". more... |
| ~ArrayOutputStream() |
implements ZeroCopyOutputStream | |
virtual bool | Next(void ** data, int * size)Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) |
virtual int64_t | ByteCount() constReturns the total number of bytes written since this object was created. |
ArrayOutputStream::ArrayOutputStream(
void * data,
int size,
int block_size = -1)Create an OutputStream that writes to the bytes pointed to by "data".
"data" remains the property of the caller but must remain valid until the stream is destroyed. If a block_size is given, calls to Next() will return data blocks no larger than the given size. Otherwise, the first call to Next() returns the entire array. block_size is mainly useful for testing; in production you would probably never want to set it.
-virtual bool ArrayOutputStream::Next(
void ** data,
int * size)Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void ArrayOutputStream::BackUp(
int count)Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyOutputStream which appends bytes to a string.
Members | |
|---|---|
explicit | StringOutputStream(std::string * target)Create a StringOutputStream which appends bytes to the given string. more... |
| ~StringOutputStream() |
implements ZeroCopyOutputStream | |
virtual bool | Next(void ** data, int * size)Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) |
virtual int64_t | ByteCount() constReturns the total number of bytes written since this object was created. |
explicit StringOutputStream::StringOutputStream(
std::string * target)Create a StringOutputStream which appends bytes to the given string.
The string remains property of the caller, but it is mutated in arbitrary ways and MUST NOT be accessed in any way until you're done with the stream. Either be sure there's no further usage, or (safest) destroy the stream before using the contents.
-Hint: If you call target->reserve(n) before creating the stream, the first call to Next() will return at least n bytes of buffer space.
-virtual bool StringOutputStream::Next(
void ** data,
int * size)Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void StringOutputStream::BackUp(
int count)Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A generic traditional input stream interface.
Lots of traditional input streams (e.g. file descriptors, C stdio streams, and C++ iostreams) expose an interface where every read involves copying bytes into a buffer. If you want to take such an interface and make a ZeroCopyInputStream based on it, simply implement CopyingInputStream and then use CopyingInputStreamAdaptor.
-CopyingInputStream implementations should avoid buffering if possible. CopyingInputStreamAdaptor does its own buffering and will read data in large blocks.
-Members | |
|---|---|
virtual | ~CopyingInputStream() |
virtual int | Read(void * buffer, int size) = 0Reads up to "size" bytes into the given buffer. more... |
virtual int | Skip(int count)Skips the next "count" bytes of input. more... |
virtual int CopyingInputStream::Read(
void * buffer,
int size) = 0Reads up to "size" bytes into the given buffer.
Returns the number of bytes read. Read() waits until at least one byte is available, or returns zero if no bytes will ever become available (EOF), or -1 if a permanent read error occurred.
-virtual int CopyingInputStream::Skip(
int count)Skips the next "count" bytes of input.
Returns the number of bytes actually skipped. This will always be exactly equal to "count" unless EOF was reached or a permanent read error occurred.
-The default implementation just repeatedly calls Read() into a scratch buffer.
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyInputStream which reads from a CopyingInputStream.
This is useful for implementing ZeroCopyInputStreams that read from traditional streams. Note that this class is not really zero-copy.
-If you want to read from file descriptors or C++ istreams, this is already implemented for you: use FileInputStream or IstreamInputStream respectively.
-Members | |
|---|---|
explicit | CopyingInputStreamAdaptor(CopyingInputStream * copying_stream, int block_size = -1)Creates a stream that reads from the given CopyingInputStream. more... |
| ~CopyingInputStreamAdaptor() |
void | SetOwnsCopyingStream(bool value)Call SetOwnsCopyingStream(true) to tell the CopyingInputStreamAdaptor to delete the underlying CopyingInputStream when it is destroyed. |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
explicit CopyingInputStreamAdaptor::CopyingInputStreamAdaptor(
CopyingInputStream * copying_stream,
int block_size = -1)Creates a stream that reads from the given CopyingInputStream.
If a block_size is given, it specifies the number of bytes that should be read and returned with each call to Next(). Otherwise, a reasonable default is used. The caller retains ownership of copying_stream unless SetOwnsCopyingStream(true) is called.
-virtual bool CopyingInputStreamAdaptor::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void CopyingInputStreamAdaptor::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool CopyingInputStreamAdaptor::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A generic traditional output stream interface.
Lots of traditional output streams (e.g. file descriptors, C stdio streams, and C++ iostreams) expose an interface where every write involves copying bytes from a buffer. If you want to take such an interface and make a ZeroCopyOutputStream based on it, simply implement CopyingOutputStream and then use CopyingOutputStreamAdaptor.
-CopyingOutputStream implementations should avoid buffering if possible. CopyingOutputStreamAdaptor does its own buffering and will write data in large blocks.
-Members | |
|---|---|
virtual | ~CopyingOutputStream() |
virtual bool | Write(const void * buffer, int size) = 0Writes "size" bytes from the given buffer to the output. more... |
virtual bool CopyingOutputStream::Write(
const void * buffer,
int size) = 0Writes "size" bytes from the given buffer to the output.
Returns true if successful, false on a write error.
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyOutputStream which writes to a CopyingOutputStream.
This is useful for implementing ZeroCopyOutputStreams that write to traditional streams. Note that this class is not really zero-copy.
-If you want to write to file descriptors or C++ ostreams, this is already implemented for you: use FileOutputStream or OstreamOutputStream respectively.
-Known subclasses:
Members | |
|---|---|
explicit | CopyingOutputStreamAdaptor(CopyingOutputStream * copying_stream, int block_size = -1)Creates a stream that writes to the given Unix file descriptor. more... |
| ~CopyingOutputStreamAdaptor() |
bool | Flush()Writes all pending data to the underlying stream. more... |
void | SetOwnsCopyingStream(bool value)Call SetOwnsCopyingStream(true) to tell the CopyingOutputStreamAdaptor to delete the underlying CopyingOutputStream when it is destroyed. |
implements ZeroCopyOutputStream | |
virtual bool | Next(void ** data, int * size)Obtains a buffer into which data can be written. more... |
virtual void | BackUp(int count) |
virtual int64_t | ByteCount() constReturns the total number of bytes written since this object was created. |
virtual bool | WriteAliasedRaw(const void * data, int size)Write a given chunk of data to the output. more... |
virtual bool | AllowsAliasing() const |
explicit CopyingOutputStreamAdaptor::CopyingOutputStreamAdaptor(
CopyingOutputStream * copying_stream,
int block_size = -1)Creates a stream that writes to the given Unix file descriptor.
If a block_size is given, it specifies the size of the buffers that should be returned by Next(). Otherwise, a reasonable default is used.
-bool CopyingOutputStreamAdaptor::Flush()Writes all pending data to the underlying stream.
Returns false if a write error occurred on the underlying stream. (The underlying stream itself is not necessarily flushed.)
-virtual bool CopyingOutputStreamAdaptor::Next(
void ** data,
int * size)Obtains a buffer into which data can be written.
Any data written into this buffer will eventually (maybe instantly, maybe later on) be written to the output.
-Preconditions:
-Postconditions:
-virtual void CopyingOutputStreamAdaptor::BackUp(
int count)Backs up a number of bytes, so that the end of the last buffer returned by Next() is not actually written.
This is needed when you finish writing all the data you want to write, but the last buffer was bigger than you needed. You don't want to write a bunch of garbage after the end of your data, so you use BackUp() to back up.
-Preconditions:
-Postconditions:
-virtual bool CopyingOutputStreamAdaptor::WriteAliasedRaw(
const void * data,
int size)Write a given chunk of data to the output.
Some output streams may implement this in a way that avoids copying. Check AllowsAliasing() before calling WriteAliasedRaw(). It will GOOGLE_CHECK fail if WriteAliasedRaw() is called on a stream that does not allow aliasing.
-NOTE: It is caller's responsibility to ensure that the chunk of memory remains live until all of the data has been consumed from the stream.
-#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
namespace google::protobuf::io
A ZeroCopyInputStream which wraps some other stream and limits it to a particular byte count.
Members | |
|---|---|
| LimitingInputStream(ZeroCopyInputStream * input, int64 limit) |
| ~LimitingInputStream() |
implements ZeroCopyInputStream | |
virtual bool | Next(const void ** data, int * size)Obtains a chunk of data from the stream. more... |
virtual void | BackUp(int count) |
virtual bool | Skip(int count)Skips a number of bytes. more... |
virtual int64_t | ByteCount() constReturns the total number of bytes read since this object was created. |
virtual bool LimitingInputStream::Next(
const void ** data,
int * size)Obtains a chunk of data from the stream.
Preconditions:
-Postconditions:
-virtual void LimitingInputStream::BackUp(
int count)Backs up a number of bytes, so that the next call to Next() returns data again that was already returned by the last call to Next().
This is useful when writing procedures that are only supposed to read up to a certain point in the input, then return. If Next() returns a buffer that goes beyond what you wanted to read, you can use BackUp() to return to the point where you intended to finish.
-Preconditions:
-Postconditions:
- -virtual bool LimitingInputStream::Skip(
int count)Skips a number of bytes.
Returns false if the end of the stream is reached or some input error occurred. In the end-of-stream case, the stream is advanced to the end of the stream (so ByteCount() will return the total size of the stream).
-#include <google/protobuf/map.h>
namespace google::protobuf
This file defines the map container and its helpers to support protobuf maps.
The Map and MapIterator types are provided by this header file. Please avoid using other types defined here, unless they are public types within Map or MapIterator, such as Map::value_type.
- -Classes in this file | |
|---|---|
This is the class for Map's internal value_type. | |
Map is an associative container type used to store protobuf map fields. | |
Iterators. | |
#include <google/protobuf/map.h>
namespace google::protobuf
template <typename , typename >
This is the class for Map's internal value_type, which is just an alias to std::pair.
-#include <google/protobuf/map.h>
namespace google::protobuf
template <typename , typename >
Map is an associative container type used to store protobuf map fields.
Each Map instance may or may not use a different hash function, a different iteration order, and so on. E.g., please don't examine implementation details to decide if the following would work: Map<int, int> m0, m1; m0[0] = m1[0] = m0[1] = m1[1] = 0; assert(m0.begin()->first == m1.begin()->first); // Bug!
-Map's interface is similar to std::unordered_map, except that Map is not designed to play well with exceptions.
-Members | |
|---|---|
typedef | Key key_type |
typedef | T mapped_type |
typedef | MapPair< Key, T > value_type |
typedef | value_type * pointer |
typedef | const value_type * const_pointer |
typedef | value_type & reference |
typedef | const value_type & const_reference |
typedef | size_t size_type |
typedef | typename internal::TransparentSupport< Key >::hash hasher |
constexpr | Map() |
explicit | Map(Arena * arena) |
| Map(const Map & other) |
| Map(Map && other) |
Map & | operator=(Map && other) |
template | Map(const InputIt & first, const InputIt & last) |
| ~Map() |
iterator | begin() |
iterator | end() |
const_iterator | begin() const |
const_iterator | end() const |
const_iterator | cbegin() const |
const_iterator | cend() const |
size_type | size() constCapacity. |
bool | empty() const |
template T & | operator[](const key_arg< K > & key)Element access. |
template T & | operator[](key_arg< K > && key) |
template const T & | at(const key_arg< K > & key) const |
template T & | at(const key_arg< K > & key) |
template size_type | count(const key_arg< K > & key) constLookup. |
template const_iterator | find(const key_arg< K > & key) const |
template iterator | find(const key_arg< K > & key) |
template bool | contains(const key_arg< K > & key) const |
template std::pair< const_iterator, const_iterator > | equal_range(const key_arg< K > & key) const |
template std::pair< iterator, iterator > | equal_range(const key_arg< K > & key) |
std::pair< iterator, bool > | insert(const value_type & value)insert |
template void | insert(InputIt first, InputIt last) |
void | insert(std::initializer_list< value_type > values) |
template size_type | erase(const key_arg< K > & key)Erase and clear. |
iterator | erase(iterator pos) |
void | |
void | clear() |
Map & | operator=(const Map & other)Assign. |
void | swap(Map & other) |
void | InternalSwap(Map & other) |
hasher | hash_function() constAccess to hasher. more... |
size_t | SpaceUsedExcludingSelfLong() const |
hasher Map::hash_function() constAccess to hasher.
Currently this returns a copy, but it may be modified to return a const reference in the future.
-#include <google/protobuf/map.h>
namespace google::protobuf
Iterators.
Members | |
|---|---|
typedef | std::forward_iterator_tag iterator_category |
typedef | typename Map::value_type value_type |
typedef | ptrdiff_t difference_type |
typedef | const value_type * pointer |
typedef | const value_type & reference |
| const_iterator() |
explicit | const_iterator(const InnerIt & it) |
const_reference | operator*() const |
const_pointer | operator->() const |
const_iterator & | operator++() |
const_iterator | operator++(int ) |
#include <google/protobuf/map.h>
namespace google::protobuf
Members | |
|---|---|
typedef | std::forward_iterator_tag iterator_category |
typedef | typename Map::value_type value_type |
typedef | ptrdiff_t difference_type |
typedef | value_type * pointer |
typedef | value_type & reference |
| iterator() |
explicit | iterator(const InnerIt & it) |
reference | operator*() const |
pointer | operator->() const |
iterator & | operator++() |
iterator | operator++(int ) |
| operator const_iterator() constAllow implicit conversion to const_iterator. |
#include <google/protobuf/message.h>
namespace google::protobuf
Defines Message, the abstract interface implemented by non-lite protocol message objects.
Although it's possible to implement this interface manually, most users will use the protocol compiler to generate implementations.
- -Example usage:
- -Say you have a message defined as:
- -message Foo {
- optional string text = 1;
- repeated int32 numbers = 2;
-}
-
-Then, if you used the protocol compiler to generate a class from the above definition, you could use it like so:
- -std::string data; // Will store a serialized version of the message.
-
-{
- // Create a message and serialize it.
- Foo foo;
- foo.set_text("Hello World!");
- foo.add_numbers(1);
- foo.add_numbers(5);
- foo.add_numbers(42);
-
- foo.SerializeToString(&data);
-}
-
-{
- // Parse the serialized message and check that it contains the
- // correct data.
- Foo foo;
- foo.ParseFromString(data);
-
- assert(foo.text() == "Hello World!");
- assert(foo.numbers_size() == 3);
- assert(foo.numbers(0) == 1);
- assert(foo.numbers(1) == 5);
- assert(foo.numbers(2) == 42);
-}
-
-{
- // Same as the last block, but do it dynamically via the Message
- // reflection interface.
- Message* foo = new Foo;
- const Descriptor* descriptor = foo->GetDescriptor();
-
- // Get the descriptors for the fields we're interested in and verify
- // their types.
- const FieldDescriptor* text_field = descriptor->FindFieldByName("text");
- assert(text_field != nullptr);
- assert(text_field->type() == FieldDescriptor::TYPE_STRING);
- assert(text_field->label() == FieldDescriptor::LABEL_OPTIONAL);
- const FieldDescriptor* numbers_field = descriptor->
- FindFieldByName("numbers");
- assert(numbers_field != nullptr);
- assert(numbers_field->type() == FieldDescriptor::TYPE_INT32);
- assert(numbers_field->label() == FieldDescriptor::LABEL_REPEATED);
-
- // Parse the message.
- foo->ParseFromString(data);
-
- // Use the reflection interface to examine the contents.
- const Reflection* reflection = foo->GetReflection();
- assert(reflection->GetString(*foo, text_field) == "Hello World!");
- assert(reflection->FieldSize(*foo, numbers_field) == 3);
- assert(reflection->GetRepeatedInt32(*foo, numbers_field, 0) == 1);
- assert(reflection->GetRepeatedInt32(*foo, numbers_field, 1) == 5);
- assert(reflection->GetRepeatedInt32(*foo, numbers_field, 2) == 42);
-
- delete foo;
-}
-
-Classes in this file | |
|---|---|
A container to hold message metadata. | |
Abstract interface for protocol messages. | |
This interface contains methods that can be used to dynamically access and modify the fields of a protocol message. | |
Abstract interface for a factory for message objects. | |
File MembersThese definitions are not part of any class. | |
|---|---|
template const T * | DynamicCastToGenerated(const Message * from)Tries to downcast this message to a generated message type. more... |
template T * | DynamicCastToGenerated(Message * from) |
template void | LinkMessageReflection()Call this function to ensure that this message's reflection is linked into the binary: more... |
const RepeatedPtrField< std::string > & | Reflection::GetRepeatedPtrFieldInternal< std::string >(const Message & message, const FieldDescriptor * field) const |
RepeatedPtrField< std::string > * | Reflection::MutableRepeatedPtrFieldInternal< std::string >(Message * message, const FieldDescriptor * field) const |
template const T * protobuf::DynamicCastToGenerated(
const Message * from)Tries to downcast this message to a generated message type.
Returns nullptr if this class is not an instance of T. This works even if RTTI is disabled.
-This also has the effect of creating a strong reference to T that will prevent the linker from stripping it out at link time. This can be important if you are using a DynamicMessageFactory that delegates to the generated factory.
-template void protobuf::LinkMessageReflection()Call this function to ensure that this message's reflection is linked into the binary:
google::protobuf::LinkMessageReflection<FooMessage>();-
This will ensure that the following lookup will succeed:
-DescriptorPool::generated_pool()->FindMessageTypeByName("FooMessage");
-As a side-effect, it will also guarantee that anything else from the same .proto file will also be available for lookup in the generated pool.
-This function does not actually register the message, so it does not need to be called before the lookup. However it does need to occur in a function that cannot be stripped from the binary (ie. it must be reachable from main).
-Best practice is to call this function as close as possible to where the reflection is actually needed. This function is very cheap to call, so you should not need to worry about its runtime overhead except in the tightest of loops (on x86-64 it compiles into two "mov" instructions).
-#include <google/protobuf/message.h>
namespace google::protobuf
A container to hold message metadata.
Members | |
|---|---|
const Descriptor * | descriptor |
const Reflection * | reflection |
#include <google/protobuf/message.h>
namespace google::protobuf
Abstract interface for protocol messages.
See also MessageLite, which contains most every-day operations. Message adds descriptors and reflection on top of that.
-The methods of this class that are virtual but not pure-virtual have default implementations based on reflection. Message classes which are optimized for speed will want to override these with faster implementations, but classes optimized for code size may be happy with keeping them. See the optimize_for option in descriptor.proto.
-Users must not derive from this class. Only the protocol compiler and the internal library are allowed to create subclasses.
-Members | |
|---|---|
constexpr | Message() |
protected virtual Metadata | GetMetadata() const = 0Get a struct containing the metadata for the Message, which is used in turn to implement GetDescriptor() and GetReflection() above. |
protected explicit | Message(Arena * arena) |
protected static uint64 | GetInvariantPerBuild(uint64 salt) |
Basic Operations | |
virtual Message * | New() const = 0Construct a new instance of the same type. more... |
virtual Message * | New(Arena * arena) constConstruct a new instance on the arena. more... |
virtual void | CopyFrom(const Message & from)Make this message into a copy of the given message. more... |
virtual void | MergeFrom(const Message & from)Merge the fields from the given message into this message. more... |
void | CheckInitialized() constVerifies that IsInitialized() returns true. more... |
void | FindInitializationErrors(std::vector< std::string > * errors) constSlowly build a list of all required fields that are not set. more... |
virtual std::string | InitializationErrorString() constLike FindInitializationErrors, but joins all the strings, delimited by commas, and returns them. |
virtual void | DiscardUnknownFields()Clears all unknown fields from this message and all embedded messages. more... |
virtual size_t | SpaceUsedLong() constComputes (an estimate of) the total number of bytes currently used for storing the message in memory. more... |
int | SpaceUsed() const |
Debugging & Testing | |
std::string | DebugString() constGenerates a human readable form of this message, useful for debugging and other purposes. |
std::string | ShortDebugString() constLike DebugString(), but with less whitespace. |
std::string | Utf8DebugString() constLike DebugString(), but do not escape UTF-8 byte sequences. |
void | PrintDebugString() constConvenience function useful in GDB. Prints DebugString() to stdout. |
Reflection-based methodsThese methods are pure-virtual in MessageLite, but Message provides reflection-based default implementations. | |
virtual std::string | GetTypeName() constGet the name of this message type, e.g. "foo.bar.BazProto". |
virtual void | Clear()Clear all fields of the message and set them to their default values. more... |
virtual bool | IsInitialized() constReturns whether all required fields have been set. more... |
virtual void | CheckTypeAndMergeFrom(const MessageLite & other)If |other| is the exact same class as this, calls MergeFrom(). more... |
virtual const char * | _InternalParse(const char * ptr, internal::ParseContext * ctx)Reflective parser. |
virtual size_t | ByteSizeLong() constComputes the serialized size of the message. more... |
virtual uint8 * | _InternalSerialize(uint8 * ptr, io::EpsCopyOutputStream * stream) constFast path when conditions match (ie. more... |
Introspection | |
const Descriptor * | GetDescriptor() constGet a non-owning pointer to a Descriptor for this message's type. more... |
const Reflection * | GetReflection() constGet a non-owning pointer to the Reflection interface for this Message, which can be used to read and modify the fields of the Message dynamically (in other words, without knowing the message type at compile time). more... |
virtual Message * Message::New() const = 0Construct a new instance of the same type.
Ownership is passed to the caller. (This is also defined in MessageLite, but is defined again here for return-type covariance.)
-virtual Message * Message::New(
Arena * arena) constConstruct a new instance on the arena.
Ownership is passed to the caller if arena is a nullptr. Default implementation allows for API compatibility during the Arena transition.
-virtual void Message::CopyFrom(
const Message & from)Make this message into a copy of the given message.
The given message must have the same descriptor, but need not necessarily be the same class. By default this is just implemented as "Clear(); MergeFrom(from);".
-virtual void Message::MergeFrom(
const Message & from)Merge the fields from the given message into this message.
Singular fields will be overwritten, if specified in from, except for embedded messages which will be merged. Repeated fields will be concatenated. The given message must be of the same type as this message (i.e. the exact same class).
-void Message::CheckInitialized() constVerifies that IsInitialized() returns true.
GOOGLE_CHECK-fails otherwise, with a nice error message.
-void Message::FindInitializationErrors(
std::vector< std::string > * errors) constSlowly build a list of all required fields that are not set.
This is much, much slower than IsInitialized() as it is implemented purely via reflection. Generally, you should not call this unless you have already determined that an error exists by calling IsInitialized().
-virtual void Message::DiscardUnknownFields()Clears all unknown fields from this message and all embedded messages.
Normally, if unknown tag numbers are encountered when parsing a message, the tag and value are stored in the message's UnknownFieldSet and then written back out when the message is serialized. This allows servers which simply route messages to other servers to pass through messages that have new field definitions which they don't yet know about. However, this behavior can have security implications. To avoid it, call this method after parsing.
-See Reflection::GetUnknownFields() for more on unknown fields.
-virtual size_t Message::SpaceUsedLong() constComputes (an estimate of) the total number of bytes currently used for storing the message in memory.
The default implementation calls the Reflection object's SpaceUsed() method.
-SpaceUsed() is noticeably slower than ByteSize(), as it is implemented using reflection (rather than the generated code implementation for ByteSize()). Like ByteSize(), its CPU time is linear in the number of fields defined for the proto.
-virtual void Message::Clear()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 bool Message::IsInitialized() constReturns whether all required fields have been set.
Note that required fields no longer exist starting in proto3.
-virtual void Message::CheckTypeAndMergeFrom(
const MessageLite & other)If |other| is the exact same class as this, calls MergeFrom().
Otherwise, results are undefined (probably crash).
-virtual size_t Message::ByteSizeLong() constComputes 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 uint8 * Message::_InternalSerialize(
uint8 * ptr,
io::EpsCopyOutputStream * stream) constFast path when conditions match (ie.
non-deterministic) uint8* _InternalSerialize(uint8* ptr) const;
-const Descriptor *
Message::GetDescriptor() constGet a non-owning pointer to a Descriptor for this message's type.
This describes what fields the message contains, the types of those fields, etc. This object remains property of the Message.
-const Reflection *
Message::GetReflection() constGet a non-owning pointer to the Reflection interface for this Message, which can be used to read and modify the fields of the Message dynamically (in other words, without knowing the message type at compile time).
This object remains property of the Message.
-#include <google/protobuf/message.h>
namespace google::protobuf
This interface contains methods that can be used to dynamically access and modify the fields of a protocol message.
Their semantics are similar to the accessors the protocol compiler generates.
-To get the Reflection for a given Message, call Message::GetReflection().
-This interface is separate from Message only for efficiency reasons; the vast majority of implementations of Message will share the same implementation of Reflection (GeneratedMessageReflection, defined in generated_message.h), and all Messages of a particular class should share the same Reflection object (though you should not rely on the latter fact).
-There are several ways that these methods can be used incorrectly. For example, any of the following conditions will lead to undefined results (probably assertion failures):
-You might wonder why there is not any abstract representation for a field of arbitrary type. E.g., why isn't there just a "GetField()" method that returns "const Field&", where "Field" is some class with accessors like "GetInt32Value()". The problem is that someone would have to deal with allocating these Field objects. For generated message classes, having to allocate space for an additional object to wrap every field would at least double the message's memory footprint, probably worse. Allocating the objects on-demand, on the other hand, would be expensive and prone to memory leaks. So, instead we ended up with this flat interface.
-Members | |
|---|---|
const UnknownFieldSet & | GetUnknownFields(const Message & message) constGet the UnknownFieldSet for the message. more... |
UnknownFieldSet * | MutableUnknownFields(Message * message) constGet a mutable pointer to the UnknownFieldSet for the message. more... |
size_t | SpaceUsedLong(const Message & message) constEstimate the amount of memory used by the message object. |
int | SpaceUsed(const Message & message) const |
bool | HasField(const Message & message, const FieldDescriptor * field) constCheck if the given non-repeated field is set. |
int | FieldSize(const Message & message, const FieldDescriptor * field) constGet the number of elements of a repeated field. |
void | ClearField(Message * message, const FieldDescriptor * field) constClear the value of a field, so that HasField() returns false or FieldSize() returns zero. |
bool | HasOneof(const Message & message, const OneofDescriptor * oneof_descriptor) constCheck if the oneof is set. more... |
void | ClearOneof(Message * message, const OneofDescriptor * oneof_descriptor) const |
const FieldDescriptor * | GetOneofFieldDescriptor(const Message & message, const OneofDescriptor * oneof_descriptor) constReturns the field descriptor if the oneof is set. nullptr otherwise. |
void | RemoveLast(Message * message, const FieldDescriptor * field) constRemoves the last element of a repeated field. more... |
PROTOBUF_FUTURE_MUST_USE_RESULT Message * | ReleaseLast(Message * message, const FieldDescriptor * field) constRemoves the last element of a repeated message field, and returns the pointer to the caller. more... |
void | Swap the complete contents of two messages. |
void | SwapFields(Message * message1, Message * message2, const std::vector< const FieldDescriptor * > & fields) constSwap fields listed in fields vector of two messages. |
void | SwapElements(Message * message, const FieldDescriptor * field, int index1, int index2) constSwap two elements of a repeated field. |
void | ListFields(const Message & message, std::vector< const FieldDescriptor * > * output) constList all fields of the message which are currently set, except for unknown fields, but including extension known to the parser (i.e. more... |
const RepeatedPtrField< Message > & | GetRepeatedPtrFieldInternal(const Message & message, const FieldDescriptor * field) const |
RepeatedPtrField< Message > * | MutableRepeatedPtrFieldInternal(Message * message, const FieldDescriptor * field) const |
Singular field gettersThese get the value of a non-repeated field. They return the default value for fields that aren't set. | |
int32 | GetInt32(const Message & message, const FieldDescriptor * field) const |
int64 | GetInt64(const Message & message, const FieldDescriptor * field) const |
uint32 | GetUInt32(const Message & message, const FieldDescriptor * field) const |
uint64 | GetUInt64(const Message & message, const FieldDescriptor * field) const |
float | GetFloat(const Message & message, const FieldDescriptor * field) const |
double | GetDouble(const Message & message, const FieldDescriptor * field) const |
bool | GetBool(const Message & message, const FieldDescriptor * field) const |
std::string | GetString(const Message & message, const FieldDescriptor * field) const |
const EnumValueDescriptor * | GetEnum(const Message & message, const FieldDescriptor * field) const |
int | GetEnumValue(const Message & message, const FieldDescriptor * field) constGetEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*. more... |
const Message & | GetMessage(const Message & message, const FieldDescriptor * field, MessageFactory * factory = nullptr) constSee MutableMessage() for the meaning of the "factory" parameter. |
const std::string & | GetStringReference(const Message & message, const FieldDescriptor * field, std::string * scratch) constGet a string value without copying, if possible. more... |
Singular field mutatorsThese mutate the value of a non-repeated field. | |
void | SetInt32(Message * message, const FieldDescriptor * field, int32 value) const |
void | SetInt64(Message * message, const FieldDescriptor * field, int64 value) const |
void | SetUInt32(Message * message, const FieldDescriptor * field, uint32 value) const |
void | SetUInt64(Message * message, const FieldDescriptor * field, uint64 value) const |
void | SetFloat(Message * message, const FieldDescriptor * field, float value) const |
void | SetDouble(Message * message, const FieldDescriptor * field, double value) const |
void | SetBool(Message * message, const FieldDescriptor * field, bool value) const |
void | SetString(Message * message, const FieldDescriptor * field, std::string value) const |
void | SetEnum(Message * message, const FieldDescriptor * field, const EnumValueDescriptor * value) const |
void | SetEnumValue(Message * message, const FieldDescriptor * field, int value) constSet an enum field's value with an integer rather than EnumValueDescriptor. more... |
Message * | MutableMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = nullptr) constGet a mutable pointer to a field with a message type. more... |
void | SetAllocatedMessage(Message * message, Message * sub_message, const FieldDescriptor * field) constReplaces the message specified by 'field' with the already-allocated object sub_message, passing ownership to the message. more... |
void | UnsafeArenaSetAllocatedMessage(Message * message, Message * sub_message, const FieldDescriptor * field) constSimilar to SetAllocatedMessage, but omits all internal safety and ownership checks. more... |
PROTOBUF_FUTURE_MUST_USE_RESULT Message * | ReleaseMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = nullptr) constReleases the message specified by 'field' and returns the pointer, ReleaseMessage() will return the message the message object if it exists. more... |
Message * | UnsafeArenaReleaseMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = nullptr) constSimilar to ReleaseMessage, but omits all internal safety and ownership checks. more... |
Repeated field gettersThese get the value of one element of a repeated field. | |
int32 | GetRepeatedInt32(const Message & message, const FieldDescriptor * field, int index) const |
int64 | GetRepeatedInt64(const Message & message, const FieldDescriptor * field, int index) const |
uint32 | GetRepeatedUInt32(const Message & message, const FieldDescriptor * field, int index) const |
uint64 | GetRepeatedUInt64(const Message & message, const FieldDescriptor * field, int index) const |
float | GetRepeatedFloat(const Message & message, const FieldDescriptor * field, int index) const |
double | GetRepeatedDouble(const Message & message, const FieldDescriptor * field, int index) const |
bool | GetRepeatedBool(const Message & message, const FieldDescriptor * field, int index) const |
std::string | GetRepeatedString(const Message & message, const FieldDescriptor * field, int index) const |
const EnumValueDescriptor * | GetRepeatedEnum(const Message & message, const FieldDescriptor * field, int index) const |
int | GetRepeatedEnumValue(const Message & message, const FieldDescriptor * field, int index) constGetRepeatedEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*. more... |
const Message & | GetRepeatedMessage(const Message & message, const FieldDescriptor * field, int index) const |
const std::string & | GetRepeatedStringReference(const Message & message, const FieldDescriptor * field, int index, std::string * scratch) constSee GetStringReference(), above. |
Repeated field mutatorsThese mutate the value of one element of a repeated field. | |
void | SetRepeatedInt32(Message * message, const FieldDescriptor * field, int index, int32 value) const |
void | SetRepeatedInt64(Message * message, const FieldDescriptor * field, int index, int64 value) const |
void | SetRepeatedUInt32(Message * message, const FieldDescriptor * field, int index, uint32 value) const |
void | SetRepeatedUInt64(Message * message, const FieldDescriptor * field, int index, uint64 value) const |
void | SetRepeatedFloat(Message * message, const FieldDescriptor * field, int index, float value) const |
void | SetRepeatedDouble(Message * message, const FieldDescriptor * field, int index, double value) const |
void | SetRepeatedBool(Message * message, const FieldDescriptor * field, int index, bool value) const |
void | SetRepeatedString(Message * message, const FieldDescriptor * field, int index, std::string value) const |
void | SetRepeatedEnum(Message * message, const FieldDescriptor * field, int index, const EnumValueDescriptor * value) const |
void | SetRepeatedEnumValue(Message * message, const FieldDescriptor * field, int index, int value) constSet an enum field's value with an integer rather than EnumValueDescriptor. more... |
Message * | MutableRepeatedMessage(Message * message, const FieldDescriptor * field, int index) constGet a mutable pointer to an element of a repeated field with a message type. |
Repeated field addersThese add an element to a repeated field. | |
void | AddInt32(Message * message, const FieldDescriptor * field, int32 value) const |
void | AddInt64(Message * message, const FieldDescriptor * field, int64 value) const |
void | AddUInt32(Message * message, const FieldDescriptor * field, uint32 value) const |
void | AddUInt64(Message * message, const FieldDescriptor * field, uint64 value) const |
void | AddFloat(Message * message, const FieldDescriptor * field, float value) const |
void | AddDouble(Message * message, const FieldDescriptor * field, double value) const |
void | AddBool(Message * message, const FieldDescriptor * field, bool value) const |
void | AddString(Message * message, const FieldDescriptor * field, std::string value) const |
void | AddEnum(Message * message, const FieldDescriptor * field, const EnumValueDescriptor * value) const |
void | AddEnumValue(Message * message, const FieldDescriptor * field, int value) constAdd an integer value to a repeated enum field rather than EnumValueDescriptor. more... |
Message * | AddMessage(Message * message, const FieldDescriptor * field, MessageFactory * factory = nullptr) constSee MutableMessage() for comments on the "factory" parameter. |
void | AddAllocatedMessage(Message * message, const FieldDescriptor * field, Message * new_entry) constAppends an already-allocated object 'new_entry' to the repeated field specified by 'field' passing ownership to the message. |
template RepeatedFieldRef< T > | GetRepeatedFieldRef(const Message & message, const FieldDescriptor * field) constGet a RepeatedFieldRef object that can be used to read the underlying repeated field. more... |
template MutableRepeatedFieldRef< T > | GetMutableRepeatedFieldRef(Message * message, const FieldDescriptor * field) constLike GetRepeatedFieldRef() but return an object that can also be used manipulate the underlying repeated field. |
template const RepeatedField< T > & | GetRepeatedField(const Message & msg, const FieldDescriptor * d) constDEPRECATED. more... |
template RepeatedField< T > * | MutableRepeatedField(Message * msg, const FieldDescriptor * d) constDEPRECATED. more... |
template const RepeatedPtrField< T > & | GetRepeatedPtrField(const Message & msg, const FieldDescriptor * d) constDEPRECATED. more... |
template RepeatedPtrField< T > * | MutableRepeatedPtrField(Message * msg, const FieldDescriptor * d) constDEPRECATED. more... |
Extensions | |
const FieldDescriptor * | FindKnownExtensionByName(const std::string & name) constTry to find an extension of this message type by fully-qualified field name. more... |
const FieldDescriptor * | FindKnownExtensionByNumber(int number) constTry to find an extension of this message type by field number. more... |
Feature Flags | |
bool | SupportsUnknownEnumValues() constDoes this message support storing arbitrary integer values in enum fields? If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions take arbitrary integer values, and the legacy GetEnum() getter will dynamically create an EnumValueDescriptor for any integer value without one. more... |
MessageFactory * | GetMessageFactory() constReturns the MessageFactory associated with this message. more... |
const UnknownFieldSet &
Reflection::GetUnknownFields(
const Message & message) constGet the UnknownFieldSet for the message.
This contains fields which were seen when the Message was parsed but were not recognized according to the Message's definition.
-UnknownFieldSet *
Reflection::MutableUnknownFields(
Message * message) constGet a mutable pointer to the UnknownFieldSet for the message.
This contains fields which were seen when the Message was parsed but were not recognized according to the Message's definition.
-bool Reflection::HasOneof(
const Message & message,
const OneofDescriptor * oneof_descriptor) constCheck if the oneof is set.
Returns true if any field in oneof is set, false otherwise.
-void Reflection::RemoveLast(
Message * message,
const FieldDescriptor * field) constRemoves the last element of a repeated field.
We don't provide a way to remove any element other than the last because it invites inefficient use, such as O(n^2) filtering loops that should have been O(n). If you want to remove an element other than the last, the best way to do it is to re-arrange the elements (using Swap()) so that the one you want removed is at the end, then call RemoveLast().
-PROTOBUF_FUTURE_MUST_USE_RESULT Message *
Reflection::ReleaseLast(
Message * message,
const FieldDescriptor * field) constRemoves the last element of a repeated message field, and returns the pointer to the caller.
Caller takes ownership of the returned pointer.
-void Reflection::ListFields(
const Message & message,
std::vector< const FieldDescriptor * > * output) constList all fields of the message which are currently set, except for unknown fields, but including extension known to the parser (i.e.
compiled in). Singular fields will only be listed if HasField(field) would return true and repeated fields will only be listed if FieldSize(field) would return non-zero. Fields (both normal fields and extension fields) will be listed ordered by field number. Use Reflection::GetUnknownFields() or message.unknown_fields() to also get access to fields/extensions unknown to the parser.
-int Reflection::GetEnumValue(
const Message & message,
const FieldDescriptor * field) constGetEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*.
If the integer value does not correspond to a known value descriptor, a new value descriptor is created. (Such a value will only be present when the new unknown-enum-value semantics are enabled for a message.)
-const std::string &
Reflection::GetStringReference(
const Message & message,
const FieldDescriptor * field,
std::string * scratch) constGet a string value without copying, if possible.
GetString() necessarily returns a copy of the string. This can be inefficient when the std::string is already stored in a std::string object in the underlying message. GetStringReference() will return a reference to the underlying std::string in this case. Otherwise, it will copy the string into *scratch and return that.
-Note: It is perfectly reasonable and useful to write code like:
-str = reflection->GetStringReference(message, field, &str);-
This line would ensure that only one copy of the string is made regardless of the field's underlying representation. When initializing a newly-constructed string, though, it's just as fast and more readable to use code like:
-std::string str = reflection->GetString(message, field);-
void Reflection::SetEnumValue(
Message * message,
const FieldDescriptor * field,
int value) constSet an enum field's value with an integer rather than EnumValueDescriptor.
For proto3 this is just setting the enum field to the value specified, for proto2 it's more complicated. If value is a known enum value the field is set as usual. If the value is unknown then it is added to the unknown field set. Note this matches the behavior of parsing unknown enum values. If multiple calls with unknown values happen than they are all added to the unknown field set in order of the calls.
-Message * Reflection::MutableMessage(
Message * message,
const FieldDescriptor * field,
MessageFactory * factory = nullptr) constGet a mutable pointer to a field with a message type.
If a MessageFactory is provided, it will be used to construct instances of the sub-message; otherwise, the default factory is used. If the field is an extension that does not live in the same pool as the containing message's descriptor (e.g. it lives in an overlay pool), then a MessageFactory must be provided. If you have no idea what that meant, then you probably don't need to worry about it (don't provide a MessageFactory). WARNING: If the FieldDescriptor is for a compiled-in extension, then factory->GetPrototype(field->message_type()) MUST return an instance of the compiled-in class for this type, NOT DynamicMessage.
-void Reflection::SetAllocatedMessage(
Message * message,
Message * sub_message,
const FieldDescriptor * field) constReplaces the message specified by 'field' with the already-allocated object sub_message, passing ownership to the message.
If the field contained a message, that message is deleted. If sub_message is nullptr, the field is cleared.
-void Reflection::UnsafeArenaSetAllocatedMessage(
Message * message,
Message * sub_message,
const FieldDescriptor * field) constSimilar to SetAllocatedMessage, but omits all internal safety and ownership checks.
This method should only be used when the objects are on the same arena or paired with a call to UnsafeArenaReleaseMessage.
PROTOBUF_FUTURE_MUST_USE_RESULT Message *
Reflection::ReleaseMessage(
Message * message,
const FieldDescriptor * field,
MessageFactory * factory = nullptr) constReleases the message specified by 'field' and returns the pointer, ReleaseMessage() will return the message the message object if it exists.
Otherwise, it may or may not return nullptr. In any case, if the return value is non-null, the caller takes ownership of the pointer. If the field existed (HasField() is true), then the returned pointer will be the same as the pointer returned by MutableMessage(). This function has the same effect as ClearField().
-Message * Reflection::UnsafeArenaReleaseMessage(
Message * message,
const FieldDescriptor * field,
MessageFactory * factory = nullptr) constSimilar to ReleaseMessage, but omits all internal safety and ownership checks.
This method should only be used when the objects are on the same arena or paired with a call to UnsafeArenaSetAllocatedMessage.
int Reflection::GetRepeatedEnumValue(
const Message & message,
const FieldDescriptor * field,
int index) constGetRepeatedEnumValue() returns an enum field's value as an integer rather than an EnumValueDescriptor*.
If the integer value does not correspond to a known value descriptor, a new value descriptor is created. (Such a value will only be present when the new unknown-enum-value semantics are enabled for a message.)
-void Reflection::SetRepeatedEnumValue(
Message * message,
const FieldDescriptor * field,
int index,
int value) constSet an enum field's value with an integer rather than EnumValueDescriptor.
For proto3 this is just setting the enum field to the value specified, for proto2 it's more complicated. If value is a known enum value the field is set as usual. If the value is unknown then it is added to the unknown field set. Note this matches the behavior of parsing unknown enum values. If multiple calls with unknown values happen than they are all added to the unknown field set in order of the calls.
-void Reflection::AddEnumValue(
Message * message,
const FieldDescriptor * field,
int value) constAdd an integer value to a repeated enum field rather than EnumValueDescriptor.
For proto3 this is just setting the enum field to the value specified, for proto2 it's more complicated. If value is a known enum value the field is set as usual. If the value is unknown then it is added to the unknown field set. Note this matches the behavior of parsing unknown enum values. If multiple calls with unknown values happen than they are all added to the unknown field set in order of the calls.
-template RepeatedFieldRef< T >
Reflection::GetRepeatedFieldRef(
const Message & message,
const FieldDescriptor * field) constGet a RepeatedFieldRef object that can be used to read the underlying repeated field.
The type parameter T must be set according to the field's cpp type. The following table shows the mapping from cpp type to acceptable T.
-field->cpp_type() T -CPPTYPE_INT32 int32 -CPPTYPE_UINT32 uint32 -CPPTYPE_INT64 int64 -CPPTYPE_UINT64 uint64 -CPPTYPE_DOUBLE double -CPPTYPE_FLOAT float -CPPTYPE_BOOL bool -CPPTYPE_ENUM generated enum type or int32 -CPPTYPE_STRING std::string -CPPTYPE_MESSAGE generated message type or google::protobuf::Message-
A RepeatedFieldRef object can be copied and the resulted object will point to the same repeated field in the same message. The object can be used as long as the message is not destroyed.
-Note that to use this method users need to include the header file "reflection.h" (which defines the RepeatedFieldRef class templates).
-template const RepeatedField< T > &
Reflection::GetRepeatedField(
const Message & msg,
const FieldDescriptor * d) constDEPRECATED.
Please use GetRepeatedFieldRef().
-for T = Cord and all protobuf scalar types except enums.
-template RepeatedField< T > *
Reflection::MutableRepeatedField(
Message * msg,
const FieldDescriptor * d) constDEPRECATED.
Please use GetMutableRepeatedFieldRef().
-for T = Cord and all protobuf scalar types except enums.
-template const RepeatedPtrField< T > &
Reflection::GetRepeatedPtrField(
const Message & msg,
const FieldDescriptor * d) constDEPRECATED.
Please use GetRepeatedFieldRef().
-for T = std::string, google::protobuf::internal::StringPieceField
-google::protobuf::Message & descendants.-
template RepeatedPtrField< T > *
Reflection::MutableRepeatedPtrField(
Message * msg,
const FieldDescriptor * d) constDEPRECATED.
Please use GetMutableRepeatedFieldRef().
-for T = std::string, google::protobuf::internal::StringPieceField
-google::protobuf::Message & descendants.-
const FieldDescriptor *
Reflection::FindKnownExtensionByName(
const std::string & name) constTry to find an extension of this message type by fully-qualified field name.
Returns nullptr if no extension is known for this name or number.
-const FieldDescriptor *
Reflection::FindKnownExtensionByNumber(
int number) constTry to find an extension of this message type by field number.
Returns nullptr if no extension is known for this name or number.
-bool Reflection::SupportsUnknownEnumValues() constDoes this message support storing arbitrary integer values in enum fields? If |true|, GetEnumValue/SetEnumValue and associated repeated-field versions take arbitrary integer values, and the legacy GetEnum() getter will dynamically create an EnumValueDescriptor for any integer value without one.
If |false|, setting an unknown enum value via the integer-based setters results in undefined behavior (in practice, GOOGLE_DCHECK-fails).
-Generic code that uses reflection to handle messages with enum fields should check this flag before using the integer-based setter, and either downgrade to a compatible value or use the UnknownFieldSet if not. For example:
-int new_value = GetValueFromApplicationLogic();
-if (reflection->SupportsUnknownEnumValues()) {
- reflection->SetEnumValue(message, field, new_value);
-} else {
- if (field_descriptor->enum_type()->
- FindValueByNumber(new_value) != nullptr) {
- reflection->SetEnumValue(message, field, new_value);
- } else if (emit_unknown_enum_values) {
- reflection->MutableUnknownFields(message)->AddVarint(
- field->number(), new_value);
- } else {
- // convert value to a compatible/default value.
- new_value = CompatibleDowngrade(new_value);
- reflection->SetEnumValue(message, field, new_value);
- }
-}
-MessageFactory * Reflection::GetMessageFactory() constReturns the MessageFactory associated with this message.
This can be useful for determining if a message is a generated message or not, for example:
-if (message->GetReflection()->GetMessageFactory() ==
- google::protobuf::MessageFactory::generated_factory()) {
- // This is a generated message.
-}
-It can also be used to create more messages of this type, though Message::New() is an easier way to accomplish this.
-#include <google/protobuf/message.h>
namespace google::protobuf
Abstract interface for a factory for message objects.
Known subclasses:
Members | |
|---|---|
| MessageFactory() |
virtual | ~MessageFactory() |
virtual const Message * | GetPrototype(const Descriptor * type) = 0 |
static MessageFactory * | generated_factory()Gets a MessageFactory which supports all generated, compiled-in messages. more... |
static void | InternalRegisterGeneratedFile(const google::protobuf::internal::DescriptorTable * table)For internal use only: Registers a .proto file at static initialization time, to be placed in generated_factory. more... |
static void | InternalRegisterGeneratedMessage(const Descriptor * descriptor, const Message * prototype)For internal use only: Registers a message type. more... |
virtual const Message * MessageFactory::GetPrototype(
const Descriptor * type) = 0Given a Descriptor, gets or constructs the default (prototype) Message of that type.
You can then call that message's New() method to construct a mutable message of that type.
-Calling this method twice with the same Descriptor returns the same object. The returned object remains property of the factory. Also, any objects created by calling the prototype's New() method share some data with the prototype, so these must be destroyed before the MessageFactory is destroyed.
-The given descriptor must outlive the returned message, and hence must outlive the MessageFactory.
-Some implementations do not support all types. GetPrototype() will return nullptr if the descriptor passed in is not supported.
-This method may or may not be thread-safe depending on the implementation. Each implementation should document its own degree thread-safety.
-static MessageFactory * MessageFactory::generated_factory()Gets a MessageFactory which supports all generated, compiled-in messages.
In other words, for any compiled-in type FooMessage, the following is true:
-MessageFactory::generated_factory()->GetPrototype( - FooMessage::descriptor()) == FooMessage::default_instance()-
This factory supports all types which are found in DescriptorPool::generated_pool(). If given a descriptor from any other pool, GetPrototype() will return nullptr. (You can also check if a descriptor is for a generated message by checking if descriptor->file()->pool() == DescriptorPool::generated_pool().)
-This factory is 100% thread-safe; calling GetPrototype() does not modify any shared data.
-This factory is a singleton. The caller must not delete the object.
-static void MessageFactory::InternalRegisterGeneratedFile(
const google::protobuf::internal::DescriptorTable * table)For internal use only: Registers a .proto file at static initialization time, to be placed in generated_factory.
The first time GetPrototype() is called with a descriptor from this file, |register_messages| will be called, with the file name as the parameter. It must call InternalRegisterGeneratedMessage() (below) to register each message type in the file. This strange mechanism is necessary because descriptors are built lazily, so we can't register types by their descriptor until we know that the descriptor exists. |filename| must be a permanent string.
-static void MessageFactory::InternalRegisterGeneratedMessage(
const Descriptor * descriptor,
const Message * prototype)For internal use only: Registers a message type.
Called only by the functions which are registered with InternalRegisterGeneratedFile(), above.
-#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 | |
|---|---|
Interface to light weight protocol messages. | |
File MembersThese 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:
- -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.
-#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:
Members | |
|---|---|
enum | ParseFlags |
protected internal::InternalMetadata | _internal_metadata_ |
constexpr | MessageLite() |
virtual | ~MessageLite() |
template bool | ParseFrom(const T & input) |
virtual uint8 * | _InternalSerialize(uint8 * ptr, io::EpsCopyOutputStream * stream) const = 0Fast path when conditions match (ie. more... |
bool | IsInitializedWithErrors() constIdentical to IsInitialized() except that it logs an error message. |
protected template static T * | CreateMaybeMessage(Arena * arena) |
protected explicit | MessageLite(Arena * arena) |
protected Arena * | GetOwningArena() constReturns 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() constReturns 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 = 0Get the name of this message type, e.g. "foo.bar.BazProto". |
virtual MessageLite * | New() const = 0Construct a new instance of the same type. more... |
virtual MessageLite * | New(Arena * arena) constConstruct a new instance on the arena. more... |
Arena * | GetArena() constSame as GetOwningArena. |
void * | GetMaybeArenaPointer() constGet a pointer that may be equal to this message's arena, or may not be. more... |
virtual void | Clear() = 0Clear all fields of the message and set them to their default values. more... |
virtual bool | IsInitialized() const = 0Quickly check if all required fields have values set. |
virtual std::string | InitializationErrorString() constThis is not implemented for Lite messages – it just returns "(cannot
-determine missing fields for lite message)". more... |
virtual void | CheckTypeAndMergeFrom(const MessageLite & other) = 0If |other| is the exact same class as this, calls MergeFrom(). more... |
std::string | DebugString() constThese methods return a human-readable summary of the message. more... |
std::string | ShortDebugString() const |
std::string | Utf8DebugString() constMessageLite::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) |
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) constWrite a protocol buffer of this message to the given output. more... |
bool | SerializePartialToCodedStream(io::CodedOutputStream * output) constLike SerializeToCodedStream(), but allows missing required fields. |
bool | SerializeToZeroCopyStream(io::ZeroCopyOutputStream * output) constWrite the message to the given zero-copy output stream. more... |
bool | SerializePartialToZeroCopyStream(io::ZeroCopyOutputStream * output) constLike SerializeToZeroCopyStream(), but allows missing required fields. |
bool | SerializeToString(std::string * output) constSerialize the message and store it in the given string. more... |
bool | SerializePartialToString(std::string * output) constLike SerializeToString(), but allows missing required fields. |
bool | SerializeToArray(void * data, int size) constSerialize the message and store it in the given byte array. more... |
bool | SerializePartialToArray(void * data, int size) constLike SerializeToArray(), but allows missing required fields. |
std::string | SerializeAsString() constMake a string encoding the message. more... |
std::string | SerializePartialAsString() constLike SerializeAsString(), but allows missing required fields. |
bool | SerializeToFileDescriptor(int file_descriptor) constSerialize the message and write it to the given file descriptor. more... |
bool | SerializePartialToFileDescriptor(int file_descriptor) constLike SerializeToFileDescriptor(), but allows missing required fields. |
bool | SerializeToOstream(std::ostream * output) constSerialize the message and write it to the given C++ ostream. more... |
bool | SerializePartialToOstream(std::ostream * output) constLike SerializeToOstream(), but allows missing required fields. |
bool | AppendToString(std::string * output) constLike SerializeToString(), but appends to the data to the string's existing contents. more... |
bool | AppendPartialToString(std::string * output) constLike AppendToString(), but allows missing required fields. |
virtual size_t | ByteSizeLong() const = 0Computes the serialized size of the message. more... |
int | ByteSize() constLegacy ByteSize() API. |
void | SerializeWithCachedSizes(io::CodedOutputStream * output) constSerializes the message without recomputing the size. more... |
uint8 * | SerializeWithCachedSizesToArray(uint8 * target) constLike SerializeWithCachedSizes, but writes directly to *target, returning a pointer to the byte immediately after the last byte written. more... |
virtual int | GetCachedSize() const = 0Returns 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 = 0Fast path when conditions match (ie.
non-deterministic) uint8* _InternalSerialize(uint8* ptr) const;
-protected Arena * MessageLite::GetOwningArena() constReturns 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 = 0Construct a new instance of the same type.
Ownership is passed to the caller.
-virtual MessageLite * MessageLite::New(
Arena * arena) constConstruct 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() constGet 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() = 0Clear 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() constThis 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) = 0If |other| is the exact same class as this, calls MergeFrom().
Otherwise, results are undefined (probably crash).
-std::string MessageLite::DebugString() constThese 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() constMessageLite::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) constWrite 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) constWrite the message to the given zero-copy output stream.
All required fields must be set.
-bool MessageLite::SerializeToString(
std::string * output) constSerialize the message and store it in the given string.
All required fields must be set.
-bool MessageLite::SerializeToArray(
void * data,
int size) constSerialize the message and store it in the given byte array.
All required fields must be set.
-std::string MessageLite::SerializeAsString() constMake 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) constSerialize the message and write it to the given file descriptor.
All required fields must be set.
-bool MessageLite::SerializeToOstream(
std::ostream * output) constSerialize the message and write it to the given C++ ostream.
All required fields must be set.
-bool MessageLite::AppendToString(
std::string * output) constLike SerializeToString(), but appends to the data to the string's existing contents.
All required fields must be set.
-virtual size_t MessageLite::ByteSizeLong() const = 0Computes 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) constSerializes 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) constLike 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 = 0Returns 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.)
- -#include <google/protobuf/repeated_field.h>
namespace google::protobuf
RepeatedField and RepeatedPtrField are used by generated protocol message classes to manipulate repeated fields.
These classes are very similar to STL's vector, but include a number of optimizations found to be useful specifically in the case of Protocol Buffers. RepeatedPtrField is particularly different from STL vector as it manages ownership of the pointers that it contains.
- -Typically, clients should not need to access RepeatedField objects directly, but should instead use the accessor functions generated automatically by the protocol compiler.
- -Classes in this file | |
|---|---|
RepeatedField is used to represent repeated fields of a primitive type (in other words, everything except strings and nested Messages). | |
RepeatedPtrField is like RepeatedField, but used for repeated strings or Messages. | |
File MembersThese definitions are not part of any class. | |
|---|---|
template internal::RepeatedFieldBackInsertIterator< T > | RepeatedFieldBackInserter(RepeatedField< T > *const mutable_field)Provides a back insert iterator for RepeatedField instances, similar to std::back_inserter(). |
template internal::RepeatedPtrFieldBackInsertIterator< T > | RepeatedPtrFieldBackInserter(RepeatedPtrField< T > *const mutable_field)Provides a back insert iterator for RepeatedPtrField instances, similar to std::back_inserter(). |
template internal::RepeatedPtrFieldBackInsertIterator< T > | RepeatedFieldBackInserter(RepeatedPtrField< T > *const mutable_field)Special back insert iterator for RepeatedPtrField instances, just in case someone wants to write generic template code that can access both RepeatedFields and RepeatedPtrFields using a common name. |
template internal::AllocatedRepeatedPtrFieldBackInsertIterator< T > | AllocatedRepeatedPtrFieldBackInserter(RepeatedPtrField< T > *const mutable_field)Provides a back insert iterator for RepeatedPtrField instances similar to std::back_inserter() which transfers the ownership while copying elements. |
template internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator< T > | UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(RepeatedPtrField< T > *const mutable_field)Similar to AllocatedRepeatedPtrFieldBackInserter, using UnsafeArenaAddAllocated instead of AddAllocated. more... |
template internal::UnsafeArenaAllocatedRepeatedPtrFieldBackInsertIterator< T >
protobuf::UnsafeArenaAllocatedRepeatedPtrFieldBackInserter(
RepeatedPtrField< T > *const mutable_field)Similar to AllocatedRepeatedPtrFieldBackInserter, using UnsafeArenaAddAllocated instead of AddAllocated.
This is slightly faster if that matters. It is also useful in legacy code that uses temporary ownership to avoid copies. Example:
-RepeatedPtrField<T> temp_field; -temp_field.AddAllocated(new T); -... // Do something with temp_field -temp_field.ExtractSubrange(0, temp_field.size(), nullptr);-
If you put temp_field on the arena this fails, because the ownership transfers to the arena at the "AddAllocated" call and is not released anymore causing a double delete. Using UnsafeArenaAddAllocated prevents this.
-#include <google/protobuf/repeated_field.h>
namespace google::protobuf
template <typename >
RepeatedField is used to represent repeated fields of a primitive type (in other words, everything except strings and nested Messages).
Most users will not ever use a RepeatedField directly; they will use the get-by-index, set-by-index, and add accessors that are generated for all repeated fields.
-Members | |
|---|---|
typedef | Element * iteratorSTL-like iterator support. |
typedef | const Element * const_iterator |
typedef | Element value_type |
typedef | value_type & reference |
typedef | const value_type & const_reference |
typedef | value_type * pointer |
typedef | const value_type * const_pointer |
typedef | int size_type |
typedef | ptrdiff_t difference_type |
typedef | std::reverse_iterator< const_iterator > const_reverse_iteratorReverse iterator support. |
typedef | std::reverse_iterator< iterator > reverse_iterator |
constexpr | RepeatedField() |
explicit | RepeatedField(Arena * arena) |
| RepeatedField(const RepeatedField & other) |
template | RepeatedField(Iter begin, Iter end) |
| ~RepeatedField() |
RepeatedField & | operator=(const RepeatedField & other) |
| RepeatedField(RepeatedField && other) |
RepeatedField & | operator=(RepeatedField && other) |
bool | empty() const |
int | size() const |
const Element & | Get(int index) const |
Element * | Mutable(int index) |
const Element & | operator[](int index) const |
Element & | operator[](int index) |
const Element & | at(int index) const |
Element & | at(int index) |
void | Set(int index, const Element & value) |
void | Add(const Element & value) |
Element * | Add()Appends a new element and return a pointer to it. more... |
template void | Add(Iter begin, Iter end)Append elements in the range [begin, end) after reserving the appropriate number of elements. |
void | RemoveLast()Remove the last element in the array. |
void | ExtractSubrange(int start, int num, Element * elements)Extract elements with indices in "[start .. start+num-1]". more... |
void | Clear() |
void | MergeFrom(const RepeatedField & other) |
void | CopyFrom(const RepeatedField & other) |
template void | Assign(Iter begin, Iter end)Replaces the contents with RepeatedField(begin, end). |
void | Reserve(int new_size)Reserve space to expand the field to at least the given size. more... |
void | Truncate(int new_size)Resize the RepeatedField to a new, smaller size. This is O(1). |
void | AddAlreadyReserved(const Element & value) |
Element * | AddAlreadyReserved()Appends a new element and return a pointer to it. more... |
Element * | AddNAlreadyReserved(int elements) |
int | Capacity() const |
void | Resize(int new_size, const Element & value)Like STL resize. more... |
Element * | mutable_data()Gets the underlying array. more... |
const Element * | data() const |
void | Swap(RepeatedField * other)Swap entire contents with "other". more... |
void | UnsafeArenaSwap(RepeatedField * other)Swap entire contents with "other". more... |
void | SwapElements(int index1, int index2)Swap two elements. |
iterator | begin() |
const_iterator | begin() const |
const_iterator | cbegin() const |
iterator | end() |
const_iterator | end() const |
const_iterator | cend() const |
reverse_iterator | rbegin() |
const_reverse_iterator | rbegin() const |
reverse_iterator | rend() |
const_reverse_iterator | rend() const |
size_t | SpaceUsedExcludingSelfLong() constReturns the number of bytes used by the repeated field, excluding sizeof(*this) |
int | SpaceUsedExcludingSelf() const |
iterator | erase(const_iterator position)Removes the element referenced by position. more... |
iterator | erase(const_iterator first, const_iterator last)Removes the elements in the range [first, last). more... |
Arena * | GetArena() constGet the Arena on which this RepeatedField stores its elements. |
void | InternalSwap(RepeatedField * other)For internal use only. more... |
template | RepeatedField(Iter begin, Iter end) |
Element * RepeatedField::Add()Appends a new element and return a pointer to it.
The new element is uninitialized if |Element| is a POD type.
-void RepeatedField::ExtractSubrange(
int start,
int num,
Element * elements)Extract elements with indices in "[start .. start+num-1]".
Copy them into "elements[0 .. num-1]" if "elements" is not NULL. Caution: implementation also moves elements with indices [start+num ..]. Calling this routine inside a loop can cause quadratic behavior.
-void RepeatedField::Reserve(
int new_size)Reserve space to expand the field to at least the given size.
Avoid inlining of Reserve(): new, copy, and delete[] lead to a significant amount of code bloat.
-If the array is grown, it will always be at least doubled in size.
-Element * RepeatedField::AddAlreadyReserved()Appends a new element and return a pointer to it.
The new element is uninitialized if |Element| is a POD type. Should be called only if Capacity() > Size().
-void RepeatedField::Resize(
int new_size,
const Element & value)Like STL resize.
Uses value to fill appended elements. Like Truncate() if new_size <= size(), otherwise this is O(new_size - size()).
-Element * RepeatedField::mutable_data()Gets the underlying array.
This pointer is possibly invalidated by any add or remove operation.
-void RepeatedField::Swap(
RepeatedField * other)Swap entire contents with "other".
If they are separate arenas then, copies data between each other.
-void RepeatedField::UnsafeArenaSwap(
RepeatedField * other)Swap entire contents with "other".
Should be called only if the caller can guarantee that both repeated fields are on the same arena or are on the heap. Swapping between different arenas is disallowed and caught by a GOOGLE_DCHECK (see API docs for details).
-iterator RepeatedField::erase(
const_iterator position)Removes the element referenced by position.
Returns an iterator to the element immediately following the removed element.
-Invalidates all iterators at or after the removed element, including end().
-iterator RepeatedField::erase(
const_iterator first,
const_iterator last)Removes the elements in the range [first, last).
Returns an iterator to the element immediately following the removed range.
-Invalidates all iterators at or after the removed range, including end().
-void RepeatedField::InternalSwap(
RepeatedField * other)For internal use only.
This is public due to it being called by generated code.
-#include <google/protobuf/repeated_field.h>
namespace google::protobuf
template <typename >
RepeatedPtrField is like RepeatedField, but used for repeated strings or Messages.
Members | |
|---|---|
typedef | internal::RepeatedPtrIterator< Element > iteratorSTL-like iterator support. |
typedef | internal::RepeatedPtrIterator< const Element > const_iterator |
typedef | Element value_type |
typedef | value_type & reference |
typedef | const value_type & const_reference |
typedef | value_type * pointer |
typedef | const value_type * const_pointer |
typedef | int size_type |
typedef | ptrdiff_t difference_type |
typedef | std::reverse_iterator< const_iterator > const_reverse_iteratorReverse iterator support. |
typedef | std::reverse_iterator< iterator > reverse_iterator |
typedef | internal::RepeatedPtrOverPtrsIterator< Element *, void * > pointer_iteratorCustom STL-like iterator that iterates over and returns the underlying pointers to Element rather than Element itself. |
typedef | internal::RepeatedPtrOverPtrsIterator< const Element *const, const void *const > const_pointer_iterator |
constexpr | RepeatedPtrField() |
explicit | RepeatedPtrField(Arena * arena) |
| RepeatedPtrField(const RepeatedPtrField & other) |
template | RepeatedPtrField(Iter begin, Iter end) |
| ~RepeatedPtrField() |
RepeatedPtrField & | operator=(const RepeatedPtrField & other) |
| RepeatedPtrField(RepeatedPtrField && other) |
RepeatedPtrField & | operator=(RepeatedPtrField && other) |
bool | empty() const |
int | size() const |
const Element & | Get(int index) const |
Element * | Mutable(int index) |
Element * | Add() |
void | Add(Element && value) |
template void | Add(Iter begin, Iter end)Append elements in the range [begin, end) after reserving the appropriate number of elements. |
const Element & | operator[](int index) const |
Element & | operator[](int index) |
const Element & | at(int index) const |
Element & | at(int index) |
void | RemoveLast()Remove the last element in the array. more... |
void | DeleteSubrange(int start, int num)Delete elements with indices in the range [start . more... |
void | Clear() |
void | MergeFrom(const RepeatedPtrField & other) |
void | CopyFrom(const RepeatedPtrField & other) |
template void | Assign(Iter begin, Iter end)Replaces the contents with RepeatedPtrField(begin, end). |
void | Reserve(int new_size)Reserve space to expand the field to at least the given size. more... |
int | Capacity() const |
Element ** | mutable_data()Gets the underlying array. more... |
const Element *const * | data() const |
void | Swap(RepeatedPtrField * other)Swap entire contents with "other". more... |
void | UnsafeArenaSwap(RepeatedPtrField * other)Swap entire contents with "other". more... |
void | SwapElements(int index1, int index2)Swap two elements. |
iterator | begin() |
const_iterator | begin() const |
const_iterator | cbegin() const |
iterator | end() |
const_iterator | end() const |
const_iterator | cend() const |
reverse_iterator | rbegin() |
const_reverse_iterator | rbegin() const |
reverse_iterator | rend() |
const_reverse_iterator | rend() const |
pointer_iterator | pointer_begin() |
const_pointer_iterator | pointer_begin() const |
pointer_iterator | pointer_end() |
const_pointer_iterator | pointer_end() const |
size_t | SpaceUsedExcludingSelfLong() constReturns (an estimate of) the number of bytes used by the repeated field, excluding sizeof(*this). |
int | SpaceUsedExcludingSelf() const |
template | RepeatedPtrField(Iter begin, Iter end) |
Advanced memory managementWhen hardcore memory management becomes necessary – as it sometimes does here at Google – the following methods may be useful. | |
void | AddAllocated(Element * value)Add an already-allocated object, passing ownership to the RepeatedPtrField. more... |
PROTOBUF_FUTURE_MUST_USE_RESULT Element * | ReleaseLast()Remove the last element and return it, passing ownership to the caller. more... |
void | UnsafeArenaAddAllocated(Element * value)Add an already-allocated object, skipping arena-ownership checks. more... |
Element * | UnsafeArenaReleaseLast()Remove the last element and return it. more... |
void | ExtractSubrange(int start, int num, Element ** elements)Extract elements with indices in the range "[start .. start+num-1]". more... |
void | UnsafeArenaExtractSubrange(int start, int num, Element ** elements)Identical to ExtractSubrange() described above, except that when this repeated field is on an arena, no object copies are performed. more... |
int | ClearedCount() constGet the number of cleared objects that are currently being kept around for reuse. |
void | AddCleared(Element * value)Add an element to the pool of cleared objects, passing ownership to the RepeatedPtrField. more... |
PROTOBUF_FUTURE_MUST_USE_RESULT Element * | ReleaseCleared()Remove a single element from the cleared pool and return it, passing ownership to the caller. more... |
iterator | erase(const_iterator position)Removes the element referenced by position. more... |
iterator | erase(const_iterator first, const_iterator last)Removes the elements in the range [first, last). more... |
Arena * | GetArena() constGets the arena on which this RepeatedPtrField stores its elements. |
void | InternalSwap(RepeatedPtrField * other)For internal use only. more... |
void RepeatedPtrField::RemoveLast()Remove the last element in the array.
Ownership of the element is retained by the array.
-void RepeatedPtrField::DeleteSubrange(
int start,
int num)Delete elements with indices in the range [start .
. start+num-1]. Caution: implementation moves all elements with indices [start+num .. ]. Calling this routine inside a loop can cause quadratic behavior.
-void RepeatedPtrField::Reserve(
int new_size)Reserve space to expand the field to at least the given size.
This only resizes the pointer array; it doesn't allocate any objects. If the array is grown, it will always be at least doubled in size.
-Element ** RepeatedPtrField::mutable_data()Gets the underlying array.
This pointer is possibly invalidated by any add or remove operation.
-void RepeatedPtrField::Swap(
RepeatedPtrField * other)Swap entire contents with "other".
If they are on separate arenas, then copies data.
-void RepeatedPtrField::UnsafeArenaSwap(
RepeatedPtrField * other)Swap entire contents with "other".
Caller should guarantee that either both fields are on the same arena or both are on the heap. Swapping between different arenas with this function is disallowed and is caught via GOOGLE_DCHECK.
-void RepeatedPtrField::AddAllocated(
Element * value)Add an already-allocated object, passing ownership to the RepeatedPtrField.
Note that some special behavior occurs with respect to arenas:
-(i) if this field holds submessages, the new submessage will be copied if -the original is in an arena and this RepeatedPtrField is either in a -different arena, or on the heap. -(ii) if this field holds strings, the passed-in string *must* be -heap-allocated, not arena-allocated. There is no way to dynamically check -this at runtime, so User Beware.-
PROTOBUF_FUTURE_MUST_USE_RESULT Element *
RepeatedPtrField::ReleaseLast()Remove the last element and return it, passing ownership to the caller.
Requires: size() > 0
-If this RepeatedPtrField is on an arena, an object copy is required to pass ownership back to the user (for compatible semantics). Use UnsafeArenaReleaseLast() if this behavior is undesired.
-void RepeatedPtrField::UnsafeArenaAddAllocated(
Element * value)Add an already-allocated object, skipping arena-ownership checks.
The user must guarantee that the given object is in the same arena as this RepeatedPtrField. It is also useful in legacy code that uses temporary ownership to avoid copies. Example:
-RepeatedPtrField<T> temp_field; -temp_field.AddAllocated(new T); -... // Do something with temp_field -temp_field.ExtractSubrange(0, temp_field.size(), nullptr);-
If you put temp_field on the arena this fails, because the ownership transfers to the arena at the "AddAllocated" call and is not released anymore causing a double delete. UnsafeArenaAddAllocated prevents this.
-Element * RepeatedPtrField::UnsafeArenaReleaseLast()Remove the last element and return it.
Works only when operating on an arena. The returned pointer is to the original object in the arena, hence has the arena's lifetime. Requires: current_size_ > 0
-void RepeatedPtrField::ExtractSubrange(
int start,
int num,
Element ** elements)Extract elements with indices in the range "[start .. start+num-1]".
The caller assumes ownership of the extracted elements and is responsible for deleting them when they are no longer needed. If "elements" is non-NULL, then pointers to the extracted elements are stored in "elements[0 .. num-1]" for the convenience of the caller. If "elements" is NULL, then the caller must use some other mechanism to perform any further operations (like deletion) on these elements. Caution: implementation also moves elements with indices [start+num ..]. Calling this routine inside a loop can cause quadratic behavior.
-Memory copying behavior is identical to ReleaseLast(), described above: if this RepeatedPtrField is on an arena, an object copy is performed for each returned element, so that all returned element pointers are to heap-allocated copies. If this copy is not desired, the user should call UnsafeArenaExtractSubrange().
-void RepeatedPtrField::UnsafeArenaExtractSubrange(
int start,
int num,
Element ** elements)Identical to ExtractSubrange() described above, except that when this repeated field is on an arena, no object copies are performed.
Instead, the raw object pointers are returned. Thus, if on an arena, the returned objects must not be freed, because they will not be heap-allocated objects.
-void RepeatedPtrField::AddCleared(
Element * value)Add an element to the pool of cleared objects, passing ownership to the RepeatedPtrField.
The element must be cleared prior to calling this method.
-This method cannot be called when the repeated field is on an arena or when |value| is; both cases will trigger a GOOGLE_DCHECK-failure.
-PROTOBUF_FUTURE_MUST_USE_RESULT Element *
RepeatedPtrField::ReleaseCleared()Remove a single element from the cleared pool and return it, passing ownership to the caller.
The element is guaranteed to be cleared. Requires: ClearedCount() > 0
-This method cannot be called when the repeated field is on an arena; doing so will trigger a GOOGLE_DCHECK-failure.
-iterator RepeatedPtrField::erase(
const_iterator position)Removes the element referenced by position.
Returns an iterator to the element immediately following the removed element.
-Invalidates all iterators at or after the removed element, including end().
-iterator RepeatedPtrField::erase(
const_iterator first,
const_iterator last)Removes the elements in the range [first, last).
Returns an iterator to the element immediately following the removed range.
-Invalidates all iterators at or after the removed range, including end().
-void RepeatedPtrField::InternalSwap(
RepeatedPtrField * other)For internal use only.
This is public due to it being called by generated code.
-#include <google/protobuf/service.h>
namespace google::protobuf
DEPRECATED: This module declares the abstract interfaces underlying proto2 RPC services.
These are intended to be independent of any particular RPC implementation, so that proto2 services can be used on top of a variety of implementations. Starting with version 2.3.0, RPC implementations should not try to build on these, but should instead provide code generator plugins which generate code specific to the particular RPC implementation. This way the generated code can be more appropriate for the implementation in use and can avoid unnecessary layers of indirection.
- -When you use the protocol compiler to compile a service definition, it generates two classes: An abstract interface for the service (with methods matching the service definition) and a "stub" implementation. A stub is just a type-safe wrapper around an RpcChannel which emulates a local implementation of the service.
- -For example, the service definition:
- -service MyService {
- rpc Foo(MyRequest) returns(MyResponse);
-}
-
-will generate abstract interface "MyService" and class "MyService::Stub". You could implement a MyService as follows:
- -class MyServiceImpl : public MyService {
- public:
- MyServiceImpl() {}
- ~MyServiceImpl() {}
-
- // implements MyService ---------------------------------------
-
- void Foo(google::protobuf::RpcController* controller,
- const MyRequest* request,
- MyResponse* response,
- Closure* done) {
- // ... read request and fill in response ...
- done->Run();
- }
-};
-
-You would then register an instance of MyServiceImpl with your RPC server implementation. (How to do that depends on the implementation.)
- -To call a remote MyServiceImpl, first you need an RpcChannel connected to it. How to construct a channel depends, again, on your RPC implementation. Here we use a hypothetical "MyRpcChannel" as an example:
- -MyRpcChannel channel("rpc:hostname:1234/myservice");
-MyRpcController controller;
-MyServiceImpl::Stub stub(&channel);
-FooRequest request;
-FooResponse response;
-
-// ... fill in request ...
-
-stub.Foo(&controller, request, &response, NewCallback(HandleResponse));
-
-On Thread-Safety:
- -Different RPC implementations may make different guarantees about what threads they may run callbacks on, and what threads the application is allowed to use to call the RPC system. Portable software should be ready for callbacks to be called on any thread, but should not try to call the RPC system from any thread except for the ones on which it received the callbacks. Realistically, though, simple software will probably want to use a single-threaded RPC system while high-end software will want to use multiple threads. RPC implementations should provide multiple choices.
- -Classes in this file | |
|---|---|
Abstract base interface for protocol-buffer-based RPC services. | |
An RpcController mediates a single method call. | |
Abstract interface for an RPC channel. | |
#include <google/protobuf/service.h>
namespace google::protobuf
Abstract base interface for protocol-buffer-based RPC services.
Services themselves are abstract interfaces (implemented either by servers or as stubs), but they subclass this base interface. The methods of this interface can be used to call the methods of the Service without knowing its exact type at compile time (analogous to Reflection).
-Members | |
|---|---|
enum | ChannelOwnershipWhen constructing a stub, you may pass STUB_OWNS_CHANNEL as the second parameter to the constructor to tell it to delete its RpcChannel when destroyed. more... |
| Service() |
virtual | ~Service() |
virtual const ServiceDescriptor * | GetDescriptor() = 0Get the ServiceDescriptor describing this service and its methods. |
virtual void | CallMethod(const MethodDescriptor * method, RpcController * controller, const Message * request, Message * response, Closure * done) = 0Call a method of the service specified by MethodDescriptor. more... |
virtual const Message & | GetRequestPrototype(const MethodDescriptor * method) const = 0CallMethod() requires that the request and response passed in are of a particular subclass of Message. more... |
virtual const Message & | GetResponsePrototype(const MethodDescriptor * method) const = 0 |
enum Service::ChannelOwnership {
STUB_OWNS_CHANNEL,
STUB_DOESNT_OWN_CHANNEL
}When constructing a stub, you may pass STUB_OWNS_CHANNEL as the second parameter to the constructor to tell it to delete its RpcChannel when destroyed.
| STUB_OWNS_CHANNEL | |
| STUB_DOESNT_OWN_CHANNEL |
virtual void Service::CallMethod(
const MethodDescriptor * method,
RpcController * controller,
const Message * request,
Message * response,
Closure * done) = 0Call a method of the service specified by MethodDescriptor.
This is normally implemented as a simple switch() that calls the standard definitions of the service's methods.
-Preconditions:
-Postconditions:
-virtual const Message & Service::GetRequestPrototype(
const MethodDescriptor * method) const = 0CallMethod() requires that the request and response passed in are of a particular subclass of Message.
GetRequestPrototype() and GetResponsePrototype() get the default instances of these required types. You can then call Message::New() on these instances to construct mutable objects which you can then pass to CallMethod().
-Example:
-const MethodDescriptor* method =
- service->GetDescriptor()->FindMethodByName("Foo");
-Message* request = stub->GetRequestPrototype (method)->New();
-Message* response = stub->GetResponsePrototype(method)->New();
-request->ParseFromString(input);
-service->CallMethod(method, *request, response, callback);
-#include <google/protobuf/service.h>
namespace google::protobuf
An RpcController mediates a single method call.
The primary purpose of the controller is to provide a way to manipulate settings specific to the RPC implementation and to find out about RPC-level errors.
-The methods provided by the RpcController interface are intended to be a "least common denominator" set of features which we expect all implementations to support. Specific implementations may provide more advanced features (e.g. deadline propagation).
-Members | |
|---|---|
| RpcController() |
virtual | ~RpcController() |
Client-side methodsThese calls may be made from the client side only. Their results are undefined on the server side (may crash). | |
virtual void | Reset() = 0Resets the RpcController to its initial state so that it may be reused in a new call. more... |
virtual bool | Failed() const = 0After a call has finished, returns true if the call failed. more... |
virtual std::string | ErrorText() const = 0If Failed() is true, returns a human-readable description of the error. |
virtual void | StartCancel() = 0Advises the RPC system that the caller desires that the RPC call be canceled. more... |
Server-side methods
- These calls may be made from the server side only. -Their results are undefined on the client side (may crash). - | |
virtual void | SetFailed(const std::string & reason) = 0 |
virtual bool | IsCanceled() const = 0If true, indicates that the client canceled the RPC, so the server may as well give up on replying to it. more... |
virtual void | NotifyOnCancel(Closure * callback) = 0Asks that the given callback be called when the RPC is canceled. more... |
virtual void RpcController::Reset() = 0Resets the RpcController to its initial state so that it may be reused in a new call.
Must not be called while an RPC is in progress.
-virtual bool RpcController::Failed() const = 0After a call has finished, returns true if the call failed.
The possible reasons for failure depend on the RPC implementation. Failed() must not be called before a call has finished. If Failed() returns true, the contents of the response message are undefined.
-virtual void RpcController::StartCancel() = 0Advises the RPC system that the caller desires that the RPC call be canceled.
The RPC system may cancel it immediately, may wait awhile and then cancel it, or may not even cancel the call at all. If the call is canceled, the "done" callback will still be called and the RpcController will indicate that the call failed at that time.
-virtual void RpcController::SetFailed(
const std::string & reason) = 0Causes Failed() to return true on the client side.
"reason" will be incorporated into the message returned by ErrorText(). If you find you need to return machine-readable information about failures, you should incorporate it into your response protocol buffer and should NOT call SetFailed().
-virtual bool RpcController::IsCanceled() const = 0If true, indicates that the client canceled the RPC, so the server may as well give up on replying to it.
The server should still call the final "done" callback.
-virtual void RpcController::NotifyOnCancel(
Closure * callback) = 0Asks that the given callback be called when the RPC is canceled.
The callback will always be called exactly once. If the RPC completes without being canceled, the callback will be called after completion. If the RPC has already been canceled when NotifyOnCancel() is called, the callback will be called immediately.
-NotifyOnCancel() must be called no more than once per request.
-#include <google/protobuf/service.h>
namespace google::protobuf
Abstract interface for an RPC channel.
An RpcChannel represents a communication line to a Service which can be used to call that Service's methods. The Service may be running on another machine. Normally, you should not call an RpcChannel directly, but instead construct a stub Service wrapping it. Example:
-RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234");
-MyService* service = new MyService::Stub(channel);
-service->MyMethod(request, &response, callback);
-Members | |
|---|---|
| RpcChannel() |
virtual | ~RpcChannel() |
virtual void | CallMethod(const MethodDescriptor * method, RpcController * controller, const Message * request, Message * response, Closure * done) = 0Call the given method of the remote service. more... |
virtual void RpcChannel::CallMethod(
const MethodDescriptor * method,
RpcController * controller,
const Message * request,
Message * response,
Closure * done) = 0Call the given method of the remote service.
The signature of this procedure looks the same as Service::CallMethod(), but the requirements are less strict in one important way: the request and response objects need not be of any specific class as long as their descriptors are method->input_type() and method->output_type().
-#include <google/protobuf/text_format.h>
namespace google::protobuf
Utilities for printing and parsing protocol messages in a human-readable, text-based format.
Classes in this file | |
|---|---|
This class implements protocol buffer text format, colloquially known as text proto. | |
The default printer that converts scalar values from fields into their string representation. | |
Deprecated: please use FastFieldValuePrinter instead. | |
Interface that Printers or Parsers can use to find extensions, or types referenced in Any messages. | |
Data structure which is populated with the locations of each field value parsed from the text. | |
A location in the parsed text. | |
For more control over parsing, use this class. | |
Class for those users which require more fine-grained control over how a protobuffer message is printed out. | |
#include <google/protobuf/text_format.h>
namespace google::protobuf
This class implements protocol buffer text format, colloquially known as text proto.
Printing and parsing protocol messages in text format is useful for debugging and human editing of messages.
- -This class is really a namespace that contains only static methods.
- -Members | |
|---|---|
static bool | Print(const Message & message, io::ZeroCopyOutputStream * output)Outputs a textual representation of the given message to the given output stream. more... |
static bool | PrintUnknownFields(const UnknownFieldSet & unknown_fields, io::ZeroCopyOutputStream * output)Print the fields in an UnknownFieldSet. more... |
static bool | PrintToString(const Message & message, std::string * output) |
static bool | PrintUnknownFieldsToString(const UnknownFieldSet & unknown_fields, std::string * output)Like PrintUnknownFields(), but outputs directly to a string. more... |
static void | PrintFieldValueToString(const Message & message, const FieldDescriptor * field, int index, std::string * output)Outputs a textual representation of the value of the field supplied on the message supplied. more... |
static bool | Parse(io::ZeroCopyInputStream * input, Message * output)Parses a text-format protocol message from the given input stream to the given message object. more... |
static bool | ParseFromString(ConstStringParam input, Message * output)Like Parse(), but reads directly from a string. |
static bool | Merge(io::ZeroCopyInputStream * input, Message * output)Like Parse(), but the data is merged into the given message, as if using Message::MergeFrom(). |
static bool | MergeFromString(ConstStringParam input, Message * output)Like Merge(), but reads directly from a string. |
static bool | ParseFieldValueFromString(const std::string & input, const FieldDescriptor * field, Message * message)Parse the given text as a single field value and store it into the given field of the given message. more... |
static bool TextFormat::Print(
const Message & message,
io::ZeroCopyOutputStream * output)Outputs a textual representation of the given message to the given output stream.
Returns false if printing fails.
-static bool TextFormat::PrintUnknownFields(
const UnknownFieldSet & unknown_fields,
io::ZeroCopyOutputStream * output)Print the fields in an UnknownFieldSet.
They are printed by tag number only. Embedded messages are heuristically identified by attempting to parse them. Returns false if printing fails.
-static bool TextFormat::PrintToString(
const Message & message,
std::string * output)Like Print(), but outputs directly to a string.
Note: output will be cleared prior to printing, and will be left empty even if printing fails. Returns false if printing fails.
-static bool TextFormat::PrintUnknownFieldsToString(
const UnknownFieldSet & unknown_fields,
std::string * output)Like PrintUnknownFields(), but outputs directly to a string.
Returns false if printing fails.
-static void TextFormat::PrintFieldValueToString(
const Message & message,
const FieldDescriptor * field,
int index,
std::string * output)Outputs a textual representation of the value of the field supplied on the message supplied.
For non-repeated fields, an index of -1 must be supplied. Note that this method will print the default value for a field if it is not set.
-static bool TextFormat::Parse(
io::ZeroCopyInputStream * input,
Message * output)Parses a text-format protocol message from the given input stream to the given message object.
This function parses the human-readable format written by Print(). Returns true on success. The message is cleared first, even if the function fails – See Merge() to avoid this behavior.
-Example input: "user {\n id: 123 extra { gender: MALE language: 'en' }\n}"
-One use for this function is parsing handwritten strings in test code. Another use is to parse the output from google::protobuf::Message::DebugString() (or ShortDebugString()), because these functions output using google::protobuf::TextFormat::Print().
-If you would like to read a protocol buffer serialized in the (non-human-readable) binary wire format, see google::protobuf::MessageLite::ParseFromString().
-static bool TextFormat::ParseFieldValueFromString(
const std::string & input,
const FieldDescriptor * field,
Message * message)Parse the given text as a single field value and store it into the given field of the given message.
If the field is a repeated field, the new value will be added to the end
-#include <google/protobuf/text_format.h>
namespace google::protobuf
Members | |
|---|---|
virtual | ~BaseTextGenerator() |
virtual void | Indent() |
virtual void | Outdent() |
virtual size_t | GetCurrentIndentationSize() constReturns the current indentation size in characters. |
virtual void | Print(const char * text, size_t size) = 0Print text to the output stream. |
void | PrintString(const std::string & str) |
template void | PrintLiteral(const char(&) text) |
#include <google/protobuf/text_format.h>
namespace google::protobuf
The default printer that converts scalar values from fields into their string representation.
You can derive from this FastFieldValuePrinter if you want to have fields to be printed in a different way and register it at the Printer.
-Members | |
|---|---|
| FastFieldValuePrinter() |
virtual | ~FastFieldValuePrinter() |
virtual void | PrintBool(bool val, BaseTextGenerator * generator) const |
virtual void | PrintInt32(int32 val, BaseTextGenerator * generator) const |
virtual void | PrintUInt32(uint32 val, BaseTextGenerator * generator) const |
virtual void | PrintInt64(int64 val, BaseTextGenerator * generator) const |
virtual void | PrintUInt64(uint64 val, BaseTextGenerator * generator) const |
virtual void | PrintFloat(float val, BaseTextGenerator * generator) const |
virtual void | PrintDouble(double val, BaseTextGenerator * generator) const |
virtual void | PrintString(const std::string & val, BaseTextGenerator * generator) const |
virtual void | PrintBytes(const std::string & val, BaseTextGenerator * generator) const |
virtual void | PrintEnum(int32 val, const std::string & name, BaseTextGenerator * generator) const |
virtual void | PrintFieldName(const Message & message, int field_index, int field_count, const Reflection * reflection, const FieldDescriptor * field, BaseTextGenerator * generator) const |
virtual void | PrintFieldName(const Message & message, const Reflection * reflection, const FieldDescriptor * field, BaseTextGenerator * generator) const |
virtual void | PrintMessageStart(const Message & message, int field_index, int field_count, bool single_line_mode, BaseTextGenerator * generator) const |
virtual bool | PrintMessageContent(const Message & message, int field_index, int field_count, bool single_line_mode, BaseTextGenerator * generator) constAllows to override the logic on how to print the content of a message. more... |
virtual void | PrintMessageEnd(const Message & message, int field_index, int field_count, bool single_line_mode, BaseTextGenerator * generator) const |
virtual bool FastFieldValuePrinter::PrintMessageContent(
const Message & message,
int field_index,
int field_count,
bool single_line_mode,
BaseTextGenerator * generator) constAllows to override the logic on how to print the content of a message.
Return false to use the default printing logic. Note that it is legal for this function to print something and then return false to use the default content printing (although at that point it would behave similarly to PrintMessageStart).
-#include <google/protobuf/text_format.h>
namespace google::protobuf
Deprecated: please use FastFieldValuePrinter instead.
Members | |
|---|---|
| FieldValuePrinter() |
virtual | ~FieldValuePrinter() |
virtual std::string | PrintBool(bool val) const |
virtual std::string | PrintInt32(int32 val) const |
virtual std::string | PrintUInt32(uint32 val) const |
virtual std::string | PrintInt64(int64 val) const |
virtual std::string | PrintUInt64(uint64 val) const |
virtual std::string | PrintFloat(float val) const |
virtual std::string | PrintDouble(double val) const |
virtual std::string | PrintString(const std::string & val) const |
virtual std::string | PrintBytes(const std::string & val) const |
virtual std::string | PrintEnum(int32 val, const std::string & name) const |
virtual std::string | PrintFieldName(const Message & message, const Reflection * reflection, const FieldDescriptor * field) const |
virtual std::string | PrintMessageStart(const Message & message, int field_index, int field_count, bool single_line_mode) const |
virtual std::string | PrintMessageEnd(const Message & message, int field_index, int field_count, bool single_line_mode) const |
#include <google/protobuf/text_format.h>
namespace google::protobuf
Interface that Printers or Parsers can use to find extensions, or types referenced in Any messages.
Members | |
|---|---|
virtual | ~Finder() |
virtual const FieldDescriptor * | FindExtension(Message * message, const std::string & name) constTry to find an extension of *message by fully-qualified field name. more... |
virtual const FieldDescriptor * | FindExtensionByNumber(const Descriptor * descriptor, int number) constSimilar to FindExtension, but uses a Descriptor and the extension number instead of using a Message and the name when doing the look up. |
virtual const Descriptor * | FindAnyType(const Message & message, const std::string & prefix, const std::string & name) constFind the message type for an Any proto. more... |
virtual MessageFactory * | FindExtensionFactory(const FieldDescriptor * field) constFind the message factory for the given extension field. more... |
virtual const FieldDescriptor *
Finder::FindExtension(
Message * message,
const std::string & name) constTry to find an extension of *message by fully-qualified field name.
Returns NULL if no extension is known for this name or number. The base implementation uses the extensions already known by the message.
-virtual const Descriptor *
Finder::FindAnyType(
const Message & message,
const std::string & prefix,
const std::string & name) constFind the message type for an Any proto.
Returns NULL if no message is known for this name. The base implementation only accepts prefixes of type.googleprod.com/ or type.googleapis.com/, and searches the DescriptorPool of the parent message.
-virtual MessageFactory * Finder::FindExtensionFactory(
const FieldDescriptor * field) constFind the message factory for the given extension field.
This can be used to generalize the Parser to add extension fields to a message in the same way as the "input" message for the Parser.
-#include <google/protobuf/text_format.h>
namespace google::protobuf
Members | |
|---|---|
| MessagePrinter() |
virtual | ~MessagePrinter() |
virtual void | Print(const Message & message, bool single_line_mode, BaseTextGenerator * generator) const = 0 |
#include <google/protobuf/text_format.h>
namespace google::protobuf
Data structure which is populated with the locations of each field value parsed from the text.
Members | |
|---|---|
| ParseInfoTree() |
| ParseInfoTree(const ParseInfoTree & ) |
ParseInfoTree & | operator=(const ParseInfoTree & ) |
ParseLocation | GetLocation(const FieldDescriptor * field, int index) constReturns the parse location for index-th value of the field in the parsed text. more... |
ParseInfoTree * | GetTreeForNested(const FieldDescriptor * field, int index) constReturns the parse info tree for the given field, which must be a message type. more... |
ParseLocation ParseInfoTree::GetLocation(
const FieldDescriptor * field,
int index) constReturns the parse location for index-th value of the field in the parsed text.
If none exists, returns a location with line = -1. Index should be -1 for not-repeated fields.
-ParseInfoTree * ParseInfoTree::GetTreeForNested(
const FieldDescriptor * field,
int index) constReturns the parse info tree for the given field, which must be a message type.
The nested information tree is owned by the root tree and will be deleted when it is deleted.
-#include <google/protobuf/text_format.h>
namespace google::protobuf
A location in the parsed text.
Members | |
|---|---|
int | line |
int | column |
| ParseLocation() |
| ParseLocation(int line_param, int column_param) |
#include <google/protobuf/text_format.h>
namespace google::protobuf
For more control over parsing, use this class.
Members | |
|---|---|
| Parser() |
| ~Parser() |
bool | Parse(io::ZeroCopyInputStream * input, Message * output)Like TextFormat::Parse(). |
bool | ParseFromString(ConstStringParam input, Message * output) |
bool | Merge(io::ZeroCopyInputStream * input, Message * output)Like TextFormat::Merge(). |
bool | MergeFromString(ConstStringParam input, Message * output) |
void | RecordErrorsTo(io::ErrorCollector * error_collector)Set where to report parse errors. more... |
void | SetFinder(const Finder * finder)Set how parser finds extensions. more... |
void | WriteLocationsTo(ParseInfoTree * tree)Sets where location information about the parse will be written. more... |
void | AllowPartialMessage(bool allow)Normally parsing fails if, after parsing, output->IsInitialized() returns false. more... |
void | AllowCaseInsensitiveField(bool allow)Allow field names to be matched case-insensitively. more... |
bool | ParseFieldValueFromString(const std::string & input, const FieldDescriptor * field, Message * output) |
void | AllowUnknownExtension(bool allow)When an unknown extension is met, parsing will fail if this option is set to false (the default). more... |
void | AllowUnknownField(bool allow)When an unknown field is met, parsing will fail if this option is set to false (the default). more... |
void | AllowFieldNumber(bool allow) |
void | SetRecursionLimit(int limit)Sets maximum recursion depth which parser can use. more... |
void Parser::RecordErrorsTo(
io::ErrorCollector * error_collector)Set where to report parse errors.
If NULL (the default), errors will be printed to stderr.
-void Parser::SetFinder(
const Finder * finder)Set how parser finds extensions.
If NULL (the default), the parser will use the standard Reflection object associated with the message being parsed.
-void Parser::WriteLocationsTo(
ParseInfoTree * tree)Sets where location information about the parse will be written.
If NULL (the default), then no location will be written.
-void Parser::AllowPartialMessage(
bool allow)Normally parsing fails if, after parsing, output->IsInitialized() returns false.
Call AllowPartialMessage(true) to skip this check.
-void Parser::AllowCaseInsensitiveField(
bool allow)Allow field names to be matched case-insensitively.
This is not advisable if there are fields that only differ in case, or if you want to enforce writing in the canonical form. This is 'false' by default.
-void Parser::AllowUnknownExtension(
bool allow)When an unknown extension is met, parsing will fail if this option is set to false (the default).
If true, unknown extensions will be ignored and a warning message will be generated. Beware! Setting this option true may hide some errors (e.g. spelling error on extension name). This allows data loss; unlike binary format, text format cannot preserve unknown extensions. Avoid using this option if possible.
-void Parser::AllowUnknownField(
bool allow)When an unknown field is met, parsing will fail if this option is set to false (the default).
If true, unknown fields will be ignored and a warning message will be generated. Beware! Setting this option true may hide some errors (e.g. spelling error on field name). This allows data loss; unlike binary format, text format cannot preserve unknown fields. Avoid using this option if possible.
-void Parser::SetRecursionLimit(
int limit)Sets maximum recursion depth which parser can use.
This is effectively the maximum allowed nesting of proto messages.
-#include <google/protobuf/text_format.h>
namespace google::protobuf
Class for those users which require more fine-grained control over how a protobuffer message is printed out.
Members | |
|---|---|
| Printer() |
bool | Print(const Message & message, io::ZeroCopyOutputStream * output) constLike TextFormat::Print. |
bool | PrintUnknownFields(const UnknownFieldSet & unknown_fields, io::ZeroCopyOutputStream * output) const |
bool | PrintToString(const Message & message, std::string * output) const |
bool | PrintUnknownFieldsToString(const UnknownFieldSet & unknown_fields, std::string * output) const |
void | PrintFieldValueToString(const Message & message, const FieldDescriptor * field, int index, std::string * output) const |
void | SetInitialIndentLevel(int indent_level)Adjust the initial indent level of all output. more... |
void | SetSingleLineMode(bool single_line_mode)If printing in single line mode, then the entire message will be output on a single line with no line breaks. |
bool | IsInSingleLineMode() const |
void | SetUseFieldNumber(bool use_field_number)If use_field_number is true, uses field number instead of field name. |
void | SetUseShortRepeatedPrimitives(bool use_short_repeated_primitives)Set true to print repeated primitives in a format like: more... |
void | SetUseUtf8StringEscaping(bool as_utf8)Set true to output UTF-8 instead of ASCII. more... |
void | SetDefaultFieldValuePrinter(const FastFieldValuePrinter * printer)Set the default FastFieldValuePrinter that is used for all fields that don't have a field-specific printer registered. more... |
void | SetDefaultFieldValuePrinter(const FieldValuePrinter * printer) |
void | SetHideUnknownFields(bool hide)Sets whether we want to hide unknown fields or not. more... |
void | SetPrintMessageFieldsInIndexOrder(bool print_message_fields_in_index_order)If print_message_fields_in_index_order is true, fields of a proto message will be printed using the order defined in source code instead of the field number, extensions will be printed at the end of the message and their relative order is determined by the extension number. more... |
void | SetExpandAny(bool expand)If expand==true, expand google.protobuf.Any payloads. more... |
void | SetFinder(const Finder * finder)Set how parser finds message for Any payloads. |
void | SetTruncateStringFieldLongerThan(const int64 truncate_string_field_longer_than)If non-zero, we truncate all string fields that are longer than this threshold. more... |
bool | RegisterFieldValuePrinter(const FieldDescriptor * field, const FastFieldValuePrinter * printer)Register a custom field-specific FastFieldValuePrinter for fields with a particular FieldDescriptor. more... |
bool | RegisterFieldValuePrinter(const FieldDescriptor * field, const FieldValuePrinter * printer) |
bool | RegisterMessagePrinter(const Descriptor * descriptor, const MessagePrinter * printer)Register a custom message-specific MessagePrinter for messages with a particular Descriptor. more... |
void Printer::SetInitialIndentLevel(
int indent_level)Adjust the initial indent level of all output.
Each indent level is equal to two spaces.
-void Printer::SetUseShortRepeatedPrimitives(
bool use_short_repeated_primitives)Set true to print repeated primitives in a format like:
field_name: [1, 2, 3, 4]-
instead of printing each value on its own line. Short format applies only to primitive values – i.e. everything except strings and sub-messages/groups.
-void Printer::SetUseUtf8StringEscaping(
bool as_utf8)Set true to output UTF-8 instead of ASCII.
The only difference is that bytes >= 0x80 in string fields will not be escaped, because they are assumed to be part of UTF-8 multi-byte sequences. This will change the default FastFieldValuePrinter.
-void Printer::SetDefaultFieldValuePrinter(
const FastFieldValuePrinter * printer)Set the default FastFieldValuePrinter that is used for all fields that don't have a field-specific printer registered.
Takes ownership of the printer.
-void Printer::SetHideUnknownFields(
bool hide)Sets whether we want to hide unknown fields or not.
Usually unknown fields are printed in a generic way that includes the tag number of the field instead of field name. However, sometimes it is useful to be able to print the message without unknown fields (e.g. for the python protobuf version to maintain consistency between its pure python and c++ implementations).
-void Printer::SetPrintMessageFieldsInIndexOrder(
bool print_message_fields_in_index_order)If print_message_fields_in_index_order is true, fields of a proto message will be printed using the order defined in source code instead of the field number, extensions will be printed at the end of the message and their relative order is determined by the extension number.
By default, use the field number order.
-void Printer::SetExpandAny(
bool expand)If expand==true, expand google.protobuf.Any payloads.
The output will be of form
-[type_url] { <value_printed_in_text> }
-If expand==false, print Any using the default printer. The output will look like
-type_url: "<type_url>" value: "serialized_content"-
void Printer::SetTruncateStringFieldLongerThan(
const int64 truncate_string_field_longer_than)If non-zero, we truncate all string fields that are longer than this threshold.
This is useful when the proto message has very long strings, e.g., dump of encoded image file.
-NOTE(hfgong): Setting a non-zero value breaks round-trip safe property of TextFormat::Printer. That is, from the printed message, we cannot fully recover the original string field any more.
-bool Printer::RegisterFieldValuePrinter(
const FieldDescriptor * field,
const FastFieldValuePrinter * printer)Register a custom field-specific FastFieldValuePrinter for fields with a particular FieldDescriptor.
Returns "true" if the registration succeeded, or "false", if there is already a printer for that FieldDescriptor. Takes ownership of the printer on successful registration.
-bool Printer::RegisterMessagePrinter(
const Descriptor * descriptor,
const MessagePrinter * printer)Register a custom message-specific MessagePrinter for messages with a particular Descriptor.
Returns "true" if the registration succeeded, or "false" if there is already a printer for that Descriptor.
-#include <google/protobuf/unknown_field_set.h>
namespace google::protobuf
Contains classes used to keep track of unrecognized fields seen while parsing a protocol message.
Classes in this file | |
|---|---|
An UnknownFieldSet contains fields that were encountered while parsing a message but were not defined by its type. | |
Represents one field in an UnknownFieldSet. | |
#include <google/protobuf/unknown_field_set.h>
namespace google::protobuf
An UnknownFieldSet contains fields that were encountered while parsing a message but were not defined by its type.
Keeping track of these can be useful, especially in that they may be written if the message is serialized again without being cleared in between. This means that software which simply receives messages and forwards them to other servers does not need to be updated every time a new field is added to the message definition.
- -To get the UnknownFieldSet attached to any message, call Reflection::GetUnknownFields().
- -This class is necessarily tied to the protocol buffer wire format, unlike the Reflection interface which is independent of any serialization scheme.
- -Members | |
|---|---|
| UnknownFieldSet() |
| ~UnknownFieldSet() |
void | Clear()Remove all fields. |
void | ClearAndFreeMemory()Remove all fields and deallocate internal data objects. |
bool | empty() constIs this set empty? |
void | MergeFrom(const UnknownFieldSet & other)Merge the contents of some other UnknownFieldSet with this one. |
void | MergeFromAndDestroy(UnknownFieldSet * other)Similar to above, but this function will destroy the contents of other. |
void | Swap(UnknownFieldSet * x)Swaps the contents of some other UnknownFieldSet with this one. |
size_t | SpaceUsedExcludingSelfLong() constComputes (an estimate of) the total number of bytes currently used for storing the unknown fields in memory. more... |
int | SpaceUsedExcludingSelf() const |
size_t | SpaceUsedLong() constVersion of SpaceUsed() including sizeof(*this). |
int | SpaceUsed() const |
int | field_count() constReturns the number of fields present in the UnknownFieldSet. |
const UnknownField & | field(int index) constGet a field in the set, where 0 <= index < field_count(). more... |
UnknownField * | mutable_field(int index)Get a mutable pointer to a field in the set, where 0 <= index < field_count(). more... |
static void | MergeToInternalMetadata(const UnknownFieldSet & other, internal::InternalMetadata * metadata)Merge the contents an UnknownFieldSet with the UnknownFieldSet in *metadata, if there is one. more... |
Adding fields | |
void | AddVarint(int number, uint64 value) |
void | AddFixed32(int number, uint32 value) |
void | AddFixed64(int number, uint64 value) |
void | AddLengthDelimited(int number, const std::string & value) |
std::string * | AddLengthDelimited(int number) |
UnknownFieldSet * | AddGroup(int number) |
void | AddField(const UnknownField & field)Adds an unknown field from another set. |
void | DeleteSubrange(int start, int num)Delete fields with indices in the range [start . more... |
void | DeleteByNumber(int number)Delete all fields with a specific field number. more... |
Parsing helpersThese work exactly like the similarly-named methods of Message. | |
bool | MergeFromCodedStream(io::CodedInputStream * input) |
bool | ParseFromCodedStream(io::CodedInputStream * input) |
bool | ParseFromZeroCopyStream(io::ZeroCopyInputStream * input) |
bool | ParseFromArray(const void * data, int size) |
bool | ParseFromString(const std::string & data) |
template bool | MergeFromMessage(const MessageType & message)Merges this message's unknown field data (if any). more... |
static const UnknownFieldSet & | default_instance() |
size_t UnknownFieldSet::SpaceUsedExcludingSelfLong() constComputes (an estimate of) the total number of bytes currently used for storing the unknown fields in memory.
Does NOT include sizeof(*this) in the calculation.
-const UnknownField &
UnknownFieldSet::field(
int index) constGet a field in the set, where 0 <= index < field_count().
The fields appear in the order in which they were added.
-UnknownField * UnknownFieldSet::mutable_field(
int index)Get a mutable pointer to a field in the set, where 0 <= index < field_count().
The fields appear in the order in which they were added.
-static void UnknownFieldSet::MergeToInternalMetadata(
const UnknownFieldSet & other,
internal::InternalMetadata * metadata)Merge the contents an UnknownFieldSet with the UnknownFieldSet in *metadata, if there is one.
If *metadata doesn't have an UnknownFieldSet then add one to it and make it be a copy of the first arg.
-void UnknownFieldSet::DeleteSubrange(
int start,
int num)Delete fields with indices in the range [start .
. start+num-1]. Caution: implementation moves all fields with indices [start+num .. ].
-void UnknownFieldSet::DeleteByNumber(
int number)Delete all fields with a specific field number.
The order of left fields is preserved. Caution: implementation moves all fields after the first deleted field.
-template bool UnknownFieldSet::MergeFromMessage(
const MessageType & message)Merges this message's unknown field data (if any).
This works whether the message is a lite or full proto (for legacy reasons, lite and full return different types for MessageType::unknown_fields()).
-#include <google/protobuf/unknown_field_set.h>
namespace google::protobuf
Represents one field in an UnknownFieldSet.
Members | |
|---|---|
enum | Type |
uint64 | varint_ |
uint32 | fixed32_ |
uint64 | fixed64_ |
union LengthDelimited | length_delimited_ |
UnknownFieldSet * | group_ |
int | number() constThe field's field number, as seen on the wire. |
Type | type() constThe field type. |
AccessorsEach method works only for UnknownFields of the corresponding type. | |
uint32 | number_ |
uint32 | type_ |
union google::protobuf::UnknownField::@35 | data_ |
uint64 | varint() const |
uint32 | fixed32() const |
uint64 | fixed64() const |
const std::string & | length_delimited() const |
const UnknownFieldSet & | group() const |
void | set_varint(uint64 value) |
void | set_fixed32(uint32 value) |
void | set_fixed64(uint64 value) |
void | set_length_delimited(const std::string & value) |
std::string * | mutable_length_delimited() |
UnknownFieldSet * | mutable_group() |
void | SerializeLengthDelimitedNoTag(io::CodedOutputStream * output) constSerialization API. more... |
size_t | GetLengthDelimitedSize() const |
uint8 * | InternalSerializeLengthDelimitedNoTag(uint8 * target, io::EpsCopyOutputStream * stream) const |
void | Delete()If this UnknownField contains a pointer, delete it. |
void | DeepCopy(const UnknownField & other)Make a deep copy of any pointers in this UnknownField. |
void | SetType(Type type)Set the wire type of this UnknownField. more... |
enum UnknownField::Type {
TYPE_VARINT,
TYPE_FIXED32,
TYPE_FIXED64,
TYPE_LENGTH_DELIMITED,
TYPE_GROUP
}| TYPE_VARINT | |
| TYPE_FIXED32 | |
| TYPE_FIXED64 | |
| TYPE_LENGTH_DELIMITED | |
| TYPE_GROUP |
void UnknownField::SerializeLengthDelimitedNoTag(
io::CodedOutputStream * output) constSerialization API.
These methods can take advantage of the underlying implementation and may achieve a better performance than using getters to retrieve the data and do the serialization yourself.
-void UnknownField::SetType(
Type type)Set the wire type of this UnknownField.
Should only be used when this UnknownField is being created.
-#include <google/protobuf/unknown_field_set.h>
namespace google::protobuf
Members | |
|---|---|
std::string * | string_value |
#include <google/protobuf/util/field_comparator.h>
namespace google::protobuf::util
Defines classes for field comparison.
Classes in this file | |
|---|---|
Base class specifying the interface for comparing protocol buffer fields. | |
Basic implementation of FieldComparator. | |
#include <google/protobuf/util/field_comparator.h>
namespace google::protobuf::util
Base class specifying the interface for comparing protocol buffer fields.
Regular users should consider using or subclassing DefaultFieldComparator rather than this interface. Currently, this does not support comparing unknown fields.
- -Known subclasses:
Members | |
|---|---|
enum | ComparisonResult |
| FieldComparator() |
virtual | ~FieldComparator() |
virtual ComparisonResult | Compare(const Message & message_1, const Message & message_2, const FieldDescriptor * field, int index_1, int index_2, const util::FieldContext * field_context) = 0Compares the values of a field in two protocol buffer messages. more... |
enum FieldComparator::ComparisonResult {
SAME,
DIFFERENT,
RECURSE
}| SAME | Compared fields are equal. In case of comparing submessages, user should not recursively compare their contents. - |
| DIFFERENT | Compared fields are different. In case of comparing submessages, user should not recursively compare their contents. - |
| RECURSE | Compared submessages need to be compared recursively. FieldComparator does not specify the semantics of recursive comparison. This value should not be returned for simple values. - |
virtual ComparisonResult FieldComparator::Compare(
const Message & message_1,
const Message & message_2,
const FieldDescriptor * field,
int index_1,
int index_2,
const util::FieldContext * field_context) = 0Compares the values of a field in two protocol buffer messages.
Returns SAME or DIFFERENT for simple values, and SAME, DIFFERENT or RECURSE for submessages. Returning RECURSE for fields not being submessages is illegal. In case the given FieldDescriptor points to a repeated field, the indices need to be valid. Otherwise they should be ignored.
- -FieldContext contains information about the specific instances of the fields being compared, versus FieldDescriptor which only contains general type information about the fields.
-#include <google/protobuf/util/field_comparator.h>
namespace google::protobuf::util
Basic implementation of FieldComparator.
Supports three modes of floating point value comparison: exact, approximate using MathUtil::AlmostEqual method, and arbitrarily precise using MathUtil::WithinFractionOrMargin.
- -Known subclasses:
Members | |
|---|---|
enum | FloatComparison |
| SimpleFieldComparator()Creates new comparator with float comparison set to EXACT. |
| ~SimpleFieldComparator() |
void | set_float_comparison(FloatComparison float_comparison) |
FloatComparison | float_comparison() const |
void | set_treat_nan_as_equal(bool treat_nan_as_equal)Set whether the FieldComparator shall treat floats or doubles that are both NaN as equal (treat_nan_as_equal = true) or as different (treat_nan_as_equal = false). more... |
bool | treat_nan_as_equal() const |
void | SetFractionAndMargin(const FieldDescriptor * field, double fraction, double margin)Sets the fraction and margin for the float comparison of a given field. more... |
void | SetDefaultFractionAndMargin(double fraction, double margin)Sets the fraction and margin for the float comparison of all float and double fields, unless a field has been given a specific setting via SetFractionAndMargin() above. more... |
protected ComparisonResult | SimpleCompare(const Message & message_1, const Message & message_2, const FieldDescriptor * field, int index_1, int index_2, const util::FieldContext * field_context)Returns the comparison result for the given field in two messages. more... |
protected bool | CompareWithDifferencer(MessageDifferencer * differencer, const Message & message1, const Message & message2, const util::FieldContext * field_context)Compare using the provided message_differencer. more... |
protected ComparisonResult | ResultFromBoolean(bool boolean_result) constReturns FieldComparator::SAME if boolean_result is true and FieldComparator::DIFFERENT otherwise. |
enum SimpleFieldComparator::FloatComparison {
EXACT,
APPROXIMATE
}| EXACT | Floats and doubles are compared exactly. |
| APPROXIMATE | Floats and doubles are compared using the MathUtil::AlmostEqual method or MathUtil::WithinFractionOrMargin method. |
void SimpleFieldComparator::set_treat_nan_as_equal(
bool treat_nan_as_equal)Set whether the FieldComparator shall treat floats or doubles that are both NaN as equal (treat_nan_as_equal = true) or as different (treat_nan_as_equal = false).
Default is treating NaNs always as different.
-void SimpleFieldComparator::SetFractionAndMargin(
const FieldDescriptor * field,
double fraction,
double margin)Sets the fraction and margin for the float comparison of a given field.
Uses MathUtil::WithinFractionOrMargin to compare the values.
- -REQUIRES: field->cpp_type == FieldDescriptor::CPPTYPE_DOUBLE or
- -field->cpp_type == FieldDescriptor::CPPTYPE_FLOAT- -
REQUIRES: float_comparison_ == APPROXIMATE
-void SimpleFieldComparator::SetDefaultFractionAndMargin(
double fraction,
double margin)Sets the fraction and margin for the float comparison of all float and double fields, unless a field has been given a specific setting via SetFractionAndMargin() above.
Uses MathUtil::WithinFractionOrMargin to compare the values.
- -REQUIRES: float_comparison_ == APPROXIMATE
-protected ComparisonResult SimpleFieldComparator::SimpleCompare(
const Message & message_1,
const Message & message_2,
const FieldDescriptor * field,
int index_1,
int index_2,
const util::FieldContext * field_context)Returns the comparison result for the given field in two messages.
This function is called directly by DefaultFieldComparator::Compare. Subclasses can call this function to compare fields they do not need to handle specially.
-protected bool SimpleFieldComparator::CompareWithDifferencer(
MessageDifferencer * differencer,
const Message & message1,
const Message & message2,
const util::FieldContext * field_context)Compare using the provided message_differencer.
For example, a subclass can use this method to compare some field in a certain way using the same message_differencer instance and the field context.
-#include <google/protobuf/util/field_comparator.h>
namespace google::protobuf::util
Members | |
|---|---|
virtual ComparisonResult | Compare(const Message & message_1, const Message & message_2, const FieldDescriptor * field, int index_1, int index_2, const util::FieldContext * field_context)Compares the values of a field in two protocol buffer messages. more... |
virtual ComparisonResult DefaultFieldComparator::Compare(
const Message & message_1,
const Message & message_2,
const FieldDescriptor * field,
int index_1,
int index_2,
const util::FieldContext * field_context)Compares the values of a field in two protocol buffer messages.
Returns SAME or DIFFERENT for simple values, and SAME, DIFFERENT or RECURSE for submessages. Returning RECURSE for fields not being submessages is illegal. In case the given FieldDescriptor points to a repeated field, the indices need to be valid. Otherwise they should be ignored.
- -FieldContext contains information about the specific instances of the fields being compared, versus FieldDescriptor which only contains general type information about the fields.
- -#include <google/protobuf/util/field_mask_util.h>
namespace google::protobuf::util
Defines utilities for the FieldMask well known type.
Classes in this file | |
|---|---|
#include <google/protobuf/util/field_mask_util.h>
namespace google::protobuf::util
Members | |
|---|---|
static std::string | ToString(const FieldMask & mask)Converts FieldMask to/from string, formatted by separating each path with a comma (e.g., "foo_bar,baz.quz"). |
static void | FromString(StringPiece str, FieldMask * out) |
template static void | FromFieldNumbers(const std::vector< int64_t > & field_numbers, FieldMask * out)Populates the FieldMask with the paths corresponding to the fields with the given numbers, after checking that all field numbers are valid. |
static bool | ToJsonString(const FieldMask & mask, std::string * out)Converts FieldMask to/from string, formatted according to proto3 JSON spec for FieldMask (e.g., "fooBar,baz.quz"). more... |
static bool | FromJsonString(StringPiece str, FieldMask * out) |
static bool | GetFieldDescriptors(const Descriptor * descriptor, StringPiece path, std::vector< const FieldDescriptor * > * field_descriptors)Get the descriptors of the fields which the given path from the message descriptor traverses, if field_descriptors is not null. more... |
template static bool | IsValidPath(StringPiece path)Checks whether the given path is valid for type T. |
template static bool | IsValidFieldMask(const FieldMask & mask)Checks whether the given FieldMask is valid for type T. |
template static void | AddPathToFieldMask(StringPiece path, FieldMask * mask)Adds a path to FieldMask after checking whether the given path is valid. more... |
template static FieldMask | GetFieldMaskForAllFields()Creates a FieldMask with all fields of type T. more... |
template static void | GetFieldMaskForAllFields(FieldMask * out) |
static void | GetFieldMaskForAllFields(const Descriptor * descriptor, FieldMask * out)This flavor takes the protobuf type descriptor as an argument. more... |
static void | ToCanonicalForm(const FieldMask & mask, FieldMask * out)Converts a FieldMask to the canonical form. more... |
static void | Union(const FieldMask & mask1, const FieldMask & mask2, FieldMask * out)Creates an union of two FieldMasks. |
static void | Intersect(const FieldMask & mask1, const FieldMask & mask2, FieldMask * out)Creates an intersection of two FieldMasks. |
template static void | Subtract(const FieldMask & mask1, const FieldMask & mask2, FieldMask * out)Subtracts mask2 from mask1 base of type T. |
static void | Subtract(const Descriptor * descriptor, const FieldMask & mask1, const FieldMask & mask2, FieldMask * out)This flavor takes the protobuf type descriptor as an argument. more... |
static bool | IsPathInFieldMask(StringPiece path, const FieldMask & mask)Returns true if path is covered by the given FieldMask. more... |
static void | MergeMessageTo(const Message & source, const FieldMask & mask, const MergeOptions & options, Message * destination)Merges fields specified in a FieldMask into another message. |
static bool | TrimMessage(const FieldMask & mask, Message * message)Removes from 'message' any field that is not represented in the given FieldMask. more... |
static bool | TrimMessage(const FieldMask & mask, Message * message, const TrimOptions & options)Removes from 'message' any field that is not represented in the given FieldMask with customized TrimOptions. more... |
static bool FieldMaskUtil::ToJsonString(
const FieldMask & mask,
std::string * out)Converts FieldMask to/from string, formatted according to proto3 JSON spec for FieldMask (e.g., "fooBar,baz.quz").
If the field name is not style conforming (i.e., not snake_case when converted to string, or not camelCase when converted from string), the conversion will fail.
-static bool FieldMaskUtil::GetFieldDescriptors(
const Descriptor * descriptor,
StringPiece path,
std::vector< const FieldDescriptor * > * field_descriptors)Get the descriptors of the fields which the given path from the message descriptor traverses, if field_descriptors is not null.
Return false if the path is not valid, and the content of field_descriptors is unspecified.
-template static void FieldMaskUtil::AddPathToFieldMask(
StringPiece path,
FieldMask * mask)Adds a path to FieldMask after checking whether the given path is valid.
This method check-fails if the path is not a valid path for type T.
-template static FieldMask FieldMaskUtil::GetFieldMaskForAllFields()Creates a FieldMask with all fields of type T.
This FieldMask only contains fields of T but not any sub-message fields.
-static void FieldMaskUtil::GetFieldMaskForAllFields(
const Descriptor * descriptor,
FieldMask * out)This flavor takes the protobuf type descriptor as an argument.
Useful when the type is not known at compile time.
-static void FieldMaskUtil::ToCanonicalForm(
const FieldMask & mask,
FieldMask * out)Converts a FieldMask to the canonical form.
It will:
- -1. Remove paths that are covered by another path. For example, - "foo.bar" is covered by "foo" and will be removed if "foo" - is also in the FieldMask. -2. Sort all paths in alphabetical order.- -
static void FieldMaskUtil::Subtract(
const Descriptor * descriptor,
const FieldMask & mask1,
const FieldMask & mask2,
FieldMask * out)This flavor takes the protobuf type descriptor as an argument.
Useful when the type is not known at compile time.
-static bool FieldMaskUtil::IsPathInFieldMask(
StringPiece path,
const FieldMask & mask)Returns true if path is covered by the given FieldMask.
Note that path "foo.bar" covers all paths like "foo.bar.baz", "foo.bar.quz.x", etc. Also note that parent paths are not covered by explicit child path, i.e. "foo.bar" does NOT cover "foo", even if "bar" is the only child.
-static bool FieldMaskUtil::TrimMessage(
const FieldMask & mask,
Message * message)Removes from 'message' any field that is not represented in the given FieldMask.
If the FieldMask is empty, does nothing. Returns true if the message is modified.
-static bool FieldMaskUtil::TrimMessage(
const FieldMask & mask,
Message * message,
const TrimOptions & options)Removes from 'message' any field that is not represented in the given FieldMask with customized TrimOptions.
If the FieldMask is empty, does nothing. Returns true if the message is modified.
-#include <google/protobuf/util/field_mask_util.h>
namespace google::protobuf::util
Members | |
|---|---|
| MergeOptions() |
void | set_replace_message_fields(bool value)When merging message fields, the default behavior is to merge the content of two message fields together. more... |
bool | replace_message_fields() const |
void | set_replace_repeated_fields(bool value)The default merging behavior will append entries from the source repeated field to the destination repeated field. more... |
bool | replace_repeated_fields() const |
void MergeOptions::set_replace_message_fields(
bool value)When merging message fields, the default behavior is to merge the content of two message fields together.
If you instead want to use the field from the source message to replace the corresponding field in the destination message, set this flag to true. When this flag is set, specified submessage fields that are missing in source will be cleared in destination.
-void MergeOptions::set_replace_repeated_fields(
bool value)The default merging behavior will append entries from the source repeated field to the destination repeated field.
If you only want to keep the entries from the source repeated field, set this flag to true.
-#include <google/protobuf/util/field_mask_util.h>
namespace google::protobuf::util
Members | |
|---|---|
| TrimOptions() |
void | set_keep_required_fields(bool value)When trimming message fields, the default behavior is to trim required fields of the present message if they are not specified in the field mask. more... |
bool | keep_required_fields() const |
void TrimOptions::set_keep_required_fields(
bool value)When trimming message fields, the default behavior is to trim required fields of the present message if they are not specified in the field mask.
If you instead want to keep required fields of the present message even they are not specified in the field mask, set this flag to true.
-#include <google/protobuf/util/json_util.h>
namespace google::protobuf::util
Utility functions to convert between protobuf binary format and proto3 JSON format.
Classes in this file | |
|---|---|
File MembersThese definitions are not part of any class. | |
|---|---|
typedef | JsonPrintOptions JsonOptionsDEPRECATED. Use JsonPrintOptions instead. |
util::Status | MessageToJsonString(const Message & message, std::string * output, const JsonOptions & options)Converts from protobuf message to JSON and appends it to |output|. more... |
util::Status | MessageToJsonString(const Message & message, std::string * output) |
util::Status | JsonStringToMessage(StringPiece input, Message * message, const JsonParseOptions & options)Converts from JSON to protobuf message. more... |
util::Status | JsonStringToMessage(StringPiece input, Message * message) |
util::Status | BinaryToJsonStream(TypeResolver * resolver, const std::string & type_url, io::ZeroCopyInputStream * binary_input, io::ZeroCopyOutputStream * json_output, const JsonPrintOptions & options)Converts protobuf binary data to JSON. more... |
util::Status | BinaryToJsonStream(TypeResolver * resolver, const std::string & type_url, io::ZeroCopyInputStream * binary_input, io::ZeroCopyOutputStream * json_output) |
util::Status | BinaryToJsonString(TypeResolver * resolver, const std::string & type_url, const std::string & binary_input, std::string * json_output, const JsonPrintOptions & options) |
util::Status | BinaryToJsonString(TypeResolver * resolver, const std::string & type_url, const std::string & binary_input, std::string * json_output) |
util::Status | JsonToBinaryStream(TypeResolver * resolver, const std::string & type_url, io::ZeroCopyInputStream * json_input, io::ZeroCopyOutputStream * binary_output, const JsonParseOptions & options)Converts JSON data to protobuf binary format. more... |
util::Status | JsonToBinaryStream(TypeResolver * resolver, const std::string & type_url, io::ZeroCopyInputStream * json_input, io::ZeroCopyOutputStream * binary_output) |
util::Status | JsonToBinaryString(TypeResolver * resolver, const std::string & type_url, StringPiece json_input, std::string * binary_output, const JsonParseOptions & options) |
util::Status | JsonToBinaryString(TypeResolver * resolver, const std::string & type_url, StringPiece json_input, std::string * binary_output) |
util::Status util::MessageToJsonString(
const Message & message,
std::string * output,
const JsonOptions & options)Converts from protobuf message to JSON and appends it to |output|.
This is a simple wrapper of BinaryToJsonString(). It will use the DescriptorPool of the passed-in message to resolve Any types.
-util::Status util::JsonStringToMessage(
StringPiece input,
Message * message,
const JsonParseOptions & options)Converts from JSON to protobuf message.
This is a simple wrapper of JsonStringToBinary(). It will use the DescriptorPool of the passed-in message to resolve Any types.
-util::Status util::BinaryToJsonStream(
TypeResolver * resolver,
const std::string & type_url,
io::ZeroCopyInputStream * binary_input,
io::ZeroCopyOutputStream * json_output,
const JsonPrintOptions & options)Converts protobuf binary data to JSON.
The conversion will fail if:
- -1. TypeResolver fails to resolve a type. -2. input is not valid protobuf wire format, or conflicts with the type - information returned by TypeResolver.- -
Note that unknown fields will be discarded silently.
-util::Status util::JsonToBinaryStream(
TypeResolver * resolver,
const std::string & type_url,
io::ZeroCopyInputStream * json_input,
io::ZeroCopyOutputStream * binary_output,
const JsonParseOptions & options)Converts JSON data to protobuf binary format.
The conversion will fail if:
- -1. TypeResolver fails to resolve a type. -2. input is not valid JSON format, or conflicts with the type - information returned by TypeResolver.- -
#include <google/protobuf/util/json_util.h>
namespace google::protobuf::util
Members | |
|---|---|
bool | ignore_unknown_fieldsWhether to ignore unknown JSON fields during parsing. |
bool | case_insensitive_enum_parsingIf true, when a lowercase enum value fails to parse, try convert it to UPPER_CASE and see if it matches a valid enum. more... |
| JsonParseOptions() |
bool JsonParseOptions::case_insensitive_enum_parsingIf true, when a lowercase enum value fails to parse, try convert it to UPPER_CASE and see if it matches a valid enum.
WARNING: This option exists only to preserve legacy behavior. Avoid using this option. If your enum needs to support different casing, consider using allow_alias instead.
-#include <google/protobuf/util/json_util.h>
namespace google::protobuf::util
Members | |
|---|---|
bool | add_whitespaceWhether to add spaces, line breaks and indentation to make the JSON output easy to read. |
bool | always_print_primitive_fieldsWhether to always print primitive fields. more... |
bool | always_print_enums_as_intsWhether to always print enums as ints. more... |
bool | preserve_proto_field_namesWhether to preserve proto field names. |
| JsonPrintOptions() |
bool JsonPrintOptions::always_print_primitive_fieldsWhether to always print primitive fields.
By default proto3 primitive fields with default values will be omitted in JSON output. For example, an int32 field set to 0 will be omitted. Set this flag to true will override the default behavior and print primitive fields regardless of their values.
-bool JsonPrintOptions::always_print_enums_as_intsWhether to always print enums as ints.
By default they are rendered as strings.
-#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
This file defines static methods and classes for comparing Protocol Messages.
Aug. 2008: Added Unknown Fields Comparison for messages. Aug. 2009: Added different options to compare repeated fields. Apr. 2010: Moved field comparison to FieldComparator Sep. 2020: Added option to output map keys in path
- -Classes in this file | |
|---|---|
A basic differencer that can be used to determine the differences between two specified Protocol Messages. | |
Abstract base class from which all IgnoreCriteria derive. | |
MapKeyComparator is used to determine if two elements have the same key when comparing elements of a repeated field as a map. | |
Abstract base class from which all MessageDifferencer reporters derive. | |
Identifies an individual field in a message instance. | |
An implementation of the MessageDifferencer Reporter that outputs any differences found in human-readable form to the supplied ZeroCopyOutputStream or Printer. | |
Class for processing Any deserialization. | |
This class provides extra information to the FieldComparator::Compare function. | |
File MembersThese definitions are not part of any class. | |
|---|---|
typedef | std::vector< const FieldDescriptor * > FieldDescriptorArrayDefines a collection of field descriptors. more... |
typedef util::FieldDescriptorArrayDefines a collection of field descriptors.
In case of internal google codebase we are using absl::FixedArray instead of vector. It significantly speeds up proto comparison (by ~30%) by reducing the number of malloc/free operations
-#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
A basic differencer that can be used to determine the differences between two specified Protocol Messages.
If any differences are found, the Compare method will return false, and any differencer reporter specified via ReportDifferencesTo will have its reporting methods called (see below for implementation of the report). Based off of the original ProtocolDifferencer implementation in //net/proto/protocol-differencer.h (Thanks Todd!).
-MessageDifferencer REQUIRES that compared messages be the same type, defined as messages that share the same descriptor. If not, the behavior of this class is undefined.
-People disagree on what MessageDifferencer should do when asked to compare messages with different descriptors. Some people think it should always return false. Others expect it to try to look for similar fields and compare them anyway – especially if the descriptors happen to be identical. If we chose either of these behaviors, some set of people would find it surprising, and could end up writing code expecting the other behavior without realizing their error. Therefore, we forbid that usage.
-This class is implemented based on the proto2 reflection. The performance should be good enough for normal usages. However, for places where the performance is extremely sensitive, there are several alternatives:
-Note on handling of google.protobuf.Any: MessageDifferencer automatically unpacks Any::value into a Message and compares its individual fields. Messages encoded in a repeated Any cannot be compared using TreatAsMap.
-Note on thread-safety: MessageDifferencer is not thread-safe. You need to guard it with a lock to use the same MessageDifferencer instance from multiple threads. Note that it's fine to call static comparison methods (like MessageDifferencer::Equals) concurrently, but it's not recommended for performance critical code as it leads to extra allocations.
-Members | |
|---|---|
enum | MessageFieldComparison |
enum | Scope |
enum | FloatComparisonDEPRECATED. Use FieldComparator::FloatComparison instead. more... |
enum | RepeatedFieldComparison |
DefaultFieldComparator * | default_impl |
FieldComparator * | base |
static bool | Determines whether the supplied messages are equal. more... |
static bool | Determines whether the supplied messages are equivalent. more... |
static bool | Determines whether the supplied messages are approximately equal. more... |
static bool | Determines whether the supplied messages are approximately equivalent. more... |
explicit | MessageDifferencer()To add a Reporter, construct default here, then use ReportDifferencesTo or ReportDifferencesToString. |
| ~MessageDifferencer() |
void | TreatAsSet(const FieldDescriptor * field)The elements of the given repeated field will be treated as a set for diffing purposes, so different orderings of the same elements will be considered equal. more... |
void | TreatAsSmartSet(const FieldDescriptor * field) |
void | TreatAsList(const FieldDescriptor * field)The elements of the given repeated field will be treated as a list for diffing purposes, so different orderings of the same elements will NOT be considered equal. more... |
void | TreatAsSmartList(const FieldDescriptor * field)Note that the complexity is similar to treating as SET. |
void | TreatAsMap(const FieldDescriptor * field, const FieldDescriptor * key)The elements of the given repeated field will be treated as a map for diffing purposes, with |key| being the map key. more... |
void | TreatAsMapWithMultipleFieldsAsKey(const FieldDescriptor * field, const std::vector< const FieldDescriptor * > & key_fields)Same as TreatAsMap except that this method will use multiple fields as the key in comparison. more... |
void | TreatAsMapWithMultipleFieldPathsAsKey(const FieldDescriptor * field, const std::vector< std::vector< const FieldDescriptor * > > & key_field_paths)Same as TreatAsMapWithMultipleFieldsAsKey, except that each of the field do not necessarily need to be a direct subfield. more... |
void | TreatAsMapUsingKeyComparator(const FieldDescriptor * field, const MapKeyComparator * key_comparator)Uses a custom MapKeyComparator to determine if two elements have the same key when comparing a repeated field as a map. more... |
MapKeyComparator * | CreateMultipleFieldsMapKeyComparator(const std::vector< std::vector< const FieldDescriptor * > > & key_field_paths)Initiates and returns a new instance of MultipleFieldsMapKeyComparator. |
void | AddIgnoreCriteria(IgnoreCriteria * ignore_criteria)Add a custom ignore criteria that is evaluated in addition to the ignored fields added with IgnoreField. more... |
void | IgnoreField(const FieldDescriptor * field)Indicates that any field with the given descriptor should be ignored for the purposes of comparing two messages. more... |
void | set_field_comparator(FieldComparator * comparator)Sets the field comparator used to determine differences between protocol buffer fields. more... |
void | SetFractionAndMargin(const FieldDescriptor * field, double fraction, double margin)DEPRECATED. more... |
void | set_message_field_comparison(MessageFieldComparison comparison)Sets the type of comparison (as defined in the MessageFieldComparison enumeration above) that is used by this differencer when determining how to compare fields in messages. |
void | set_report_matches(bool report_matches)Tells the differencer whether or not to report matches. more... |
void | set_report_moves(bool report_moves)Tells the differencer whether or not to report moves (in a set or map repeated field). more... |
void | set_report_ignores(bool report_ignores)Tells the differencer whether or not to report ignored values. more... |
void | set_scope(Scope scope)Sets the scope of the comparison (as defined in the Scope enumeration above) that is used by this differencer when determining which fields to compare between the messages. |
Scope | scope()Returns the current scope used by this differencer. |
void | set_float_comparison(FloatComparison comparison)DEPRECATED. more... |
void | set_repeated_field_comparison(RepeatedFieldComparison comparison)Sets the type of comparison for repeated field (as defined in the RepeatedFieldComparison enumeration above) that is used by this differencer when compare repeated fields in messages. |
RepeatedFieldComparison | repeated_field_comparison()Returns the current repeated field comparison used by this differencer. |
bool | Compares the two specified messages, returning true if they are the same, false otherwise. more... |
bool | CompareWithFields(const Message & message1, const Message & message2, const std::vector< const FieldDescriptor * > & message1_fields, const std::vector< const FieldDescriptor * > & message2_fields)Same as above, except comparing only the list of fields specified by the two vectors of FieldDescriptors. |
void | ReportDifferencesToString(std::string * output)Automatically creates a reporter that will output the differences found (if any) to the specified output string pointer. more... |
void | ReportDifferencesTo(Reporter * reporter)Tells the MessageDifferencer to report differences via the specified reporter. more... |
enum MessageDifferencer::MessageFieldComparison {
EQUAL,
EQUIVALENT
}| EQUAL | Fields must be present in both messages for the messages to be considered the same. |
| EQUIVALENT | Fields with default values are considered set for comparison purposes even if not explicitly set in the messages themselves. Unknown fields are ignored. - |
enum MessageDifferencer::Scope {
FULL,
PARTIAL
}| FULL | All fields of both messages are considered in the comparison. |
| PARTIAL | Only fields present in the first message are considered; fields set only in the second message will be skipped during comparison. |
enum MessageDifferencer::FloatComparison {
EXACT,
APPROXIMATE
}DEPRECATED. Use FieldComparator::FloatComparison instead.
| EXACT | Floats and doubles are compared exactly. |
| APPROXIMATE | Floats and doubles are compared using the MathUtil::AlmostEquals method. |
enum MessageDifferencer::RepeatedFieldComparison {
AS_LIST,
AS_SET,
AS_SMART_LIST,
AS_SMART_SET
}| AS_LIST | Repeated fields are compared in order. Differing values at the same index are reported using ReportModified(). If the repeated fields have different numbers of elements, the unpaired elements are reported using ReportAdded() or ReportDeleted(). - |
| AS_SET | Treat all the repeated fields as sets. See TreatAsSet(), as below. - |
| AS_SMART_LIST | Similar to AS_SET, but preserve the order and find the longest matching sequence from the first matching element. To use an optimal solution, call SetMatchIndicesForSmartListCallback() to pass it in. - |
| AS_SMART_SET | Similar to AS_SET, but match elements with fewest diffs. |
static bool MessageDifferencer::Equals(
const Message & message1,
const Message & message2)Determines whether the supplied messages are equal.
Equality is defined as all fields within the two messages being set to the same value. Primitive fields and strings are compared by value while embedded messages/groups are compared as if via a recursive call. Use Compare() with IgnoreField() if some fields should be ignored in the comparison. Use Compare() with TreatAsSet() if there are repeated fields where ordering does not matter.
-This method REQUIRES that the two messages have the same Descriptor (message1.GetDescriptor() == message2.GetDescriptor()).
-static bool MessageDifferencer::Equivalent(
const Message & message1,
const Message & message2)Determines whether the supplied messages are equivalent.
Equivalency is defined as all fields within the two messages having the same value. This differs from the Equals method above in that fields with default values are considered set to said value automatically. For details on how default values are defined for each field type, see: Determines whether the supplied messages are approximately equal. Approximate equality is defined as all fields within the two messages being approximately equal. Primitive (non-float) fields and strings are compared by value, floats are compared using MathUtil::AlmostEquals() and embedded messages/groups are compared as if via a recursive call. Use IgnoreField() and Compare() if some fields should be ignored in the comparison. This method REQUIRES that the two messages have the same Descriptor (message1.GetDescriptor() == message2.GetDescriptor()). Determines whether the supplied messages are approximately equivalent. Approximate equivalency is defined as all fields within the two messages being approximately equivalent. As in MessageDifferencer::ApproximatelyEquals, primitive (non-float) fields and strings are compared by value, floats are compared using MathUtil::AlmostEquals() and embedded messages/groups are compared as if via a recursive call. However, fields with default values are considered set to said value, as per MessageDiffencer::Equivalent. Use IgnoreField() and Compare() if some fields should be ignored in the comparison. This method REQUIRES that the two messages have the same Descriptor (message1.GetDescriptor() == message2.GetDescriptor()). The elements of the given repeated field will be treated as a set for diffing purposes, so different orderings of the same elements will be considered equal. Elements which are present on both sides of the comparison but which have changed position will be reported with ReportMoved(). Elements which only exist on one side or the other are reported with ReportAdded() and ReportDeleted() regardless of their positions. ReportModified() is never used for this repeated field. If the only differences between the compared messages is that some fields have been moved, then the comparison returns true. Note that despite the name of this method, this is really comparison as multisets: if one side of the comparison has a duplicate in the repeated field but the other side doesn't, this will count as a mismatch. If the scope of comparison is set to PARTIAL, then in addition to what's above, extra values added to repeated fields of the second message will not cause the comparison to fail. Note that set comparison is currently O(k * n^2) (where n is the total number of elements, and k is the average size of each element). In theory it could be made O(n * k) with a more complex hashing implementation. Feel free to contribute one if the current implementation is too slow for you. If partial matching is also enabled, the time complexity will be O(k * n^2 REQUIRES: field->is_repeated() and field not registered with TreatAsMap* The elements of the given repeated field will be treated as a list for diffing purposes, so different orderings of the same elements will NOT be considered equal. REQUIRES: field->is_repeated() and field not registered with TreatAsMap* The elements of the given repeated field will be treated as a map for diffing purposes, with |key| being the map key. Thus, elements with the same key will be compared even if they do not appear at the same index. Differences are reported similarly to TreatAsSet(), except that ReportModified() is used to report elements with the same key but different values. Note that if an element is both moved and modified, only ReportModified() will be called. As with TreatAsSet, if the only differences between the compared messages is that some fields have been moved, then the comparison returns true. See TreatAsSet for notes on performance. REQUIRES: field->is_repeated() REQUIRES: field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE REQUIRES: key->containing_type() == field->message_type() Same as TreatAsMap except that this method will use multiple fields as the key in comparison. All specified fields in 'key_fields' should be present in the compared elements. Two elements will be treated as having the same key iff they have the same value for every specified field. There are two steps in the comparison process. The first one is key matching. Every element from one message will be compared to every element from the other message. Only fields in 'key_fields' are compared in this step to decide if two elements have the same key. The second step is value comparison. Those pairs of elements with the same key (with equal value for every field in 'key_fields') will be compared in this step. Time complexity of the first step is O(s * m * n ^ 2) where s is the average size of the fields specified in 'key_fields', m is the number of fields in 'key_fields' and n is the number of elements. If partial matching is enabled, an extra O(n^3) will be incured by the maximum matching algorithm. The second step is O(k * n) where k is the average size of each element. Same as TreatAsMapWithMultipleFieldsAsKey, except that each of the field do not necessarily need to be a direct subfield. Each element in key_field_paths indicate a path from the message being compared, listing successive subfield to reach the key field. REQUIRES: Uses a custom MapKeyComparator to determine if two elements have the same key when comparing a repeated field as a map. The caller is responsible to delete the key_comparator. This method varies from TreatAsMapWithMultipleFieldsAsKey only in the first key matching step. Rather than comparing some specified fields, it will invoke the IsMatch method of the given 'key_comparator' to decide if two elements have the same key. Add a custom ignore criteria that is evaluated in addition to the ignored fields added with IgnoreField. Takes ownership of ignore_criteria. Indicates that any field with the given descriptor should be ignored for the purposes of comparing two messages. This applies to fields nested in the message structure as well as top level ones. When the MessageDifferencer encounters an ignored field, ReportIgnored is called on the reporter, if one is specified. The only place where the field's 'ignored' status is not applied is when it is being used as a key in a field passed to TreatAsMap or is one of the fields passed to TreatAsMapWithMultipleFieldsAsKey. In this case it is compared in key matching but after that it's ignored in value comparison. Sets the field comparator used to determine differences between protocol buffer fields. By default it's set to a DefaultFieldComparator instance. MessageDifferencer doesn't take ownership over the passed object. Note that this method must be called before Compare for the comparator to be used. DEPRECATED. Pass a DefaultFieldComparator instance instead. Sets the fraction and margin for the float comparison of a given field. Uses MathUtil::WithinFractionOrMargin to compare the values. NOTE: this method does nothing if differencer's field comparator has been REQUIRES: field->cpp_type == FieldDescriptor::CPPTYPE_DOUBLE or REQUIRES: float_comparison_ == APPROXIMATE Tells the differencer whether or not to report matches. This method must be called before Compare. The default for a new differencer is false. Tells the differencer whether or not to report moves (in a set or map repeated field). This method must be called before Compare. The default for a new differencer is true. Tells the differencer whether or not to report ignored values. This method must be called before Compare. The default for a new differencer is true. DEPRECATED. Pass a DefaultFieldComparator instance instead. Sets the type of comparison (as defined in the FloatComparison enumeration above) that is used by this differencer when comparing float (and double) fields in messages. NOTE: this method does nothing if differencer's field comparator has been Compares the two specified messages, returning true if they are the same, false otherwise. If this method returns false, any changes between the two messages will be reported if a Reporter was specified via ReportDifferencesTo (see also ReportDifferencesToString). This method REQUIRES that the two messages have the same Descriptor (message1.GetDescriptor() == message2.GetDescriptor()). Automatically creates a reporter that will output the differences found (if any) to the specified output string pointer. Note that this method must be called before Compare. Tells the MessageDifferencer to report differences via the specified reporter. Note that this method must be called before Compare for the reporter to be used. It is the responsibility of the caller to delete this object. If the provided pointer equals NULL, the MessageDifferencer stops reporting differences to any previously set reporters or output strings. Abstract base class from which all IgnoreCriteria derive. By adding IgnoreCriteria more complex ignore logic can be implemented. IgnoreCriteria are registered with AddIgnoreCriteria. For each compared field IsIgnored is called on each added IgnoreCriteria until one returns true or all return false. IsIgnored is called for fields where at least one side has a value. static bool MessageDifferencer::ApproximatelyEquals(
const Message & message1,
const Message & message2)static bool MessageDifferencer::ApproximatelyEquivalent(
const Message & message1,
const Message & message2)void MessageDifferencer::TreatAsSet(
const FieldDescriptor * field)
-
-void MessageDifferencer::TreatAsList(
const FieldDescriptor * field)void MessageDifferencer::TreatAsMap(
const FieldDescriptor * field,
const FieldDescriptor * key)void MessageDifferencer::TreatAsMapWithMultipleFieldsAsKey(
const FieldDescriptor * field,
const std::vector< const FieldDescriptor * > & key_fields)void MessageDifferencer::TreatAsMapWithMultipleFieldPathsAsKey(
const FieldDescriptor * field,
const std::vector< std::vector< const FieldDescriptor * > > & key_field_paths)for key_field_path in key_field_paths:
- key_field_path[0]->containing_type() == field->message_type()
- for i in [0, key_field_path.size() - 1):
- key_field_path[i+1]->containing_type() ==
- key_field_path[i]->message_type()
- key_field_path[i]->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE
- !key_field_path[i]->is_repeated()
-void MessageDifferencer::TreatAsMapUsingKeyComparator(
const FieldDescriptor * field,
const MapKeyComparator * key_comparator)void MessageDifferencer::AddIgnoreCriteria(
IgnoreCriteria * ignore_criteria)void MessageDifferencer::IgnoreField(
const FieldDescriptor * field)void MessageDifferencer::set_field_comparator(
FieldComparator * comparator)void MessageDifferencer::SetFractionAndMargin(
const FieldDescriptor * field,
double fraction,
double margin)set to a custom object.
-field->cpp_type == FieldDescriptor::CPPTYPE_FLOAT
-void MessageDifferencer::set_report_matches(
bool report_matches)void MessageDifferencer::set_report_moves(
bool report_moves)void MessageDifferencer::set_report_ignores(
bool report_ignores)void MessageDifferencer::set_float_comparison(
FloatComparison comparison)set to a custom object.
-bool MessageDifferencer::Compare(
const Message & message1,
const Message & message2)void MessageDifferencer::ReportDifferencesToString(
std::string * output)void MessageDifferencer::ReportDifferencesTo(
Reporter * reporter)class MessageDifferencer::IgnoreCriteria
#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
Members | |
|---|---|
| IgnoreCriteria() |
virtual | ~IgnoreCriteria() |
virtual bool | IsIgnored(const Message & , const Message & , const FieldDescriptor * , const std::vector< SpecificField > & ) = 0Returns true if the field should be ignored. |
virtual bool | IsUnknownFieldIgnored(const Message & , const Message & , const SpecificField & , const std::vector< SpecificField > & )Returns true if the unknown field should be ignored. more... |
virtual bool IgnoreCriteria::IsUnknownFieldIgnored(
const Message & ,
const Message & ,
const SpecificField & ,
const std::vector< SpecificField > & )Returns true if the unknown field should be ignored.
Note: This will be called for unknown fields as well in which case
-field.field will be null.-
#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
MapKeyComparator is used to determine if two elements have the same key when comparing elements of a repeated field as a map.
Members | |
|---|---|
| MapKeyComparator() |
virtual | ~MapKeyComparator() |
virtual bool | IsMatch(const Message & , const Message & , const std::vector< SpecificField > & ) const |
#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
Abstract base class from which all MessageDifferencer reporters derive.
The five Report* methods below will be called when a field has been added, deleted, modified, moved, or matched. The third argument is a vector of FieldDescriptor pointers which describes the chain of fields that was taken to find the current field. For example, for a field found in an embedded message, the vector will contain two FieldDescriptors. The first will be the field of the embedded message itself and the second will be the actual field in the embedded message that was added/deleted/modified. Fields will be reported in PostTraversalOrder. For example, given the following proto, if both baz and mooo are changed. -
foo {
- bar {
- baz: 1
- mooo: 2
- }
-}
-ReportModified will be invoked with following order:
-Known subclasses:
Members | |
|---|---|
| Reporter() |
virtual | ~Reporter() |
virtual void | ReportAdded(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path) = 0Reports that a field has been added into Message2. |
virtual void | ReportDeleted(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path) = 0Reports that a field has been deleted from Message1. |
virtual void | ReportModified(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path) = 0Reports that the value of a field has been modified. |
virtual void | ReportMoved(const Message & , const Message & , const std::vector< SpecificField > & )Reports that a repeated field has been moved to another location. more... |
virtual void | ReportMatched(const Message & , const Message & , const std::vector< SpecificField > & )Reports that two fields match. more... |
virtual void | ReportIgnored(const Message & , const Message & , const std::vector< SpecificField > & )Reports that two fields would have been compared, but the comparison has been skipped because the field was marked as 'ignored' using IgnoreField(). more... |
virtual void | ReportUnknownFieldIgnored(const Message & , const Message & , const std::vector< SpecificField > & )Report that an unknown field is ignored. more... |
virtual void Reporter::ReportMoved(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that a repeated field has been moved to another location.
This only applies when using TreatAsSet or TreatAsMap() – see below. Also note that for any given field, ReportModified and ReportMoved are mutually exclusive. If a field has been both moved and modified, then only ReportModified will be called.
-virtual void Reporter::ReportMatched(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that two fields match.
Useful for doing side-by-side diffs. This function is mutually exclusive with ReportModified and ReportMoved. Note that you must call set_report_matches(true) before calling Compare to make use of this function.
-virtual void Reporter::ReportIgnored(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that two fields would have been compared, but the comparison has been skipped because the field was marked as 'ignored' using IgnoreField().
This function is mutually exclusive with all the other Report() functions.
-The contract of ReportIgnored is slightly different than the other Report() functions, in that |field_path.back().index| is always equal to -1, even if the last field is repeated. This is because while the other Report() functions indicate where in a repeated field the action (Addition, Deletion, etc...) happened, when a repeated field is 'ignored', the differencer simply calls ReportIgnored on the repeated field as a whole and moves on without looking at its individual elements.
-Furthermore, ReportIgnored() does not indicate whether the fields were in fact equal or not, as Compare() does not inspect these fields at all. It is up to the Reporter to decide whether the fields are equal or not (perhaps with a second call to Compare()), if it cares.
-virtual void Reporter::ReportUnknownFieldIgnored(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Report that an unknown field is ignored.
(see comment above). Note this is a different function since the last SpecificField in field path has a null field. This could break existing Reporter.
-#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
Identifies an individual field in a message instance.
Used for field_path, below.
-Members | |
|---|---|
const FieldDescriptor * | field = = nullptrFor known fields, "field" is filled in and "unknown_field_number" is -1. more... |
int | unknown_field_number = = -1 |
UnknownField::Type | unknown_field_type = = UnknownField::Type::TYPE_VARINT |
int | index = = -1If this a repeated field, "index" is the index within it. more... |
int | new_index = = -1If "field" is a repeated field which is being treated as a map or a set (see TreatAsMap() and TreatAsSet(), below), new_index indicates the index the position to which the element has moved. more... |
const UnknownFieldSet * | unknown_field_set1 = = nullptrFor unknown fields, these are the pointers to the UnknownFieldSet containing the unknown fields. more... |
const UnknownFieldSet * | unknown_field_set2 = = nullptr |
int | unknown_field_index1 = = -1For unknown fields, these are the index of the field within the UnknownFieldSets. more... |
int | unknown_field_index2 = = -1 |
const FieldDescriptor * SpecificField::field = = nullptrFor known fields, "field" is filled in and "unknown_field_number" is -1.
For unknown fields, "field" is NULL, "unknown_field_number" is the field number, and "unknown_field_type" is its type.
-int SpecificField::index = = -1If this a repeated field, "index" is the index within it.
For unknown fields, this is the index of the field among all unknown fields of the same field number and type.
-int SpecificField::new_index = = -1If "field" is a repeated field which is being treated as a map or a set (see TreatAsMap() and TreatAsSet(), below), new_index indicates the index the position to which the element has moved.
If the element has not moved, "new_index" will have the same value as "index".
-const UnknownFieldSet * SpecificField::unknown_field_set1 = = nullptrFor unknown fields, these are the pointers to the UnknownFieldSet containing the unknown fields.
In certain cases (e.g. proto1's MessageSet, or nested groups of unknown fields), these may differ from the messages' internal UnknownFieldSets.
-int SpecificField::unknown_field_index1 = = -1For unknown fields, these are the index of the field within the UnknownFieldSets.
One or the other will be -1 when reporting an addition or deletion.
-#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
An implementation of the MessageDifferencer Reporter that outputs any differences found in human-readable form to the supplied ZeroCopyOutputStream or Printer.
If a printer is used, the delimiter must be '$'.
-WARNING: this reporter does not necessarily flush its output until it is destroyed. As a result, it is not safe to assume the output is valid or complete until after you destroy the reporter. For example, if you use a StreamReporter to write to a StringOutputStream, the target string may contain uninitialized data until the reporter is destroyed.
-Members | |
|---|---|
explicit | StreamReporter(io::ZeroCopyOutputStream * output) |
explicit | StreamReporter(io::Printer * printer)delimiter '$' |
| ~StreamReporter() |
void | set_report_modified_aggregates(bool report)When set to true, the stream reporter will also output aggregates nodes (i.e. more... |
virtual void | ReportAdded(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path)Reports that a field has been added into Message2. |
virtual void | ReportDeleted(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path)Reports that a field has been deleted from Message1. |
virtual void | ReportModified(const Message & message1, const Message & message2, const std::vector< SpecificField > & field_path)Reports that the value of a field has been modified. |
virtual void | ReportMoved(const Message & , const Message & , const std::vector< SpecificField > & )Reports that a repeated field has been moved to another location. more... |
virtual void | ReportMatched(const Message & , const Message & , const std::vector< SpecificField > & )Reports that two fields match. more... |
virtual void | ReportIgnored(const Message & , const Message & , const std::vector< SpecificField > & )Reports that two fields would have been compared, but the comparison has been skipped because the field was marked as 'ignored' using IgnoreField(). more... |
virtual void | ReportUnknownFieldIgnored(const Message & , const Message & , const std::vector< SpecificField > & )Report that an unknown field is ignored. more... |
void | Messages that are being compared must be provided to StreamReporter prior to processing. |
protected virtual void | PrintPath(const std::vector< SpecificField > & field_path, bool left_side)Prints the specified path of fields to the buffer. |
protected virtual void | PrintValue(const Message & message, const std::vector< SpecificField > & field_path, bool left_side)Prints the value of fields to the buffer. more... |
protected virtual void | PrintUnknownFieldValue(const UnknownField * unknown_field)Prints the specified path of unknown fields to the buffer. |
protected void | Print(const std::string & str)Just print a string. |
protected void | PrintMapKey(const std::vector< SpecificField > & field_path, bool left_side, const SpecificField & specific_field, size_t target_field_index)helper function for PrintPath that contains logic for printing maps |
void StreamReporter::set_report_modified_aggregates(
bool report)When set to true, the stream reporter will also output aggregates nodes (i.e.
messages and groups) whose subfields have been modified. When false, will only report the individual subfields. Defaults to false.
-virtual void StreamReporter::ReportMoved(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that a repeated field has been moved to another location.
This only applies when using TreatAsSet or TreatAsMap() – see below. Also note that for any given field, ReportModified and ReportMoved are mutually exclusive. If a field has been both moved and modified, then only ReportModified will be called.
-virtual void StreamReporter::ReportMatched(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that two fields match.
Useful for doing side-by-side diffs. This function is mutually exclusive with ReportModified and ReportMoved. Note that you must call set_report_matches(true) before calling Compare to make use of this function.
-virtual void StreamReporter::ReportIgnored(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Reports that two fields would have been compared, but the comparison has been skipped because the field was marked as 'ignored' using IgnoreField().
This function is mutually exclusive with all the other Report() functions.
-The contract of ReportIgnored is slightly different than the other Report() functions, in that |field_path.back().index| is always equal to -1, even if the last field is repeated. This is because while the other Report() functions indicate where in a repeated field the action (Addition, Deletion, etc...) happened, when a repeated field is 'ignored', the differencer simply calls ReportIgnored on the repeated field as a whole and moves on without looking at its individual elements.
-Furthermore, ReportIgnored() does not indicate whether the fields were in fact equal or not, as Compare() does not inspect these fields at all. It is up to the Reporter to decide whether the fields are equal or not (perhaps with a second call to Compare()), if it cares.
-virtual void StreamReporter::ReportUnknownFieldIgnored(
const Message & ,
const Message & ,
const std::vector< SpecificField > & )Report that an unknown field is ignored.
(see comment above). Note this is a different function since the last SpecificField in field path has a null field. This could break existing Reporter.
-protected virtual void StreamReporter::PrintValue(
const Message & message,
const std::vector< SpecificField > & field_path,
bool left_side)Prints the value of fields to the buffer.
left_side is true if the given message is from the left side of the comparison, false if it was the right. This is relevant only to decide whether to follow unknown_field_index1 or unknown_field_index2 when an unknown field is encountered in field_path.
-#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
Class for processing Any deserialization.
This logic is used by both the MessageDifferencer and StreamReporter classes.
-Members | |
|---|---|
| UnpackAnyField() |
| ~UnpackAnyField() |
bool | If "any" is of type google.protobuf.Any, extract its payload using DynamicMessageFactory and store in "data". |
#include <google/protobuf/util/message_differencer.h>
namespace google::protobuf::util
This class provides extra information to the FieldComparator::Compare function.
Members | |
|---|---|
explicit | FieldContext(std::vector< MessageDifferencer::SpecificField > * parent_fields) |
std::vector< MessageDifferencer::SpecificField > * | parent_fields() const |
#include <google/protobuf/util/time_util.h>
namespace google::protobuf::util
Defines utilities for the Timestamp and Duration well known types.
Classes in this file | |
|---|---|
Utility functions for Timestamp and Duration. | |
#include <google/protobuf/util/time_util.h>
namespace google::protobuf::util
Utility functions for Timestamp and Duration.
Members | |
|---|---|
const int64_t | kTimestampMinSeconds = = -62135596800LLThe min/max Timestamp/Duration values we support. more... |
const int64_t | kTimestampMaxSeconds = = 253402300799LLFor "9999-12-31T23:59:59.999999999Z". |
const int64_t | kDurationMinSeconds = = -315576000000LL |
const int64_t | kDurationMaxSeconds = = 315576000000LL |
static std::string | ToString(const Timestamp & timestamp)Converts Timestamp to/from RFC 3339 date string format. more... |
static bool | FromString(const std::string & value, Timestamp * timestamp) |
static std::string | ToString(const Duration & duration)Converts Duration to/from string format. more... |
static bool | FromString(const std::string & value, Duration * timestamp) |
static Timestamp | GetCurrentTime()Gets the current UTC time. |
static Timestamp | GetEpoch()Returns the Time representing "1970-01-01 00:00:00". |
static Duration | NanosecondsToDuration(int64_t nanos)Converts between Duration and integer types. more... |
static Duration | MicrosecondsToDuration(int64_t micros) |
static Duration | MillisecondsToDuration(int64_t millis) |
static Duration | SecondsToDuration(int64_t seconds) |
static Duration | MinutesToDuration(int64_t minutes) |
static Duration | HoursToDuration(int64_t hours) |
static int64_t | DurationToNanoseconds(const Duration & duration)Result will be truncated towards zero. more... |
static int64_t | DurationToMicroseconds(const Duration & duration) |
static int64_t | DurationToMilliseconds(const Duration & duration) |
static int64_t | DurationToSeconds(const Duration & duration) |
static int64_t | DurationToMinutes(const Duration & duration) |
static int64_t | DurationToHours(const Duration & duration) |
static Timestamp | NanosecondsToTimestamp(int64_t nanos)Creates Timestamp from integer types. more... |
static Timestamp | MicrosecondsToTimestamp(int64_t micros) |
static Timestamp | MillisecondsToTimestamp(int64_t millis) |
static Timestamp | SecondsToTimestamp(int64_t seconds) |
static int64_t | TimestampToNanoseconds(const Timestamp & timestamp)Result will be truncated down to the nearest integer value. more... |
static int64_t | TimestampToMicroseconds(const Timestamp & timestamp) |
static int64_t | TimestampToMilliseconds(const Timestamp & timestamp) |
static int64_t | TimestampToSeconds(const Timestamp & timestamp) |
static Timestamp | TimeTToTimestamp(time_t value)Conversion to/from other time/date types. more... |
static time_t | TimestampToTimeT(const Timestamp & value) |
static Timestamp | TimevalToTimestamp(const timeval & value)Conversion to/from timeval. |
static timeval | TimestampToTimeval(const Timestamp & value) |
static Duration | TimevalToDuration(const timeval & value) |
static timeval | DurationToTimeval(const Duration & value) |
const int64_t TimeUtil::kTimestampMinSeconds = = -62135596800LLThe min/max Timestamp/Duration values we support.
For "0001-01-01T00:00:00Z".
-static std::string TimeUtil::ToString(
const Timestamp & timestamp)Converts Timestamp to/from RFC 3339 date string format.
Generated output will always be Z-normalized and uses 3, 6 or 9 fractional digits as required to represent the exact time. When parsing, any fractional digits (or none) and any offset are accepted as long as they fit into nano-seconds precision. Note that Timestamp can only represent time from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. Converting a Timestamp outside of this range is undefined behavior. See https://www.ietf.org/rfc/rfc3339.txt.
- -Example of generated format:
- -"1972-01-01T10:00:20.021Z"- -
Example of accepted format:
- -"1972-01-01T10:00:20.021-05:00"-
static std::string TimeUtil::ToString(
const Duration & duration)Converts Duration to/from string format.
The string format will contains 3, 6, or 9 fractional digits depending on the precision required to represent the exact Duration value. For example:
-"1s", "1.010s", "1.000000100s", "-3.100s"- -
The range that can be represented by Duration is from -315,576,000,000 to +315,576,000,000 inclusive (in seconds).
-static Duration TimeUtil::NanosecondsToDuration(
int64_t nanos)Converts between Duration and integer types.
The behavior is undefined if the input value is not in the valid range of Duration.
-static int64_t TimeUtil::DurationToNanoseconds(
const Duration & duration)Result will be truncated towards zero.
For example, "-1.5s" will be truncated to "-1s", and "1.5s" to "1s" when converting to seconds. It's undefined behavior if the input duration is not valid or the result exceeds the range of int64. A duration is not valid if it's not in the valid range of Duration, or have an invalid nanos value (i.e., larger than 999999999, less than -999999999, or have a different sign from the seconds part).
-static Timestamp TimeUtil::NanosecondsToTimestamp(
int64_t nanos)Creates Timestamp from integer types.
The integer value indicates the time elapsed from Epoch time. The behavior is undefined if the input value is not in the valid range of Timestamp.
-static int64_t TimeUtil::TimestampToNanoseconds(
const Timestamp & timestamp)Result will be truncated down to the nearest integer value.
For example, with "1969-12-31T23:59:59.9Z", TimestampToMilliseconds() returns -100 and TimestampToSeconds() returns -1. It's undefined behavior if the input Timestamp is not valid (i.e., its seconds part or nanos part does not fall in the valid range) or the return value doesn't fit into int64.
-static Timestamp TimeUtil::TimeTToTimestamp(
time_t value)Conversion to/from other time/date types.
Note that these types may have a different precision and time range from Timestamp/Duration. When converting to a lower precision type, the value will be truncated to the nearest value that can be represented. If the value is out of the range of the result type, the return value is undefined.
- -Conversion to/from time_t
- -#include <google/protobuf/util/type_resolver.h>
namespace google::protobuf::util
Defines a TypeResolver for the Any message.
Classes in this file | |
|---|---|
Abstract interface for a type resolver. | |
#include <google/protobuf/util/type_resolver.h>
namespace google::protobuf::util
Abstract interface for a type resolver.
Implementations of this interface must be thread-safe.
- -Members | |
|---|---|
| TypeResolver() |
virtual | ~TypeResolver() |
virtual util::Status | ResolveMessageType(const std::string & type_url, google::protobuf::Type * message_type) = 0Resolves a type url for a message type. |
virtual util::Status | ResolveEnumType(const std::string & type_url, google::protobuf::Enum * enum_type) = 0Resolves a type url for an enum type. |
#include <google/protobuf/util/type_resolver_util.h>
namespace google::protobuf::util
Defines utilities for the TypeResolver.
Classes in this file |
|---|
File MembersThese definitions are not part of any class. | |
|---|---|
TypeResolver * | NewTypeResolverForDescriptorPool(const std::string & url_prefix, const DescriptorPool * pool)Creates a TypeResolver that serves type information in the given descriptor pool. more... |
TypeResolver * util::NewTypeResolverForDescriptorPool(
const std::string & url_prefix,
const DescriptorPool * pool)Creates a TypeResolver that serves type information in the given descriptor pool.
Caller takes ownership of the returned TypeResolver.
- -| Open Struct API (old) | -Opaque API (new) | -
| - -```go -m := &pb.Foo{ - Uint32: proto.Uint32(5), - Bytes: []byte("hello"), -} -``` - - | -- -```go -m := pb.Foo_builder{ - Uint32: proto.Uint32(5), - Bytes: []byte("hello"), -}.Build() -``` - - | -
| Open Struct API (old) | -Opaque API (new) | -
| - -```go -m := &pb.Foo{ - Uint32: myScalar, // could be nil - Union: &pb.Foo_String{myString}, - Kind: pb.Foo_SPECIAL_KIND.Enum(), -} -``` - - | -- -```go -m := pb.Foo_builder{ - Uint32: myScalar, - String: myString, - Kind: pb.Foo_SPECIAL_KIND.Enum(), -}.Build() -``` - - | -
| Open Struct API (old) | -Opaque API (new) | -
| - -```go -// Getting the value. -s := m.GetBirthYear() - -// Setting the field. -m.BirthYear = proto.Int32(1989) - -// Check for presence. -if s.BirthYear != nil { … } - -// Clearing the field. -m.BirthYear = nil -``` - - | -- -```go -// Getting the field value. -s := m.GetBirthYear() - -// Setting the field. -m.SetBirthYear(1989) - -// Check for presence. -if m.HasBirthYear() { … } - -// Clearing the field -m.ClearBirthYear() -``` - - | -
| Open Struct API (old) | -Opaque (new) | -
| - -```go -// Getting the value. -b := m.GetHeadliner() - -// Setting the field. -m.Headliner = &pb.Band{} - -// Check for presence. -if s.Headliner != nil { … } - -// Clearing the field. -m.Headliner = nil -``` - - | -- -```go -// Getting the value. -s := m.GetHeadliner() - -// Setting the field. -m.SetHeadliner(&pb.Band{}) - -// Check for presence. -if m.HasHeadliner() { … } - -// Clearing the field -m.ClearHeadliner() -``` - - | -
| Open Struct API (old) | -Opaque API (new) | -
| - -```go -// Getting the entire repeated value. -v := m.GetSupportActs() - -// Setting the field. -m.SupportActs = v - -// Get an element in a repeated field. -e := m.SupportActs[i] - -// Set an element in a repeated field. -m.SupportActs[i] = e - -// Get the length of a repeated field. -n := len(m.GetSupportActs()) - -// Truncate a repeated field. -m.SupportActs = m.SupportActs[:i] - -// Append to a repeated field. -m.SupportActs = append(m.GetSupportActs(), e) -m.SupportActs = append(m.GetSupportActs(), v...) - -// Clearing the field. -m.SupportActs = nil -``` - - | -- -```go -// Getting the entire repeated value. -v := m.GetSupportActs() - -// Setting the field. -m.SetSupportActs(v) - -// Get an element in a repeated field. -e := m.GetSupportActs()[i] - -// Set an element in a repeated field. -m.GetSupportActs()[i] = e - -// Get the length of a repeated field. -n := len(m.GetSupportActs()) - -// Truncate a repeated field. -m.SetSupportActs(m.GetSupportActs()[:i]) - -// Append to a repeated field. -m.SetSupportActs(append(m.GetSupportActs(), e)) -m.SetSupportActs(append(m.GetSupportActs(), v...)) - -// Clearing the field. -m.SetSupportActs(nil) -``` - - | -
| Open Struct API (old) | -Opaque API (new) | -
| - -```go -// Getting the entire map value. -v := m.GetItems() - -// Setting the field. -m.Items = v - -// Get an element in a map field. -v := m.Items[k] - -// Set an element in a map field. -// This will panic if m.Items is nil. -// You should check m.Items for nil -// before doing the assignment to ensure -// it won't panic. -m.Items[k] = v - -// Delete an element in a map field. -delete(m.Items, k) - -// Get the size of a map field. -n := len(m.GetItems()) - -// Clearing the field. -m.Items = nil -``` - - | -- -```go -// Getting the entire map value. -v := m.GetItems() - -// Setting the field. -m.SetItems(v) - -// Get an element in a map field. -v := m.GetItems()[k] - -// Set an element in a map field. -// This will panic if m.GetItems() is nil. -// You should check m.GetItems() for nil -// before doing the assignment to ensure -// it won't panic. -m.GetItems()[k] = v - -// Delete an element in a map field. -delete(m.GetItems(), k) - -// Get the size of a map field. -n := len(m.GetItems()) - -// Clearing the field. -m.SetItems(nil) -``` - - | -
| Open Struct API (old) | -Opaque API (new) | -
| - -```go -// Getting the oneof field that is set. -switch m.GetAvatar().(type) { -case *pb.Profile_ImageUrl: - … = m.GetImageUrl() -case *pb.Profile_ImageData: - … = m.GetImageData() -} - -// Setting the fields. -m.Avatar = &pb.Profile_ImageUrl{"http://"} -m.Avatar = &pb.Profile_ImageData{img} - -// Checking whether any oneof field is set -if m.Avatar != nil { … } - -// Clearing the field. -m.Avatar = nil - -// Checking if a specific field is set. -_, ok := m.GetAvatar().(*pb.Profile_ImageUrl) -if ok { … } - -// Clearing a specific field -_, ok := m.GetAvatar().(*pb.Profile_ImageUrl) -if ok { - m.Avatar = nil -} - -// Copy a oneof field. -m.Avatar = src.Avatar -``` - - | -- -```go -// Getting the oneof field that is set. -switch m.WhichAvatar() { -case pb.Profile_ImageUrl_case: - … = m.GetImageUrl() -case pb.Profile_ImageData_case: - … = m.GetImageData() -} - -// Setting the fields. -m.SetImageUrl("http://") -m.SetImageData([]byte("…")) - -// Checking whether any oneof field is set -if m.HasAvatar() { … } - -// Clearing the field. -m.ClearAvatar() - -// Checking if a specific field is set. -if m.HasImageUrl() { … } - -// Clearing a specific field. -m.ClearImageUrl() - -// Copy a oneof field -switch src.WhichAvatar() { -case pb.Profile_ImageUrl_case: - m.SetImageUrl(src.GetImageUrl()) -case pb.Profile_ImageData_case: - m.SetImageData(src.GetImageData()) -} -``` - - | -
This class is used by Kotlin protocol buffer extensions, and its constructor
-is public only because generated message code is in a different compilation
-unit. Others should not use this class directly in any way.
-
-## Constructors
-
-Name | Summary
---- | ---
-[DslList]() | [JVM] fun <[E]()> [DslList]()(delegate: [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E]()>)
-
-## Functions
-
-Name | Summary
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------
-[contains](../-extension-list/#765883978%2FFunctions%2F-246181541) | [JVM] This class is used by Kotlin protocol buffer extensions, and its constructor
-is public only because generated message code is in a different compilation
-unit. Others should not use this class directly in any way.
-
-## Constructors
-
-Name | Summary
---- | ---
-[DslMap]) | [JVM] fun <[K](), [V]()> [DslMap]()(delegate: [Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](), [V]()>)
-
-## Functions
-
-Name | Summary
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------
-[containsKey](#189495335%2FFunctions%2F-246181541) | [JVM]
Content
open operator override fun [contains](../-extension-list/#765883978%2FFunctions%2F-246181541)(element: [E]()): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[containsAll](../-extension-list/#-225903147%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [containsAll](../-extension-list/#-225903147%2FFunctions%2F-246181541)(elements: [Collection](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-collection/index.html)<[E]()>): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[equals](equals) | [JVM]
Content
open operator override fun [equals](equals)(other: [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[forEach](../-extension-list/#1532301601%2FFunctions%2F-246181541) | [JVM]
Content
open fun [forEach](../-extension-list/#1532301601%2FFunctions%2F-246181541)(p0: [Consumer](https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html)
-[get](../-extension-list/#961975567%2FFunctions%2F-246181541) | [JVM]
Content
open operator override fun [get](../-extension-list/#961975567%2FFunctions%2F-246181541)(index: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [E]()
-[hashCode](hash-code) | [JVM]
Content
open override fun [hashCode](hash-code)(): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[indexOf](../-extension-list/#-407930336%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [indexOf](../-extension-list/#-407930336%2FFunctions%2F-246181541)(element: [E]()): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[isEmpty](../-extension-list/#-1000881820%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [isEmpty](../-extension-list/#-1000881820%2FFunctions%2F-246181541)(): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[iterator](iterator) | [JVM]
Content
open operator override fun [iterator](iterator)(): [Iterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/index.html)<[E]()>
-[lastIndexOf](../-extension-list/#1327716778%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [lastIndexOf](../-extension-list/#1327716778%2FFunctions%2F-246181541)(element: [E]()): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[listIterator](list-iterator) | [JVM]
Content
open override fun [listIterator](list-iterator)(): [ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
open override fun [listIterator](list-iterator)(index: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
-[parallelStream](../-extension-list/#-1592339412%2FFunctions%2F-246181541) | [JVM]
Content
open fun [parallelStream](../-extension-list/#-1592339412%2FFunctions%2F-246181541)(): [Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)<[E]()>
-[spliterator](../-extension-list/#703021258%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [spliterator](../-extension-list/#703021258%2FFunctions%2F-246181541)(): [Spliterator](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html)<[E]()>
-[stream](../-extension-list/#135225651%2FFunctions%2F-246181541) | [JVM]
Content
open fun [stream](../-extension-list/#135225651%2FFunctions%2F-246181541)(): [Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)<[E]()>
-[subList](../-extension-list/#423386006%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [subList](../-extension-list/#423386006%2FFunctions%2F-246181541)(fromIndex: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html), toIndex: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E]()>
-[toArray](../-extension-list/#-1215154575%2FFunctions%2F-246181541) | [JVM]
Content
~~open~~ ~~fun~~ ~~<~~[T](../-extension-list/#-1215154575%2FFunctions%2F-246181541) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)~~>~~ [~~toArray~~](../-extension-list/#-1215154575%2FFunctions%2F-246181541)~~(~~~~p0~~~~:~~ [IntFunction](https://docs.oracle.com/javase/8/docs/api/java/util/function/IntFunction.html)<[Array](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)<[T](../-extension-list/#-1215154575%2FFunctions%2F-246181541)>>~~)~~~~:~~ [Array](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)<[T](../-extension-list/#-1215154575%2FFunctions%2F-246181541)>
-[toString](to-string) | [JVM]
Content
open override fun [toString](to-string)(): [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
-
-## Properties
-
-Name | Summary
------------------------------------------------------------------------------------------------------------------------------------- | -------
-[size](#1874448885%2FProperties%2F-246181541) | [JVM] open override val [size](#1874448885%2FProperties%2F-246181541): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/equals.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/equals.md
deleted file mode 100644
index 504c09b0a..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/equals.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslList]()/equals
-
-# equals
-
-[JVM] \
-Content \
-open operator override fun [`equals`]()(other:
-[`Any`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?):
-[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/hash-code.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/hash-code.md
deleted file mode 100644
index 57dccb396..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/hash-code.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslList]()/hashCode
-
-# hashCode
-
-[JVM] \
-Content \
-open override fun [hashCode]()():
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/iterator.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/iterator.md
deleted file mode 100644
index 54ac64f90..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/iterator.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslList]()/iterator
-
-# iterator
-
-[JVM] \
-Content \
-open operator override fun [iterator]()():
-[Iterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/index.html)<[E]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/list-iterator.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/list-iterator.md
deleted file mode 100644
index f820e3664..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/list-iterator.md
+++ /dev/null
@@ -1,12 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslList]()/listIterator
-
-# listIterator
-
-[JVM] \
-Content \
-open override fun [listIterator]()():
-[ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
-\
-open override fun [listIterator]()(index:
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)):
-[ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/to-string.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/to-string.md
deleted file mode 100644
index 0bd1be208..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/to-string.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslList]()/toString
-
-# toString
-
-[JVM] \
-Content \
-open override fun [toString]()():
-[String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/-dsl-map.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/-dsl-map.md
deleted file mode 100644
index 908e39e5b..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/-dsl-map.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/DslMap
-
-# DslMap
-
-[JVM] \
-Content \
-fun <[K](), [V]()> [DslMap]()(delegate:
-[Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](),
-[V]()>)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/_index.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/_index.md
deleted file mode 100644
index 30b83d8ba..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/_index.md
+++ /dev/null
@@ -1,48 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/DslMap
-
-# DslMap
-
-[JVM] class [DslMap]()<[K](), [V](), [P]() :
-[DslProxy](../-dsl-proxy/)>constructor(**delegate**:
-[Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](),
-[V]()>) :
-[Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](),
-[V]()>
-
-A simple wrapper around a
-[Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)
-with an extra generic parameter that can be used to disambiguate extension
-methods.
-
-
Content
open override fun [containsKey](#189495335%2FFunctions%2F-246181541)(key: [K]()): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[containsValue](#-337993863%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [containsValue](#-337993863%2FFunctions%2F-246181541)(value: [V]()): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[equals](equals) | [JVM]
Content
open operator override fun [equals](equals)(other: [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[forEach](#1890068580%2FFunctions%2F-246181541) | [JVM]
Content
open fun [forEach](#1890068580%2FFunctions%2F-246181541)(p0: [BiConsumer](https://docs.oracle.com/javase/8/docs/api/java/util/function/BiConsumer.html)
-[get](#1589144509%2FFunctions%2F-246181541) | [JVM]
Content
open operator override fun [get](#1589144509%2FFunctions%2F-246181541)(key: [K]()): [V]()?
-[getOrDefault](#1493482850%2FFunctions%2F-246181541) | [JVM]
Content
open fun [getOrDefault](#1493482850%2FFunctions%2F-246181541)(key: [K](), defaultValue: [V]()): [V]()
-[hashCode](hash-code) | [JVM]
Content
open override fun [hashCode](hash-code)(): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[isEmpty](#-1708477740%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [isEmpty](#-1708477740%2FFunctions%2F-246181541)(): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[toString](to-string) | [JVM]
Content
open override fun [toString](to-string)(): [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
-
-## Properties
-
-Name | Summary
------------------------------------------------------------------------------------------------------------------------------------- | -------
-[entries](entries) | [JVM] open override val [entries](entries): [Set](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)<[Map.Entry](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/-entry/index.html)<[K](), [V]()>>
-[keys](keys) | [JVM] open override val [keys](keys): [Set](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)<[K]()>
-[size](#-2063973537%2FProperties%2F-246181541) | [JVM] open override val [size](#-2063973537%2FProperties%2F-246181541): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[values](values) | [JVM] open override val [values](values): [Collection](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-collection/index.html)<[V]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/entries.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/entries.md
deleted file mode 100644
index 9555268b0..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/entries.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/entries
-
-# entries
-
-[JVM] \
-Content \
-open override val [entries]():
-[Set](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)<[Map.Entry](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/-entry/index.html)<[K](),
-[V]()>>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/equals.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/equals.md
deleted file mode 100644
index 8023cb680..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/equals.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/equals
-
-# equals
-
-[JVM] \
-Content \
-open operator override fun [equals]()(other:
-[Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?):
-[Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/hash-code.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/hash-code.md
deleted file mode 100644
index b7dd94084..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/hash-code.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/hashCode
-
-# hashCode
-
-[JVM] \
-Content \
-open override fun [hashCode]()():
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/keys.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/keys.md
deleted file mode 100644
index be30a76fc..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/keys.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/keys
-
-# keys
-
-[JVM] \
-Content \
-open override val [keys]():
-[Set](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-set/index.html)<[K]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/to-string.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/to-string.md
deleted file mode 100644
index 4be12f8c8..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/to-string.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/toString
-
-# toString
-
-[JVM] \
-Content \
-open override fun [toString]()():
-[String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/values.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/values.md
deleted file mode 100644
index 3d5a4f842..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-map/values.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[DslMap]()/values
-
-# values
-
-[JVM] \
-Content \
-open override val [values]():
-[Collection](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-collection/index.html)<[V]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-proxy/_index.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-proxy/_index.md
deleted file mode 100644
index 0ca1b647c..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-proxy/_index.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/DslProxy
-
-# DslProxy
-
-[JVM] abstract class [DslProxy]()
-
-A type meaningful only for its existence, never intended to be instantiated. For
-example, a DslList
Content
open operator override fun [contains](#765883978%2FFunctions%2F-246181541)(element: [E]()): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[containsAll](#-225903147%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [containsAll](#-225903147%2FFunctions%2F-246181541)(elements: [Collection](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-collection/index.html)<[E]()>): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[equals](equals) | [JVM]
Content
open operator override fun [equals](equals)(other: [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[forEach](#1532301601%2FFunctions%2F-246181541) | [JVM]
Content
open fun [forEach](#1532301601%2FFunctions%2F-246181541)(p0: [Consumer](https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html)
-[get](#961975567%2FFunctions%2F-246181541) | [JVM]
Content
open operator override fun [get](#961975567%2FFunctions%2F-246181541)(index: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [E]()
-[hashCode](hash-code) | [JVM]
Content
open override fun [hashCode](hash-code)(): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[indexOf](#-407930336%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [indexOf](#-407930336%2FFunctions%2F-246181541)(element: [E]()): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[isEmpty](#-1000881820%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [isEmpty](#-1000881820%2FFunctions%2F-246181541)(): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-[iterator](iterator) | [JVM]
Content
open operator override fun [iterator](iterator)(): [Iterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/index.html)<[E]()>
-[lastIndexOf](#1327716778%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [lastIndexOf](#1327716778%2FFunctions%2F-246181541)(element: [E]()): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
-[listIterator](list-iterator) | [JVM]
Content
open override fun [listIterator](list-iterator)(): [ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
open override fun [listIterator](list-iterator)(index: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
-[parallelStream](#-1592339412%2FFunctions%2F-246181541) | [JVM]
Content
open fun [parallelStream](#-1592339412%2FFunctions%2F-246181541)(): [Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)<[E]()>
-[spliterator](#703021258%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [spliterator](#703021258%2FFunctions%2F-246181541)(): [Spliterator](https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html)<[E]()>
-[stream](#135225651%2FFunctions%2F-246181541) | [JVM]
Content
open fun [stream](#135225651%2FFunctions%2F-246181541)(): [Stream](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html)<[E]()>
-[subList](#423386006%2FFunctions%2F-246181541) | [JVM]
Content
open override fun [subList](#423386006%2FFunctions%2F-246181541)(fromIndex: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html), toIndex: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E]()>
-[toArray](#-1215154575%2FFunctions%2F-246181541) | [JVM]
Content
~~open~~ ~~fun~~ ~~<~~[T](#-1215154575%2FFunctions%2F-246181541) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)~~>~~ [~~toArray~~](#-1215154575%2FFunctions%2F-246181541)~~(~~~~p0~~~~:~~ [IntFunction](https://docs.oracle.com/javase/8/docs/api/java/util/function/IntFunction.html)<[Array](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)<[T](#-1215154575%2FFunctions%2F-246181541)>>~~)~~~~:~~ [Array](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html)<[T](#-1215154575%2FFunctions%2F-246181541)>
-[toString](to-string) | [JVM]
Content
open override fun [toString](to-string)(): [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
-
-## Properties
-
-Name | Summary
---------------------------------------------------------------------------------------------------------------------------------- | -------
-[extension](extension) | [JVM] val [extension](extension): [ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](), [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E]()>>
-[size](#648753719%2FProperties%2F-246181541) | [JVM] open override val [size](#648753719%2FProperties%2F-246181541): [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/equals.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/equals.md
deleted file mode 100644
index ed11b9460..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/equals.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/equals
-
-# equals
-
-[JVM] \
-Content \
-open operator override fun [equals]()(other:
-[Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)?):
-[Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/extension.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/extension.md
deleted file mode 100644
index 40e43e1c7..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/extension.md
+++ /dev/null
@@ -1,9 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/extension
-
-# extension
-
-[JVM] \
-Content \
-val [extension]():
-[ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](),
-[List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E]()>>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/hash-code.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/hash-code.md
deleted file mode 100644
index 5e5e04189..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/hash-code.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/hashCode
-
-# hashCode
-
-[JVM] \
-Content \
-open override fun [hashCode]()():
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/iterator.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/iterator.md
deleted file mode 100644
index 1619ef9a5..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/iterator.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/iterator
-
-# iterator
-
-[JVM] \
-Content \
-open operator override fun iterator():
-[Iterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-iterator/index.html)<[E]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/list-iterator.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/list-iterator.md
deleted file mode 100644
index 2b19a33af..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/list-iterator.md
+++ /dev/null
@@ -1,12 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/listIterator
-
-# listIterator
-
-[JVM] \
-Content \
-open override fun [listIterator]()():
-[ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
-\
-open override fun [listIterator]()(index:
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)):
-[ListIterator](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list-iterator/index.html)<[E]()>
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/to-string.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/to-string.md
deleted file mode 100644
index b85c4e618..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-extension-list/to-string.md
+++ /dev/null
@@ -1,8 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ExtensionList]()/toString
-
-# toString
-
-[JVM] \
-Content \
-open override fun [toString]()():
-[String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/-only-for-use-by-generated-proto-code.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/-only-for-use-by-generated-proto-code.md
deleted file mode 100644
index 297dba225..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/-only-for-use-by-generated-proto-code.md
+++ /dev/null
@@ -1,7 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[OnlyForUseByGeneratedProtoCode]()/OnlyForUseByGeneratedProtoCode
-
-# OnlyForUseByGeneratedProtoCode
-
-[JVM] \
-Content \
-fun [OnlyForUseByGeneratedProtoCode]()()
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/_index.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/_index.md
deleted file mode 100644
index 4ffd55c12..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-only-for-use-by-generated-proto-code/_index.md
+++ /dev/null
@@ -1,21 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/OnlyForUseByGeneratedProtoCode
-
-# OnlyForUseByGeneratedProtoCode
-
-[JVM]
-@[Target](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-target/index.html)(allowedTargets =
-[[AnnotationTarget.CONSTRUCTOR](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-o-n-s-t-r-u-c-t-o-r.html#kotlin.annotation.AnnotationTarget.CONSTRUCTOR),
-[AnnotationTarget.ANNOTATION_CLASS](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-l-a-s-s.html#kotlin.annotation.AnnotationTarget.CLASS)])
-
-annotation class [OnlyForUseByGeneratedProtoCode]()
-
-Opt-in annotation to make it difficult to accidentally use APIs only intended
-for use by proto generated code. See
-https://kotlinlang.org/docs/reference/opt-in-requirements.html for details on
-how this API works.
-
-## Constructors
-
-Name | Summary
---- | ---
-[OnlyForUseByGeneratedProtoCode]() | [JVM] fun [OnlyForUseByGeneratedProtoCode]()()
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/-proto-dsl-marker.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/-proto-dsl-marker.md
deleted file mode 100644
index deb76062b..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/-proto-dsl-marker.md
+++ /dev/null
@@ -1,7 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ProtoDslMarker]()/[ProtoDslMarker]()
-
-# ProtoDslMarker
-
-[JVM] \
-Content \
-fun [ProtoDslMarker]()()
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/_index.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/_index.md
deleted file mode 100644
index 6b1708523..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-proto-dsl-marker/_index.md
+++ /dev/null
@@ -1,19 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[ProtoDslMarker]()
-
-# ProtoDslMarker
-
-[JVM]
-@[DslMarker](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-dsl-marker/index.html)()
-\
-@[Target](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-target/index.html)(allowedTargets =
-[[AnnotationTarget.CLASS](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-l-a-s-s/index.html)])
-
-annotation class [ProtoDslMarker]()
-
-Indicates an API that is part of a DSL to generate protocol buffer messages.
-
-## Constructors
-
-Name | Summary
---- | ---
-[ProtoDslMarker]() | [JVM] fun [ProtoDslMarker]()()
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/_index.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/_index.md
deleted file mode 100644
index cf93d1b6b..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/_index.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# Package com.google.protobuf.kotlin
-
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)
-
-## Types
-
-Name | Summary
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------
-[DslList](-dsl-list/) | [JVM]
Content
class [DslList](-dsl-list/)<[E](-dsl-list/), [P](-dsl-list/) : [DslProxy](-dsl-proxy/)>constructor(**delegate**: [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E](-dsl-list/)>) : [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E](-dsl-list/)>
A simple wrapper around a [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html) with an extra generic parameter that can be used to disambiguate extension methods.
-[DslMap](-dsl-map/) | [JVM]
Content
class [DslMap](-dsl-map/)<[K](-dsl-map/), [V](-dsl-map/), [P](-dsl-map/) : [DslProxy](-dsl-proxy/)>constructor(**delegate**: [Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](-dsl-map/), [V](-dsl-map/)>) : [Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html)<[K](-dsl-map/), [V](-dsl-map/)>
A simple wrapper around a [Map](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-map/index.html) with an extra generic parameter that can be used to disambiguate extension methods.
-[DslProxy](-dsl-proxy/) | [JVM]
Content
abstract class [DslProxy](-dsl-proxy/)
A type meaningful only for its existence, never intended to be instantiated.
-[ExtensionList](-extension-list/) | [JVM]
Content
class [ExtensionList](-extension-list/)<[E](-extension-list/), [M](-extension-list/) : [MessageLite](/reference/java/api-docs/com/google/protobuf/MessageLite.html)>constructor(**extension**: [ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](-extension-list/), [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E](-extension-list/)>>, **delegate**: [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E](-extension-list/)>) : [List](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-list/index.html)<[E](-extension-list/)>
Implementation for ExtensionList and ExtensionListLite.
-[OnlyForUseByGeneratedProtoCode](-only-for-use-by-generated-proto-code/) | [JVM]
Content
@[Target](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-target/index.html)(allowedTargets = [[AnnotationTarget.CONSTRUCTOR](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-o-n-s-t-r-u-c-t-o-r.html#kotlin.annotation.AnnotationTarget.CONSTRUCTOR), [AnnotationTarget.ANNOTATION_CLASS](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-l-a-s-s.html#kotlin.annotation.AnnotationTarget.CLASS)])
annotation class [OnlyForUseByGeneratedProtoCode](-only-for-use-by-generated-proto-code/)
Opt-in annotation to make it difficult to accidentally use APIs only intended for use by proto generated code.
-[ProtoDslMarker](-proto-dsl-marker/) | [JVM]
Content
@[DslMarker](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-dsl-marker/index.html)()
@[Target](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-target/index.html)(allowedTargets = [[AnnotationTarget.CLASS](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.annotation/-annotation-target/-c-l-a-s-s/index.html)])
annotation class [ProtoDslMarker](-proto-dsl-marker/)
Indicates an API that is part of a DSL to generate protocol buffer messages.
-
-## Functions
-
-Name | Summary
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------
-[contains](contains) | [JVM]
Content
operator fun <[M](contains) : [GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M](contains)>, [MorBT](contains) : [GeneratedMessageV3.ExtendableMessageOrBuilder](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M](contains)>> [MorBT](contains).[contains](contains)(extension: [ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](contains), *>): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
Returns true if the specified extension is set on this builder.
-[get](get) | [JVM]
Content
operator fun <[M](get) : [GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M](get)>, [MorBT](get) : [GeneratedMessageV3.ExtendableMessageOrBuilder](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M](get)>, [T](get) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)> [MorBT](get).[get](get)(extension: [ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](get), [T](get)>): [T](get)
Gets the current value of the proto extension.
[JVM]
Content
operator fun [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).[get](get)(index: [Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)): [Byte](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte/index.html)
Gets the byte at [index](get).
-[isA](is-a) | [JVM]
Content
inline fun <[T](is-a) : [Message](/reference/java/api-docs/com/google/protobuf/Message.html)> [Any](/reference/java/api-docs/com/google/protobuf/Any.html).[isA](is-a)(): [Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
Returns true if this [com.google.protobuf.Any](/reference/java/api-docs/com/google/protobuf/Any.html) contains a message of type T.
-[plus](plus) | [JVM]
Content
operator fun [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).[plus](plus)(other: [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)): [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
Concatenates the given [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html) to this one.
-[set](set) | [JVM]
Content
operator fun <[M](set) : [GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M](set)>, [B](set) : [GeneratedMessageV3.ExtendableBuilder](/reference/java/api-docs/com/google/protobuf/GeneratedMessageV3.ExtendableBuilder.html)<[M](set), [B](set)>, [T](set) : [Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)> [B](set).[set](set)(extension: [ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](set), [T](set)>, value: [T](set))
Sets the current value of the proto extension in this builder.
-[toByteString](to-byte-string) | [JVM]
Content
fun [ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html).[toByteString](to-byte-string)(): [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
Copies the remaining bytes from this [ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html) to a [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
[JVM]
Content
fun [ByteArray](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte-array/index.html).[toByteString](to-byte-string)(): [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
Returns a copy of this [ByteArray](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte-array/index.html) as an immutable [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
-[toByteStringUtf8](to-byte-string-utf8) | [JVM]
Content
fun [String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html).[toByteStringUtf8](to-byte-string-utf8)(): [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
Encodes this String into a sequence of UTF-8 bytes and returns the result as a [ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
-[unpack](unpack) | [JVM]
Content
inline fun <[T](unpack) : [Message](/reference/java/api-docs/com/google/protobuf/Message.html)> [Any](/reference/java/api-docs/com/google/protobuf/Any.html).[unpack](unpack)(): [T](unpack)
Returns the message of type T encoded in this [com.google.protobuf.Any](/reference/java/api-docs/com/google/protobuf/Any.html).
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/contains.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/contains.md
deleted file mode 100644
index a51cf5ef9..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/contains.md
+++ /dev/null
@@ -1,16 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/contains
-
-# contains
-
-[JVM] \
-Content \
-operator fun <[M]() :
-[GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M]()>,
-[MorBT]() :
-[GeneratedMessageV3.ExtendableMessageOrBuilder](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M]()>>
-[MorBT]().[contains]()(extension:
-[ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](),
-*>):
-[Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-
-Returns true if the specified extension is set on this builder.
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/get.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/get.md
deleted file mode 100644
index 4152d4e8a..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/get.md
+++ /dev/null
@@ -1,26 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[get]()
-
-# get
-
-[JVM] \
-Content \
-operator fun
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).[get]()(index:
-[Int](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/index.html)):
-[Byte](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte/index.html)
-
-Gets the byte at [index]().
-
-[JVM] \
-Content \
-operator fun <[M]() :
-[GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M]()>,
-[MorBT]() :
-[GeneratedMessageV3.ExtendableMessageOrBuilder](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M]()>,
-[T]() :
-[Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)>
-[MorBT]().[get]()(extension:
-[ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](),
-[T]()>): [T]()
-
-Gets the current value of the proto extension.
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/is-a.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/is-a.md
deleted file mode 100644
index c9e512cae..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/is-a.md
+++ /dev/null
@@ -1,15 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/[isA]()
-
-# isA
-
-[JVM] \
-Content \
-inline fun <[T]() :
-[Message](/reference/java/api-docs/com/google/protobuf/Message.html)>
-[Any](/reference/java/api-docs/com/google/protobuf/Any.html).[isA]()():
-[Boolean](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)
-
-
-Returns true if this
-[com.google.protobuf.Any](/reference/java/api-docs/com/google/protobuf/Any.html)
-contains a message of type T.
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/plus.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/plus.md
deleted file mode 100644
index f9346a40a..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/plus.md
+++ /dev/null
@@ -1,16 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/plus
-
-# plus
-
-[JVM] \
-Content \
-operator fun
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).plus(other:
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)):
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
-\
-
-
-Concatenates the given
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
-to this one.
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/set.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/set.md
deleted file mode 100644
index 7d702fe7d..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/set.md
+++ /dev/null
@@ -1,17 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/set
-
-# set
-
-[JVM] \
-Content \
-operator fun <[M]() :
-[GeneratedMessageV3.ExtendableMessage](https://github.com/protocolbuffers/protobuf/blob/master/java/core/src/main/java/com/google/protobuf/GeneratedMessageV3.java)<[M]()>,
-[B]() :
-[GeneratedMessageV3.ExtendableBuilder](/reference/java/api-docs/com/google/protobuf/GeneratedMessageV3.ExtendableBuilder.html)<[M](),
-[B]()>, [T]() :
-[Any](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)>
-[B]().[set]()(extension:
-[ExtensionLite](/reference/java/api-docs/com/google/protobuf/ExtensionLite.html)<[M](set),
-[T]()>, value: [T]())
-
-Sets the current value of the proto extension in this builder.
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string-utf8.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string-utf8.md
deleted file mode 100644
index e3a379fdd..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string-utf8.md
+++ /dev/null
@@ -1,13 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/toByteStringUtf8
-
-# toByteStringUtf8
-
-[JVM] \
-Content \
-fun
-[String](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html).[toByteStringUtf8]()():
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
-
-
-Encodes this String into a sequence of UTF-8 bytes and returns the result as a
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string.md
deleted file mode 100644
index 6b46a7c2d..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/to-byte-string.md
+++ /dev/null
@@ -1,27 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/toByteString
-
-# toByteString
-
-[JVM] \
-Content \
-fun
-[ByteArray](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte-array/index.html).[toByteString]()():
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
-
-
-Returns a copy of this
-[ByteArray](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-byte-array/index.html)
-as an immutable
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
-
-[JVM] \
-Content \
-fun
-[ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html).[toByteString]()():
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html)
-
-
-Copies the remaining bytes from this
-[ByteBuffer](https://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html)
-to a
-[ByteString](/reference/java/api-docs/com/google/protobuf/ByteString.html).
diff --git a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/unpack.md b/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/unpack.md
deleted file mode 100644
index c4f8a0396..000000000
--- a/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/unpack.md
+++ /dev/null
@@ -1,19 +0,0 @@
-//[protobuf-kotlin](/reference/kotlin/api-docs/)/[com.google.protobuf.kotlin](/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/)/unpack
-
-# unpack
-
-[JVM] \
-Content \
-inline fun <[T]() :
-[Message](/reference/java/api-docs/com/google/protobuf/Message.html)>
-[Any](/reference/java/api-docs/com/google/protobuf/Any.html).[unpack]()():
-[T]()
-
-Returns the message of type T encoded in this
-[com.google.protobuf.Any](/reference/java/api-docs/com/google/protobuf/Any.html).
-
-#### Throws
-
- | |
-------------------------------------------------------------------------------------------------------------------------------- | ---
-InvalidProtocolBufferException |
if this [com.google.protobuf.Any](/reference/java/api-docs/com/google/protobuf/Any.html) does not contain a T message.
diff --git a/content/reference/kotlin/kotlin-generated.md b/content/reference/kotlin/kotlin-generated.md
deleted file mode 100644
index 703324afa..000000000
--- a/content/reference/kotlin/kotlin-generated.md
+++ /dev/null
@@ -1,322 +0,0 @@
-+++
-title = "Kotlin Generated Code Guide"
-weight = 680
-linkTitle = "Generated Code Guide"
-description = "Describes exactly what Kotlin code the protocol buffer compiler generates for any given protocol definition, in addition to the code generated for Java."
-type = "docs"
-+++
-
-Any differences between proto2, proto3, and editions
-generated code are highlighted—note that these differences are in the
-generated code as described in this document, not the base message
-classes/interfaces, which are the same in both versions. You should read the
-[proto2 language guide](/programming-guides/proto2),
-[proto3 language guide](/programming-guides/proto3),
-and/or the [Editions guide](/programming-guides/editions)
-before reading this document.
-
-## Compiler Invocation {#invocation}
-
-The protocol buffer compiler produces Kotlin code that builds on top of Java
-code. As a result, it must be invoked with two command-line flags, `--java_out=`
-and `--kotlin_out=`. The parameter to the `--java_out=` option is the directory
-where you want the compiler to write your Java output, and the same for the
-`--kotlin_out=`. For each `.proto` file input, the compiler creates a wrapper
-`.java` file containing a Java class which represents the `.proto` file itself.
-
-**Regardless** of whether or not your `.proto` file contains a line like the
-following:
-
-```proto
-option java_multiple_files = true;
-```
-
-The compiler will create separate `.kt` files for each of the classes and
-factory methods which it will generate for each top-level message declared in
-the `.proto` file.
-
-The Java package name for each file is the same as that used by the generated
-Java code as described in the
-[Java generated code reference](/reference/java/java-generated#package).
-
-The output file is chosen by concatenating the parameter to `--kotlin_out=`, the
-package name (with periods [.] replaced with slashes [/]), and the suffix
-`Kt.kt` file name.
-
-So, for example, let's say you invoke the compiler as follows:
-
-```shell
-protoc --proto_path=src --java_out=build/gen/java --kotlin_out=build/gen/kotlin src/foo.proto
-```
-
-If `foo.proto`'s Java package is `com.example` and it contains a message named
-`Bar`, then the protocol buffer compiler will generate the file
-`build/gen/kotlin/com/example/BarKt.kt`. The protocol buffer compiler will
-automatically create the `build/gen/kotlin/com` and
-`build/gen/kotlin/com/example` directories if needed. However, it will not
-create `build/gen/kotlin`, `build/gen`, or `build`; they must already exist. You
-can specify multiple `.proto` files in a single invocation; all output files
-will be generated at once.
-
-## Messages {#message}
-
-Given a simple message declaration:
-
-```proto
-message FooBar {}
-```
-
-The protocol buffer compiler generates—in addition to the generated Java
-code—an object called `FooBarKt`, as well as two top-level functions,
-having the following structure:
-
-```kotlin
-object FooBarKt {
- class Dsl private constructor { ... }
-}
-inline fun fooBar(block: FooBarKt.Dsl.() -> Unit): FooBar
-inline fun FooBar.copy(block: FooBarKt.Dsl.() -> Unit): FooBar
-```
-
-### Nested Types
-
-A message can be declared inside another message. For example:
-
-```proto
-message Foo {
- message Bar { }
-}
-```
-
-In this case, the compiler nests the `BarKt` object and the `bar` factory method
-inside `FooKt`, though the `copy` method remains top-level:
-
-```kotlin
-object FooKt {
- class Dsl { ... }
- object BarKt {
- class Dsl private constructor { ... }
- }
- inline fun bar(block: FooKt.BarKt.Dsl.() -> Unit): Foo.Bar
-}
-inline fun foo(block: FooKt.Dsl.() -> Unit): Foo
-inline fun Foo.copy(block: FooKt.Dsl.() -> Unit): Foo
-inline fun Foo.Bar.copy(block: FooKt.BarKt.Dsl.() -> Unit): Foo.Bar
-```
-
-## Fields
-
-In addition to the methods described in the previous section, the protocol
-buffer compiler generates mutable properties in the DSL for each field defined
-within the message in the `.proto` file. (Kotlin already infers read-only
-properties on the message object from the getters generated by Java.)
-
-Note that properties always use camel-case naming, even if the field name in the
-`.proto` file uses lower-case with underscores
-([as it should](/programming-guides/style)). The
-case-conversion works as follows:
-
-1. For each underscore in the name, the underscore is removed, and the
- following letter is capitalized.
-2. If the name will have a prefix attached (for example, "clear"), the first
- letter is capitalized. Otherwise, it is lower-cased.
-
-Thus, the field `foo_bar_baz` becomes `fooBarBaz`.
-
-In a few special cases in which a field name conflicts with reserved words in
-Kotlin or methods already defined in the protobuf library, an extra underscore
-is appended. For instance, the clearer for a field named `in` is `clearIn_()`.
-
-### Singular Fields
-
-For this field definition:
-
-```proto
-int32 foo = 1;
-```
-
-The compiler will generate the following accessors in the DSL:
-
-- `fun hasFoo(): Boolean`: Returns `true` if the field is set. This is not
- generated for fields using implicit presence.
-- `var foo: Int`: The current value of the field. If the field is not set,
- returns the default value.
-- `fun clearFoo()`: Clears the value of the field. After calling this,
- `hasFoo()` will return `false` and `getFoo()` will return the default value.
-
-For other simple field types, the corresponding Java type is chosen according to
-the
-[scalar value types table](/programming-guides/proto2#scalar).
-For message and enum types, the value type is replaced with the message or enum
-class. As the message type is still defined in Java, unsigned types in the
-message are represented using the standard corresponding signed types in the
-DSL, for compatibility with Java and older versions of Kotlin.
-
-#### Embedded Message Fields
-
-Note that there is no special handling of submessages. For example, if you have
-a field
-
-```proto
-optional Foo my_foo = 1;
-```
-
-you must write
-
-```kotlin
-myFoo = foo {
- ...
-}
-```
-
-In general, this is because the compiler does not know whether `Foo` has a
-Kotlin DSL at all, or e.g. only has the Java APIs generated. This means that you
-do not have to wait for messages you depend on to add Kotlin code generation.
-
-### Repeated Fields {#repeated}
-
-For this field definition:
-
-```proto
-repeated string foo = 1;
-```
-
-The compiler will generate the following members in the DSL:
-
-- `class FooProxy: DslProxy`, an unconstructable type used only in generics
-- `val fooList: DslList