### Option Statement Examples Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/edition-2023-spec.md Examples of setting protobuf-defined and custom options. ```proto option java_package = "com.example.foo"; option features.enum_type = CLOSED; ``` -------------------------------- ### Install Protoc using apt (Linux) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/installation.md Installs the protocol compiler using the apt package manager on Linux. It's recommended to verify the installed version afterward. ```sh apt install -y protobuf-compiler protoc --version # Ensure compiler version is 33.0+ ``` -------------------------------- ### Example Proto2 File Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/proto2-spec.md A comprehensive example demonstrating syntax, imports, options, enums with aliases, nested messages, maps, and extensions. ```proto syntax = "proto2"; import public "other.proto"; option java_package = "com.example.foo"; enum EnumAllowingAlias { option allow_alias = true; EAA_UNSPECIFIED = 0; EAA_STARTED = 1; EAA_RUNNING = 1; EAA_FINISHED = 2 [(custom_option) = "hello world"]; } message Outer { option (my_option).a = true; message Inner { // Level 2 required int64 ival = 1; } repeated Inner inner_message = 2; optional EnumAllowingAlias enum_field = 3; map my_map = 4; extensions 20 to 30; } message Foo { optional group GroupMessage = 1 { optional bool a = 1; } } ``` -------------------------------- ### Install Protoc using Winget (Windows) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/installation.md Installs the protocol compiler using the Winget package manager on Windows. It's recommended to verify the installed version afterward. ```powershell > winget install protobuf > protoc --version # Ensure compiler version is 33.0+ ``` -------------------------------- ### Install protoc-gen-go Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/go/go-generated-opaque.md Install the protocol buffer compiler plugin for Go using Go 1.16 or higher. ```APIDOC ## Install protoc-gen-go ### Description Install the protocol buffer compiler plugin for Go using Go 1.16 or higher. ### Method Shell Command ### Endpoint N/A ### Parameters N/A ### Request Example ```shell go install google.golang.org/protobuf/cmd/protoc-gen-go@latest ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Complete Proto3 File Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/proto3-spec.md An example of a complete .proto file, including syntax declaration, imports, options, enum, message, and map definitions. Demonstrates the overall structure of a proto file. ```proto syntax = "proto3"; import public "other.proto"; option java_package = "com.example.foo"; enum EnumAllowingAlias { option allow_alias = true; EAA_UNSPECIFIED = 0; EAA_STARTED = 1; EAA_RUNNING = 1; EAA_FINISHED = 2 [(custom_option) = "hello world"]; } message Outer { option (my_option).a = true; message Inner { // Level 2 int64 ival = 1; } repeated Inner inner_message = 2; EnumAllowingAlias enum_field = 3; map my_map = 4; } ``` -------------------------------- ### Install Protoc using Homebrew (macOS) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/installation.md Installs the protocol compiler using the Homebrew package manager on macOS. It's recommended to verify the installed version afterward. ```sh brew install protobuf protoc --version # Ensure compiler version is 33.0+ ``` -------------------------------- ### Install Go Protocol Buffers Plugin Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/getting-started/gotutorial.md Installs the Go protocol buffers compiler plugin using the go install command. This plugin is necessary for protoc to generate Go code from .proto files. Ensure the plugin is in your system's PATH. ```shell go install google.golang.org/protobuf/cmd/protoc-gen-go@latest ``` -------------------------------- ### Example Proto2 Service Definition Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/proto2-spec.md An example of a service definition with a single RPC method. ```proto service SearchService { rpc Search (SearchRequest) returns (SearchResponse); } ``` -------------------------------- ### Example Protocol Buffer Text Format Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/textformat-spec.md An example demonstrating the structure of a protocol buffer message in text format, including nested messages and fields. ```textproto convolution_benchmark { label: "NHWC_128x20x20x56x160" input { dimension: [128, 56, 20, 20] data_type: DATA_HALF format: TENSOR_NHWC } } ``` -------------------------------- ### Get Extension Range Start Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/Google/Protobuf/Internal/DescriptorProto/ExtensionRange.html Retrieves the inclusive start value of an extension range. This corresponds to the 'start' field in the protobuf descriptor. ```php return $this->start; ``` -------------------------------- ### Example Protocol Buffers .proto File Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/edition-2024-spec.md Demonstrates a comprehensive .proto file with syntax, imports, options, enums, messages, and extensions. ```proto edition = "2024"; import public "other.proto"; import option "custom_option.proto"; option java_package = "com.example.foo"; enum EnumAllowingAlias { option allow_alias = true; EAA_UNSPECIFIED = 0; EAA_STARTED = 1; EAA_RUNNING = 1; EAA_FINISHED = 2 [(custom_option) = "hello world"]; } message Outer { option (my_option).a = true; message Inner { // Level 2 int64 ival = 1 [features.field_presence = LEGACY_REQUIRED]; } repeated Inner inner_message = 2; EnumAllowingAlias enum_field = 3; map my_map = 4; extensions 20 to 30; reserved reserved_field; } message Foo { message GroupMessage { bool a = 1; } GroupMessage groupmessage = [features.message_encoding = DELIMITED]; } ``` -------------------------------- ### GET Request Annotation Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Mixin.html Example of defining a GET request using the `google.api.http` option in Protocol Buffers. ```APIDOC ## GET /v2/{resource=**}:getAcl ### Description This endpoint retrieves an ACL object. ### Method GET ### Endpoint /v2/{resource=**}:getAcl ### Parameters #### Path Parameters - **resource** (string) - Required - The resource identifier for the ACL. ### Response #### Success Response (200) - **Acl** (object) - The ACL object retrieved. ``` -------------------------------- ### Get Start Field - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ReservedRange.html Retrieves the value of the 'start' field. This method is part of the ReservedRangeOrBuilder interface and is used to access the starting point of a reserved range. ```Java public int getStart() { return start; } ``` -------------------------------- ### Get ReservedRange Start Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/Google/Protobuf/Internal/DescriptorProto/ReservedRange.html Retrieves the inclusive start value of a reserved range. This method is part of the DescriptorProto internal API. ```php int **getStart**() ``` -------------------------------- ### GET /start Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ReservedRange.Builder.html Accessors for the 'start' field in the ReservedRange. ```APIDOC ## GET /start ### Description Retrieves the value of the 'start' field or checks if it has been set. ### Method GET ### Endpoint /start ### Response #### Success Response (200) - **hasStart** (boolean) - Whether the field is set. - **start** (int) - The inclusive start value. #### Response Example { "hasStart": true, "start": 1 } ``` -------------------------------- ### Example Proto File (Edition 2023) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/edition-2023-spec.md An example .proto file demonstrating various Protocol Buffers features including edition declaration, public imports, options, enums with aliases, nested messages, repeated fields, maps, extensions, and reserved fields. ```protobuf edition = "2023"; import public "other.proto"; option java_package = "com.example.foo"; enum EnumAllowingAlias { option allow_alias = true; EAA_UNSPECIFIED = 0; EAA_STARTED = 1; EAA_RUNNING = 1; EAA_FINISHED = 2 [(custom_option) = "hello world"]; } message Outer { option (my_option).a = true; message Inner { // Level 2 int64 ival = 1 [features.field_presence = LEGACY_REQUIRED]; } repeated Inner inner_message = 2; EnumAllowingAlias enum_field = 3; map my_map = 4; extensions 20 to 30; reserved reserved_field; } message Foo { message GroupMessage { bool a = 1; } GroupMessage groupmessage = [features.message_encoding = DELIMITED]; } ``` -------------------------------- ### Instantiate FileOptions Builder Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.FileOptions.html Demonstrates how to create a new builder for FileOptions, either from scratch or initialized from an existing prototype message. ```java DescriptorProtos.FileOptions.Builder builder = DescriptorProtos.FileOptions.newBuilder(); DescriptorProtos.FileOptions.Builder derivedBuilder = DescriptorProtos.FileOptions.newBuilder(prototype); ``` -------------------------------- ### Get Start of Reserved Range Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.EnumDescriptorProto.EnumReservedRange.Builder.html Retrieves the inclusive start value of the reserved range. This method is part of the EnumReservedRange.Builder and returns an integer. ```java DescriptorProtos.EnumDescriptorProto.EnumReservedRange.Builder.getStart() ``` -------------------------------- ### Check and Get Start Field - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ExtensionRange.html Provides methods to check if the 'start' field is set and to retrieve its integer value. The 'start' field is an optional int32 representing the beginning of an extension range. ```java public boolean hasStart() public int getStart() ``` -------------------------------- ### RpcChannel Usage Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.service.md Demonstrates how to initialize an RpcChannel and use it to construct a service stub for remote method invocation. ```cpp RpcChannel* channel = new MyRpcChannel("remotehost.example.com:1234"); MyService* service = new MyService::Stub(channel); service->MyMethod(request, &response, callback); ``` -------------------------------- ### ReservedRange::getStart Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/doc-index.html Gets the inclusive start of a reserved range. ```APIDOC ## ReservedRange::getStart ### Description Gets the inclusive start of a reserved range. ### Method _Method in class [ReservedRange](Google/Protobuf/Internal/DescriptorProto/ReservedRange.html)_ ### Parameters None ### Response - Returns the starting number of the reserved range. ``` -------------------------------- ### ExtensionRange::getStart Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/doc-index.html Gets the inclusive start of an extension range. ```APIDOC ## ExtensionRange::getStart ### Description Gets the inclusive start of an extension range. ### Method _Method in class [ExtensionRange](Google/Protobuf/Internal/DescriptorProto/ExtensionRange.html)_ ### Parameters None ### Response - Returns the starting number of the extension range. ``` -------------------------------- ### getStart Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/Google/Protobuf/Internal/DescriptorProto/ReservedRange.html Gets the starting field number of the reserved range. ```APIDOC ## getStart ### Description Gets the starting field number of the reserved range. This is inclusive. ### Method `getStart()` ### Returns (int) - The starting field number. ``` -------------------------------- ### Get Start Field Value in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ReservedRange.html Retrieves the integer value of the 'start' field from a ReservedRange message. This field is an optional int32 and is inclusive. ```Java public int getStart() { // Implementation details... } ``` -------------------------------- ### Initialize GzipInputStream Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.io.gzip_stream.md Demonstrates how to instantiate a GzipInputStream to decompress data from an existing ZeroCopyInputStream. The constructor accepts a sub-stream, a format type, and an optional buffer size. ```cpp #include // Assuming sub_stream is a valid ZeroCopyInputStream* google::protobuf::io::GzipInputStream input(sub_stream, google::protobuf::io::GzipInputStream::GZIP, 65536); ``` -------------------------------- ### GET /start Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.EnumDescriptorProto.EnumReservedRangeOrBuilder.html Retrieves the inclusive start value of the reserved range. ```APIDOC ## GET /start ### Description Returns the inclusive start value defined in the reserved range. ### Method GET ### Endpoint /start ### Response #### Success Response (200) - **start** (int) - The inclusive start value of the range. #### Response Example { "start": 1 } ``` -------------------------------- ### GET /descriptor/extension-range Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/index-all.html Retrieves the starting index for an extension range within a descriptor. ```APIDOC ## GET /descriptor/extension-range ### Description Retrieves the inclusive starting index of an extension range defined within a DescriptorProto. ### Method GET ### Endpoint /descriptor/extension-range ### Parameters #### Query Parameters - **range_id** (string) - Required - The identifier for the extension range. ### Response #### Success Response (200) - **start** (integer) - The inclusive starting value of the extension range. #### Response Example { "start": 100 } ``` -------------------------------- ### Go: Constructing Empty Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/go/opaque-faq.md Demonstrates the most efficient and idiomatic ways to create an empty Protocol Buffer message in Go. Using `new(pb.M)` or `&pb.M{}` is preferred over `pb.M_builder{}.Build()` for performance and simplicity. ```go m1 := new(pb.M) m2 := &pb.M{} ``` ```go // BAD: avoid: unnecessarily complex m1 := pb.M_builder{}.Build() ``` -------------------------------- ### MethodOptions Builder Initialization (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.MethodOptions.html Demonstrates how to create a new builder for MethodOptions, initialized with an existing MethodOptions prototype. This is useful for deriving new configurations from existing ones. ```Java public static DescriptorProtos.MethodOptions.Builder newBuilder(DescriptorProtos.MethodOptions prototype) ``` -------------------------------- ### GET /ReservedRange/getStart Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ReservedRange.html Retrieves the inclusive start value of the reserved field number range. ```APIDOC ## GET /ReservedRange/getStart ### Description Returns the inclusive starting field number of the reserved range. ### Method GET ### Endpoint /ReservedRange/getStart ### Response #### Success Response (200) - **start** (int) - The inclusive start field number. #### Response Example { "start": 10 } ``` -------------------------------- ### Get Span Count from LocationOrBuilder (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.Location.Builder.html Returns the number of elements in the span array. This count is usually three or four, representing start line, start column, end line, and end column. ```Java public int getSpanCount() { return span_.size(); } ``` -------------------------------- ### Plugin Executable Usage Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.command_line_interface.md Shows the expected command-line usage for a Protocol Buffer compiler plugin. Plugins accept an optional output directory and parameter, followed by the list of protocol buffer files. They receive compiled descriptors via standard input. ```bash plugin [--out=OUTDIR] [--parameter=PARAMETER] PROTO_FILES < DESCRIPTORS ``` -------------------------------- ### Get Span Information - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.LocationOrBuilder.html Provides methods to access and count the span information for a location. The span typically includes start line, start column, and optionally end line and end column. ```java int getSpan(int index); int getSpanCount(); java.util.List getSpanList(); ``` -------------------------------- ### Example of Protoc Command with Plugin Parameters Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.command_line_interface.md Illustrates invoking the Protocol Compiler with a plugin generator, passing parameters similarly to built-in generators. The parameters are provided via the main output flag and an optional parameter flag, which are then passed to the plugin executable. ```bash protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz ``` -------------------------------- ### Get Start Value for Reserved Range (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ReservedRange.Builder.html Provides the `getStart` method to retrieve the inclusive start value of a reserved range. This method is specified in the `DescriptorProtos.DescriptorProto.ReservedRangeOrBuilder` interface and operates on an `optional int32` field. ```Java public int getStart() ``` -------------------------------- ### Initialize a ParseInfoTree Builder in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/TextFormatParseInfoTree.html Demonstrates how to instantiate a new builder for creating a TextFormatParseInfoTree object. ```java TextFormatParseInfoTree.Builder builder = TextFormatParseInfoTree.builder(); ``` -------------------------------- ### Get Span List from LocationOrBuilder (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.Location.Builder.html Retrieves a list containing the span information from a LocationOrBuilder object. The span typically includes start line, start column, and optionally end line and end column. ```Java public List getSpanList() { return span_; } ``` -------------------------------- ### Get Span List (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.Location.html Retrieves a list of integers representing the span (start line, start column, end line, end column) for a SourceCodeInfo.Location. The span is packed for efficiency and uses zero-based indexing. ```Java public java.util.List getSpanList() ``` -------------------------------- ### Packing and Unpacking Any Messages in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Any.html Demonstrates how to pack a message into an Any instance and how to unpack it back into a specific message type. ```java import com.google.protobuf.Any; import com.google.protobuf.Message; // Packing a message Any anyMessage = Any.pack(myMessage); // Packing with a custom type URL prefix Any anyMessageWithPrefix = Any.pack(myMessage, "type.googleapis.com"); // Unpacking a message if (anyMessage.is(MyMessage.class)) { MyMessage unpacked = anyMessage.unpack(MyMessage.class); } ``` -------------------------------- ### Get Span Count - Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.LocationOrBuilder.html Retrieves the number of elements in the 'span' field, which typically represents location information (start line, start column, end line, end column). These are zero-based indices. ```protobuf repeated int32 span = 2 [packed = true]; ``` -------------------------------- ### Pre-sizing Buffer with proto.MarshalOptions in Go Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/go/size.md Demonstrates using proto.MarshalOptions to pre-calculate the size of a Protocol Buffer message before marshaling. This allows for pre-allocation of a buffer with sufficient capacity, potentially avoiding runtime allocations. It highlights the use of MarshalAppend for efficient marshaling into a pre-sized buffer and notes that the final buffer length might be less than its capacity. ```go opts := proto.MarshalOptions{ // Possibly avoid an extra proto.Size in Marshal itself (see docs): UseCachedSize: true, } // DO NOT SUBMIT without implementing this Optimization opportunity: // instead of allocating, grab a sufficiently-sized buffer from a pool. // Knowing the size of the buffer means we can discard // outliers from the pool to prevent uncontrolled // memory growth in long-running RPC services. buf := make([]byte, 0, opts.Size(m)) var err error buf, err = opts.MarshalAppend(buf, m) // does not allocate // Note that len(buf) might be less than cap(buf)! Read below: ``` -------------------------------- ### Define Service and Method Options in Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.descriptor.pb.md Illustrates the configuration of service and method options, including deprecation flags and reserved field ranges for internal frameworks. ```protobuf message ServiceOptions { optional bool deprecated = 33 [default = false]; repeated UninterpretedOption uninterpreted_option = 999; extensions 1000 to max; } message MethodOptions { optional bool deprecated = 33 [default = false]; repeated UninterpretedOption uninterpreted_option = 999; extensions 1000 to max; } ``` -------------------------------- ### UninterpretedOption.NamePart Builder Creation (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.UninterpretedOption.NamePart.html Provides examples of creating a builder for the UninterpretedOption.NamePart message. This includes static methods to get a new builder or a builder from a prototype, and a method to get a builder for a new message of the same type. ```Java static DescriptorProtos.UninterpretedOption.NamePart.Builder newBuilder(); static DescriptorProtos.UninterpretedOption.NamePart.Builder newBuilder(DescriptorProtos.UninterpretedOption.NamePart prototype); DescriptorProtos.UninterpretedOption.NamePart.Builder newBuilderForType(); ``` -------------------------------- ### Get Span List - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfo.Location.html Retrieves the complete list of integers representing the span, which defines the exact location within a source file. This includes start line, start column, and optionally end line and column. ```Java descriptorProtos.SourceCodeInfo.Location.getSpanList() ``` -------------------------------- ### Protocol Buffers Import Statement Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/edition-2024-spec.md Demonstrates the usage of import statements with 'public' and 'option' keywords. ```proto import public "other.proto"; import option "custom_option.proto"; ``` -------------------------------- ### Get Default EnumValueOptions Instance (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.EnumValueOptions.html Retrieves the default, immutable instance of EnumValueOptions. This is often used as a starting point or for comparison. ```java public static DescriptorProtos.EnumValueOptions getDefaultInstance() ``` -------------------------------- ### Defining and Using Option Targets Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/programming-guides/editions.md Illustrates how to use the 'targets' option to restrict where a field can be applied, showing valid and invalid usage examples. ```proto message MyOptions { string file_only_option = 1 [targets = TARGET_TYPE_FILE]; int32 message_and_enum_option = 2 [targets = TARGET_TYPE_MESSAGE, targets = TARGET_TYPE_ENUM]; } extend google.protobuf.FileOptions { MyOptions file_options = 50000; } extend google.protobuf.MessageOptions { MyOptions message_options = 50000; } extend google.protobuf.EnumOptions { MyOptions enum_options = 50000; } // OK: this field is allowed on file options option (file_options).file_only_option = "abc"; message MyMessage { // OK: this field is allowed on both message and enum options option (message_options).message_and_enum_option = 42; } enum MyEnum { MY_ENUM_UNSPECIFIED = 0; // Error: file_only_option cannot be set on an enum. option (enum_options).file_only_option = "xyz"; } ``` -------------------------------- ### Initialize TextFormatParseInfoTree Builder Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/TextFormatParseInfoTree.html Demonstrates how to instantiate a builder for the TextFormatParseInfoTree, which is the standard way to construct the tree structure. ```java import com.google.protobuf.TextFormatParseInfoTree; // Create a new builder instance TextFormatParseInfoTree.Builder builder = TextFormatParseInfoTree.builder(); ``` -------------------------------- ### Get List Iterator for DslList in Kotlin Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/kotlin/api-docs/protobuf-kotlin/com.google.protobuf.kotlin/-dsl-list/list-iterator.md Provides methods to obtain a ListIterator for the DslList. The first overload returns an iterator starting from the beginning of the list, while the second overload allows specifying a starting index. These are essential for traversing and modifying list elements. ```kotlin open override fun listIterator(): ListIterator open override fun listIterator(index: Int): ListIterator ``` -------------------------------- ### Get Default Timestamp Instance (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Timestamp.html Retrieves the default, immutable instance of the Timestamp message. This is often used as a starting point or for comparison. ```java public static Timestamp getDefaultInstance() ``` -------------------------------- ### Example Protocol Buffers Text Format File Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/protobuf/textformat-spec.md Demonstrates the syntax of a Protocol Buffer text format file, including message structure, nested messages, repeated fields, and string escapes. Supports shell-style line comments. ```textproto # This is an example of Protocol Buffer's text format. # Unlike .proto files, only shell-style line comments are supported. name: "John Smith" pet { kind: DOG name: "Fluffy" tail_wagginess: 0.65f } pet < kind: LIZARD name: "Lizzy" legs: 4 > string_value_with_escape: "valid \n escape" repeated_values: [ "one", "two", "three" ] ``` -------------------------------- ### Proto2 JSON Format Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/editions/features.md Shows a proto2 file before and after applying Prototiller with a JSON format feature setting. ```proto syntax = "proto2"; message Foo { // Warning only string bar = 1; string bar_ = 2; } ``` ```proto edition = "2024"; option features.json_format = LEGACY_BEST_EFFORT; message Foo { string bar = 1; string bar_ = 2; } ``` -------------------------------- ### Retrieve StringValue metadata Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/StringValue.Builder.html Examples of accessing metadata and field values from the StringValue.Builder. This includes getting the descriptor for the type or the current string value. ```java String value = builder.getValue(); ByteString bytes = builder.getValueBytes(); Descriptors.Descriptor descriptor = builder.getDescriptorForType(); boolean initialized = builder.isInitialized(); ``` -------------------------------- ### Implement a C++ Protoc Plugin Entry Point Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.plugin.md Demonstrates how to create a main function for a protoc plugin by instantiating a CodeGenerator and passing it to PluginMain. This function handles the communication between protoc and the generator. ```cpp int main(int argc, char* argv[]) { MyCodeGenerator generator; return google::protobuf::compiler::PluginMain(argc, argv, &generator); } ``` -------------------------------- ### Get Default Instance in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/UnknownFieldSet.Field.html Returns an empty, immutable instance of UnknownFieldSet.Field. This is useful for comparisons or as a starting point when no specific field data is present. ```java public static com.google.protobuf.UnknownFieldSet.Field getDefaultInstance() { return defaultInstance; } ``` -------------------------------- ### Get Default Instance of OneofDescriptorProto (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.OneofDescriptorProto.html Retrieves the default, immutable instance of OneofDescriptorProto. This is often used as a starting point or for comparison. It is a static method. ```java public static DescriptorProtos.OneofDescriptorProto getDefaultInstance() ``` -------------------------------- ### Pack and Unpack Any Messages Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Any.Builder.html Demonstrates how to pack a message into an Any container and subsequently unpack it back into the original message type. Examples are provided for C++, Java, Python, and Go. ```cpp Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } ``` ```java Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } ``` ```python foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ``` ```go foo := &pb.Foo{...} any, err := anypb.New(foo) if err != nil { ... } ... foo := &pb.Foo{} if err := any.UnmarshalTo(foo); err != nil { ... } ``` -------------------------------- ### Go: Limit Program Output Size with proto.Size Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/go/size.md Illustrates how to use proto.Size to enforce an upper bound on the size of Protocol Buffer messages before emitting them. This prevents overwhelming downstream systems that have size limitations. ```go func (*beamFn) ProcessElement(key string, value []byte, emit func(proto.Message)) { task := produceWorkTask(value) if proto.Size(task) > 500 * 1024 * 1024 { // Skip every work task over 500 MB to not overwhelm // the brittle downstream system. return } emit(task) } ``` -------------------------------- ### Get Default FloatValue Instance (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/FloatValue.html Retrieves the default instance of the FloatValue message. This is a pre-initialized, immutable instance that can be used directly or as a starting point for modifications. ```java public static FloatValue getDefaultInstance() ``` -------------------------------- ### Get Default Instance of Value in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Value.html Retrieves the default instance of the Value message. This is a pre-configured instance with no fields set, useful for starting message construction or as a reference. ```Java public static com.google.protobuf.Value getDefaultInstance() ``` -------------------------------- ### Defining and Using Option Targets Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/programming-guides/proto2.md Illustrates how to define custom options with specific targets (e.g., file, message, enum) and how protoc enforces these constraints. ```proto message MyOptions { optional string file_only_option = 1 [targets = TARGET_TYPE_FILE]; optional int32 message_and_enum_option = 2 [targets = TARGET_TYPE_MESSAGE, targets = TARGET_TYPE_ENUM]; } extend google.protobuf.FileOptions { optional MyOptions file_options = 50000; } extend google.protobuf.MessageOptions { optional MyOptions message_options = 50000; } extend google.protobuf.EnumOptions { optional MyOptions enum_options = 50000; } // OK: this field is allowed on file options option (file_options).file_only_option = "abc"; message MyMessage { // OK: this field is allowed on both message and enum options option (message_options).message_and_enum_option = 42; } enum MyEnum { MY_ENUM_UNSPECIFIED = 0; // Error: file_only_option cannot be set on an enum. option (enum_options).file_only_option = "xyz"; } ``` -------------------------------- ### Get Default Instance for UInt32Value in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/UInt32Value.html Provides a default instance of the UInt32Value message. This instance represents a message with no fields set and is used as a starting point or for comparison. ```Java public com.google.protobuf.UInt32Value getDefaultInstanceForType() Description copied from interface: getDefaultInstanceForType Get an instance of the type with no fields set. Because no fields are set, all getters for singular fields will return default values and repeated fields will appear empty. This may or may not be a singleton. This differs from the getDefaultInstance() method of generated message classes in that this method is an abstract method of the MessageLite interface whereas getDefaultInstance() is a static method of a specific class. They return the same thing. Specified by: getDefaultInstanceForType in interface com.google.protobuf.MessageLiteOrBuilder Specified by: getDefaultInstanceForType in interface com.google.protobuf.MessageOrBuilder ``` -------------------------------- ### C++ Protocol Buffers: CallMethod Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.service.md Demonstrates how to use CallMethod with Service, including obtaining request and response prototypes using GetRequestPrototype and GetResponsePrototype. It shows parsing input, creating message objects, and initiating the RPC call. ```cpp 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); ``` -------------------------------- ### Get Default Instance of OneofOptions (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.OneofOptions.html Provides a static method to retrieve the default instance of DescriptorProtos.OneofOptions. This is a pre-configured, immutable instance that can be used as a starting point or for comparison. ```java public static DescriptorProtos.OneofOptions getDefaultInstance() ``` -------------------------------- ### Constructing Protobuf Messages with Builders Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/go/opaque-migration-manual.md Demonstrates the transition from direct struct initialization in the Open Struct API to using the builder pattern in the Opaque API. Builders are recommended for better readability in most use cases. ```go // Open Struct API (old) m := &pb.Foo{ Uint32: proto.Uint32(5), Bytes: []byte("hello"), } // Opaque API (new) m := pb.Foo_builder{ Uint32: proto.Uint32(5), Bytes: []byte("hello"), }.Build() ``` -------------------------------- ### Get Default Instance of MethodDescriptorProto Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.MethodDescriptorProto.html Retrieves the default instance of MethodDescriptorProto. This is a singleton instance representing an empty or default state of the message, useful for comparisons or as a starting point. ```Java public static DescriptorProtos.MethodDescriptorProto getDefaultInstance() ``` -------------------------------- ### Register a Protoc Plugin via Command Line Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.plugin.md Shows the command-line syntax for registering a custom plugin with protoc. This allows the compiler to locate and execute the plugin binary during the code generation process. ```bash protoc --plugin=protoc-gen-NAME=path/to/mybinary --NAME_out=OUT_DIR # Windows example protoc --plugin=protoc-gen-NAME=path/to/mybinary.exe --NAME_out=OUT_DIR ``` -------------------------------- ### Proto2 Syntax Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/editions/overview.md This snippet demonstrates the syntax of a Protocol Buffers file using proto2. It includes examples of optional, required, and repeated fields, as well as enum definitions and reserved fields. Note the explicit presence for optional fields and the 'required' keyword. ```proto syntax = "proto2"; package com.example; message Player { // in proto2, optional fields have explicit presence optional string name = 1 [default = "N/A"]; // proto2 still supports the problematic "required" field rule required int32 id = 2; // in proto2 this is not packed by default repeated int32 scores = 3; enum Handed { HANDED_UNSPECIFIED = 0; HANDED_LEFT = 1; HANDED_RIGHT = 2; HANDED_AMBIDEXTROUS = 3; } // in proto2 enums are closed optional Handed handed = 4; reserved "gender"; } ``` -------------------------------- ### Get Default Instance for UInt64Value in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/UInt64Value.html Provides a default, empty instance of the UInt64Value message. This instance represents a message with no fields set, useful for initialization or as a starting point. It adheres to the MessageLiteOrBuilder interface. ```Java public UInt64Value getDefaultInstanceForType() { return defaultInstance; } ``` -------------------------------- ### Get Default Instance of NamePart in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.UninterpretedOption.NamePart.html Retrieves the default instance of DescriptorProtos.UninterpretedOption.NamePart. This instance represents a NamePart with no fields set and is often used as a starting point for building new instances or for default comparisons. ```Java public static DescriptorProtos.UninterpretedOption.NamePart getDefaultInstance() ``` -------------------------------- ### Define a Service in Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/cpp-generated.md Example of a service definition in a .proto file. ```proto service Foo { rpc Bar(FooRequest) returns(FooResponse); } ``` -------------------------------- ### Constructing MethodOptions Builders Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.MethodOptions.html Shows how to create new instances of MethodOptions.Builder, either from scratch or by using an existing prototype for cloning. ```java DescriptorProtos.MethodOptions.Builder builder = DescriptorProtos.MethodOptions.newBuilder(); DescriptorProtos.MethodOptions.Builder cloneBuilder = DescriptorProtos.MethodOptions.newBuilder(prototype); DescriptorProtos.MethodOptions.Builder typeBuilder = methodOptions.newBuilderForType(); ``` -------------------------------- ### Manage API Methods in Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Api.Builder.html Provides examples of how to access and manage the methods associated with an API definition using the Api.Builder. This includes getting counts, lists, and individual method builders or or builders. ```java int methodCount = apiBuilder.getMethodsCount(); List methodList = apiBuilder.getMethodsList(); Method.Builder methodBuilder = apiBuilder.getMethodsBuilder(index); List methodOrBuilderList = apiBuilder.getMethodsOrBuilderList(); ``` -------------------------------- ### Get Default Instance and Parser for FileDescriptorSet (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.FileDescriptorSet.html Retrieves the default, immutable instance of FileDescriptorSet and its associated parser. The default instance is often used as a starting point or for comparison. The parser is used for deserializing the message. ```java public static DescriptorProtos.FileDescriptorSet getDefaultInstance() ``` ```java public static Parser parser() ``` ```java public Parser getParserForType() ``` -------------------------------- ### Initialize and Use AnnotationProtoCollector Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.io.printer.md Demonstrates how to instantiate the AnnotationProtoCollector with a target protocol buffer and add an annotation to it. This requires an existing AnnotationProto instance to store the metadata. ```cpp #include // Assuming annotation_proto is a pointer to your target protocol buffer google::protobuf::io::AnnotationProtoCollector collector(annotation_proto); // Adding an annotation std::vector path = {1, 2, 3}; collector.AddAnnotation(0, 10, "source.proto", path); ``` -------------------------------- ### Get Reserved Enum Range (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.EnumDescriptorProto.html Retrieves a specific reserved numeric range by its index. This method returns an EnumReservedRange object, detailing the start and end of a reserved numerical value. It is part of the EnumDescriptorProto class. ```java public com.google.protobuf.DescriptorProtos.EnumDescriptorProto.EnumReservedRange getReservedRange(int index) ``` -------------------------------- ### Pack and Unpack Messages using Any Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/csharp/api-docs/class/google/protobuf/well-known-types/any.html Demonstrates how to pack a message into an Any container and subsequently unpack it back into the original message type across different programming languages. ```cpp Foo foo = ...; Any any; any.PackFrom(foo); ... if (any.UnpackTo(&foo)) { ... } ``` ```java Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } ``` ```python foo = Foo(...) any = Any() any.Pack(foo) ... if any.Is(Foo.DESCRIPTOR): any.Unpack(foo) ... ``` -------------------------------- ### Protocol Buffers: Getting Default Instance Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/BoolValue.Builder.html The `getDefaultInstanceForType()` method returns an immutable instance of the message representing its default state. This is useful for comparisons or as a starting point for building new messages. It is part of the `MessageLiteOrBuilder` interface. ```java public BoolValue getDefaultInstanceForType() { // Description copied from interface: MessageLiteOrBuilder // ... } ``` -------------------------------- ### Protoc C# Compiler Options Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/csharp/csharp-generated.md These examples demonstrate various C#-specific options for the protocol buffer compiler, controlled via the `--csharp_opt` flag. Options include setting the file extension, defining a base namespace for directory hierarchy, and controlling access modifiers or serializability. ```shell protoc --proto_path=src --csharp_out=build/gen --csharp_opt=file_extension=.g.cs,base_namespace=Example,internal_access src/foo.proto ``` -------------------------------- ### Setting Extension Range Boundaries and Unknown Fields with Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.DescriptorProto.ExtensionRange.Builder.html Provides examples of setting the start and end boundaries of an extension range, as well as managing unknown fields using the DescriptorProtos.DescriptorProto.ExtensionRange.Builder. The 'setEnd' method is exclusive. ```java builder.setStart(value); builder.setEnd(value); builder.mergeUnknownFields(unknownFields); builder.setUnknownFields(unknownFields); ``` -------------------------------- ### Run Protocol Compiler (C++) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.command_line_interface.md Executes the Protocol Compiler with the provided command-line arguments. It takes the argument count and an array of C-style strings representing the arguments. This is the main entry point for running the compiler. ```cpp int CommandLineInterface::Run(int argc, const char *const argv) ``` -------------------------------- ### Protobuf Group Syntax Example Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/programming-guides/encoding.md Demonstrates the Protoscope syntax for defining groups in Protocol Buffers. Groups are a deprecated feature used for structuring data within messages, delimited by special start and end tags. ```proto 8:SGROUP 1: 2 3: {"foo"} 8:EGROUP ``` ```proto 8: !{ 1: 2 3: {"foo"} } ``` -------------------------------- ### Create Protobuf Structs using Java Utility Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/util/Structs.html Demonstrates how to use the Structs.of() static methods to create a google.protobuf.Struct instance from one or more key-value pairs. Note that providing duplicate keys to these methods results in undefined behavior. ```java import com.google.protobuf.Struct; import com.google.protobuf.Value; import com.google.protobuf.util.Structs; // Creating a Struct with one key-value pair Struct struct1 = Structs.of("key1", Value.newBuilder().setStringValue("value1").build()); // Creating a Struct with two key-value pairs Struct struct2 = Structs.of( "key1", Value.newBuilder().setNumberValue(1.0).build(), "key2", Value.newBuilder().setStringValue("value2").build() ); ``` -------------------------------- ### Get Default Instance for Int64Value - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Int64Value.html Obtains the default instance of the Int64Value message. This instance represents a message with no fields set, useful for default values or as a starting point for building new messages. It adheres to the MessageLiteOrBuilder interface. ```java public Int64Value getDefaultInstanceForType() Description copied from interface: MessageLiteOrBuilder Get an instance of the type with no fields set. Because no fields are set, all getters for singular fields will return default values and repeated fields will appear empty. This may or may not be a singleton. This differs from the getDefaultInstance() method of generated message classes in that this method is an abstract method of the MessageLite interface whereas getDefaultInstance() is a static method of a specific class. They return the same thing. Specified by: getDefaultInstanceForType in interface MessageLiteOrBuilder Specified by: getDefaultInstanceForType in interface MessageOrBuilder ``` -------------------------------- ### Check and Get Begin Offset (Java) Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.GeneratedCodeInfo.AnnotationOrBuilder.html Provides methods to check if the 'begin' field is set and to retrieve its integer value. The 'begin' field represents the starting offset in bytes within the generated code that corresponds to the identified object. ```java boolean hasBegin() Identifies the starting offset in bytes in the generated code that relates to the identified object. Returns: Whether the begin field is set. ``` ```java int getBegin() Identifies the starting offset in bytes in the generated code that relates to the identified object. Returns: The begin. ``` -------------------------------- ### Define Protobuf Editions Syntax Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/editions/overview.md Example of a Protobuf file using the 2024 edition syntax. It demonstrates setting global options and field-level features for presence, encoding, and enum behavior. ```proto edition = "2024"; package com.example; option features.utf8_validation = NONE; option features.enforce_naming_style = STYLE_LEGACY; option features.default_symbol_visibility = EXPORT_ALL; option features.(pb.cpp).string_type = STRING; message Player { string name = 1 [default = "N/A"]; int32 id = 2 [features.field_presence = LEGACY_REQUIRED]; repeated int32 scores = 3 [features.repeated_field_encoding = EXPANDED]; export enum Handed { option features.enum_type = CLOSED; HANDED_UNSPECIFIED = 0; HANDED_LEFT = 1; HANDED_RIGHT = 2; HANDED_AMBIDEXTROUS = 3; } Handed handed = 4; reserved gender; } ``` -------------------------------- ### Example of Protoc Command with Custom Generator Parameters Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.compiler.command_line_interface.md Demonstrates how to invoke the Protocol Compiler with a custom code generator, specifying parameters through both the main output flag and an optional parameter flag. The parameters are combined and passed to the generator. ```bash protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz ``` -------------------------------- ### Get Default Instance for Enum Type - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/Enum.html Provides a default instance of the Enum type with no fields set. This is useful for creating messages with default values or as a starting point for building new messages. It is specified by the MessageLiteOrBuilder and MessageOrBuilder interfaces. ```Java public Enum getDefaultInstanceForType() ``` -------------------------------- ### Get Type Name Field in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.FieldDescriptorProto.html This Java method retrieves the name of the type for message and enum fields from a FieldDescriptorProto. If the name starts with a '.', it's fully-qualified; otherwise, C++-like scoping rules apply. This method is part of the DescriptorProtos.FieldDescriptorProtoOrBuilder interface. ```Java public java.lang.String getTypeName() { java.lang.Object ref = typeName_; if (ref instanceof java.lang.String) { return ((java.lang.String) ref); } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (com.google.protobuf.Internal.isValidUtf8(bs)) { typeName_ = s; } return s; } } ``` -------------------------------- ### Handling Any Fields in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/java-generated.md Demonstrates how to define an Any field in a proto file and the corresponding Java methods for packing and unpacking messages. These methods allow for dynamic type handling within a protobuf message. ```proto import "google/protobuf/any.proto"; message ErrorStatus { string message = 1; google.protobuf.Any details = 2; } ``` ```java class Any { public static Any pack(Message message); public static Any pack(Message message, String typeUrlPrefix); public boolean is(class clazz); public boolean isSameTypeAs(Message message); public T unpackSameTypeAs(T message) throws InvalidProtocolBufferException; public T unpack(class clazz) throws InvalidProtocolBufferException; } ``` -------------------------------- ### Check and Get Type Name - Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.FieldDescriptorProto.Builder.html Offers methods to determine if the 'type_name' field is set and to retrieve its string value. The 'type_name' represents the name of a message or enum type. It can be fully-qualified (starting with '.') or relative, using C++-like scoping rules for resolution. ```java public boolean hasTypeName() Returns: Whether the typeName field is set. public java.lang.String getTypeName() Returns: The typeName. ``` -------------------------------- ### Message Construction and Parsing in Protocol Buffers Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.MessageOptions.html Demonstrates how to derive a new message builder from an existing instance and how to retrieve parsers for message types. ```java DescriptorProtos.MessageOptions.Builder builder = message.toBuilder(); Parser parser = DescriptorProtos.MessageOptions.parser(); Parser instanceParser = message.getParserForType(); DescriptorProtos.MessageOptions defaultInstance = DescriptorProtos.MessageOptions.getDefaultInstance(); ``` -------------------------------- ### Initialize CodedInputStream from ZeroCopyInputStream Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/cpp/api-docs/google.protobuf.io.coded_stream.md Demonstrates how to instantiate a CodedInputStream by passing a pointer to an existing ZeroCopyInputStream. This allows the stream to read and decode data from the underlying source. ```cpp #include // Assuming 'input' is a pointer to a ZeroCopyInputStream google::protobuf::io::CodedInputStream coded_input(input); ``` -------------------------------- ### GET /message/field/count Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/GeneratedMessage.ExtendableMessage.html Gets the number of elements in a repeated field. ```APIDOC ## GET /message/field/count ### Description Returns the count of elements for a repeated field. ### Method GET ### Endpoint /message/field/count ### Parameters #### Query Parameters - **field** (String) - Required - The repeated field descriptor. ### Response #### Success Response (200) - **count** (int) - The number of elements in the field. #### Response Example { "count": 5 } ``` -------------------------------- ### Example Protocol Buffers Field Definition with Location Mapping Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/java/api-docs/com/google/protobuf/DescriptorProtos.SourceCodeInfoOrBuilder.html This example illustrates a simple Protocol Buffers field definition ('optional string foo = 1;') and maps specific parts of the definition (label, type, name, number) to their corresponding source code locations using spans and paths. ```protobuf optional string foo = 1; ``` -------------------------------- ### Pack and Unpack Any Message in Java Source: https://github.com/protocolbuffers/protocolbuffers.github.io/blob/main/content/reference/php/api-docs/Google/Protobuf/Any.html Shows how to pack a Foo message into an Any object and then unpack it. Includes checks for message type before unpacking. ```java Foo foo = ...; Any any = Any.pack(foo); ... if (any.is(Foo.class)) { foo = any.unpack(Foo.class); } // or ... if (any.isSameTypeAs(Foo.getDefaultInstance())) { foo = any.unpack(Foo.getDefaultInstance()); } ```