Repository: google/protobuf.dart Branch: master Commit: 84079e8b8531 Files: 380 Total size: 1.9 MB Directory structure: gitextract_2g3fdimv/ ├── .github/ │ ├── dependabot.yml │ └── workflows/ │ ├── benchmark.yaml │ ├── post_summaries.yaml │ ├── protobuf.yaml │ ├── protoc_plugin.yaml │ └── publish.yaml ├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── analysis_options.yaml ├── benchmarks/ │ ├── .gitignore │ ├── README.md │ ├── analysis_options.yaml │ ├── bin/ │ │ ├── binary_decode_packed.dart │ │ ├── deep_copy.dart │ │ ├── from_binary.dart │ │ ├── from_json_string.dart │ │ ├── from_proto3_json_object.dart │ │ ├── from_proto3_json_string.dart │ │ ├── hash_code.dart │ │ ├── query_decode_binary.dart │ │ ├── query_decode_json.dart │ │ ├── query_encode_binary.dart │ │ ├── query_encode_json.dart │ │ ├── query_set_nested_value.dart │ │ ├── repeated_field.dart │ │ ├── to_binary.dart │ │ ├── to_json_string.dart │ │ ├── to_proto3_json_object.dart │ │ └── to_proto3_json_string.dart │ ├── datasets/ │ │ ├── google_message1_proto2.pb │ │ ├── google_message1_proto3.pb │ │ ├── google_message2.pb │ │ └── query_benchmark.pb │ ├── lib/ │ │ ├── benchmark_base.dart │ │ ├── readfile.dart │ │ ├── readfile_js.dart │ │ └── readfile_vm.dart │ ├── protoc_version │ ├── protos/ │ │ ├── google_message1_proto2.proto │ │ ├── google_message1_proto3.proto │ │ ├── google_message2.proto │ │ ├── packed_fields.proto │ │ └── query_benchmark/ │ │ ├── f0.proto │ │ ├── f1.proto │ │ ├── f10.proto │ │ ├── f11.proto │ │ ├── f12.proto │ │ ├── f13.proto │ │ ├── f14.proto │ │ ├── f15.proto │ │ ├── f16.proto │ │ ├── f17.proto │ │ ├── f18.proto │ │ ├── f19.proto │ │ ├── f2.proto │ │ ├── f20.proto │ │ ├── f21.proto │ │ ├── f22.proto │ │ ├── f23.proto │ │ ├── f24.proto │ │ ├── f25.proto │ │ ├── f26.proto │ │ ├── f27.proto │ │ ├── f28.proto │ │ ├── f3.proto │ │ ├── f4.proto │ │ ├── f5.proto │ │ ├── f6.proto │ │ ├── f7.proto │ │ ├── f8.proto │ │ └── f9.proto │ ├── pubspec.yaml │ └── tool/ │ ├── compile_benchmarks.dart │ ├── compile_protos.sh │ └── run_protoc_plugin.sh ├── protobuf/ │ ├── CHANGELOG.md │ ├── LICENSE │ ├── README.md │ ├── analysis_options.yaml │ ├── build_wkts.sh │ ├── google/ │ │ └── protobuf/ │ │ ├── any.proto │ │ ├── api.proto │ │ ├── duration.proto │ │ ├── empty.proto │ │ ├── field_mask.proto │ │ ├── source_context.proto │ │ ├── struct.proto │ │ ├── timestamp.proto │ │ ├── type.proto │ │ └── wrappers.proto │ ├── lib/ │ │ ├── meta.dart │ │ ├── protobuf.dart │ │ ├── src/ │ │ │ └── protobuf/ │ │ │ ├── annotations.dart │ │ │ ├── builder_info.dart │ │ │ ├── coded_buffer.dart │ │ │ ├── coded_buffer_reader.dart │ │ │ ├── coded_buffer_writer.dart │ │ │ ├── consts.dart │ │ │ ├── exceptions.dart │ │ │ ├── extension.dart │ │ │ ├── extension_field_set.dart │ │ │ ├── extension_registry.dart │ │ │ ├── field_error.dart │ │ │ ├── field_info.dart │ │ │ ├── field_set.dart │ │ │ ├── field_type.dart │ │ │ ├── generated_message.dart │ │ │ ├── generated_service.dart │ │ │ ├── internal.dart │ │ │ ├── json/ │ │ │ │ ├── json.dart │ │ │ │ ├── json_vm.dart │ │ │ │ └── json_web.dart │ │ │ ├── json_parsing_context.dart │ │ │ ├── message_set.dart │ │ │ ├── mixins/ │ │ │ │ ├── map_mixin.dart │ │ │ │ └── well_known.dart │ │ │ ├── pb_list.dart │ │ │ ├── pb_map.dart │ │ │ ├── permissive_compare.dart │ │ │ ├── proto3_json.dart │ │ │ ├── protobuf_enum.dart │ │ │ ├── rpc_client.dart │ │ │ ├── type_registry.dart │ │ │ ├── unknown_field_set.dart │ │ │ ├── unpack.dart │ │ │ ├── utils.dart │ │ │ └── wire_format.dart │ │ └── well_known_types/ │ │ └── google/ │ │ └── protobuf/ │ │ ├── any.pb.dart │ │ ├── any.pbjson.dart │ │ ├── api.pb.dart │ │ ├── api.pbjson.dart │ │ ├── duration.pb.dart │ │ ├── duration.pbjson.dart │ │ ├── empty.pb.dart │ │ ├── empty.pbjson.dart │ │ ├── field_mask.pb.dart │ │ ├── field_mask.pbjson.dart │ │ ├── source_context.pb.dart │ │ ├── source_context.pbjson.dart │ │ ├── struct.pb.dart │ │ ├── struct.pbenum.dart │ │ ├── struct.pbjson.dart │ │ ├── timestamp.pb.dart │ │ ├── timestamp.pbjson.dart │ │ ├── type.pb.dart │ │ ├── type.pbenum.dart │ │ ├── type.pbjson.dart │ │ ├── wrappers.pb.dart │ │ └── wrappers.pbjson.dart │ ├── pubspec.yaml │ └── test/ │ ├── builder_info_test.dart │ ├── codec_test.dart │ ├── coded_buffer_reader_test.dart │ ├── dummy_field_test.dart │ ├── json_test.dart │ ├── json_vm_test.dart │ ├── list_equality_test.dart │ ├── list_test.dart │ ├── map_mixin_test.dart │ ├── message_test.dart │ ├── mock_util.dart │ ├── permissive_compare_test.dart │ ├── readonly_message_test.dart │ └── test_util.dart ├── protoc_plugin/ │ ├── .gitignore │ ├── CHANGELOG.md │ ├── LICENSE │ ├── Makefile │ ├── README.md │ ├── analysis_options.yaml │ ├── bin/ │ │ ├── protoc-gen-dart │ │ ├── protoc-gen-dart-debug │ │ ├── protoc-gen-dart.bat │ │ ├── protoc_plugin.dart │ │ └── protoc_plugin_bazel.dart │ ├── lib/ │ │ ├── bazel.dart │ │ ├── const_generator.dart │ │ ├── indenting_writer.dart │ │ ├── mixins.dart │ │ ├── names.dart │ │ ├── protoc.dart │ │ ├── src/ │ │ │ ├── base_type.dart │ │ │ ├── client_generator.dart │ │ │ ├── code_generator.dart │ │ │ ├── enum_generator.dart │ │ │ ├── extension_generator.dart │ │ │ ├── file_generator.dart │ │ │ ├── formatter.dart │ │ │ ├── gen/ │ │ │ │ ├── dart_options.pb.dart │ │ │ │ ├── dart_options.pbenum.dart │ │ │ │ └── google/ │ │ │ │ ├── api/ │ │ │ │ │ ├── client.pb.dart │ │ │ │ │ ├── client.pbenum.dart │ │ │ │ │ ├── http.pb.dart │ │ │ │ │ ├── http.pbenum.dart │ │ │ │ │ ├── launch_stage.pb.dart │ │ │ │ │ ├── launch_stage.pbenum.dart │ │ │ │ │ ├── routing.pb.dart │ │ │ │ │ └── routing.pbenum.dart │ │ │ │ └── protobuf/ │ │ │ │ ├── compiler/ │ │ │ │ │ ├── plugin.pb.dart │ │ │ │ │ └── plugin.pbenum.dart │ │ │ │ ├── dart_edition_defaults.pb.dart │ │ │ │ ├── descriptor.pb.dart │ │ │ │ ├── descriptor.pbenum.dart │ │ │ │ ├── unittest_features.pb.dart │ │ │ │ └── unittest_features.pbenum.dart │ │ │ ├── grpc_generator.dart │ │ │ ├── linker.dart │ │ │ ├── message_generator.dart │ │ │ ├── options.dart │ │ │ ├── output_config.dart │ │ │ ├── paths.dart │ │ │ ├── protobuf_field.dart │ │ │ ├── service_generator.dart │ │ │ ├── shared.dart │ │ │ └── well_known_types.dart │ │ ├── string_escape.dart │ │ └── testing/ │ │ └── mixins.dart │ ├── protos/ │ │ ├── README.md │ │ ├── dart_options.proto │ │ └── google/ │ │ ├── api/ │ │ │ ├── client.proto │ │ │ ├── http.proto │ │ │ ├── launch_stage.proto │ │ │ └── routing.proto │ │ └── protobuf/ │ │ ├── compiler/ │ │ │ └── plugin.proto │ │ ├── descriptor.proto │ │ └── unittest_features.proto │ ├── pubspec.yaml │ ├── test/ │ │ ├── any_test.dart │ │ ├── bazel_test.dart │ │ ├── client_generator_test.dart │ │ ├── coded_buffer_test.dart │ │ ├── const_generator_test.dart │ │ ├── constructor_args_test.dart │ │ ├── default_value_escape_test.dart │ │ ├── deprecations_test.dart │ │ ├── descriptor_test.dart │ │ ├── doc_comments_test.dart │ │ ├── duration_test.dart │ │ ├── enum_generator_test.dart │ │ ├── extension_generator_test.dart │ │ ├── extension_test.dart │ │ ├── extension_unknown_interaction_test.dart │ │ ├── feature_set_defaults_test.dart │ │ ├── file_generator_test.dart │ │ ├── freeze_test.dart │ │ ├── generated_message_test.dart │ │ ├── goldens/ │ │ │ ├── client.pb.dart │ │ │ ├── deprecations.pb.dart │ │ │ ├── deprecations.pbenum.dart │ │ │ ├── doc_comments.pb.dart │ │ │ ├── doc_comments.pbenum.dart │ │ │ ├── enum.pbenum.dart │ │ │ ├── enum.pbenum.dart.meta │ │ │ ├── extension.pb.dart │ │ │ ├── extension.pb.dart.meta │ │ │ ├── grpc_service.pb.dart │ │ │ ├── grpc_service.pbgrpc.~dart │ │ │ ├── header_in_package.pb.dart │ │ │ ├── header_with_fixnum.pb.dart │ │ │ ├── imports.pb.dart │ │ │ ├── imports.pbjson.dart │ │ │ ├── int64.pb.dart │ │ │ ├── messageGenerator.pb.dart │ │ │ ├── messageGenerator.pb.dart.meta │ │ │ ├── messageGeneratorEnums.pb.dart │ │ │ ├── messageGeneratorEnums.pb.dart.meta │ │ │ ├── oneMessage.pb.dart │ │ │ ├── oneMessage.pb.dart.meta │ │ │ ├── oneMessage.pbjson.dart │ │ │ ├── service.pb.dart │ │ │ ├── service.pbserver.dart │ │ │ ├── serviceGenerator.pb.dart │ │ │ ├── serviceGenerator.pbjson.dart │ │ │ ├── topLevelEnum.pb.dart │ │ │ ├── topLevelEnum.pb.dart.meta │ │ │ ├── topLevelEnum.pbenum.dart │ │ │ ├── topLevelEnum.pbenum.dart.meta │ │ │ └── topLevelEnum.pbjson.dart │ │ ├── hash_code_test.dart │ │ ├── high_tagnumber_test.dart │ │ ├── import_option_test.dart │ │ ├── import_public_test.dart │ │ ├── import_test.dart │ │ ├── indenting_writer_test.dart │ │ ├── json_test.dart │ │ ├── leading_underscores_test.dart │ │ ├── list_iterator_args_test.dart │ │ ├── map_field_test.dart │ │ ├── map_test.dart │ │ ├── merge_test.dart │ │ ├── message_generator_test.dart │ │ ├── message_set_test.dart │ │ ├── message_test.dart │ │ ├── mixin_test.dart │ │ ├── names_test.dart │ │ ├── omit_enum_names_test.dart │ │ ├── omit_field_names_test.dart │ │ ├── omit_message_names_test.dart │ │ ├── oneof_test.dart │ │ ├── proto3_json_test.dart │ │ ├── proto3_optional_test.dart │ │ ├── protoc_options_test.dart │ │ ├── protos/ │ │ │ ├── ExtensionEnumNameConflict.proto │ │ │ ├── ExtensionNameConflict.proto │ │ │ ├── _leading_underscores.proto │ │ │ ├── custom_option.proto │ │ │ ├── custom_option_unlinked.proto │ │ │ ├── dart_name.proto │ │ │ ├── default_value_escape.proto │ │ │ ├── deprecations.proto │ │ │ ├── doc_comments.proto │ │ │ ├── duplicate_names_import.proto │ │ │ ├── entity.proto │ │ │ ├── enum_extension.proto │ │ │ ├── enum_name.proto │ │ │ ├── enum_test.proto │ │ │ ├── enums.proto │ │ │ ├── extend_unittest.proto │ │ │ ├── foo.proto │ │ │ ├── google/ │ │ │ │ └── protobuf/ │ │ │ │ ├── unittest.proto │ │ │ │ ├── unittest_import.proto │ │ │ │ ├── unittest_import_public.proto │ │ │ │ ├── unittest_optimize_for.proto │ │ │ │ └── unittest_well_known_types.proto │ │ │ ├── high_tagnumber.proto │ │ │ ├── import_clash.proto │ │ │ ├── import_option.proto │ │ │ ├── import_public.proto │ │ │ ├── json_name.proto │ │ │ ├── map_api.proto │ │ │ ├── map_api2.proto │ │ │ ├── map_enum_value.proto │ │ │ ├── map_field.proto │ │ │ ├── message_set.proto │ │ │ ├── mixins.proto │ │ │ ├── multiple_files_test.proto │ │ │ ├── nested_any.proto │ │ │ ├── nested_extension.proto │ │ │ ├── nested_message.proto │ │ │ ├── non_nested_extension.proto │ │ │ ├── oneof.proto │ │ │ ├── package1.proto │ │ │ ├── package2.proto │ │ │ ├── package3.proto │ │ │ ├── proto2_repeated.proto │ │ │ ├── proto3_optional.proto │ │ │ ├── proto3_repeated.proto │ │ │ ├── reserved_names.proto │ │ │ ├── reserved_names_extension.proto │ │ │ ├── reserved_names_message.proto │ │ │ ├── service.proto │ │ │ ├── service2.proto │ │ │ ├── service3.proto │ │ │ ├── toplevel.proto │ │ │ ├── toplevel_import.proto │ │ │ └── using_any.proto │ │ ├── repeated_encoding_test.dart │ │ ├── repeated_field_test.dart │ │ ├── reserved_names_test.dart │ │ ├── send_protos_via_sendports_test.dart │ │ ├── service_generator_test.dart │ │ ├── service_test.dart │ │ ├── shared_test.dart │ │ ├── src/ │ │ │ ├── golden_file.dart │ │ │ ├── mirror_util.dart │ │ │ ├── service_util.dart │ │ │ ├── test_features.dart │ │ │ └── test_util.dart │ │ ├── timestamp_test.dart │ │ ├── to_builder_test.dart │ │ ├── unknown_enums_test.dart │ │ ├── unknown_field_set_test.dart │ │ ├── validate_fail_test.dart │ │ └── wire_format_test.dart │ └── tool/ │ └── update_protos.dart ├── pubspec.yaml └── tool/ ├── generate.sh └── setup.sh ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/dependabot.yml ================================================ # Dependabot configuration file. # See https://docs.github.com/en/code-security/dependabot/dependabot-version-updates version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "monthly" ================================================ FILE: .github/workflows/benchmark.yaml ================================================ name: benchmarks permissions: read-all on: pull_request: push: branches: [master] schedule: - cron: "0 0 * * 0" # weekly defaults: run: working-directory: benchmarks jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: sdk: [dev] steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - uses: dart-lang/setup-dart@65eb853c7ba17dde3be364c3d2858773e7144260 with: sdk: ${{matrix.sdk}} - run: ../tool/setup.sh - run: dart pub get - run: ./tool/compile_protos.sh - run: dart analyze --fatal-infos - run: dart format --output=none --set-exit-if-changed . if: ${{ matrix.sdk == 'dev' }} - run: dart tool/compile_benchmarks.dart ================================================ FILE: .github/workflows/post_summaries.yaml ================================================ name: Comment on the pull request on: # Trigger this workflow after the Publish workflow completes. This workflow # will have permissions to do things like create comments on the PR, even if # the original workflow couldn't. workflow_run: workflows: - Publish types: - completed jobs: upload: uses: dart-lang/ecosystem/.github/workflows/post_summaries.yaml@main permissions: pull-requests: write ================================================ FILE: .github/workflows/protobuf.yaml ================================================ name: protobuf permissions: read-all on: pull_request: push: branches: [master] schedule: - cron: "0 0 * * 0" # weekly defaults: run: working-directory: protobuf jobs: build: strategy: fail-fast: false matrix: sdk: [stable, dev] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - uses: dart-lang/setup-dart@65eb853c7ba17dde3be364c3d2858773e7144260 with: sdk: ${{matrix.sdk}} - run: ../tool/setup.sh - run: dart pub get - run: dart analyze --fatal-infos - run: dart format --output=none --set-exit-if-changed . if: ${{ matrix.sdk == 'dev' }} - run: dart test - run: dart test -p chrome -c dart2js - run: dart test -p chrome -c dart2wasm ================================================ FILE: .github/workflows/protoc_plugin.yaml ================================================ name: protoc_plugin permissions: read-all on: pull_request: push: branches: [master] schedule: - cron: "0 0 * * 0" # weekly defaults: run: working-directory: protoc_plugin jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: sdk: [stable, dev] steps: - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 - uses: dart-lang/setup-dart@65eb853c7ba17dde3be364c3d2858773e7144260 with: sdk: ${{matrix.sdk}} - run: ../tool/setup.sh - run: dart pub get - run: make protos - run: dart analyze --fatal-infos - run: dart format --output=none --set-exit-if-changed lib if: ${{ matrix.sdk == 'dev' }} - run: dart test - run: dart test -p chrome -c dart2js - run: dart test -p chrome -c dart2wasm ================================================ FILE: .github/workflows/publish.yaml ================================================ # A CI configuration to auto-publish pub packages. name: Publish on: pull_request: branches: [master] push: tags: ['[A-z]+-v[0-9]+.[0-9]+.[0-9]+*'] jobs: publish: if: ${{ github.repository_owner == 'google' }} uses: dart-lang/ecosystem/.github/workflows/publish.yaml@main permissions: id-token: write pull-requests: write with: write-comments: false ================================================ FILE: .gitignore ================================================ .dart_tool/ .pub build/ pubspec.lock doc/ # `dart compile exe` outputs *.exe # `dart compile js` outputs *.js *.js.deps *.js.map # `dart compile wasm` outputs *.wasm *.mjs ================================================ FILE: AUTHORS ================================================ # Below is a list of people and organizations that have contributed # to the Dart project. Names should be added to the list like so: # # Name/Organization Google Inc. ================================================ FILE: LICENSE ================================================ Copyright 2013, the Dart project authors. 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 LLC 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. ================================================ FILE: README.md ================================================ ## Protobuf support for Dart [Protocol Buffers](https://developers.google.com/protocol-buffers) (protobuf) are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data. This repository is home to packages related to [protobuf support for Dart](https://pub.dev/documentation/protobuf/latest/). | Package | Description | Published Version | | --- | --- | --- | | [protobuf](protobuf/) | Runtime library for protocol buffers support. | [![pub package](https://img.shields.io/pub/v/protobuf.svg)](https://pub.dev/packages/protobuf) | | [protoc_plugin](protoc_plugin/) | A protobuf protoc compiler plugin used to generate Dart code. | [![pub package](https://img.shields.io/pub/v/protoc_plugin.svg)](https://pub.dev/packages/protoc_plugin) | | [benchmarks](benchmarks/) | Benchmarks for various protobuf functions. | | ## Publishing automation For information about our publishing automation and release process, see https://github.com/dart-lang/ecosystem/wiki/Publishing-automation. ================================================ FILE: analysis_options.yaml ================================================ include: package:lints/recommended.yaml linter: rules: - avoid_bool_literals_in_conditional_expressions - comment_references - prefer_relative_imports ================================================ FILE: benchmarks/.gitignore ================================================ # Generated by pub .dart_tool/ pubspec.lock lib/generated/ out/ ================================================ FILE: benchmarks/README.md ================================================ ## Running benchmarks - Compile protos with `./tool/compile_protos.sh` - **JIT:** Run benchmark programs in `bin/`, e.g. `dart bin/from_binary.dart` - **AOT and JS:** - Compile benchmark programs to native, JS, and JIT snapshots with `./tool/compile_benchmarks.dart` - Run benchmark programs in `out/`: - AOT: `./out/from_binary.exe` - JS: `d8 $DART_SDK/lib/_internal/js_runtime/lib/preambles/d8.js out/from_binary.js` - **Wasm:** - Get the Dart SDK source code following instructions [here][1], and build `dart2wasm_platform` target with `tools/build.py -m release dart2wasm_platform`. - Make sure `$DART_SDK` environment variable set to the path of [Dart SDK's "sdk" directory][1]. - Compile benchmarks with `./tool/compile_benchmarks.dart --target=` where `` is one of: - `wasm`: Default optimized build - `wasm-omit-checks`: Optimized build with `--omit-checks` - Run with: `$DART_SDK/bin/run_dart2wasm_d8 out/from_binary.wasm`, or use `.omit-checks.wasm` extension for the `wasm-omit-checks` target: `from_binary.omit-checks.wasm`. [1]: https://github.com/dart-lang/sdk/wiki/Building [2]: https://github.com/dart-lang/sdk/tree/main/sdk ## Development `protoc_version` file specifies the version of protoc Golem will use when building the benchmarks, and allows updating the protoc version without changing Golem. ================================================ FILE: benchmarks/analysis_options.yaml ================================================ include: ../analysis_options.yaml ================================================ FILE: benchmarks/bin/binary_decode_packed.dart ================================================ // Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:math'; import 'dart:typed_data'; import 'package:fixnum/fixnum.dart'; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/packed_fields.pb.dart'; PackedFields? sink; class PackedInt32DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedInt32DecodingBenchmark() : super('PackedInt32Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { message.packedInt32.add(rand.nextInt(2147483647)); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedInt64DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedInt64DecodingBenchmark() : super('PackedInt64Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { // Note: `Random` cannot generate more than the number below. message.packedInt64.add(Int64(rand.nextInt(4294967296))); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedUint32DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedUint32DecodingBenchmark() : super('PackedUint32Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { message.packedUint32.add(rand.nextInt(4294967295)); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedUint64DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedUint64DecodingBenchmark() : super('PackedUint64Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { // Note: `Random` cannot generate more than the number below. message.packedUint64.add(Int64(rand.nextInt(4294967296))); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedSint32DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedSint32DecodingBenchmark() : super('PackedSint32Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { message.packedSint32.add(rand.nextInt(2147483647)); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedSint64DecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedSint64DecodingBenchmark() : super('PackedSint64Decoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { // Note: `Random` cannot generate more than the number below. message.packedSint64.add(Int64(rand.nextInt(4294967296))); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedBoolDecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedBoolDecodingBenchmark() : super('PackedBoolDecoding') { final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 1000000; i += 1) { message.packedBool.add(rand.nextBool()); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedEnumDecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedEnumDecodingBenchmark() : super('PackedEnumDecoding') { final rand = Random(123); final message = PackedFields(); final numEnums = Enum1.values.length; for (var i = 0; i < 1000000; i += 1) { message.packedEnum1.add(Enum1.values[rand.nextInt(numEnums)]); } encoded = message.writeToBuffer(); } @override void setup() { // Decode different enums to prevent TFA from specializing enum decoding // code to one type. final rand = Random(123); final message = PackedFields(); for (var i = 0; i < 100; i += 1) { message.packedEnum1.add(Enum1.values[rand.nextInt(Enum1.values.length)]); } for (var i = 0; i < 100; i += 1) { message.packedEnum2.add(Enum2.values[rand.nextInt(Enum2.values.length)]); } final encoded = message.writeToBuffer(); final decoded = PackedFields()..mergeFromBuffer(encoded); if (decoded.packedEnum1.length != 100) { throw AssertionError('BUG'); } if (decoded.packedEnum2.length != 100) { throw AssertionError('BUG'); } } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } class PackedSparseEnumDecodingBenchmark extends BenchmarkBase { late final Uint8List encoded; PackedSparseEnumDecodingBenchmark() : super('PackedSparseEnumDecoding') { final rand = Random(123); final message = PackedFields(); final numEnums = SparseEnum.values.length; for (var i = 0; i < 1000000; i += 1) { message.sparseEnum.add(SparseEnum.values[rand.nextInt(numEnums)]); } encoded = message.writeToBuffer(); } @override void run() { sink = PackedFields()..mergeFromBuffer(encoded); } } void main() { PackedInt32DecodingBenchmark().report(); PackedInt64DecodingBenchmark().report(); PackedUint32DecodingBenchmark().report(); PackedUint64DecodingBenchmark().report(); PackedSint32DecodingBenchmark().report(); PackedSint64DecodingBenchmark().report(); PackedBoolDecodingBenchmark().report(); PackedEnumDecodingBenchmark().report(); PackedSparseEnumDecodingBenchmark().report(); if (int.parse('1') == 0) print(sink); } ================================================ FILE: benchmarks/bin/deep_copy.dart ================================================ // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink1; GeneratedMessage? sink2; GeneratedMessage? sink3; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = _message1Proto2.deepCopy(); sink2 = _message1Proto3.deepCopy(); sink3 = _message2.deepCopy(); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'deep_copy', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/from_binary.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:typed_data'; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink1; GeneratedMessage? sink2; GeneratedMessage? sink3; class Benchmark extends BenchmarkBase { final Uint8List _message1Proto2Input; final Uint8List _message1Proto3Input; final Uint8List _message2Input; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2Input = Uint8List.fromList(message1Proto2Input), _message1Proto3Input = Uint8List.fromList(message1Proto3Input), _message2Input = Uint8List.fromList(message2Input); @override void run() { sink1 = p2.GoogleMessage1.fromBuffer(_message1Proto2Input); sink2 = p3.GoogleMessage1.fromBuffer(_message1Proto3Input); sink3 = GoogleMessage2.fromBuffer(_message2Input); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'from_binary', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/from_json_string.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink1; GeneratedMessage? sink2; GeneratedMessage? sink3; class Benchmark extends BenchmarkBase { final String _message1Proto2JsonString; final String _message1Proto3JsonString; final String _message2JsonString; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2JsonString = p2.GoogleMessage1.fromBuffer(message1Proto2Input).writeToJson(), _message1Proto3JsonString = p3.GoogleMessage1.fromBuffer(message1Proto3Input).writeToJson(), _message2JsonString = GoogleMessage2.fromBuffer(message2Input).writeToJson(); @override void run() { sink1 = p2.GoogleMessage1.fromJson(_message1Proto2JsonString); sink2 = p3.GoogleMessage1.fromJson(_message1Proto3JsonString); sink3 = GoogleMessage2.fromJson(_message2JsonString); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'from_json_string', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/from_proto3_json_object.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink1; GeneratedMessage? sink2; GeneratedMessage? sink3; class Benchmark extends BenchmarkBase { final Object? _message1Proto2Proto3JsonObject; final Object? _message1Proto3Proto3JsonObject; final Object? _message2Proto3JsonObject; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2Proto3JsonObject = p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json(), _message1Proto3Proto3JsonObject = p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json(), _message2Proto3JsonObject = GoogleMessage2.fromBuffer(message2Input).toProto3Json(); @override void run() { sink1 = p2.GoogleMessage1.create() ..mergeFromProto3Json(_message1Proto2Proto3JsonObject); sink2 = p3.GoogleMessage1.create() ..mergeFromProto3Json(_message1Proto3Proto3JsonObject); sink3 = GoogleMessage2.create()..mergeFromProto3Json(_message2Proto3JsonObject); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'from_proto3_json_object', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/from_proto3_json_string.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show jsonDecode, jsonEncode; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink1; GeneratedMessage? sink2; GeneratedMessage? sink3; class Benchmark extends BenchmarkBase { final String _message1Proto2Proto3JsonString; final String _message1Proto3Proto3JsonString; final String _message2Proto3JsonString; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2Proto3JsonString = jsonEncode( p2.GoogleMessage1.fromBuffer(message1Proto2Input).toProto3Json(), ), _message1Proto3Proto3JsonString = jsonEncode( p3.GoogleMessage1.fromBuffer(message1Proto3Input).toProto3Json(), ), _message2Proto3JsonString = jsonEncode( GoogleMessage2.fromBuffer(message2Input).toProto3Json(), ); @override void run() { sink1 = p2.GoogleMessage1.create() ..mergeFromProto3Json(jsonDecode(_message1Proto2Proto3JsonString)); sink2 = p3.GoogleMessage1.create() ..mergeFromProto3Json(jsonDecode(_message1Proto3Proto3JsonString)); sink3 = GoogleMessage2.create() ..mergeFromProto3Json(jsonDecode(_message2Proto3JsonString)); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'from_proto3_json_string', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/hash_code.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; int sink1 = 0; int sink2 = 0; int sink3 = 0; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = _message1Proto2.hashCode; sink2 = _message1Proto3.hashCode; sink3 = _message2.hashCode; } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'hash_code', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/query_decode_binary.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f0.pb.dart' as f0; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink; class Benchmark extends BenchmarkBase { final List _input; Benchmark(super.name, this._input); @override void run() { sink = f0.A0.fromBuffer(_input); } } void main() { final List encoded = readfile('datasets/query_benchmark.pb'); Benchmark('query_decode_binary', encoded).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/query_decode_json.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f0.pb.dart' as f0; import 'package:protobuf_benchmarks/readfile.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink; class Benchmark extends BenchmarkBase { final String _input; Benchmark(super.name, List input) : _input = f0.A0.fromBuffer(input).writeToJson(); @override void run() { sink = f0.A0.fromJson(_input); } } void main() { final List encoded = readfile('datasets/query_benchmark.pb'); Benchmark('query_decode_json', encoded).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/query_encode_binary.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f0.pb.dart' as f0; import 'package:protobuf_benchmarks/readfile.dart'; import 'dart:typed_data'; Uint8List? sink; class Benchmark extends BenchmarkBase { final f0.A0 _input; Benchmark(super.name, List input) : _input = f0.A0.fromBuffer(input); @override void run() { sink = _input.writeToBuffer(); } } void main() { final List encoded = readfile('datasets/query_benchmark.pb'); Benchmark('query_encode_binary', encoded).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/query_encode_json.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f0.pb.dart' as f0; import 'package:protobuf_benchmarks/readfile.dart'; String? sink; class Benchmark extends BenchmarkBase { final f0.A0 _input; Benchmark(super.name, List input) : _input = f0.A0.fromBuffer(input); @override void run() { sink = _input.writeToJson(); } } void main() { final List encoded = readfile('datasets/query_benchmark.pb'); Benchmark('query_encode_json', encoded).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/query_set_nested_value.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf/protobuf.dart'; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f0.pb.dart' as f0; import 'package:protobuf_benchmarks/generated/f19.pb.dart' as f19; import 'package:protobuf_benchmarks/generated/f2.pb.dart' as f2; import 'package:protobuf_benchmarks/readfile.dart'; GeneratedMessage? sink; class Benchmark extends BenchmarkBase { final f0.A0 _input; Benchmark(super.name, List input) : _input = f0.A0.fromBuffer(input)..freeze(); @override void run() { sink = _input.rebuild((f0.A0 a0Builder) { a0Builder.a4.last = a0Builder.a4.last.rebuild((f2.A1 a1builder) { a1builder.a378 = a1builder.a378.rebuild( (f19.A220 a220builder) => a220builder.a234 = 'new_value', ); }); }); } } void main() { final List encoded = readfile('datasets/query_benchmark.pb'); Benchmark('query_set_nested_value', encoded).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/repeated_field.dart ================================================ // Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:typed_data'; import 'package:fixnum/fixnum.dart'; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/f12.pb.dart' as f12; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf/protobuf.dart'; GeneratedMessage? sink; class RepeatedBenchmark extends BenchmarkBase { final Uint8List _buffer; RepeatedBenchmark(super.name, GoogleMessage2 message) : _buffer = message.writeToBuffer(); @override void run() { sink = GoogleMessage2.fromBuffer(_buffer); } } class RepeatedEnumBenchmark extends BenchmarkBase { final Uint8List _buffer; RepeatedEnumBenchmark(super.name, f12.A58 message) : _buffer = message.writeToBuffer(); @override void run() { sink = f12.A58.fromBuffer(_buffer); } } void main() { const kSize = 500000; RepeatedBenchmark( 'repeated_int64', GoogleMessage2(field130: List.generate(kSize, Int64.new)), ).report(); RepeatedBenchmark( 'repeated_string', GoogleMessage2(field128: List.generate(kSize, (i) => i.toString())), ).report(); RepeatedEnumBenchmark( 'repeated_enum', f12.A58(a306: List.generate(kSize, (_) => f12.A322.A324)), ).report(); if (int.parse('1') == 0) { print(sink); } } ================================================ FILE: benchmarks/bin/to_binary.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; import 'dart:typed_data'; Uint8List? sink1; Uint8List? sink2; Uint8List? sink3; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = _message1Proto2.writeToBuffer(); sink2 = _message1Proto3.writeToBuffer(); sink3 = _message2.writeToBuffer(); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'to_binary', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/to_json_string.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; String? sink1; String? sink2; String? sink3; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = _message1Proto2.writeToJson(); sink2 = _message1Proto3.writeToJson(); sink3 = _message2.writeToJson(); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'to_json_string', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/to_proto3_json_object.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; Object? sink1; Object? sink2; Object? sink3; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = _message1Proto2.toProto3Json(); sink2 = _message1Proto3.toProto3Json(); sink3 = _message2.toProto3Json(); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'to_proto3_json_object', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/bin/to_proto3_json_string.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show jsonEncode; import 'package:protobuf_benchmarks/benchmark_base.dart'; import 'package:protobuf_benchmarks/generated/google_message1_proto2.pb.dart' as p2; import 'package:protobuf_benchmarks/generated/google_message1_proto3.pb.dart' as p3; import 'package:protobuf_benchmarks/generated/google_message2.pb.dart'; import 'package:protobuf_benchmarks/readfile.dart'; String? sink1; String? sink2; String? sink3; class Benchmark extends BenchmarkBase { final p2.GoogleMessage1 _message1Proto2; final p3.GoogleMessage1 _message1Proto3; final GoogleMessage2 _message2; Benchmark( super.name, List message1Proto2Input, List message1Proto3Input, List message2Input, ) : _message1Proto2 = p2.GoogleMessage1.fromBuffer(message1Proto2Input), _message1Proto3 = p3.GoogleMessage1.fromBuffer(message1Proto3Input), _message2 = GoogleMessage2.fromBuffer(message2Input); @override void run() { sink1 = jsonEncode(_message1Proto2.toProto3Json()); sink2 = jsonEncode(_message1Proto3.toProto3Json()); sink3 = jsonEncode(_message2.toProto3Json()); } } void main() { final List message1Proto2Input = readfile( 'datasets/google_message1_proto2.pb', ); final List message1Proto3Input = readfile( 'datasets/google_message1_proto3.pb', ); final List message2Input = readfile('datasets/google_message2.pb'); Benchmark( 'to_proto3_json_string', message1Proto2Input, message1Proto3Input, message2Input, ).report(); if (int.parse('1') == 0) { print(sink1); print(sink2); print(sink3); } } ================================================ FILE: benchmarks/lib/benchmark_base.dart ================================================ // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:benchmark_harness/benchmark_harness.dart' as bh; /// A subclass of [bh.BenchmarkBase] with a few changes: /// /// - Work around https://github.com/dart-lang/benchmark_harness/issues/30 by /// dividing the result by 10. /// /// - Report the results as "RunTimeRaw" instead of "RunTime". What /// benchmark_harness calls "RunTime" is called "RunTimeRaw" in Golem. /// /// - Add "protobuf_" prefix to test names. This is to make it easier to see /// what the benchmarks are about in Golem UI. /// abstract class BenchmarkBase extends bh.BenchmarkBase { BenchmarkBase(super.name) : super(emitter: const _ResultPrinter()); @override double measure() { return super.measure() / 10; } } class _ResultPrinter implements bh.ScoreEmitter { const _ResultPrinter() : super(); @override void emit(String testName, double value) { // Same as the default, but prints "RunTimeRaw" instead of "RunTime" print('protobuf_$testName(RunTimeRaw): $value us.'); } } ================================================ FILE: benchmarks/lib/readfile.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'readfile_vm.dart' if (dart.library.js_interop) 'readfile_js.dart' show readfile; ================================================ FILE: benchmarks/lib/readfile_js.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:js_interop'; import 'dart:typed_data'; /// Read the file at the given [path]. /// /// This relies on the `readbuffer` function provided by d8. @JS() external JSArrayBuffer readbuffer(String path); /// Read the file at the given [path]. Uint8List readfile(String path) { // Copy the contents to a new `Uint8List` to make sure in dart2wasm we // benchmark with the native arrays instead of JS arrays. return Uint8List.fromList(readbuffer(path).toDart.asUint8List()); } ================================================ FILE: benchmarks/lib/readfile_vm.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'dart:typed_data'; Uint8List readfile(String path) { return File(path).readAsBytesSync(); } ================================================ FILE: benchmarks/protoc_version ================================================ 21.2 ================================================ FILE: benchmarks/protos/google_message1_proto2.proto ================================================ // Benchmark messages for proto2. syntax = "proto2"; package benchmarks.proto2; option java_package = "com.google.protobuf.benchmarks"; // This is the default, but we specify it here explicitly. option optimize_for = SPEED; option cc_enable_arenas = true; message GoogleMessage1 { required string field1 = 1; optional string field9 = 9; optional string field18 = 18; optional bool field80 = 80 [default = false]; optional bool field81 = 81 [default = true]; required int32 field2 = 2; required int32 field3 = 3; optional int32 field280 = 280; optional int32 field6 = 6 [default = 0]; optional int64 field22 = 22; optional string field4 = 4; repeated fixed64 field5 = 5; optional bool field59 = 59 [default = false]; optional string field7 = 7; optional int32 field16 = 16; optional int32 field130 = 130 [default = 0]; optional bool field12 = 12 [default = true]; optional bool field17 = 17 [default = true]; optional bool field13 = 13 [default = true]; optional bool field14 = 14 [default = true]; optional int32 field104 = 104 [default = 0]; optional int32 field100 = 100 [default = 0]; optional int32 field101 = 101 [default = 0]; optional string field102 = 102; optional string field103 = 103; optional int32 field29 = 29 [default = 0]; optional bool field30 = 30 [default = false]; optional int32 field60 = 60 [default = -1]; optional int32 field271 = 271 [default = -1]; optional int32 field272 = 272 [default = -1]; optional int32 field150 = 150; optional int32 field23 = 23 [default = 0]; optional bool field24 = 24 [default = false]; optional int32 field25 = 25 [default = 0]; optional GoogleMessage1SubMessage field15 = 15; optional bool field78 = 78; optional int32 field67 = 67 [default = 0]; optional int32 field68 = 68; optional int32 field128 = 128 [default = 0]; optional string field129 = 129 [default = "xxxxxxxxxxxxxxxxxxxxx"]; optional int32 field131 = 131 [default = 0]; } message GoogleMessage1SubMessage { optional int32 field1 = 1 [default = 0]; optional int32 field2 = 2 [default = 0]; optional int32 field3 = 3 [default = 0]; optional string field15 = 15; optional bool field12 = 12 [default = true]; optional int64 field13 = 13; optional int64 field14 = 14; optional int32 field16 = 16; optional int32 field19 = 19 [default = 2]; optional bool field20 = 20 [default = true]; optional bool field28 = 28 [default = true]; optional fixed64 field21 = 21; optional int32 field22 = 22; optional bool field23 = 23 [default = false]; optional bool field206 = 206 [default = false]; optional fixed32 field203 = 203; optional int32 field204 = 204; optional string field205 = 205; optional uint64 field207 = 207; optional uint64 field300 = 300; } ================================================ FILE: benchmarks/protos/google_message1_proto3.proto ================================================ // Benchmark messages for proto3. syntax = "proto3"; package benchmarks.proto3; option java_package = "com.google.protobuf.benchmarks"; // This is the default, but we specify it here explicitly. option optimize_for = SPEED; option cc_enable_arenas = true; message GoogleMessage1 { string field1 = 1; string field9 = 9; string field18 = 18; bool field80 = 80; bool field81 = 81; int32 field2 = 2; int32 field3 = 3; int32 field280 = 280; int32 field6 = 6; int64 field22 = 22; string field4 = 4; repeated fixed64 field5 = 5; bool field59 = 59; string field7 = 7; int32 field16 = 16; int32 field130 = 130; bool field12 = 12; bool field17 = 17; bool field13 = 13; bool field14 = 14; int32 field104 = 104; int32 field100 = 100; int32 field101 = 101; string field102 = 102; string field103 = 103; int32 field29 = 29; bool field30 = 30; int32 field60 = 60; int32 field271 = 271; int32 field272 = 272; int32 field150 = 150; int32 field23 = 23; bool field24 = 24; int32 field25 = 25; GoogleMessage1SubMessage field15 = 15; bool field78 = 78; int32 field67 = 67; int32 field68 = 68; int32 field128 = 128; string field129 = 129; int32 field131 = 131; } message GoogleMessage1SubMessage { int32 field1 = 1; int32 field2 = 2; int32 field3 = 3; string field15 = 15; bool field12 = 12; int64 field13 = 13; int64 field14 = 14; int32 field16 = 16; int32 field19 = 19; bool field20 = 20; bool field28 = 28; fixed64 field21 = 21; int32 field22 = 22; bool field23 = 23; bool field206 = 206; fixed32 field203 = 203; int32 field204 = 204; string field205 = 205; uint64 field207 = 207; uint64 field300 = 300; } ================================================ FILE: benchmarks/protos/google_message2.proto ================================================ // Benchmark messages for proto2. syntax = "proto2"; package benchmarks.proto2; option java_package = "com.google.protobuf.benchmarks"; // This is the default, but we specify it here explicitly. option optimize_for = SPEED; option cc_enable_arenas = true; message GoogleMessage2 { optional string field1 = 1; optional int64 field3 = 3; optional int64 field4 = 4; optional int64 field30 = 30; optional bool field75 = 75 [default = false]; optional string field6 = 6; optional bytes field2 = 2; optional int32 field21 = 21 [default = 0]; optional int32 field71 = 71; optional float field25 = 25; optional int32 field109 = 109 [default = 0]; optional int32 field210 = 210 [default = 0]; optional int32 field211 = 211 [default = 0]; optional int32 field212 = 212 [default = 0]; optional int32 field213 = 213 [default = 0]; optional int32 field216 = 216 [default = 0]; optional int32 field217 = 217 [default = 0]; optional int32 field218 = 218 [default = 0]; optional int32 field220 = 220 [default = 0]; optional int32 field221 = 221 [default = 0]; optional float field222 = 222 [default = 0.0]; optional int32 field63 = 63; repeated group Group1 = 10 { required float field11 = 11; optional float field26 = 26; optional string field12 = 12; optional string field13 = 13; repeated string field14 = 14; required uint64 field15 = 15; optional int32 field5 = 5; optional string field27 = 27; optional int32 field28 = 28; optional string field29 = 29; optional string field16 = 16; repeated string field22 = 22; repeated int32 field73 = 73; optional int32 field20 = 20 [default = 0]; optional string field24 = 24; optional GoogleMessage2GroupedMessage field31 = 31; } repeated string field128 = 128; optional int64 field131 = 131; repeated string field127 = 127; optional int32 field129 = 129; repeated int64 field130 = 130; optional bool field205 = 205 [default = false]; optional bool field206 = 206 [default = false]; } message GoogleMessage2GroupedMessage { optional float field1 = 1; optional float field2 = 2; optional float field3 = 3 [default = 0.0]; optional bool field4 = 4; optional bool field5 = 5; optional bool field6 = 6 [default = true]; optional bool field7 = 7 [default = false]; optional float field8 = 8; optional bool field9 = 9; optional float field10 = 10; optional int64 field11 = 11; } ================================================ FILE: benchmarks/protos/packed_fields.proto ================================================ syntax = "proto3"; message PackedFields { repeated int32 packedInt32 = 1 [packed = true]; repeated int64 packedInt64 = 2 [packed = true]; repeated uint32 packedUint32 = 3 [packed = true]; repeated uint64 packedUint64 = 4 [packed = true]; repeated sint32 packedSint32 = 5 [packed = true]; repeated sint64 packedSint64 = 6 [packed = true]; repeated bool packedBool = 7 [packed = true]; repeated Enum1 packedEnum1 = 8 [packed = true]; repeated Enum2 packedEnum2 = 9 [packed = true]; repeated SparseEnum sparseEnum = 10 [packed = true]; } enum Enum1 { ENUM_1_1 = 0; ENUM_1_2 = 1; ENUM_1_3 = 2; ENUM_1_4 = 4; ENUM_1_5 = 5; } enum Enum2 { ENUM_2_1 = 0; ENUM_2_2 = 1; ENUM_2_3 = 2; ENUM_2_4 = 4; ENUM_2_5 = 5; } // An enum with large gaps between the known values, and with negative values. // // This will be slower to decode as the varint to enum value mapping needs to be // done with binary search, or map lookup etc. enum SparseEnum { ENUM_ZERO = 0; ENUM_MIN_INT = -2147483648; ENUM_1 = -1000000000; ENUM_2 = -100000000; ENUM_3 = -10000000; ENUM_4 = -1000000; ENUM_5 = -100000; ENUM_6 = 100000; ENUM_7 = 1000000; ENUM_8 = 10000000; ENUM_9 = 100000000; ENUM_10 = 1000000000; ENUM_MAX_INT = 2147483647; } ================================================ FILE: benchmarks/protos/query_benchmark/f0.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a2.a3; import "f2.proto"; import "f3.proto"; message A0 { repeated .a0.a1.a2.a3.A1 a4 = 1; optional string a5 = 3; enum A2 { A3 = 0; A4 = 1; A5 = 2; A6 = 3; A7 = 4; A8 = 5; } optional A2 a6 = 2; optional a7.A9 a8 = 4; } ================================================ FILE: benchmarks/protos/query_benchmark/f1.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a274; import "f5.proto"; message A313 { optional int32 a90 = 1; optional int32 a275 = 2; } message A314 { repeated A313 a276 = 1; } message A315 { optional string a277 = 1; optional a10.A113.A59 a99 = 2; optional int64 a278 = 3; repeated string a279 = 4; } message A316 { optional string a280 = 1; optional int64 a281 = 2; repeated A315 a282 = 3; } message A317 { repeated A316 a283 = 1; } extend a10.A56 { repeated A313 a276 = 134096400; optional A314 a284 = 141473177; } message A318 { message A319 { optional int32 a285 = 1; optional string a54 = 2; } repeated A319 a286 = 1; } extend a10.A57 { optional int32 a287 = 134096400; optional A318 a288 = 185706300; } ================================================ FILE: benchmarks/protos/query_benchmark/f10.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a10.a68; message A102 { optional string a52 = 1; optional uint64 a69 = 2; optional uint64 a70 = 3; optional uint64 a71 = 4; } message A103 { optional string a52 = 1; optional uint64 a72 = 2; repeated A102 a73 = 3; } message A104 { repeated A103 message = 1; optional string a74 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f11.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f12.proto"; message A105 { optional string a75 = 1; }; message A106 { optional A105 a76 = 1; optional string a77 = 3; }; message A107 { optional string a78 = 1; } ================================================ FILE: benchmarks/protos/query_benchmark/f12.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; import "f25.proto"; import "f5.proto"; package a260; enum A322 { A323 = 0; A324 = 999; A325 = 1000; A326 = 1001; A327 = 1002; A328 = 1003; A329 = 1004; A330 = 1005; A331 = 1006; A332 = 1007; A333 = 1008; A334 = 1100; A335 = 1102; A336 = 1103; A337 = 1104; A338 = 1105; A339 = 1106; A340 = 1107; A341 = 1108; A342 = 1109; A343 = 1200; A344 = 1201; A345 = 1203; A346 = 1204; A347 = 1202; A348 = 1211; A349 = 1212; A350 = 1220; A351 = 1221; A352 = 1222; A353 = 1223; A354 = 1240; A355 = 1300; A356 = 1301; A357 = 1400; A358 = 1401; A359 = 1500; A360 = 1501; A361 = 1600; A362 = 1601; A363 = 1700; A364 = 1701; A365 = 1702; A366 = 1800; A367 = 1801; A368 = 1802; A369 = 1803; A370 = 1900; A371 = 1901; A372 = 2000; A373 = 2100; A374 = 2101; A375 = 2300; A376 = 2400; A377 = 2500; A378 = 2600; A379 = 2601; A380 = 2602; A381 = 2603; A382 = 9900; A383 = 9901; A384 = 9902; A385 = 9903; A386 = 9904; A387 = 9905; }; message A388 { optional bool a293 = 1 [default = false]; optional bool a294 = 2 [default = false]; optional bool a295 = 3 [default = false]; optional bool a296 = 4 [default = false]; optional bool a297 = 5 [default = false]; optional bool a298 = 6 [default = false]; optional bool a15 = 7 [default = false]; optional int32 a299 = 8; optional bool a300 = 9 [default = false]; optional bool a301 = 10 [default = false]; optional bool a302 = 11 [default = false]; optional bool a303 = 13 [default = false]; optional bool a304 = 12 [default = false]; }; message A389 { optional bool a300 = 1 [default = false]; optional bool a305 = 2 [default = false]; }; enum A390 { A391 = 0; A392 = 1; A393 = 2; A394 = 3; A395 = 4; A396 = 5; A397 = 6; A398 = 7; }; extend a10.A56 { optional A322 a306 = 40075780; optional A388 a307 = 40270992; optional A389 a308 = 69646961; optional A399 a309 = 40093572; optional A390 a310 = 40221563; repeated A308 a311 = 40223876; }; extend a10.A57 { optional A322 a312 = 41149386; optional A388 a313 = 41551199; optional A389 a314 = 69646961; optional A58 a21 = 41744383; repeated A308 a315 = 41909987; }; message A399 { repeated A322 a306 = 1; }; message A58 { repeated A322 a306 = 1; }; extend a10.A60 { optional bool a316 = 43601160; optional string a317 = 71304954; }; ================================================ FILE: benchmarks/protos/query_benchmark/f13.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto3"; package a205.a206; message A190 { int64 a258 = 1; int32 a259 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f14.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a10.a68.a211; message A192 { message A193 { optional string a52 = 1; optional int32 a97 = 2; optional string a212 = 3; optional string a213 = 4; optional bool a214 = 5 [default = true]; optional bool a215 = 6; optional uint32 a216 = 7 [default = 2]; } repeated A193 a86 = 2; message A194 { optional string a52 = 1; optional string a213 = 2; optional bool a214 = 3 [default = true]; optional uint32 a216 = 4 [default = 2]; } repeated A194 a217 = 3; message A195 { optional string a52 = 1; optional string a213 = 2; optional bool a214 = 3 [default = true]; optional uint32 a216 = 4 [default = 2]; } repeated A195 a218 = 4; } ================================================ FILE: benchmarks/protos/query_benchmark/f15.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto3"; package a46.a47.a1.a48.a49.a4; import "f12.proto"; message A196 { string a219 = 1; A197 a220 = 2; } message A197 { enum A198 { A199 = 0; A200 = 1; A201 = 2; A202 = 3; A203 = 4; A204 = 5; A205 = 6; A206 = 7; A207 = 8; A208 = 9; A209 = 10; } A198 a221 = 1; string a222 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f16.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f17.proto"; import "f18.proto"; import "f12.proto"; message A210 { enum A211 { A212 = 0; A213 = 1; A214 = 2; } optional string a223 = 1; optional string a224 = 3; message A215 { repeated A216 a225 = 1; } optional A215 a226 = 2; optional A211 a227 = 4; optional bool a228 = 5; } message A217 { optional A218 a229 = 1; message A219 { repeated A216 a230 = 1; } optional A219 a231 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f17.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f4.proto"; import "f12.proto"; message A320 { optional string a375 = 1; optional bytes a376 = 2; } message A216 { optional string a377 = 1; optional A320 a105 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f18.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f12.proto"; message A218 { enum A400 { A401 = 0; A402 = 1; A235 = 2; A403 = 3; A404 = 4; A405 = 5; A406 = 6; A407 = 7; A408 = 16; A409 = 8; A410 = 9; A411 = 10; A412 = 11; A413 = 12; A414 = 13; A415 = 14; A416 = 15; A417 = 17; A418 = 20; } optional A400 a318 = 1 [default = A401]; optional string a319 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f19.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a232; import "f1.proto"; message A220 { optional A221 a233 = 7; optional string a234 = 1; optional bytes a235 = 5; optional string a236 = 8; optional string a237 = 6; optional string a238 = 2; optional int32 a239 = 3; optional int32 a240 = 4; extensions 192367380; } enum A221 { A222 = 0; A223 = 1; } enum A224 { A225 = 0; A226 = 1; A227 = 2; A228 = 3; A229 = 4; }; ================================================ FILE: benchmarks/protos/query_benchmark/f2.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a2.a3; import "f1.proto"; import "f19.proto"; import "f20.proto"; import "f15.proto"; import "f9.proto"; message A1 { optional .a0.a1.a232.A220 a378 = 1; optional .a0.a1.a232.A220 a379 = 2; optional .a46.a47.a1.a48.a49.a4.A196 a380 = 5; message A465 { optional string a381 = 1; optional string a234 = 2; optional string a382 = 3; optional string a383 = 4; optional string a384 = 10; optional string a385 = 5; optional string a386 = 6; optional string a387 = 7; optional int64 a388 = 8; optional string a194 = 9; } optional A465 a389 = 3; message A466 { optional float a390 = 1; optional float a391 = 2; optional float a392 = 3; optional float a393 = 4; } optional A466 a394 = 4; optional string a395 = 6; optional A467 a274 = 7; repeated A468 a396 = 8; optional bool a397 = 9; message A469 { optional .a0.a1.a232.A230 a397 = 1; optional .a0.a1.a232.A230 a398 = 2; optional .a0.a1.a232.A230 a399 = 3; } optional A469 a400 = 10; } message A467 { message A470 { optional .a46.a47.a1.a48.a49.a4.A99 a401 = 9; optional .a46.a47.a1.a48.a49.a4.A100 a402 = 10; optional .a46.a47.a1.a48.a49.a4.A101 a403 = 11; } optional A470 a404 = 1; } message A468 { optional string a395 = 1; optional A471 a405 = 2; optional string a406 = 3; } message A471 { optional float a390 = 1; optional float a392 = 2; optional float a391 = 3; optional float a393 = 4; } ================================================ FILE: benchmarks/protos/query_benchmark/f20.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a232; import "f1.proto"; import "f21.proto"; import "f22.proto"; message A230 { optional string a222 = 1; optional string a224 = 2; optional a0.a1.A231 a241 = 5; optional A232 a242 = 3; reserved 4; } ================================================ FILE: benchmarks/protos/query_benchmark/f21.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f17.proto"; import "f12.proto"; message A232 { optional string a289 = 1; optional string a290 = 3; map a291 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f22.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f8.proto"; import "f1.proto"; import "f21.proto"; import "f16.proto"; import "f7.proto"; import "f27.proto"; import "f28.proto"; import "f23.proto"; import "f11.proto"; import "f24.proto"; import "f4.proto"; import "f12.proto"; message A419 { repeated A420 a320 = 1; optional A321 a291 = 2; }; message A421 { optional bytes a321 = 1; optional bool a322 = 6 [default = false]; optional bytes a323 = 2; repeated A420 a324 = 3; optional A321 a325 = 4; optional A231 a241 = 5; map a326 = 7; optional A422 a327 = 8; optional string a224 = 9; }; message A420 { optional int32 a328 = 1; optional int32 a329 = 2; oneof a99 { A423 a330 = 3; A424 a331 = 4; } } message A423 { optional a0.a1.a232.A239 a332 = 6; optional string a224 = 7; optional A231 a241 = 8; oneof a99 { a0.a1.A106 a333 = 1; a0.a1.A293 a334 = 4; A217 a335 = 3; A232 a242 = 5; } reserved 2; } message A424 { optional a0.a1.a232.A239 a336 = 3; optional a0.a1.a232.A241 a337 = 7; optional a0.a1.A107 a338 = 1; optional A210 a2 = 2; optional A425 a339 = 5; optional bytes a340 = 4; optional bool a341 = 6 [default = false]; optional A231 a241 = 16; } message A425 { enum A426 { A235 = 0; A427 = 1; A428 = 2; A429 = 3; } optional A426 a342 = 1; } message A231 { optional bool a322 = 1 [default = false]; optional bool a341 = 2 [default = false]; optional bool a343 = 3 [default = false]; optional int32 a344 = 4; optional bool a345 = 6; optional A430 a346 = 5; optional bytes a347 = 7; optional A66 a348 = 8; }; message A430 { repeated a0.a1.a349.A431 a350 = 5; repeated A420 a320 = 6; } message A432 { optional string a351 = 1; optional string a278 = 2; optional bytes a352 = 3; optional A66 a348 = 4; } message A422 { repeated A432 a353 = 1; repeated string a354 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f23.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a232; import "f1.proto"; import "f4.proto"; import "f12.proto"; message A233 { enum A234 { A235 = 0; A236 = 1; A237 = 2; A238 = 3; } optional A234 a243 = 1; optional string a244 = 2; optional string a245 = 3; } message A239 { optional string a246 = 3; optional string a247 = 2; optional string a248 = 8; optional string a249 = 1; optional string a250 = 4; optional string a251 = 5; optional A240 a252 = 6; optional string a253 = 7; optional string a254 = 9; optional string a255 = 10; optional string a256 = 11; } message A240 { reserved 3, 4; optional string a245 = 1; optional string a257 = 2; } message A241 { enum A59 { A235 = 0; A242 = 14; A243 = 4; A244 = 47; A245 = 33; A246 = 5; A247 = 45; A248 = 2; A249 = 28; A250 = 13; A251 = 29; A252 = 27; A253 = 42; A254 = 18; A255 = 31; A256 = 25; A257 = 3; A258 = 7; A259 = 8; A260 = 24; A261 = 9; A262 = 6; A263 = 19; A264 = 15; A265 = 10; A266 = 11; A267 = 35; A268 = 20; A269 = 1; A270 = 41; A271 = 12; A272 = 26; A273 = 17; A274 = 34; A275 = 23; A276 = 40; A277 = 46; A278 = 51; A279 = 16; A280 = 30; A281 = 38; A282 = 21; A283 = 22; A284 = 49; A285 = 32; A286 = 36; A287 = 37; A288 = 39; A289 = 48; A290 = 50; A291 = 43; A292 = 44; } optional A59 a99 = 1; } ================================================ FILE: benchmarks/protos/query_benchmark/f24.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f12.proto"; message A293 { optional string a5 = 1; } ================================================ FILE: benchmarks/protos/query_benchmark/f25.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a260; enum A294 { A295 = 0; A296 = 1; A297 = 10; A298 = 20; A299 = 21; A300 = 30; A301 = 40; A302 = 50; A303 = 58; A304 = 60; A305 = 70; A306 = 80; A307 = 1000; }; message A308 { optional A294 a261 = 1; optional string a262 = 2; }; ================================================ FILE: benchmarks/protos/query_benchmark/f26.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a10.a68; import "f10.proto"; import "f5.proto"; message A309 { optional int32 a263 = 1; optional int32 a264 = 2; optional int32 a265 = 3; optional string a266 = 4; } message A310 { repeated string a267 = 1; optional string a268 = 2; repeated A109 a269 = 15; optional A309 a270 = 3; optional A104 a271 = 16; } message A311 { optional string a272 = 1; message A312 { optional string a52 = 1; optional string a273 = 2; optional string a235 = 15; } repeated A312 a79 = 15; } ================================================ FILE: benchmarks/protos/query_benchmark/f27.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; import "f17.proto"; import "f12.proto"; message A321 { repeated A216 a292 = 1; } ================================================ FILE: benchmarks/protos/query_benchmark/f28.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1.a349; message A433 { oneof a105 { string a192 = 1; int32 a355 = 2; bool a356 = 3; double a191 = 4; } }; message A434 { optional string a357 = 1; optional A435 a358 = 2; } message A435 { oneof a359 { bool a360 = 1; A436 a361 = 2; A437 a362 = 3; } message A436 { optional bool a361 = 1; } message A437 { optional A433 a105 = 1; } } enum A438 { A439 = 0; A440 = 1; A441 = 2; A442 = 3; A443 = 4; A444 = 5; A445 = 6; A446 = 7; A447 = 8; A448 = 9; A449 = 10; A450 = 13; A451 = 14; A452 = 15; A453 = 16; A454 = 17; }; message A455 { optional A438 a363 = 1; repeated A456 a364 = 2; }; message A456 { oneof a365 { A455 a366 = 1; A434 a367 = 2; A433 a368 = 3; } }; message A457 { optional string a98 = 1; }; message A431 { enum A458 { A459 = 0; A460 = 1; A461 = 2; A462 = 3; A463 = 4; A464 = 5; } optional A458 a369 = 1; optional A456 a370 = 2; optional int32 a371 = 3; optional int32 a372 = 4; optional A434 a373 = 5; optional A457 a374 = 16; }; ================================================ FILE: benchmarks/protos/query_benchmark/f3.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; import "f13.proto"; import "f6.proto"; package a7; message A9 { optional bytes a203 = 1; optional A189 a204 = 2; } message A189 { optional a205.a206.A190 a207 = 1; message A191 { optional int64 a208 = 1; } optional A191 a209 = 2; optional A61 a210 = 3; } ================================================ FILE: benchmarks/protos/query_benchmark/f4.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; import "f5.proto"; package a9; enum A10 { A11 = 0; A12 = 1; A13 = 2; A14 = 3; A15 = 4; A16 = 5; A17 = 15; A18 = 6; A19 = 9; A20 = 7; A21 = 8; A22 = 16; A23 = 10; A24 = 11; A25 = 12; A26 = 13; A27 = 14; A28 = 20; A29 = 21; A30 = 22; A31 = 23; A32 = 24; A33 = 207; A34 = 30; A35 = 31; A36 = 32; A37 = 35; A38 = 33; A39 = 34; A40 = 50; A41 = 51; A42 = 52; A43 = 53; A44 = 54; A45 = 55; A46 = 56; A47 = 57; A48 = 100; A49 = 200; A50 = 201; A51 = 202; A52 = 203; A53 = 204; A54 = 205; A55 = 206; }; extend a10.A56 { optional A10 a11 = 21713708; optional bool a12 = 21623477; optional bool a13 = 23459630; optional bool a14 = 21596320; optional bool a15 = 26652850; optional int32 a16 = 53697879; optional string a17 = 56871503; }; extend a10.A57 { optional A10 a18 = 21713708; optional bool a19 = 21623477; optional bool a20 = 21596320; optional A58 a21 = 21467048; optional string a22 = 26652850; } message A58 { message A59 { required string a23 = 1; required string a24 = 2; }; repeated A59 a25 = 1; }; extend a10.A60 { optional bool a26 = 21596320; optional bool a27 = 28993747; }; ================================================ FILE: benchmarks/protos/query_benchmark/f5.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a10; message A108 { repeated A109 a79 = 1; } message A109 { optional string a52 = 1; optional string a407 = 2; repeated string a80 = 3; repeated int32 a81 = 10; repeated int32 a82 = 11; repeated A110 a83 = 4; repeated A111 a84 = 5; repeated A112 a85 = 6; repeated A113 a86 = 7; optional A60 a87 = 8; optional A114 a88 = 9; optional string a408 = 12; } message A110 { optional string a52 = 1; repeated A113 a73 = 2; repeated A113 a86 = 6; repeated A110 a89 = 3; repeated A111 a84 = 4; message A115 { optional int32 a90 = 1; optional int32 a91 = 2; optional A116 a87 = 3; } repeated A115 a92 = 5; repeated A117 a93 = 8; optional A57 a87 = 7; message A118 { optional int32 a90 = 1; optional int32 a91 = 2; } repeated A118 a94 = 9; repeated string a95 = 10; } message A116 { repeated A119 a96 = 999; extensions 1000 to max; } message A113 { enum A59 { A120 = 1; A121 = 2; A122 = 3; A123 = 4; A124 = 5; A125 = 6; A126 = 7; A127 = 8; A128 = 9; A129 = 10; A130 = 11; A131 = 12; A132 = 13; A133 = 14; A134 = 15; A135 = 16; A136 = 17; A137 = 18; }; enum A138 { A139 = 1; A140 = 2; A141 = 3; }; optional string a52 = 1; optional int32 a97 = 3; optional A138 a98 = 4; optional A59 a99 = 5; optional string a100 = 6; optional string a101 = 2; optional string a102 = 7; optional int32 a103 = 9; optional string a104 = 10; optional A56 a87 = 8; } message A117 { optional string a52 = 1; optional A142 a87 = 2; } message A111 { optional string a52 = 1; repeated A143 a105 = 2; optional A70 a87 = 3; message A144 { optional int32 a90 = 1; optional int32 a91 = 2; } repeated A144 a94 = 4; repeated string a95 = 5; } message A143 { optional string a52 = 1; optional int32 a97 = 2; optional A76 a87 = 3; } message A112 { optional string a52 = 1; repeated A145 a106 = 2; repeated A146 a107 = 4; optional A147 a87 = 3; } message A145 { optional string a52 = 1; optional string a108 = 2; optional string a109 = 3; optional A98 a87 = 4; optional bool a110 = 5 [default = false]; optional bool a111 = 6 [default = false]; } message A146 { optional string a52 = 1; optional string a112 = 2; optional string a113 = 3; optional A148 a87 = 4; } message A60 { optional int32 a114 = 2 [default = 2]; reserved 15; reserved 22; optional bool a115 = 24 [default = true]; reserved 25; optional string a116 = 1; optional int32 a117 = 4 [default = 2]; optional int32 a118 = 5 [default = 2]; optional bool a119 = 6 [default = true]; optional bool a120 = 7 [default = true]; reserved 13; optional bool a121 = 21 [default = false]; optional string a122 = 19; optional bool a123 = 26 [default = false]; optional string a124 = 8; optional bool a125 = 10 [default = false]; optional bool a126 = 27 [default = false]; optional bool a127 = 28 [default = false]; optional string a128 = 29; enum A149 { A150 = 1; A151 = 2; A152 = 3; } optional A149 a129 = 9 [default = A150]; optional string a130 = 11; optional string a131 = 12; optional int32 a132 = 14 [default = 1]; optional bool a133 = 16 [default = false]; optional bool a134 = 17 [default = false]; optional bool a135 = 18 [default = false]; optional bool a136 = 42 [default = false]; optional bool a31 = 23 [default = false]; optional bool a137 = 31 [default = false]; reserved 32; reserved 33; reserved 34; reserved 35; optional string a138 = 36; optional string a139 = 37; optional string a140 = 39; optional string a141 = 40; optional string a142 = 41; optional bool a143 = 43; optional string a144 = 44; optional string a145 = 45; repeated A119 a96 = 999; extensions 1000 to max; reserved 38; } message A57 { repeated string a146 = 4; repeated string a147 = 5; repeated string a148 = 6; optional bool a149 = 1 [default = false]; optional bool a150 = 2 [default = false]; optional bool a31 = 3 [default = false]; optional bool a151 = 7; reserved 8; reserved 9; repeated A119 a96 = 999; extensions 1000 to max; } message A56 { optional A153 a152 = 1 [default = A154]; enum A153 { A154 = 0; A155 = 1; A156 = 2; } optional bool a409 = 2; optional A157 a153 = 6 [default = A158]; enum A157 { A158 = 0; A159 = 1; A160 = 2; } optional bool a154 = 5 [default = false]; optional bool a31 = 3 [default = false]; optional bool a155 = 10 [default = false]; message A161 { optional string a52 = 1; optional string a105 = 2; }; repeated A161 a156 = 11; optional bool a157 = 12 [default = false]; optional bool a158 = 13 [default = true]; repeated A119 a96 = 999; extensions 1000 to max; reserved 4; } message A142 { repeated A119 a96 = 999; extensions 1000 to max; } message A70 { optional string a159 = 1; reserved 4; optional bool a160 = 2; optional bool a31 = 3 [default = false]; reserved 5; repeated A119 a96 = 999; extensions 1000 to max; } message A76 { optional bool a31 = 1 [default = false]; repeated A119 a96 = 999; extensions 1000 to max; } message A147 { optional bool a161 = 20 [default = false]; optional double a162 = 16 [default = -1.0]; optional bool a31 = 33 [default = false]; repeated A119 a96 = 999; extensions 1000 to max; } message A98 { enum A162 { A163 = 0; A164 = 1; } enum A165 { A67 = 0; A166 = 1; A167 = 2; A168 = 3; } enum A169 { A170 = 0; A171 = 1; } enum A172 { A173 = 0; A174 = 1; A175 = 2; A176 = 3; A177 = 4; } optional A162 a163 = 7 [default = A163]; optional double a164 = 8 [default = -1.0]; optional bool a165 = 9 [default = false]; optional bool a166 = 10 [default = false]; optional bool a167 = 26 [default = false]; optional sint32 a168 = 11 [default = 256]; optional sint32 a169 = 12 [default = 256]; optional A165 a170 = 13 [default = A67]; optional A169 a171 = 15 [default = A170]; optional A169 a172 = 17 [default = A170]; optional string a173 = 18; optional string a174 = 19; optional bool a110 = 20; optional bool a111 = 21; optional string a175 = 22; optional string a176 = 23; optional bool a177 = 29; optional int64 a178 = 24 [default = -1]; optional int64 a179 = 25 [default = -1]; enum A178 { A179 = 0; A180 = 1; } optional A178 a180 = 28 [default = A180]; optional A172 a181 = 27 [default = A175]; optional bool a31 = 33 [default = false]; enum A181 { A182 = 0; A183 = 1; A184 = 2; } optional A181 a182 = 34 [default = A182]; repeated A119 a96 = 999; extensions 1000 to max; } message A148 { enum A178 { A179 = 0; A180 = 1; } optional int64 a183 = 1 [default = -1]; optional int64 a184 = 2 [default = -1]; optional A178 a185 = 3 [default = A179]; optional A98.A165 a170 = 4 [default = A67]; optional string a174 = 5; optional int32 a168 = 6 [default = 256]; optional int32 a169 = 7 [default = 256]; optional double a164 = 8 [default = -1.0]; optional bool a166 = 9 [default = false]; optional bool a167 = 10 [default = false]; optional A98.A172 a181 = 11 [default = A175]; optional bool a31 = 33 [default = false]; repeated A119 a96 = 999; extensions 1000 to max; } message A119 { message A185 { required string a186 = 1; required bool a187 = 2; } repeated A185 a52 = 2; optional string a188 = 3; optional uint64 a189 = 4; optional int64 a190 = 5; optional double a191 = 6; optional bytes a192 = 7; optional string a193 = 8; } message A114 { repeated A186 a194 = 1; message A186 { repeated int32 a195 = 1 [packed = true]; repeated int32 a196 = 2 [packed = true]; optional string a197 = 3; optional string a198 = 4; repeated string a199 = 6; } } message A187 { repeated A188 a200 = 1; message A188 { repeated int32 a195 = 1 [packed = true]; optional string a201 = 2; optional int32 a202 = 3; optional int32 a91 = 4; } } ================================================ FILE: benchmarks/protos/query_benchmark/f6.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a7; message A61 { enum A62 { A63 = 0; A64 = 1; A65 = 2; } optional A62 a28 = 1; } ================================================ FILE: benchmarks/protos/query_benchmark/f7.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a0.a1; enum A66 { A67 = 0; A68 = 1; A69 = 2; } ================================================ FILE: benchmarks/protos/query_benchmark/f8.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a10.a29; import "f5.proto"; extend a10.A57 { optional bool a30 = 147618788; optional bool a32 = 149418587 [default = true]; optional string a33 = 190288050; } extend a10.A70 { optional bool a34 = 149419467 [default = true]; optional bool a35 = 163526403; optional string a36 = 190295313; } enum A71 { A72 = 0; A73 = 1; A74 = 2; A75 = 3; } extend a10.A56 { optional A71 a37 = 179701954 [default = A73]; } extend a10.A76 { optional bool a38 = 162702653 [default = false]; optional bool a39 = 163486533 [default = false]; optional bool a40 = 170261731 [default = false]; repeated string a41 = 179096040; } enum A77 { A67 = 0; A78 = 1; A79 = 2; A80 = 3; A81 = 4; A82 = 5; A83 = 6; A84 = 7; A85 = 8; A86 = 9; A87 = 10; A88 = 11; A89 = 12; A90 = 13; A91 = 14; A92 = 15; A93 = 16; A94 = 17; A95 = 18; A96 = 100; A97 = 101; } extend a10.A60 { optional A77 a42 = 155465253 [default = A67]; optional bytes a43 = 157245250; optional bool a44 = 180648220 [default = true]; } extend a10.A98 { optional bool a45 = 211030419; } ================================================ FILE: benchmarks/protos/query_benchmark/f9.proto ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. syntax = "proto2"; package a46.a47.a1.a48.a49.a4; message A99 { optional double a50 = 1; optional int32 a51 = 2; optional string a52 = 3; repeated string a53 = 4; optional string a54 = 5; optional string a55 = 6; optional string a56 = 7; } message A100 { optional double a50 = 1; optional int32 a51 = 2; optional string a52 = 3; optional string a57 = 4; optional string a54 = 5; optional bool a58 = 6; optional float a59 = 7; optional string a60 = 8; } message A101 { optional string a52 = 1; optional string a54 = 2; optional string a61 = 3; optional int64 a62 = 4; optional int64 a63 = 5; optional string a64 = 6; optional int64 a65 = 7; optional int64 a66 = 8; optional bool a67 = 9; } ================================================ FILE: benchmarks/pubspec.yaml ================================================ # Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. name: protobuf_benchmarks description: Benchmarks for various protobuf functions. publish_to: none environment: sdk: ^3.7.0 resolution: workspace dependencies: # NB. When bumping benchmark_harness check if `benchmark_base.BenchmarkBase` # needs updating benchmark_harness: ^2.0.0 fixnum: any js: ^0.6.3 protobuf: any dev_dependencies: args: ^2.3.1 lints: '>=5.0.0 <7.0.0' path: ^1.8.2 pool: ^1.5.1 # Used from the workspace. protoc_plugin: any ================================================ FILE: benchmarks/tool/compile_benchmarks.dart ================================================ #!/usr/bin/env dart // Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: only_throw_errors import 'dart:io' show Directory, Platform, Process, ProcessResult, exit; import 'package:args/args.dart' show ArgParser; import 'package:path/path.dart' as path; import 'package:pool/pool.dart' show Pool; Future main(List args) async { final argParser = ArgParser() ..addOption( 'target', mandatory: false, defaultsTo: 'aot,exe,jit,js,js-production', ) ..addOption('jobs', abbr: 'j', mandatory: false); final parsedArgs = argParser.parse(args); var jobs = Platform.numberOfProcessors; if (parsedArgs['jobs'] != null) { jobs = int.parse(parsedArgs['jobs'] as String); } final targets = {}; for (final targetStr in (parsedArgs['target'] as String).split(',')) { switch (targetStr) { case 'aot': targets.add(aotTarget); break; case 'exe': targets.add(exeTarget); break; case 'jit': targets.add(jitTarget); break; case 'js': targets.add(jsTarget); break; case 'js-production': targets.add(jsProductionTarget); break; case 'wasm': targets.add(wasmTarget); break; default: print( 'Unsupported target: $targetStr. Supported targets: aot, exe, ' 'jit, js, js-production, wasm, wasm-omit-checks', ); exit(1); } } var sourceFiles = parsedArgs.rest; if (sourceFiles.isEmpty) { // Compile all files in bin/ sourceFiles = Directory('bin') .listSync(recursive: false) .where((dirFile) => path.extension(dirFile.path) == '.dart') .map((dirFile) => dirFile.path) .toList(); } final commands = >[]; if (sourceFiles.isNotEmpty && targets.isNotEmpty) { try { Directory('out').createSync(recursive: true); } catch (e) { print("Error while creating 'out' directory: $e"); exit(1); } } for (final sourceFile in sourceFiles) { for (final target in targets) { commands.add(target.compileArgs(sourceFile)); } } final pool = Pool(jobs); final stream = pool.forEach, CompileProcess>(commands, ( List command, ) async { final commandStr = command.join(' '); print(commandStr); final result = await Process.run(command[0], command.sublist(1)); return CompileProcess(commandStr, result); }); await for (final compileProcess in stream) { final exitCode = compileProcess.result.exitCode; if (exitCode != 0) { print('Process exited with $exitCode'); print('Command: ${compileProcess.command}'); print( 'Process stdout ---------------------------------------------------', ); print(compileProcess.result.stdout); print( 'Process stderr ---------------------------------------------------', ); print(compileProcess.result.stderr); print( '------------------------------------------------------------------', ); exit(1); } } await pool.done; } class CompileProcess { final String command; final ProcessResult result; CompileProcess(this.command, this.result); } class Target { final String _name; final List Function(String) _processArgs; const Target(this._name, this._processArgs); @override String toString() { return 'Target($_name)'; } List compileArgs(String sourceFile) { return _processArgs(sourceFile); } } const aotTarget = Target('aot', aotProcessArgs); const exeTarget = Target('exe', exeProcessArgs); const jitTarget = Target('jit', jitProcessArgs); const jsTarget = Target('js', jsProcessArgs); const jsProductionTarget = Target('js-production', jsProductionProcessArgs); const wasmTarget = Target('wasm', wasmProcessArgs); List aotProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return [ 'dart', 'compile', 'aot-snapshot', sourceFile, '-o', 'out/$baseNameNoExt.aot', ]; } List exeProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return ['dart', 'compile', 'exe', sourceFile, '-o', 'out/$baseNameNoExt.exe']; } List jitProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return [ 'dart', '--snapshot-kind=kernel', '--snapshot=out/$baseNameNoExt.dill', sourceFile, ]; } List jsProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return ['dart', 'compile', 'js', sourceFile, '-o', 'out/$baseNameNoExt.js']; } List jsProductionProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return [ 'dart', 'compile', 'js', sourceFile, '-O4', '-o', 'out/$baseNameNoExt.production.js', ]; } List wasmProcessArgs(String sourceFile) { final baseName = path.basename(sourceFile); final baseNameNoExt = path.withoutExtension(baseName); return [ 'dart', 'compile', 'wasm', sourceFile, '-O2', '--no-strip-wasm', '-o', 'out/$baseNameNoExt.wasm', ]; } ================================================ FILE: benchmarks/tool/compile_protos.sh ================================================ #!/bin/bash # Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. SCRIPT_DIR=$(dirname "${BASH_SOURCE}") BENCHMARK_DIR=$SCRIPT_DIR/.. # These protos don't have any imports SIMPLE_PROTOS=( "protos/google_message1_proto2.proto" "protos/google_message1_proto3.proto" "protos/google_message2.proto" "protos/packed_fields.proto" ) set -x set -e mkdir -p lib/generated protoc --dart_out=lib/generated --plugin=protoc-gen-dart=tool/run_protoc_plugin.sh \ -I$BENCHMARK_DIR/protos \ "${SIMPLE_PROTOS[@]/#/$BENCHMARK_DIR/}" protoc --dart_out=lib/generated --plugin=protoc-gen-dart=tool/run_protoc_plugin.sh \ -I$BENCHMARK_DIR/protos/query_benchmark \ $BENCHMARK_DIR/protos/query_benchmark/*.proto ================================================ FILE: benchmarks/tool/run_protoc_plugin.sh ================================================ #!/usr/bin/env bash # Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. dart run protoc_plugin protoc-gen-dart ================================================ FILE: protobuf/CHANGELOG.md ================================================ ## 6.0.0 * New `GeneratedMessage` extension methods `toTextFormat` and `writeTextFormat` added to convert the message into the [official protocol buffers text format][text format]. ([#1080], [#125]) * Add [well-known proto types][wkts] as libraries. This change is required for protoc_plugin-25.0.0. ([#1081]) * **Breaking:** Hide `PbList` and `PbMap` constructors. It is not possible to construct these values correctly in user code, so the constructors are now private. Existing uses of `PbList` can be replaced by `List` and `PbMap` can be replaced by `Map`. For immutable lists and maps, you can use `built_value`. ([#1072]) * Map fields now check key and value validity when adding elements. ([#1065], [#1076]) [text format]: https://protobuf.dev/reference/protobuf/textformat-spec/ [#1080]: https://github.com/google/protobuf.dart/pull/1080 [#125]: https://github.com/google/protobuf.dart/issues/125 [wkts]: https://protobuf.dev/reference/protobuf/google.protobuf [#1081]: https://github.com/google/protobuf.dart/pull/1081 [#1072]: https://github.com/google/protobuf.dart/pull/1072 [#1065]: https://github.com/google/protobuf.dart/issues/1065 [#1076]: https://github.com/google/protobuf.dart/pull/1076 ## 5.1.0 * Update default size limit of `CodedBufferReader` from 67,108,864 bytes to 2,147,483,647 bytes, and default recursion limit from 64 to 100. The new limits are consistent with the Java and C++ implementations. ([#1060]) * Fix `GeneratedMessage.addExtension` returning non-frozen and `GeneratedMessage.getExtension` allowing modifying an extension when the message is frozen before initializing the extension field set. ([#1062]) * Fix `GeneratedMessage.getExtension` returning differently typed lists when the message extension field set is initialized and frozen and initialized but not frozen. ([#1062]) * Fix `PbList` methods `addAll`, `insertAll`, `replaceRange`, `setAll`, `setRange` iterating the `Iterable` argument twice. ([#730], [#1070]) * Fix `GeneratedMessage.==` throwing a type error when comparing `map` fields in some cases. ([#1075], [#1077]) This bug was introduced with protobuf-5.0.0. [#1060]: https://github.com/google/protobuf.dart/pull/1060 [#1062]: https://github.com/google/protobuf.dart/pull/1062 [#730]: https://github.com/google/protobuf.dart/issues/730 [#1070]: https://github.com/google/protobuf.dart/pull/1070 [#1075]: https://github.com/google/protobuf.dart/issues/1075 [#1077]: https://github.com/google/protobuf.dart/pull/1077 ## 5.0.0 * Improve performance of `GeneratedMessage.deepCopy`. ([#742]) * Fix unknown enum handling in `GeneratedMessage.mergeFromProto3Json` when the `ignoreUnknownFields` optional argument is `true`. ([#853]) * Add `BuilderInfo` methods to support protoc-plugin 23.0.0. ([#1047]) * Generalize argument type of `PbList.from` from `List` to `Iterable`. ([#1054]) * Fix clearing oneof fields with `GeneratedMessage.clear`. ([#1057]) * Fix unknown JSON handling when using `GeneratedMessage` methods `mergeFromJson`, `mergeFromJsonMap`, `writeToJson`, `writeToJsonMap`. ([#1058]) [#742]: https://github.com/google/protobuf.dart/pull/742 [#853]: https://github.com/google/protobuf.dart/pull/853 [#1047]: https://github.com/google/protobuf.dart/pull/1047 [#1054]: https://github.com/google/protobuf.dart/pull/1054 [#1057]: https://github.com/google/protobuf.dart/pull/1057 [#1058]: https://github.com/google/protobuf.dart/pull/1058 ## 4.2.0 * Internal refactoring to split the package into libraries. This allows conditionally importing different libraries and improving performance by using different encoding/decoding libraries based on the target platform. ([#1026]) * Some of the private `PbFieldType` members are made public, to allow using them in internal libraries. This type is for internal use only. ([#1027]) * Improve performance of `GeneratedMessage` members: `writeToJsonMap`, `writeToJson`, `mergeFromJson`, `mergeFromJsonMap`. ([#1028]) * Remove `BuilderInfo.fromProto3Json` and `BuilderInfo.toProto3Json` as a part of an internal refactoring. [#1026]: https://github.com/google/protobuf.dart/pull/1026 [#1027]: https://github.com/google/protobuf.dart/pull/1027 [#1028]: https://github.com/google/protobuf.dart/pull/1028 ## 4.1.1 * Minimum SDK dependency bumped from 3.6.0 to 3.7.0. ([#1024]) [#1024]: https://github.com/google/protobuf.dart/pull/1024 ## 4.1.0 * Improve packed field decoding performance. ([#959], [#981]) * Minimum SDK dependency bumped from 3.3.0 to 3.6.0. ([#1001]) [#959]: https://github.com/google/protobuf.dart/pull/959 [#981]: https://github.com/google/protobuf.dart/pull/981 [#1001]: https://github.com/google/protobuf.dart/pull/1001 ## 4.0.0 * **Breaking:** The following types and members are now removed: - `PbEventMixin` - `PbFieldChange` - `EventBuffer` - `GeneratedMessage.createRepeatedField` - `GeneratedMessage.createMapField` These were used to implement events, which are unused internally. To keep API surface small (to make it easier to change the library or migrate to another library) these types and members are removed. ([#738]) * **Breaking:** `CodedBufferWriter.writeRawBytes` now takes a `Uint8List` argument (instead of `TypedData`). * `GeneratedMessageGenericExtensions.deepCopy` is now annotated with `@useResult` and will generate a warning when its result is not used. ([#896]) * **Breaking:** `PbMap.unmodifiable` now takes key and value field types as arguments, instead of another `PbMap`. To migrate, use `PbMap.unmodifiable(map.keyFieldType, map.valueFieldType)` instead of `PbMap.unmodifiable(map)`. ([#902]) * Messages deserialized from JSON now generate the unknown fields when serialized as JSON. Note that, as before, unknown fields in JSON messages are not stored in the `unknownFields` of the message. They are only used by the JSON serializers to support roundtripping. ([#49], [#918]) * Minimum SDK dependency bumped from 2.19.0 to 3.3.0. (#953) [#738]: https://github.com/google/protobuf.dart/issues/738 [#896]: https://github.com/google/protobuf.dart/issues/896 [#902]: https://github.com/google/protobuf.dart/issues/902 [#49]: https://github.com/google/protobuf.dart/issues/49 [#918]: https://github.com/google/protobuf.dart/pulls/918 [#953]: https://github.com/google/protobuf.dart/pull/953 ## 3.1.0 * `CodedBufferReader` `readBytes` now copies the returned bytes to avoid accidental sharing of the input buffer with the returned `Uint8List`. New member `readBytesAsView` added with the old behavior. ([#863]) * Avoid sharing the input buffer in unknown length-delimited fields using the new `readBytes`. ([#863]) [#863]: https://github.com/google/protobuf.dart/pull/863 ## 3.0.0 * Require Dart `2.19`. * Remove `ReadonlyMessageMixin` ([#183], [#644]) * Remove `frozenMessageModificationHandler` ([#175], [#643]) * Remove `PbListBase` and `FrozenPbList` types. All proto repeated fields now use `PbList`. To check if a list is frozen, use `isFrozen` getter. ([#624], [#626]) * Initialize map fields in `GeneratedMessage.getField`. This behavior is consistent with `getField` called on repeated fields. ([#373], [#707]) * Remove unused and optional `PbMap` constructor argument `BuilderInfo? info`. ([d94d3f0]) * `UnknownFieldSetField` methods `hasRequiredFields`, `isInitialized` and getter `length` removed. ([#721]) * Update library documentation to hide internals, add documentation for public types. ([#681]) * Fix `PbMap._isReadonly` field initialization in `PbMap.unmodifiable`. ([#741], [#754]) * Fix decoding map fields when key or value (or both) fields of a map entry is missing. ([#719], [#745]) * Fix updating frozen (immutable) messages with merge methods (`mergeFromBuffer`, `mergeFromProto3Json`, ...). ([#489], [#727]) * Fix handling `null` values in proto3 JSON deserializer. ([#751], [#760], [#763]) * Fix handling negative JSON values when parsing uint32 fields. ([#839]) * Avoid serializing unknown fields twice in `reparseMessage`. ([#840]) [#183]: https://github.com/google/protobuf.dart/issues/183 [#644]: https://github.com/google/protobuf.dart/pull/644 [#175]: https://github.com/google/protobuf.dart/issues/175 [#643]: https://github.com/google/protobuf.dart/pull/643 [#624]: https://github.com/google/protobuf.dart/issues/624 [#626]: https://github.com/google/protobuf.dart/pull/626 [#373]: https://github.com/google/protobuf.dart/issues/373 [#707]: https://github.com/google/protobuf.dart/pull/707 [d94d3f0]: https://github.com/google/protobuf.dart/commit/d94d3f0 [#721]: https://github.com/google/protobuf.dart/pull/721 [#681]: https://github.com/google/protobuf.dart/pull/681 [#741]: https://github.com/google/protobuf.dart/pull/741 [#719]: https://github.com/google/protobuf.dart/issues/719 [#745]: https://github.com/google/protobuf.dart/pull/745 [#489]: https://github.com/google/protobuf.dart/issues/489 [#727]: https://github.com/google/protobuf.dart/pull/727 [#751]: https://github.com/google/protobuf.dart/issues/751 [#760]: https://github.com/google/protobuf.dart/issues/760 [#763]: https://github.com/google/protobuf.dart/pull/763 [#754]: https://github.com/google/protobuf.dart/pull/754 [#839]: https://github.com/google/protobuf.dart/pull/839 [#840]: https://github.com/google/protobuf.dart/pull/840 ## 2.1.0 * Update READMEs of `protobuf` and `protoc_plugin`: * Use `dart pub` instead of `pub` in command examples ([a7e75cb]) * Fix typos, clarify installation instructions, mention native compilation, fix proto syntax for `protoc_plugin` ([#610], [#617], [#641]) * Update some of the documentation according to Effective Dart documentation guide ([#664], [#674]) * Improve runtime perf by removing some of the runtime type checks ([#574], [#573]) * Fix a bug when converting negative `Timestamp` to Dart `DateTime` ([#580], [#577]) * Document `BuilderInfo` and `FieldInfo` properties ([#597]) * Improve `BuilderInfo` initialization by doing some of the work lazily ([#606]) * Improve enum hash code generation ([#556]) * Fix parsing nested `Any` messages from JSON ([#568]) * Improve message hash code generation performance ([#554], [#633]) * Fix reading uninitialized map fields changing equality and hash code of messages. ([#638]) * Fix setting an extension field when there's an unknown field with the same tag. ([#639]) * Fix sharing backing memory for `repeated bytes` and `optional bytes` fields. ([#640]) * `GeneratedMessage.rebuild` now generates a warning when the return value is not used. ([#631]) * Fix hash code of messages with empty unknown field set ([#648]) * Show field tags with `protobuf.omit_field_names`, enum value tags with `protobuf.omit_enum_names` in debug strings (`toString` methods) ([#649]) * `TimestampMixin.toDateTime` now takes an optional named `bool` argument `toLocal` (defaults to `false`) for generating a `DateTime` in the local time zone (instead of UTC). ([#653]) * Fix serialization of `infinity` and `nan` doubles in JSON serializers ([#652]) * Fix Dart generation for fields starting with underscore ([#651]) * Fix proto3 JSON deserialization of fixed32 fields ([#655]) * Fix uninitialized repeated field values runtime types for frozen messages ([#654]) [a7e75cb]: https://github.com/google/protobuf.dart/commit/a7e75cb [#610]: https://github.com/google/protobuf.dart/pull/610 [#617]: https://github.com/google/protobuf.dart/pull/617 [#574]: https://github.com/google/protobuf.dart/pull/574 [#573]: https://github.com/google/protobuf.dart/issues/573 [#580]: https://github.com/google/protobuf.dart/pull/580 [#577]: https://github.com/google/protobuf.dart/issues/577 [#597]: https://github.com/google/protobuf.dart/pull/597 [#606]: https://github.com/google/protobuf.dart/pull/606 [#556]: https://github.com/google/protobuf.dart/pull/556 [#568]: https://github.com/google/protobuf.dart/pull/568 [#554]: https://github.com/google/protobuf.dart/pull/554 [#633]: https://github.com/google/protobuf.dart/pull/633 [#638]: https://github.com/google/protobuf.dart/pull/638 [#639]: https://github.com/google/protobuf.dart/pull/639 [#640]: https://github.com/google/protobuf.dart/pull/640 [#641]: https://github.com/google/protobuf.dart/pull/641 [#631]: https://github.com/google/protobuf.dart/pull/631 [#648]: https://github.com/google/protobuf.dart/pull/648 [#649]: https://github.com/google/protobuf.dart/pull/649 [#653]: https://github.com/google/protobuf.dart/pull/653 [#652]: https://github.com/google/protobuf.dart/pull/652 [#651]: https://github.com/google/protobuf.dart/pull/651 [#655]: https://github.com/google/protobuf.dart/pull/655 [#654]: https://github.com/google/protobuf.dart/pull/654 [#664]: https://github.com/google/protobuf.dart/pull/664 [#674]: https://github.com/google/protobuf.dart/pull/674 ## 2.0.1 * Fix bug of parsing map-values with default values. * Merge fixes from version `1.1.2` - `1.1.4` into v2. ## 2.0.0 * Stable null safety release. ## 1.1.4 * Fix comparison of empty lists from frozen messages. * Switch repo internals to use `dart format` instead of `dartfmt`. ## 1.1.3 * Fix that fixed32 int could be negative. ## 1.1.2 * Fix proto deserialization issue for repeated and map enum value fields where the enum value is unknown. ## 1.1.1 * Fix decoding of `oneof` fields from proto3 json. The 'whichFoo' state would not be set. * Fix the return type of `copyWith`. ## 1.1.0 * Require at least Dart SDK 2.7.0 to enable usage of extension methods. * Introduce extension methods `GeneratedMessage.rebuild` and `GeneratedMessage.deepCopy` replacing `copyWith` and `clone`. Using these alternatives can result in smaller binaries, because it is defined once instead of once per class. Use `protoc_plugin` from 19.1.0 to generate deprecation warnings for `copyWith` and `clone` methods. * `GeneratedMessage.getExtension` throws when reading trying to read an extension that is present in the unknown fields. We consider this change a bug-fix because depending on the old behavior is indicative of a bug in your program. ## 1.0.4 * Requires sdk 2.3.0 * Update pedantic to 1.9.2 ## 1.0.3 * Enable hashCode memoization for frozen protos. * Add `timeout` to `ClientContext` ## 1.0.2 * Fix hashcode of bytes fields. * Fix issue with the `permissiveEnums` option to `mergeFromProto3Json`. The comparison did not work properly. * Fix binary representation of negative int32 values. ## 1.0.1 * Fix issue with `ExtensionRegistry.reparseMessage` not handling map fields with scalar value types correctly. * Fix issue with the non-json name of a field (`protoName`) not being set correctly. * Fix: Allow decoding tagnumbers of unknown fields of up to 29 bits. ## 1.0.0 * Graduate package to 1.0. No functional changes. ## 0.14.4 * Add `permissiveEnums` option to `mergeFromProto3Json`. It will do a case-insensitive matching of enum values ignoring `-` and `_`. * Add support for 'ensureX' methods generated by `protoc_plugin` 19.0.0. * Add specialized getters for `String`, `int`, and `bool` with usual default values. * Shrink dart2js generated code for `getDefault()`. * Added an annotation class `TagNumber`. This is used by code generated by `protoc_plugin` from version 19.0.0. ## 0.14.3 * Fix: Allow decoding tagnumbers of up to 29 bits. Would fail before with more than 28 bits. ## 0.14.2 * Expose `mapEntryBuilderInfo` in `MapFieldInfo`. ## 0.14.1 * Support for `import public`. The generated code for a protofile `a.proto` that `import public "b.proto"` will export the generated code for `b.proto`. See https://developers.google.com/protocol-buffers/docs/proto#importing-definitions. ## 0.14.0 * Support for proto3 json (json with field names as keys) - encoding and decoding. - Support for well-known types. - Use `GeneratedMessage.toProto3Json()` to encode and `GeneratedMessage.mergeFromProto3Json(json)` to decode. * `FieldInfo` objects have a new getter `.protoName` that gives the non-camel-case name of the field as in the `.proto`-file. * **Breaking**: The field-adder methods on `BuilderInfo` now takes only named optional arguments. To migrate, update `protoc_plugin` to version 18.0.0 or higher. * The field-adder methods on `BuilderInfo` all take a new argument `protoName`. * **Breaking**: Changed `ExtensionRegistry.reparseMessage` to reparse extensions deeply, that is it looks at every nested message and tries to reparse extensions from its unknown fields. ## 0.13.16+1 * Reverts `0.13.16` which accidentally introduced a breaking change, [#284](https://github.com/google/protobuf.dart/issues/284). This release is identical to `0.13.15`. ## 0.13.16 * Better handling of dummy calls to `BuilderInfo.add` with a tag number of 0. These would trigger assertions before. ## 0.13.15 * Add new getter `GeneratedMessage.isFrozen` to query if the message has been frozen. ## 0.13.14 * Avoid needless copy when reading from a Uint8List buffer. ## 0.13.13 * `Added`ExtensionRegistry.reparseMessage()` for decoding extensions from unknown fields after the initial decoding. ## 0.13.12 * `BuilderInfo.add` now ignores fields with tag number 0. These would never be generated by the protoc_plugin so this is not considered a breaking change. ## 0.13.11 * Save memory by only initializing `_FieldSet.oneofCases` if the message contains oneofs. ## 0.13.10 * Fix recursive merging of repeated elements. ## 0.13.9 * Move 'eventPlugin' callback when setting a field in order to notify observers about field updates in the correct order. ## 0.13.8 * Fix JSON serialization of unsigned 64-bit fields. ## 0.13.7 * Override `operator ==` and `hashCode` in `PbMap` so that two `PbMap`s are equal if they have equal key/value pairs. ## 0.13.6 * Fixed equality check between messages with and without extensions. ## 0.13.5 * Add new method `addAll` on ExtensionRegistry for more conveniently adding multiple extensions at once. ## 0.13.4 * Add new method `pc` on BuilderInfo for adding repeated composite fields and remove redundant type check on items added to a PbList. Deprecated `BuilderInfo.pp` and `PbList.forFieldType`. ## 0.13.3 * Fix issue with parsing map field entries. The values for two different keys would sometimes be merged. * Deprecated `PBMap.add`. ## 0.13.2 * Include extension fields in GeneratedMessage.toString(). ## 0.13.1 * Fix issue with not being able to read unknown fields after freezing. Reading an unknown field set after freeze() now returns the existing field set before freezing instead of an empty UnknownFieldSet. ## 0.13.0 * Breaking change: Fix issue with not being able to read extensions after freezing. Reading an extension field after freeze() now returns the value set before freezing instead of the default value. ## 0.12.0 * Breaking change: Changed `BuilderInfo.m()` to take class and package name of the protobuf message representing the map entry. Also changed `BuilderInfo.addMapField` as well as the constructors `PbMap` and `MapFieldInfo.map` to take a map entry BuilderInfo object. This mostly affects generated code, which should now be built with protoc_plugin 15.0.0 or newer. With this change we avoid creating a map entry BuilderInfo object for each PbMap instance, instead it is passed through the static BuilderInfo object in the generated subclasses of GeneratedMessage. ## 0.11.0 * Breaking change: changed semantics of `GeneratedMessage.toBuilder()` to only make a shallow copy. `GeneratedMessage` has a new abstract method: `createEmptyInstance()` that subclasses must implement. Proto files must be rebuilt using protoc_plugin 14.0.0 or newer. ## 0.10.8 * Fix freezing of map fields. ## 0.10.7 * Fixed problem with recursive merging of sub messages. ## 0.10.6 * Added support for [oneof](https://developers.google.com/protocol-buffers/docs/proto3#oneof). To use oneof support use Dart protoc_plugin version 13.0.0. ## 0.10.5 * Added support for [map fields](https://developers.google.com/protocol-buffers/docs/proto3#maps). Map fields are now represented as Dart maps and are accessed through a getter with the same name as the map field. To use the map support, use Dart protoc_plugin version 11.0.0 or newer. ## 0.10.4 * Added separate getter for `BuilderInfo.qualifiedMessageName`. ## 0.10.3 * Added type argument to `ProtobufEnum.initByValue` which allows the return value to be fully typed. ## 0.10.2 * Added ProtobufEnum reserved names. ## 0.10.1 * Added Support for [any](https://developers.google.com/protocol-buffers/docs/proto3#any) messages. ## 0.10.0 * Breaking change: Add `GeneratedMessage.freeze()`. A frozen message and its sub-messages cannot be changed. ## 0.9.1 * Fix problem with encoding negative enum values. * Fix problem with encoding byte arrays. ## 0.9.0+1 * Dart SDK upper constraint raised to declare compatibility with Dart 2.0 stable. ## 0.9.0 * Breaking change: Changed signature of `CodedBufferWriter.writeTo` to require `Uint8List` for performance. * More Dart 2 fixes. ## 0.8.0 * Breaking change: Added generics to RpcClient.invoke(). Proto files must be rebuilt using Dart protoc_plugin version 0.8.0 or newer to match. * Dart 2 fixes. ## 0.7.2+1 - Updated SDK version to 2.0.0-dev.17.0 ## 0.7.2 * Fix hashing for PbList. ## 0.7.1 * Fix type in PbList.fold() for Dart 2. * Small performance tweaks for DDC. ## 0.7.0 * Added fast getters for common types. * Only pass index instead of both tag and index to accessors. * Delegate more methods to underlying list in PbList. * Small fixes for Dart 2.0. ## 0.6.0 * Added enumValues to FieldInfo. Fixes #63. * Small performance optimization when deserializing repeated messages from JSON. * Type annotations for strong mode. ## 0.5.5 * Use real generic syntax instead of comment-based. * Support v2 dev SDKs. ## 0.5.4 * Unknown enum values are ignored when parsing JSON, instead of throwing an exception. ## 0.5.3+2 * Resolved a strong-mode error. ## 0.5.3+1 * Performance: Avoid excessive cloning in merge. * Performance: Use code patterns that dart2js handles better. ## 0.5.3 * fix zigzag function so all coded buffer reader tests work on dart2js. ## 0.5.2 * make PbMixin constructor public for use within protoc plugin. ## 0.5.1+5 * Revert previous change because it causes strong mode type error in the generated code. We will revisit this in a new version of mixin support. ## 0.5.1+4 * Use a more refined implementation of `Map` in `PbMapMixin` ## 0.5.1+3 * Performance: eliminate some dynamic calls. ## 0.5.1+2 * Bugfix: remove dependency on `pkg/crypto` for real. ## 0.5.1+1 * Require at least Dart SDK 1.13. * Removed dependency on `pkg/crypto`. ## 0.5.1 * Experimental support for strong mode. * Fixed an issue with GeneratedMessage operator== and Map mixins * Added declaration of GeneratedMessage clone method ## 0.5.0+1 * Support the latest version of package `fixnum`. ## 0.5.0 * Reorganized internals to improve performance. We now store field values in a list instead of a map. Private properties and methods are all moved to the \_FieldSet class. There are new entry points for generated getters, hazzers, and setters. Improved JSON decoding performance. * Dropped compatibility with .pb.dart files before 0.4.2 by removing internal constants from GeneratedMessage. Also, protoc plugins before 0.5.0 won't work. ## 0.4.2 * Renamed FieldType to PbFieldType. ## 0.4.1 - DO NOT USE * added FieldType class. It turned out that FieldType is a commonly used name, even in .proto files. This is renamed to PbFieldType in 0.4.2. * Added support for observing field changes. For now, this can only be enabled by using a mixin to override the eventPlugin getter. * Removed optional third parameter from setField(). It was only intended for internal use, and could be used to defeat type checks on fields. * clearExtension() removes the value and extension in all cases. (Before, the extension would be kept and the list cleared for repeated fields.) * Upcoming: clearField() will require its argument to be a known tag number (which could be an extension). For now, this is only enforced when a mixin provides an eventPlugin. ## 0.4.0 * Add ReadonlyMessageMixin. The generated message classes use this to for the default values of message fields. ## 0.3.11 * Add meta.dart which declares reserved names for the plugin. ## 0.3.10 * Add GeneratedService and ProtobufClient interfaces. ## 0.3.9 * Add experimental mixins_meta library * Add experimental PbMapMixin class (in a separate library). * Fix bug where ExtensionRegistry would not be used for nested messages. ## 0.3.7 * More docs. ## 0.3.6 * Added mergeFromMap() and writeToJsonMap() * Fixed an analyzer warning. ## 0.3.5+3 * Bugfix for `setRange()`: Do not assume Iterable has a `sublist()` method. ## 0.3.5+2 * Simplify some types used in is checks and correct PbList to match the * signature of the List setRange method. ## 0.3.5+1 * Bugfix for incorrect decoding of protobuf messages: Uint8List views with non-zero offsets were handled incorrectly. ## 0.3.5 * Allow constants as field initial values as well as creation thunks to reduce generated code size. * Improve the performance of reading a protobuf buffer. * Fixed truncation error in least significant bits with large Int64 constants. ================================================ FILE: protobuf/LICENSE ================================================ Copyright 2013, the Dart project authors. 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 LLC 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. ================================================ FILE: protobuf/README.md ================================================ [![pub package](https://img.shields.io/pub/v/protobuf.svg)](https://pub.dev/packages/protobuf) [![package publisher](https://img.shields.io/pub/publisher/protobuf.svg)](https://pub.dev/packages/protobuf/publisher) Provides runtime support for a Dart implementation of [protobufs][1]. Typically one does not need to import this library. The [protoc plugin][2] compiles proto definitions to Dart files that import this library. If your library or application uses generated protobuf libraries, add this library as a dependency. [1]: https://developers.google.com/protocol-buffers [2]: https://pub.dev/packages/protoc_plugin ### References * [Protobuf Dart tutorial](https://developers.google.com/protocol-buffers/docs/darttutorial) * [Guide to generated Dart code](https://developers.google.com/protocol-buffers/docs/reference/dart-generated) * [Dart API](https://pub.dev/documentation/protobuf/latest/protobuf/protobuf-library.html) ================================================ FILE: protobuf/analysis_options.yaml ================================================ include: ../analysis_options.yaml ================================================ FILE: protobuf/build_wkts.sh ================================================ #!/bin/bash # This scripts generates the classes for well-known protobuf types which are # included in the package. set -e set -x mkdir -p lib/well_known_types/google/protobuf protoc \ --dart_out=lib/well_known_types \ --plugin=protoc-gen-dart=$(realpath '../protoc_plugin/bin/protoc-gen-dart-debug') \ google/protobuf/*.proto # Remove empty .pbenum files. rm lib/well_known_types/google/protobuf/any.pbenum.dart rm lib/well_known_types/google/protobuf/api.pbenum.dart rm lib/well_known_types/google/protobuf/duration.pbenum.dart rm lib/well_known_types/google/protobuf/empty.pbenum.dart rm lib/well_known_types/google/protobuf/field_mask.pbenum.dart rm lib/well_known_types/google/protobuf/source_context.pbenum.dart rm lib/well_known_types/google/protobuf/timestamp.pbenum.dart rm lib/well_known_types/google/protobuf/wrappers.pbenum.dart ================================================ FILE: protobuf/google/protobuf/any.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option go_package = "google.golang.org/protobuf/types/known/anypb"; option java_package = "com.google.protobuf"; option java_outer_classname = "AnyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in 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()); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := anypb.New(foo) // if err != nil { // ... // } // ... // foo := &pb.Foo{} // if err := any.UnmarshalTo(foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": , // "lastName": // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } // message Any { // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). // // In practice, teams usually precompile into the binary all types that they // expect it to use in the context of Any. However, for URLs which use the // scheme `http`, `https`, or no scheme, one can optionally set up a type // server that maps type URLs to message definitions as follows: // // * If no scheme is provided, `https` is assumed. // * An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // * Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Note: this functionality is not currently available in the official // protobuf release, and it is not used for type URLs beginning with // type.googleapis.com. As of May 2023, there are no widely used type server // implementations and no plans to implement one. // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. // string type_url = 1; // Must be a valid serialized protocol buffer of the above specified type. bytes value = 2; } ================================================ FILE: protobuf/google/protobuf/api.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; import "google/protobuf/source_context.proto"; import "google/protobuf/type.proto"; option java_package = "com.google.protobuf"; option java_outer_classname = "ApiProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/apipb"; // Api is a light-weight descriptor for an API Interface. // // Interfaces are also described as "protocol buffer services" in some contexts, // such as by the "service" keyword in a .proto file, but they are different // from API Services, which represent a concrete implementation of an interface // as opposed to simply a description of methods and bindings. They are also // sometimes simply referred to as "APIs" in other contexts, such as the name of // this message itself. See https://cloud.google.com/apis/design/glossary for // detailed terminology. // // New usages of this message as an alternative to ServiceDescriptorProto are // strongly discouraged. This message does not reliability preserve all // information necessary to model the schema and preserve semantics. Instead // make use of FileDescriptorSet which preserves the necessary information. message Api { // The fully qualified name of this interface, including package name // followed by the interface's simple name. string name = 1; // The methods of this interface, in unspecified order. repeated Method methods = 2; // Any metadata attached to the interface. repeated Option options = 3; // A version string for this interface. If specified, must have the form // `major-version.minor-version`, as in `1.10`. If the minor version is // omitted, it defaults to zero. If the entire version field is empty, the // major version is derived from the package name, as outlined below. If the // field is not empty, the version in the package name will be verified to be // consistent with what is provided here. // // The versioning schema uses [semantic // versioning](http://semver.org) where the major version number // indicates a breaking change and the minor version an additive, // non-breaking change. Both version numbers are signals to users // what to expect from different versions, and should be carefully // chosen based on the product plan. // // The major version is also reflected in the package name of the // interface, which must end in `v`, as in // `google.feature.v1`. For major versions 0 and 1, the suffix can // be omitted. Zero major versions must only be used for // experimental, non-GA interfaces. // string version = 4; // Source context for the protocol buffer service represented by this // message. SourceContext source_context = 5; // Included interfaces. See [Mixin][]. repeated Mixin mixins = 6; // The source syntax of the service. Syntax syntax = 7; // The source edition string, only valid when syntax is SYNTAX_EDITIONS. string edition = 8; } // Method represents a method of an API interface. // // New usages of this message as an alternative to MethodDescriptorProto are // strongly discouraged. This message does not reliability preserve all // information necessary to model the schema and preserve semantics. Instead // make use of FileDescriptorSet which preserves the necessary information. message Method { // The simple name of this method. string name = 1; // A URL of the input message type. string request_type_url = 2; // If true, the request is streamed. bool request_streaming = 3; // The URL of the output message type. string response_type_url = 4; // If true, the response is streamed. bool response_streaming = 5; // Any metadata attached to the method. repeated Option options = 6; // The source syntax of this method. // // This field should be ignored, instead the syntax should be inherited from // Api. This is similar to Field and EnumValue. Syntax syntax = 7 [deprecated = true]; // The source edition string, only valid when syntax is SYNTAX_EDITIONS. // // This field should be ignored, instead the edition should be inherited from // Api. This is similar to Field and EnumValue. string edition = 8 [deprecated = true]; } // Declares an API Interface to be included in this interface. The including // interface must redeclare all the methods from the included interface, but // documentation and options are inherited as follows: // // - If after comment and whitespace stripping, the documentation // string of the redeclared method is empty, it will be inherited // from the original method. // // - Each annotation belonging to the service config (http, // visibility) which is not set in the redeclared method will be // inherited. // // - If an http annotation is inherited, the path pattern will be // modified as follows. Any version prefix will be replaced by the // version of the including interface plus the [root][] path if // specified. // // Example of a simple mixin: // // package google.acl.v1; // service AccessControl { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v1/{resource=**}:getAcl"; // } // } // // package google.storage.v2; // service Storage { // rpc GetAcl(GetAclRequest) returns (Acl); // // // Get a data record. // rpc GetData(GetDataRequest) returns (Data) { // option (google.api.http).get = "/v2/{resource=**}"; // } // } // // Example of a mixin configuration: // // apis: // - name: google.storage.v2.Storage // mixins: // - name: google.acl.v1.AccessControl // // The mixin construct implies that all methods in `AccessControl` are // also declared with same name and request/response types in // `Storage`. A documentation generator or annotation processor will // see the effective `Storage.GetAcl` method after inheriting // documentation and annotations as follows: // // service Storage { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v2/{resource=**}:getAcl"; // } // ... // } // // Note how the version in the path pattern changed from `v1` to `v2`. // // If the `root` field in the mixin is specified, it should be a // relative path under which inherited HTTP paths are placed. Example: // // apis: // - name: google.storage.v2.Storage // mixins: // - name: google.acl.v1.AccessControl // root: acls // // This implies the following inherited HTTP annotation: // // service Storage { // // Get the underlying ACL object. // rpc GetAcl(GetAclRequest) returns (Acl) { // option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; // } // ... // } message Mixin { // The fully qualified name of the interface which is included. string name = 1; // If non-empty specifies a path under which inherited HTTP paths // are rooted. string root = 2; } ================================================ FILE: protobuf/google/protobuf/duration.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/durationpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "DurationProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (duration.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". // message Duration { // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years int64 seconds = 1; // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. int32 nanos = 2; } ================================================ FILE: protobuf/google/protobuf/empty.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option go_package = "google.golang.org/protobuf/types/known/emptypb"; option java_package = "com.google.protobuf"; option java_outer_classname = "EmptyProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option cc_enable_arenas = true; // A generic empty message that you can re-use to avoid defining duplicated // empty messages in your APIs. A typical example is to use it as the request // or the response type of an API method. For instance: // // service Foo { // rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); // } // message Empty {} ================================================ FILE: protobuf/google/protobuf/field_mask.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option java_package = "com.google.protobuf"; option java_outer_classname = "FieldMaskProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/fieldmaskpb"; option cc_enable_arenas = true; // `FieldMask` represents a set of symbolic field paths, for example: // // paths: "f.a" // paths: "f.b.d" // // Here `f` represents a field in some root message, `a` and `b` // fields in the message found in `f`, and `d` a field found in the // message in `f.b`. // // Field masks are used to specify a subset of fields that should be // returned by a get operation or modified by an update operation. // Field masks also have a custom JSON encoding (see below). // // # Field Masks in Projections // // When used in the context of a projection, a response message or // sub-message is filtered by the API to only contain those fields as // specified in the mask. For example, if the mask in the previous // example is applied to a response message as follows: // // f { // a : 22 // b { // d : 1 // x : 2 // } // y : 13 // } // z: 8 // // The result will not contain specific values for fields x,y and z // (their value will be set to the default, and omitted in proto text // output): // // // f { // a : 22 // b { // d : 1 // } // } // // A repeated field is not allowed except at the last position of a // paths string. // // If a FieldMask object is not present in a get operation, the // operation applies to all fields (as if a FieldMask of all fields // had been specified). // // Note that a field mask does not necessarily apply to the // top-level response message. In case of a REST get operation, the // field mask applies directly to the response, but in case of a REST // list operation, the mask instead applies to each individual message // in the returned resource list. In case of a REST custom method, // other definitions may be used. Where the mask applies will be // clearly documented together with its declaration in the API. In // any case, the effect on the returned resource/resources is required // behavior for APIs. // // # Field Masks in Update Operations // // A field mask in update operations specifies which fields of the // targeted resource are going to be updated. The API is required // to only change the values of the fields as specified in the mask // and leave the others untouched. If a resource is passed in to // describe the updated values, the API ignores the values of all // fields not covered by the mask. // // If a repeated field is specified for an update operation, new values will // be appended to the existing repeated field in the target resource. Note that // a repeated field is only allowed in the last position of a `paths` string. // // If a sub-message is specified in the last position of the field mask for an // update operation, then new value will be merged into the existing sub-message // in the target resource. // // For example, given the target message: // // f { // b { // d: 1 // x: 2 // } // c: [1] // } // // And an update message: // // f { // b { // d: 10 // } // c: [2] // } // // then if the field mask is: // // paths: ["f.b", "f.c"] // // then the result will be: // // f { // b { // d: 10 // x: 2 // } // c: [1, 2] // } // // An implementation may provide options to override this default behavior for // repeated and message fields. // // In order to reset a field's value to the default, the field must // be in the mask and set to the default value in the provided resource. // Hence, in order to reset all fields of a resource, provide a default // instance of the resource and set all fields in the mask, or do // not provide a mask as described below. // // If a field mask is not present on update, the operation applies to // all fields (as if a field mask of all fields has been specified). // Note that in the presence of schema evolution, this may mean that // fields the client does not know and has therefore not filled into // the request will be reset to their default. If this is unwanted // behavior, a specific service may require a client to always specify // a field mask, producing an error if not. // // As with get operations, the location of the resource which // describes the updated values in the request message depends on the // operation kind. In any case, the effect of the field mask is // required to be honored by the API. // // ## Considerations for HTTP REST // // The HTTP kind of an update operation which uses a field mask must // be set to PATCH instead of PUT in order to satisfy HTTP semantics // (PUT must only be used for full updates). // // # JSON Encoding of Field Masks // // In JSON, a field mask is encoded as a single string where paths are // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. // // As an example, consider the following message declarations: // // message Profile { // User user = 1; // Photo photo = 2; // } // message User { // string display_name = 1; // string address = 2; // } // // In proto a field mask for `Profile` may look as such: // // mask { // paths: "user.display_name" // paths: "photo" // } // // In JSON, the same mask is represented as below: // // { // mask: "user.displayName,photo" // } // // # Field Masks and Oneof Fields // // Field masks treat fields in oneofs just as regular fields. Consider the // following message: // // message SampleMessage { // oneof test_oneof { // string name = 4; // SubMessage sub_message = 9; // } // } // // The field mask can be: // // mask { // paths: "name" // } // // Or: // // mask { // paths: "sub_message" // } // // Note that oneof type names ("test_oneof" in this case) cannot be used in // paths. // // ## Field Mask Verification // // The implementation of any API method which has a FieldMask type field in the // request should verify the included field paths, and return an // `INVALID_ARGUMENT` error if any path is unmappable. message FieldMask { // The set of field mask paths. repeated string paths = 1; } ================================================ FILE: protobuf/google/protobuf/source_context.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option java_package = "com.google.protobuf"; option java_outer_classname = "SourceContextProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/sourcecontextpb"; // `SourceContext` represents information about the source of a // protobuf element, like the file in which it is defined. message SourceContext { // The path-qualified name of the .proto file that contained the associated // protobuf element. For example: `"google/protobuf/source_context.proto"`. string file_name = 1; } ================================================ FILE: protobuf/google/protobuf/struct.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/structpb"; option java_package = "com.google.protobuf"; option java_outer_classname = "StructProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; // `Struct` represents a structured data value, consisting of fields // which map to dynamically typed values. In some languages, `Struct` // might be supported by a native representation. For example, in // scripting languages like JS a struct is represented as an // object. The details of that representation are described together // with the proto support for the language. // // The JSON representation for `Struct` is JSON object. message Struct { // Unordered map of dynamically typed values. map fields = 1; } // `Value` represents a dynamically typed value which can be either // null, a number, a string, a boolean, a recursive struct value, or a // list of values. A producer of value is expected to set one of these // variants. Absence of any variant indicates an error. // // The JSON representation for `Value` is JSON value. message Value { // The kind of value. oneof kind { // Represents a null value. NullValue null_value = 1; // Represents a double value. double number_value = 2; // Represents a string value. string string_value = 3; // Represents a boolean value. bool bool_value = 4; // Represents a structured value. Struct struct_value = 5; // Represents a repeated `Value`. ListValue list_value = 6; } } // `NullValue` is a singleton enumeration to represent the null value for the // `Value` type union. // // The JSON representation for `NullValue` is JSON `null`. enum NullValue { // Null value. NULL_VALUE = 0; } // `ListValue` is a wrapper around a repeated field of values. // // The JSON representation for `ListValue` is JSON array. message ListValue { // Repeated field of dynamically typed values. repeated Value values = 1; } ================================================ FILE: protobuf/google/protobuf/timestamp.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/timestamppb"; option java_package = "com.google.protobuf"; option java_outer_classname = "TimestampProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; // A Timestamp represents a point in time independent of any time zone or local // calendar, encoded as a count of seconds and fractions of seconds at // nanosecond resolution. The count is relative to an epoch at UTC midnight on // January 1, 1970, in the proleptic Gregorian calendar which extends the // Gregorian calendar backwards to year one. // // All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap // second table is needed for interpretation, using a [24-hour linear // smear](https://developers.google.com/time/smear). // // The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By // restricting to that range, we ensure that we can convert to and from [RFC // 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // Example 5: Compute Timestamp from Java `Instant.now()`. // // Instant now = Instant.now(); // // Timestamp timestamp = // Timestamp.newBuilder().setSeconds(now.getEpochSecond()) // .setNanos(now.getNano()).build(); // // Example 6: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A ProtoJSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a ProtoJSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard // [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) // method. In Python, a standard `datetime.datetime` object can be converted // to this format using // [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with // the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use // the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() // ) to obtain a formatter capable of generating timestamps in this format. // message Timestamp { // Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must // be between -62135596800 and 253402300799 inclusive (which corresponds to // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z). int64 seconds = 1; // Non-negative fractions of a second at nanosecond resolution. This field is // the nanosecond portion of the duration, not an alternative to seconds. // Negative second values with fractions must still have non-negative nanos // values that count forward in time. Must be between 0 and 999,999,999 // inclusive. int32 nanos = 2; } ================================================ FILE: protobuf/google/protobuf/type.proto ================================================ // 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. syntax = "proto3"; package google.protobuf; import "google/protobuf/any.proto"; import "google/protobuf/source_context.proto"; option cc_enable_arenas = true; option java_package = "com.google.protobuf"; option java_outer_classname = "TypeProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; option go_package = "google.golang.org/protobuf/types/known/typepb"; // A protocol buffer message type. // // New usages of this message as an alternative to DescriptorProto are strongly // discouraged. This message does not reliability preserve all information // necessary to model the schema and preserve semantics. Instead make use of // FileDescriptorSet which preserves the necessary information. message Type { // The fully qualified message name. string name = 1; // The list of fields. repeated Field fields = 2; // The list of types appearing in `oneof` definitions in this type. repeated string oneofs = 3; // The protocol buffer options. repeated Option options = 4; // The source context. SourceContext source_context = 5; // The source syntax. Syntax syntax = 6; // The source edition string, only valid when syntax is SYNTAX_EDITIONS. string edition = 7; } // A single field of a message type. // // New usages of this message as an alternative to FieldDescriptorProto are // strongly discouraged. This message does not reliability preserve all // information necessary to model the schema and preserve semantics. Instead // make use of FileDescriptorSet which preserves the necessary information. message Field { // Basic field types. enum Kind { // Field type unknown. TYPE_UNKNOWN = 0; // Field type double. TYPE_DOUBLE = 1; // Field type float. TYPE_FLOAT = 2; // Field type int64. TYPE_INT64 = 3; // Field type uint64. TYPE_UINT64 = 4; // Field type int32. TYPE_INT32 = 5; // Field type fixed64. TYPE_FIXED64 = 6; // Field type fixed32. TYPE_FIXED32 = 7; // Field type bool. TYPE_BOOL = 8; // Field type string. TYPE_STRING = 9; // Field type group. Proto2 syntax only, and deprecated. TYPE_GROUP = 10; // Field type message. TYPE_MESSAGE = 11; // Field type bytes. TYPE_BYTES = 12; // Field type uint32. TYPE_UINT32 = 13; // Field type enum. TYPE_ENUM = 14; // Field type sfixed32. TYPE_SFIXED32 = 15; // Field type sfixed64. TYPE_SFIXED64 = 16; // Field type sint32. TYPE_SINT32 = 17; // Field type sint64. TYPE_SINT64 = 18; } // Whether a field is optional, required, or repeated. enum Cardinality { // For fields with unknown cardinality. CARDINALITY_UNKNOWN = 0; // For optional fields. CARDINALITY_OPTIONAL = 1; // For required fields. Proto2 syntax only. CARDINALITY_REQUIRED = 2; // For repeated fields. CARDINALITY_REPEATED = 3; } // The field type. Kind kind = 1; // The field cardinality. Cardinality cardinality = 2; // The field number. int32 number = 3; // The field name. string name = 4; // The field type URL, without the scheme, for message or enumeration // types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. string type_url = 6; // The index of the field type in `Type.oneofs`, for message or enumeration // types. The first type has index 1; zero means the type is not in the list. int32 oneof_index = 7; // Whether to use alternative packed wire representation. bool packed = 8; // The protocol buffer options. repeated Option options = 9; // The field JSON name. string json_name = 10; // The string value of the default value of this field. Proto2 syntax only. string default_value = 11; } // Enum type definition. // // New usages of this message as an alternative to EnumDescriptorProto are // strongly discouraged. This message does not reliability preserve all // information necessary to model the schema and preserve semantics. Instead // make use of FileDescriptorSet which preserves the necessary information. message Enum { // Enum type name. string name = 1; // Enum value definitions. repeated EnumValue enumvalue = 2; // Protocol buffer options. repeated Option options = 3; // The source context. SourceContext source_context = 4; // The source syntax. Syntax syntax = 5; // The source edition string, only valid when syntax is SYNTAX_EDITIONS. string edition = 6; } // Enum value definition. // // New usages of this message as an alternative to EnumValueDescriptorProto are // strongly discouraged. This message does not reliability preserve all // information necessary to model the schema and preserve semantics. Instead // make use of FileDescriptorSet which preserves the necessary information. message EnumValue { // Enum value name. string name = 1; // Enum value number. int32 number = 2; // Protocol buffer options. repeated Option options = 3; } // A protocol buffer option, which can be attached to a message, field, // enumeration, etc. // // New usages of this message as an alternative to FileOptions, MessageOptions, // FieldOptions, EnumOptions, EnumValueOptions, ServiceOptions, or MethodOptions // are strongly discouraged. message Option { // The option's name. For protobuf built-in options (options defined in // descriptor.proto), this is the short name. For example, `"map_entry"`. // For custom options, it should be the fully-qualified name. For example, // `"google.api.http"`. string name = 1; // The option's value packed in an Any message. If the value is a primitive, // the corresponding wrapper type defined in google/protobuf/wrappers.proto // should be used. If the value is an enum, it should be stored as an int32 // value using the google.protobuf.Int32Value type. Any value = 2; } // The syntax in which a protocol buffer element is defined. enum Syntax { // Syntax `proto2`. SYNTAX_PROTO2 = 0; // Syntax `proto3`. SYNTAX_PROTO3 = 1; // Syntax `editions`. SYNTAX_EDITIONS = 2; } ================================================ FILE: protobuf/google/protobuf/wrappers.proto ================================================ // 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. // // Wrappers for primitive (non-message) types. These types were needed // for legacy reasons and are not recommended for use in new APIs. // // Historically these wrappers were useful to have presence on proto3 primitive // fields, but proto3 syntax has been updated to support the `optional` keyword. // Using that keyword is now the strongly preferred way to add presence to // proto3 primitive fields. // // A secondary usecase was to embed primitives in the `google.protobuf.Any` // type: it is now recommended that you embed your value in your own wrapper // message which can be specifically documented. // // These wrappers have no meaningful use within repeated fields as they lack // the ability to detect presence on individual elements. // These wrappers have no meaningful use within a map or a oneof since // individual entries of a map or fields of a oneof can already detect presence. syntax = "proto3"; package google.protobuf; option cc_enable_arenas = true; option go_package = "google.golang.org/protobuf/types/known/wrapperspb"; option java_package = "com.google.protobuf"; option java_outer_classname = "WrappersProto"; option java_multiple_files = true; option objc_class_prefix = "GPB"; option csharp_namespace = "Google.Protobuf.WellKnownTypes"; // Wrapper message for `double`. // // The JSON representation for `DoubleValue` is JSON number. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message DoubleValue { // The double value. double value = 1; } // Wrapper message for `float`. // // The JSON representation for `FloatValue` is JSON number. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message FloatValue { // The float value. float value = 1; } // Wrapper message for `int64`. // // The JSON representation for `Int64Value` is JSON string. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message Int64Value { // The int64 value. int64 value = 1; } // Wrapper message for `uint64`. // // The JSON representation for `UInt64Value` is JSON string. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message UInt64Value { // The uint64 value. uint64 value = 1; } // Wrapper message for `int32`. // // The JSON representation for `Int32Value` is JSON number. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message Int32Value { // The int32 value. int32 value = 1; } // Wrapper message for `uint32`. // // The JSON representation for `UInt32Value` is JSON number. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message UInt32Value { // The uint32 value. uint32 value = 1; } // Wrapper message for `bool`. // // The JSON representation for `BoolValue` is JSON `true` and `false`. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message BoolValue { // The bool value. bool value = 1; } // Wrapper message for `string`. // // The JSON representation for `StringValue` is JSON string. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message StringValue { // The string value. string value = 1; } // Wrapper message for `bytes`. // // The JSON representation for `BytesValue` is JSON string. // // Not recommended for use in new APIs, but still useful for legacy APIs and // has no plan to be removed. message BytesValue { // The bytes value. bytes value = 1; } ================================================ FILE: protobuf/lib/meta.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Provides metadata about GeneratedMessage and ProtobufEnum to /// dart-protoc-plugin. (Experimental API; subject to change.) /// @nodoc library; // ignore_for_file: constant_identifier_names // List of names which cannot be used in a subclass of GeneratedMessage. const GeneratedMessage_reservedNames = [ '==', 'GeneratedMessage', 'Object', 'addExtension', 'check', 'clear', 'clearExtension', 'clearField', 'clone', 'copyWith', 'createEmptyInstance', 'extensionsAreInitialized', 'freeze', 'getDefaultForField', 'getExtension', 'getField', 'getFieldOrNull', 'getTagNumber', 'hasExtension', 'hasField', 'hasRequiredFields', 'hashCode', 'info_', 'isFrozen', 'isInitialized', 'mergeFromBuffer', 'mergeFromCodedBufferReader', 'mergeFromJson', 'mergeFromJsonMap', 'mergeFromMessage', 'mergeFromProto3Json', 'mergeUnknownFields', 'noSuchMethod', 'runtimeType', 'setExtension', 'setField', 'toBuilder', 'toDebugString', 'toProto3Json', 'toString', 'unknownFields', 'writeToBuffer', 'writeToCodedBufferWriter', 'writeToJson', 'writeToJsonMap', r'$_clearField', r'$_ensure', r'$_get', r'$_getI64', r'$_getList', r'$_getMap', r'$_getN', r'$_getB', r'$_getBF', r'$_getI', r'$_getIZ', r'$_getS', r'$_getSZ', r'$_has', r'$_setBool', r'$_setBytes', r'$_setDouble', r'$_setField', r'$_setFloat', r'$_setInt64', r'$_setSignedInt32', r'$_setString', r'$_setUnsignedInt32', r'$_whichOneof', ]; // List of names which cannot be used in a subclass of ProtobufEnum. const ProtobufEnum_reservedNames = [ '==', 'Object', 'ProtobufEnum', 'hashCode', 'noSuchMethod', 'runtimeType', 'toString', ]; ================================================ FILE: protobuf/lib/protobuf.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Runtime library for Dart implementation of [protobufs][1]. /// /// [1]: https://developers.google.com/protocol-buffers library; export 'src/protobuf/internal.dart' hide BuilderInfoInternalExtension, ExtensionFieldSet, ExtensionFieldSetInternalExtension, FieldInfoInternalExtension, FieldSet, FieldSetInternalExtension, GeneratedMessageInternalExtension, MapFieldInfoInternalExtension, checkNotNull, mergeFromProto3JsonAny, writeToProto3JsonAny; ================================================ FILE: protobuf/lib/src/protobuf/annotations.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Annotation for marking accessors that belong together. class TagNumber { final int tagNumber; /// Annotation for marking accessors that belong together. /// /// Allows tooling to associate related accessors. The [tagNumber] is the /// protobuf field tag associated with the annotated accessor. const TagNumber(this.tagNumber); } /// Use to annotate generated gRPC classes with the ID of the corresponding /// service. class GrpcServiceName { const GrpcServiceName(this.serviceId); // This field is used by static analyzers. final String serviceId; } ================================================ FILE: protobuf/lib/src/protobuf/builder_info.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Per-message type setup. class BuilderInfo { /// Fully qualified name of this message. final String qualifiedMessageName; /// Mapping from [FieldInfo.index]s to [FieldInfo]s. final List byIndex = []; /// Mapping from [FieldInfo.tagNumber]s to [FieldInfo]s. final Map fieldInfo = {}; /// Mapping from string representation of [FieldInfo.tagNumber]s to /// [FieldInfo]s. /// /// This map is used when parsing JSON messages generated by /// [GeneratedMessage.writeToJson], which converts field tags to strings and /// uses those strings as JSON map keys. With this field we avoid parsing /// those strings to integers when parsing the generated maps. final Map byTagAsString = {}; /// Mapping from [FieldInfo.name]s to [FieldInfo]s. final Map byName = {}; /// Mapping from `oneof` field [FieldInfo.tagNumber]s to the their indices in /// [FieldSet._oneofCases]. final Map oneofs = {}; /// Whether the message has extension fields. bool hasExtensions = false; /// Whether the message has required fields. /// /// Note that proto3 doesn't have required fields, only proto2 does. bool hasRequiredFields = true; List? _sortedByTag; // For well-known types. final WellKnownType? _wellKnownType; final CreateBuilderFunc? createEmptyInstance; BuilderInfo( String? messageName, { PackageName package = const PackageName(''), this.createEmptyInstance, WellKnownType? wellKnownType, }) : qualifiedMessageName = '${package.prefix}$messageName', _wellKnownType = wellKnownType; void add( int tagNumber, String name, int? fieldType, dynamic defaultOrMaker, CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, { String? protoName, }) { if (tagNumber == 0) { addUnused(); } else { final index = byIndex.length; final fieldInfo = FieldInfo( name, tagNumber, index, fieldType!, defaultOrMaker: defaultOrMaker, subBuilder: subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName, ); _addField(fieldInfo); } } // Support for tree-shaking of unused fields. void addUnused() { final index = byIndex.length; _addField(FieldInfo.dummy(index)); } void addMapField( int tagNumber, String name, int keyFieldType, int valueFieldType, BuilderInfo mapEntryBuilderInfo, CreateBuilderFunc? valueCreator, { ProtobufEnum? defaultEnumValue, String? protoName, }) { final index = byIndex.length; _addField( MapFieldInfo( name, tagNumber, index, PbFieldType.M, keyFieldType, valueFieldType, mapEntryBuilderInfo, valueCreator, defaultEnumValue: defaultEnumValue, protoName: protoName, ), ); } void addRepeated( int tagNumber, String name, int fieldType, CheckFunc? check, CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, { ProtobufEnum? defaultEnumValue, String? protoName, }) { final index = byIndex.length; _addField( FieldInfo.repeated( name, tagNumber, index, fieldType, check, subBuilder, valueOf: valueOf, enumValues: enumValues, defaultEnumValue: defaultEnumValue, protoName: protoName, ), ); } void _addField(FieldInfo fi) { byIndex.add(fi); assert(byIndex[fi.index!] == fi); // Fields with tag number 0 are considered dummy fields added to avoid // index calculations add up. They should not be reflected in the following // maps. if (!fi._isDummy) { fieldInfo[fi.tagNumber] = fi; byTagAsString['${fi.tagNumber}'] = fi; byName[fi.name] = fi; } } void a( int tagNumber, String name, int fieldType, { dynamic defaultOrMaker, CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, String? protoName, }) { add( tagNumber, name, fieldType, defaultOrMaker, subBuilder, valueOf, enumValues, protoName: protoName, ); } /// Adds PbFieldType.OS String with no default value to reduce generated /// code size. void aOS(int tagNumber, String name, {String? protoName}) { add( tagNumber, name, PbFieldType.OS, null, null, null, null, protoName: protoName, ); } /// Adds PbFieldType.PS String with no default value. void pPS(int tagNumber, String name, {String? protoName}) { addRepeated( tagNumber, name, PbFieldType.PS, getCheckFunction(PbFieldType.PS), null, null, null, protoName: protoName, ); } /// Adds PbFieldType.QS String with no default value. void aQS(int tagNumber, String name, {String? protoName}) { add( tagNumber, name, PbFieldType.QS, null, null, null, null, protoName: protoName, ); } /// Adds Int64 field with Int64.ZERO default. void aInt64(int tagNumber, String name, {String? protoName}) { add( tagNumber, name, PbFieldType.O6, Int64.ZERO, null, null, null, protoName: protoName, ); } /// Adds a boolean with no default value. void aOB(int tagNumber, String name, {String? protoName}) { add( tagNumber, name, PbFieldType.OB, null, null, null, null, protoName: protoName, ); } /// Adds a double field. void aD( int tagNumber, String name, { int fieldType = PbFieldType.OD, dynamic defaultOrMaker, String? protoName, }) { add( tagNumber, name, fieldType, defaultOrMaker, null, null, null, protoName: protoName, ); } /// Adds an int field. void aI( int tagNumber, String name, { int fieldType = PbFieldType.O3, dynamic defaultOrMaker, String? protoName, }) { add( tagNumber, name, fieldType, defaultOrMaker, null, null, null, protoName: protoName, ); } // Enum. void e( int tagNumber, String name, int fieldType, { dynamic defaultOrMaker, ValueOfFunc? valueOf, List? enumValues, String? protoName, }) { add( tagNumber, name, fieldType, defaultOrMaker, null, valueOf, enumValues, protoName: protoName, ); } // Enum, updated version. void aE( int tagNumber, String name, { int fieldType = PbFieldType.OE, dynamic defaultOrMaker, ValueOfFunc? valueOf, required List enumValues, String? protoName, }) { defaultOrMaker ??= enumValues.first; valueOf ??= _findValueOfEnumFunction(enumValues); add( tagNumber, name, fieldType, defaultOrMaker, null, valueOf, enumValues, protoName: protoName, ); } // Repeated, not a message, group, or enum. void p(int tagNumber, String name, int fieldType, {String? protoName}) { assert( !PbFieldType.isGroupOrMessage(fieldType) && !PbFieldType.isEnum(fieldType), ); addRepeated( tagNumber, name, fieldType, getCheckFunction(fieldType), null, null, null, protoName: protoName, ); } // Repeated message, group, or enum. void pc( int tagNumber, String name, int fieldType, { CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, ProtobufEnum? defaultEnumValue, String? protoName, }) { assert( PbFieldType.isGroupOrMessage(fieldType) || PbFieldType.isEnum(fieldType), ); addRepeated( tagNumber, name, fieldType, checkNotNull, subBuilder, valueOf, enumValues, defaultEnumValue: defaultEnumValue, protoName: protoName, ); } // Repeated enum. void pPE( int tagNumber, String name, { int fieldType = PbFieldType.PE, ValueOfFunc? valueOf, required List enumValues, ProtobufEnum? defaultEnumValue, String? protoName, }) { assert(PbFieldType.isEnum(fieldType)); defaultEnumValue ??= enumValues.first; valueOf ??= _findValueOfEnumFunction(enumValues); addRepeated( tagNumber, name, fieldType, checkNotNull, null, valueOf, enumValues, defaultEnumValue: defaultEnumValue, protoName: protoName, ); } // Optional Message. void aOM( int tagNumber, String name, { required T Function() subBuilder, String? protoName, }) { add( tagNumber, name, PbFieldType.OM, GeneratedMessage._defaultMakerFor(subBuilder), subBuilder, null, null, protoName: protoName, ); } // reQuried Message. void aQM( int tagNumber, String name, { required T Function() subBuilder, String? protoName, }) { add( tagNumber, name, PbFieldType.QM, GeneratedMessage._defaultMakerFor(subBuilder), subBuilder, null, null, protoName: protoName, ); } // rePeated Message, specialization of pc. void pPM( int tagNumber, String name, { required T Function() subBuilder, String? protoName, }) { addRepeated( tagNumber, name, PbFieldType.PM, checkNotNull, subBuilder, null, null, protoName: protoName, ); } // oneof declarations. void oo(int oneofIndex, List tags) { for (final tag in tags) { oneofs[tag] = oneofIndex; } } // Map field. void m( int tagNumber, String name, { String? entryClassName, required int keyFieldType, required int valueFieldType, CreateBuilderFunc? valueCreator, ValueOfFunc? valueOf, List? enumValues, ProtobufEnum? defaultEnumValue, PackageName packageName = const PackageName(''), String? protoName, dynamic valueDefaultOrMaker, }) { final mapEntryBuilderInfo = BuilderInfo(entryClassName, package: packageName) ..add(mapKeyFieldNumber, 'key', keyFieldType, null, null, null, null) ..add( mapValueFieldNumber, 'value', valueFieldType, valueDefaultOrMaker, valueCreator, valueOf, enumValues, ); addMapField( tagNumber, name, keyFieldType, valueFieldType, mapEntryBuilderInfo, valueCreator, defaultEnumValue: defaultEnumValue, protoName: protoName, ); } bool containsTagNumber(int tagNumber) => fieldInfo.containsKey(tagNumber); dynamic defaultValue(int tagNumber) { final func = makeDefault(tagNumber); return func == null ? null : func(); } // Returns the field name for a given tag number, for debugging purposes. String? fieldName(int tagNumber) { final i = fieldInfo[tagNumber]; return i?.name; } int? fieldType(int tagNumber) { final i = fieldInfo[tagNumber]; return i?.type; } MakeDefaultFunc? makeDefault(int tagNumber) { final i = fieldInfo[tagNumber]; return i?.makeDefault; } CreateBuilderFunc? subBuilder(int tagNumber) { final i = fieldInfo[tagNumber]; return i?.subBuilder; } int? tagNumber(String fieldName) { final i = byName[fieldName]; return i?.tagNumber; } ValueOfFunc? valueOfFunc(int tagNumber) { final i = fieldInfo[tagNumber]; return i?.valueOf; } /// The [FieldInfo] for each field in tag number order. List get sortedByTag => _sortedByTag ??= _computeSortedByTag(); /// The message name. Also see [qualifiedMessageName]. String get messageName { final lastDot = qualifiedMessageName.lastIndexOf('.'); return lastDot == -1 ? qualifiedMessageName : qualifiedMessageName.substring(lastDot + 1); } List _computeSortedByTag() => // Code generator inserts fields in tag order, but it's possible for // user-written code to insert unordered. List.from(fieldInfo.values, growable: false) ..sort((FieldInfo a, FieldInfo b) => a.tagNumber.compareTo(b.tagNumber)); GeneratedMessage _makeEmptyMessage( int tagNumber, ExtensionRegistry? extensionRegistry, ) { var subBuilderFunc = subBuilder(tagNumber); if (subBuilderFunc == null && extensionRegistry != null) { subBuilderFunc = extensionRegistry .getExtension(qualifiedMessageName, tagNumber)! .subBuilder; } return subBuilderFunc!(); } ProtobufEnum? _decodeEnum( int tagNumber, ExtensionRegistry? registry, int rawValue, ) { final f = valueOfFunc(tagNumber); if (f != null) { return f(rawValue); } return registry ?.getExtension(qualifiedMessageName, tagNumber) ?.valueOf ?.call(rawValue); } } extension BuilderInfoInternalExtension on BuilderInfo { GeneratedMessage makeEmptyMessage( int tagNumber, ExtensionRegistry? extensionRegistry, ) => _makeEmptyMessage(tagNumber, extensionRegistry); ProtobufEnum? decodeEnum( int tagNumber, ExtensionRegistry? registry, int rawValue, ) => _decodeEnum(tagNumber, registry, rawValue); } E? Function(int) _findValueOfEnumFunction( List enumValues, ) { final function = _valueOfFunctions[enumValues]; if (function != null) { // 'as dynamic' causes an implicit downcast to `E? Function(int)`, which is // removed by dart2js at `-O3`. return function as dynamic; } return _valueOfFunctions[enumValues] = _makeValueOfEnumFunction( enumValues, ); } /// Map for finding 'valueOf' functions for enums. An identity map is used since /// the `const` 'values' list for the enum is canonicalized and distinct for /// each enum. final _valueOfFunctions = Map, ProtobufEnum? Function(int)>.identity(); E? Function(int) _makeValueOfEnumFunction( List values, ) { Map? map; E? intToEnumValue(int value) { return (map ??= ProtobufEnum.initByValue(values))[value]; } return intToEnumValue; } ================================================ FILE: protobuf/lib/src/protobuf/coded_buffer.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; void _writeToCodedBufferWriter(FieldSet fs, CodedBufferWriter out) { // Sorting by tag number isn't required, but it sometimes enables // performance optimizations for the receiver. See: // https://developers.google.com/protocol-buffers/docs/encoding?hl=en#order for (final fi in fs._infosSortedByTag) { final value = fs._values[fi.index!]; if (value == null) continue; out.writeField(fi.tagNumber, fi.type, value); } final extensions = fs._extensions; if (extensions != null) { for (final tagNumber in sorted(extensions._tagNumbers)) { final fi = extensions._getInfoOrNull(tagNumber)!; out.writeField(tagNumber, fi.type, extensions._getFieldOrNull(fi)); } } final unknownFields = fs._unknownFields; if (unknownFields != null) { unknownFields.writeToCodedBufferWriter(out); } } void _mergeFromCodedBufferReader( BuilderInfo meta, FieldSet fs, CodedBufferReader input, ExtensionRegistry registry, ) { fs._ensureWritable(); while (true) { final tag = input.readTag(); if (tag == 0) return; final wireType = tag & 0x7; final tagNumber = tag >> 3; var fi = fs._nonExtensionInfo(meta, tagNumber); fi ??= registry.getExtension(meta.qualifiedMessageName, tagNumber); if (fi == null || !_wireTypeMatches(fi.type, wireType)) { if (!fs._ensureUnknownFields().mergeFieldFromBuffer(tag, input)) { return; } continue; } // Ignore required/optional packed/unpacked. var fieldType = fi.type; fieldType &= ~(PbFieldType.PACKED_BIT | PbFieldType.REQUIRED_BIT); switch (fieldType) { case PbFieldType.OPTIONAL_BOOL: fs._setFieldUnchecked(meta, fi, input.readBool()); case PbFieldType.OPTIONAL_BYTES: fs._setFieldUnchecked(meta, fi, input.readBytes()); case PbFieldType.OPTIONAL_STRING: fs._setFieldUnchecked(meta, fi, input.readString()); case PbFieldType.OPTIONAL_FLOAT: fs._setFieldUnchecked(meta, fi, input.readFloat()); case PbFieldType.OPTIONAL_DOUBLE: fs._setFieldUnchecked(meta, fi, input.readDouble()); case PbFieldType.OPTIONAL_ENUM: final rawValue = input.readEnum(); final value = meta._decodeEnum(tagNumber, registry, rawValue); if (value == null) { final unknown = fs._ensureUnknownFields(); unknown.mergeVarintField(tagNumber, Int64(rawValue)); } else { fs._setFieldUnchecked(meta, fi, value); } case PbFieldType.OPTIONAL_GROUP: final subMessage = meta._makeEmptyMessage(tagNumber, registry); final oldValue = fs._getFieldOrNull(fi); if (oldValue != null) { subMessage.mergeFromMessage(oldValue); } input.readGroup(tagNumber, subMessage, registry); fs._setFieldUnchecked(meta, fi, subMessage); case PbFieldType.OPTIONAL_INT32: fs._setFieldUnchecked(meta, fi, input.readInt32()); case PbFieldType.OPTIONAL_INT64: fs._setFieldUnchecked(meta, fi, input.readInt64()); case PbFieldType.OPTIONAL_SINT32: fs._setFieldUnchecked(meta, fi, input.readSint32()); case PbFieldType.OPTIONAL_SINT64: fs._setFieldUnchecked(meta, fi, input.readSint64()); case PbFieldType.OPTIONAL_UINT32: fs._setFieldUnchecked(meta, fi, input.readUint32()); case PbFieldType.OPTIONAL_UINT64: fs._setFieldUnchecked(meta, fi, input.readUint64()); case PbFieldType.OPTIONAL_FIXED32: fs._setFieldUnchecked(meta, fi, input.readFixed32()); case PbFieldType.OPTIONAL_FIXED64: fs._setFieldUnchecked(meta, fi, input.readFixed64()); case PbFieldType.OPTIONAL_SFIXED32: fs._setFieldUnchecked(meta, fi, input.readSfixed32()); case PbFieldType.OPTIONAL_SFIXED64: fs._setFieldUnchecked(meta, fi, input.readSfixed64()); case PbFieldType.OPTIONAL_MESSAGE: final GeneratedMessage? oldValue = fs._getFieldOrNull(fi); if (oldValue != null) { input.readMessage(oldValue, registry); } else { final subMessage = meta._makeEmptyMessage(tagNumber, registry); input.readMessage(subMessage, registry); fs._setFieldUnchecked(meta, fi, subMessage); } case PbFieldType.REPEATED_BOOL: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); // No need to check the element as for `bool` fields we only need to // check that the value is not null, and we know in `add` below that // the value isn't null (`readBool` doesn't return `null`). input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readBool()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readBool()); } case PbFieldType.REPEATED_BYTES: final list = fs._ensureRepeatedField(meta, fi); list.checkModifiable('add'); list.addUnchecked(input.readBytes()); case PbFieldType.REPEATED_STRING: final list = fs._ensureRepeatedField(meta, fi); list.checkModifiable('add'); list.addUnchecked(input.readString()); case PbFieldType.REPEATED_FLOAT: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readFloat()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readFloat()); } case PbFieldType.REPEATED_DOUBLE: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readDouble()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readDouble()); } case PbFieldType.REPEATED_ENUM: final list = fs._ensureRepeatedField(meta, fi); _readPackableToListEnum( list, meta, fs, input, wireType, tagNumber, registry, ); case PbFieldType.REPEATED_GROUP: final subMessage = meta._makeEmptyMessage(tagNumber, registry); input.readGroup(tagNumber, subMessage, registry); final list = fs._ensureRepeatedField(meta, fi); list.add(subMessage); case PbFieldType.REPEATED_INT32: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readInt32()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readInt32()); } case PbFieldType.REPEATED_INT64: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readInt64()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readInt64()); } case PbFieldType.REPEATED_SINT32: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readSint32()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readSint32()); } case PbFieldType.REPEATED_SINT64: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readSint64()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readSint64()); } case PbFieldType.REPEATED_UINT32: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readUint32()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readUint32()); } case PbFieldType.REPEATED_UINT64: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readUint64()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readUint64()); } case PbFieldType.REPEATED_FIXED32: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readFixed32()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readFixed32()); } case PbFieldType.REPEATED_FIXED64: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readFixed64()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readFixed64()); } case PbFieldType.REPEATED_SFIXED32: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readSfixed32()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readSfixed32()); } case PbFieldType.REPEATED_SFIXED64: final list = fs._ensureRepeatedField(meta, fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { final limit = input.readInt32(); if (limit != 0) { list.checkModifiable('add'); input._withLimit(limit, () { while (!input.isAtEnd()) { list.addUnchecked(input.readSfixed64()); } }); } } else { list.checkModifiable('add'); list.addUnchecked(input.readSfixed64()); } case PbFieldType.REPEATED_MESSAGE: final subMessage = meta._makeEmptyMessage(tagNumber, registry); input.readMessage(subMessage, registry); final list = fs._ensureRepeatedField(meta, fi); list.add(subMessage); case PbFieldType.MAP: final mapFieldInfo = fi as MapFieldInfo; final mapEntryMeta = mapFieldInfo.mapEntryBuilderInfo; final map = fs._ensureMapField(meta, mapFieldInfo); _readMapEntry(map, mapEntryMeta, input, registry); default: throw UnsupportedError('Unknown field type $fieldType'); } } } void _readMapEntry( PbMap map, BuilderInfo meta, CodedBufferReader input, ExtensionRegistry registry, ) { final length = input.readInt32(); final oldLimit = input._currentLimit; input._currentLimit = input._bufferPos + length; final entryFieldSet = FieldSet(null, meta); _mergeFromCodedBufferReader(meta, entryFieldSet, input, registry); input.checkLastTagWas(0); input._currentLimit = oldLimit; final key = entryFieldSet._values[0] ?? meta.byIndex[0].makeDefault!(); final value = entryFieldSet._values[1] ?? meta.byIndex[1].makeDefault!(); map[key] = value; } void _readPackableToListEnum( List list, BuilderInfo meta, FieldSet fs, CodedBufferReader input, int wireType, int tagNumber, ExtensionRegistry registry, ) { if (wireType == WIRETYPE_LENGTH_DELIMITED) { // Packed. input._withLimit(input.readInt32(), () { while (!input.isAtEnd()) { _readRepeatedEnum(list, meta, fs, input, tagNumber, registry); } }); } else { // Not packed. _readRepeatedEnum(list, meta, fs, input, tagNumber, registry); } } void _readRepeatedEnum( List list, BuilderInfo meta, FieldSet fs, CodedBufferReader input, int tagNumber, ExtensionRegistry registry, ) { final rawValue = input.readEnum(); final value = meta._decodeEnum(tagNumber, registry, rawValue); if (value == null) { final unknown = fs._ensureUnknownFields(); unknown.mergeVarintField(tagNumber, Int64(rawValue)); } else { list.add(value); } } ================================================ FILE: protobuf/lib/src/protobuf/coded_buffer_reader.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Reader used for converting binary-encoded protobufs into /// [GeneratedMessage]s. class CodedBufferReader { // ignore: constant_identifier_names static const int DEFAULT_RECURSION_LIMIT = 100; // Maximum value of a 32-bit signed integer. // ignore: constant_identifier_names static const int DEFAULT_SIZE_LIMIT = (1 << 31) - 1; final Uint8List _buffer; /// [ByteData] of [_buffer], created once to be able to decode fixed-size /// integers and floats without having to allocate a [ByteData] every time. late final ByteData _byteData = ByteData.sublistView(_buffer); int _bufferPos = 0; int _currentLimit = -1; int _lastTag = 0; int _recursionDepth = 0; final int _recursionLimit; final int _sizeLimit; CodedBufferReader( List buffer, { int recursionLimit = DEFAULT_RECURSION_LIMIT, int sizeLimit = DEFAULT_SIZE_LIMIT, }) : _buffer = buffer is Uint8List ? buffer : Uint8List.fromList(buffer), _recursionLimit = recursionLimit, _sizeLimit = math.min(sizeLimit, buffer.length) { _currentLimit = _sizeLimit; } void _throwTruncatedMessageError(int limit) { if (limit > _sizeLimit && limit <= _buffer.length) { throw InvalidProtocolBufferException.truncatedMessageDueToSizeLimit( _buffer.length, _sizeLimit, ); } throw InvalidProtocolBufferException.truncatedMessage(); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void checkLastTagWas(int value) { if (_lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') bool isAtEnd() => _bufferPos >= _currentLimit; @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void _withLimit(int byteLimit, Function() callback) { if (byteLimit < 0) { throw ArgumentError( 'CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.', ); } byteLimit += _bufferPos; final oldLimit = _currentLimit; if ((oldLimit != -1 && byteLimit > oldLimit) || byteLimit > _sizeLimit) { _throwTruncatedMessageError(byteLimit); } _currentLimit = byteLimit; callback(); _currentLimit = oldLimit; } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void _checkLimit(int increment) { assert(_currentLimit != -1); _bufferPos += increment; if (_bufferPos > _currentLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } } void readGroup( int fieldNumber, GeneratedMessage message, ExtensionRegistry extensionRegistry, ) { if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++_recursionDepth; message.mergeFromCodedBufferReader(this, extensionRegistry); checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); --_recursionDepth; } UnknownFieldSet readUnknownFieldSetGroup(int fieldNumber) { if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++_recursionDepth; final unknownFieldSet = UnknownFieldSet(); unknownFieldSet.mergeFromCodedBufferReader(this); checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); --_recursionDepth; return unknownFieldSet; } void readMessage( GeneratedMessage message, ExtensionRegistry extensionRegistry, ) { final length = readInt32(); if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } if (length < 0) { throw ArgumentError( 'CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.', ); } final oldLimit = _currentLimit; _currentLimit = _bufferPos + length; if (_currentLimit > oldLimit) { _throwTruncatedMessageError(_currentLimit); } ++_recursionDepth; message.mergeFromCodedBufferReader(this, extensionRegistry); checkLastTagWas(0); --_recursionDepth; _currentLimit = oldLimit; } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readEnum() => readInt32(); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readInt32() => _readRawVarint32(true); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Int64 readInt64() => _readRawVarint64(); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readUint32() => _readRawVarint32(false); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Int64 readUint64() => _readRawVarint64(); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readSint32() => _decodeZigZag32(readUint32()); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Int64 readSint64() => _decodeZigZag64(readUint64()); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readFixed32() { final pos = _bufferPos; _checkLimit(4); return _byteData.getUint32(pos, Endian.little); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Int64 readFixed64() => readSfixed64(); @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readSfixed32() { final pos = _bufferPos; _checkLimit(4); return _byteData.getInt32(pos, Endian.little); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Int64 readSfixed64() { final pos = _bufferPos; _checkLimit(8); final view = Uint8List.sublistView(_buffer, pos, pos + 8); return Int64.fromBytes(view); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') bool readBool() => _readRawVarint32(true) != 0; /// Read a length-delimited field as bytes. @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Uint8List readBytes() => Uint8List.fromList(readBytesAsView()); /// Read a length-delimited field as a view of the [CodedBufferReader]'s /// buffer. When storing the returned value directly (instead of e.g. parsing /// it as a UTF-8 string and copying) use [readBytes] instead to avoid /// holding on to the whole message, or copy the returned view. @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') Uint8List readBytesAsView() { final length = readInt32(); _checkLimit(length); return Uint8List.view( _buffer.buffer, _buffer.offsetInBytes + _bufferPos - length, length, ); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') String readString() { final length = readInt32(); final stringPos = _bufferPos; _checkLimit(length); return const Utf8Decoder( allowMalformed: true, ).convert(_buffer, stringPos, stringPos + length); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') double readFloat() { final pos = _bufferPos; _checkLimit(4); return _byteData.getFloat32(pos, Endian.little); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') double readDouble() { final pos = _bufferPos; _checkLimit(8); return _byteData.getFloat64(pos, Endian.little); } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int readTag() { if (isAtEnd()) { _lastTag = 0; return 0; } _lastTag = readUint32(); if (getTagFieldNumber(_lastTag) == 0) { throw InvalidProtocolBufferException.invalidTag(); } return _lastTag; } bool skipField(int tag) { final tagType = getTagWireType(tag); if (isAtEnd() || tagType == WIRETYPE_END_GROUP) { return false; } switch (getTagWireType(tag)) { case WIRETYPE_VARINT: readInt64(); return true; case WIRETYPE_FIXED64: readFixed64(); return true; case WIRETYPE_LENGTH_DELIMITED: final length = readInt32(); _checkLimit(length); return true; case WIRETYPE_FIXED32: readFixed32(); return true; case WIRETYPE_START_GROUP: readUnknownFieldSetGroup(getTagFieldNumber(tag)); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') static int _decodeZigZag32(int value) { if ((value & 0x1) == 1) { return -(value >> 1) - 1; } else { return value >> 1; } } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') static Int64 _decodeZigZag64(Int64 value) { if ((value & 0x1) == 1) value = -value; return value >> 1; } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') int _readRawVarintByte() { _checkLimit(1); return _buffer[_bufferPos - 1]; } int _readRawVarint32(bool signed) { // Read up to 10 bytes. // We use a local [bufferPos] variable to avoid repeatedly loading/store the // this._bufferpos field. var bufferPos = _bufferPos; var bytes = _currentLimit - bufferPos; if (bytes > 10) bytes = 10; var result = 0; for (var i = 0; i < bytes; i++) { final byte = _buffer[bufferPos++]; result |= (byte & 0x7f) << (i * 7); if ((byte & 0x80) == 0) { result &= 0xffffffff; _bufferPos = bufferPos; return signed ? result - 2 * (0x80000000 & result) : result; } } _bufferPos = bufferPos; throw InvalidProtocolBufferException.malformedVarint(); } Int64 _readRawVarint64() { var lo = 0; var hi = 0; // Read low 28 bits. for (var i = 0; i < 4; i++) { final byte = _readRawVarintByte(); lo |= (byte & 0x7f) << (i * 7); if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo); } // Read middle 7 bits: 4 low belong to low part above, // 3 remaining belong to hi. final byte = _readRawVarintByte(); lo |= (byte & 0xf) << 28; hi = (byte >> 4) & 0x7; if ((byte & 0x80) == 0) { return Int64.fromInts(hi, lo); } // Read remaining bits of hi. for (var i = 0; i < 5; i++) { final byte = _readRawVarintByte(); hi |= (byte & 0x7f) << ((i * 7) + 3); if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo); } throw InvalidProtocolBufferException.malformedVarint(); } } ================================================ FILE: protobuf/lib/src/protobuf/coded_buffer_writer.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: constant_identifier_names part of 'internal.dart'; /// Writer used for converting [GeneratedMessage]s into binary /// representation. /// /// Note that it is impossible to serialize protobuf messages using a one pass /// streaming serialization as some values are serialized using /// length-delimited representation, which means that they are represented as /// a varint encoded length followed by specified number of bytes of data. /// /// Due to this [CodedBufferWriter] maintains two output buffers: /// [_outputChunks] which contains all continuously written bytes and /// [_splices] which describes additional bytes to splice in-between /// [_outputChunks] bytes. /// class CodedBufferWriter { /// Array of splices representing the data written into the writer. /// Each element might be one of: /// * a [Uint8List] object - represents a sequence of bytes that need to be /// emitted into the result as-is; /// * a positive integer - a number of bytes to copy from [_outputChunks] /// into resulting buffer; /// * a non-positive integer - a positive number that needs to be emitted /// into result buffer as a varint; final List _splices = []; /// Number of bytes written into [_outputChunk] and [_outputChunks] since /// the last splice was recorded. int _lastSplicePos = 0; /// Size of the [_outputChunk]. static const _chunkLength = 512; /// Current chunk used to write data into. Once it is full it is /// pushed into [_outputChunks] and a new one is allocated. Uint8List? _outputChunk; /// Number of bytes written into the [_outputChunk]. int _bytesInChunk = 0; /// ByteData pointing to [_outputChunk]. Used to write primitive values /// more efficiently. ByteData? _outputChunkAsByteData; /// Array of pairs `` - chunks are pushed /// into this array once they are full. final List _outputChunks = []; /// Total amount of bytes used in all chunks. int _outputChunksBytes = 0; /// Total amount of bytes written into this writer. int _bytesTotal = 0; int get lengthInBytes => _bytesTotal; CodedBufferWriter() { // Initialize [_outputChunk]. _commitChunk(true); } void writeField(int fieldNumber, int fieldType, dynamic fieldValue) { final valueType = PbFieldType.baseType(fieldType); if ((fieldType & PbFieldType.PACKED_BIT) != 0) { final List list = fieldValue; if (list.isNotEmpty) { _writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); final mark = _startLengthDelimited(); for (final value in list) { _writeValueAs(valueType, value); } _endLengthDelimited(mark); } return; } if ((fieldType & PbFieldType.MAP_BIT) != 0) { final PbMap map = fieldValue; final keyWireFormat = _wireTypes[_valueTypeIndex(map.keyFieldType)]; final valueWireFormat = _wireTypes[_valueTypeIndex(map.valueFieldType)]; map.forEach((key, value) { _writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); final mark = _startLengthDelimited(); _writeValue(mapKeyFieldNumber, map.keyFieldType, key, keyWireFormat); _writeValue( mapValueFieldNumber, map.valueFieldType, value, valueWireFormat, ); _endLengthDelimited(mark); }); return; } final wireFormat = _wireTypes[_valueTypeIndex(valueType)]; if ((fieldType & PbFieldType.REPEATED_BIT) != 0) { final List list = fieldValue; for (var i = 0; i < list.length; i++) { _writeValue(fieldNumber, valueType, list[i], wireFormat); } return; } _writeValue(fieldNumber, valueType, fieldValue, wireFormat); } Uint8List toBuffer() { final result = Uint8List(_bytesTotal); writeTo(result); return result; } /// Serializes everything written to this writer so far to [buffer], starting /// from [offset] in [buffer]. Returns `true` on success. bool writeTo(Uint8List buffer, [int offset = 0]) { if (buffer.length - offset < _bytesTotal) { return false; } // Move the current output chunk into _outputChunks and commit the current // splice for uniformity. _commitChunk(false); _commitSplice(); var outPos = offset; // Output position in the buffer. var chunkIndex = 0, chunkPos = 0; // Position within _outputChunks. for (var i = 0; i < _splices.length; i++) { final action = _splices[i]; if (action is int) { if (action <= 0) { // action is a positive varint to be emitted into the output buffer. var v = 0 - action; // Note: 0 - action to avoid -0.0 in JS. while (v >= 0x80) { buffer[outPos++] = 0x80 | (v & 0x7f); v >>= 7; } buffer[outPos++] = v; } else { // `action` is an amount of bytes to copy from `_outputChunks` into // the buffer. var bytesToCopy = action; while (bytesToCopy > 0) { final Uint8List chunk = _outputChunks[chunkIndex]; final int bytesInChunk = _outputChunks[chunkIndex + 1]; // Copy at most `bytesToCopy` bytes from the current chunk. final leftInChunk = bytesInChunk - chunkPos; final bytesToCopyFromChunk = leftInChunk > bytesToCopy ? bytesToCopy : leftInChunk; buffer.setRange( outPos, outPos + bytesToCopyFromChunk, chunk, chunkPos, ); chunkPos += bytesToCopyFromChunk; outPos += bytesToCopyFromChunk; bytesToCopy -= bytesToCopyFromChunk; // Move to the next chunk if the current one is exhausted. if (chunkPos == bytesInChunk) { chunkIndex += 2; chunkPos = 0; } } } } else { // action is a `Uint8List` containing bytes to emit into the output // buffer. final Uint8List value = action; final end = outPos + value.length; buffer.setRange(outPos, end, value); outPos = end; } } return true; } /// Move the current [_outputChunk] into [_outputChunks]. /// /// If [allocateNew] is `true` then allocate a new chunk, otherwise /// set [_outputChunk] to `null`. void _commitChunk(bool allocateNew) { if (_bytesInChunk != 0) { _outputChunks.add(_outputChunk); _outputChunks.add(_bytesInChunk); _outputChunksBytes += _bytesInChunk; } if (allocateNew) { _outputChunk = Uint8List(_chunkLength); _bytesInChunk = 0; _outputChunkAsByteData = ByteData.view(_outputChunk!.buffer); } else { _outputChunk = _outputChunkAsByteData = null; _bytesInChunk = 0; } } /// Check if [count] bytes would fit into the current chunk. If they will /// not then allocate a new [_outputChunk]. /// /// [count] is assumed to be small enough to fit into the newly allocated /// chunk. void _ensureBytes(int count) { if ((_bytesInChunk + count) > _chunkLength) { _commitChunk(true); } } /// Record number of bytes written into output chunks since last splice. /// /// This is used before reserving space for an unknown varint splice or /// adding a [Uint8List] array splice. void _commitSplice() { final pos = _bytesInChunk + _outputChunksBytes; final bytes = pos - _lastSplicePos; if (bytes > 0) { _splices.add(bytes); } _lastSplicePos = pos; } /// Add a [Uint8List] splice, without copying. These bytes will be directly /// copied into the output buffer by [writeTo]. void writeRawBytes(Uint8List value) { final length = value.lengthInBytes; if (length == 0) return; _commitSplice(); _splices.add(value); _bytesTotal += length; } /// Start writing a length-delimited data. /// /// This reserves the space for varint splice in the splices array and /// return its index. Once the writing is finished [_endLengthDelimited] /// would be called with this index - which would put the actual amount /// of bytes written into the reserved slice space. int _startLengthDelimited() { _commitSplice(); final index = _splices.length; // Reserve a space for a splice and use it to record the current number of // bytes written so that we can compute the length of data later in // _endLengthDelimited. _splices.add(_bytesTotal); return index; } void _endLengthDelimited(int index) { final writtenSizeInBytes = _bytesTotal - _splices[index] as int; // Note: 0 - writtenSizeInBytes to avoid -0.0 in JavaScript. _splices[index] = 0 - writtenSizeInBytes; _bytesTotal += _varint32LengthInBytes(writtenSizeInBytes); } int _varint32LengthInBytes(int value) { value &= 0xFFFFFFFF; if (value < 0x80) return 1; if (value < 0x4000) return 2; if (value < 0x200000) return 3; if (value < 0x10000000) return 4; return 5; } void _writeVarint32(int value) { _ensureBytes(5); var i = _bytesInChunk; while (value >= 0x80) { _outputChunk![i++] = 0x80 | (value & 0x7f); value >>= 7; } _outputChunk![i++] = value; _bytesTotal += i - _bytesInChunk; _bytesInChunk = i; } void _writeVarint64(Int64 value) { _ensureBytes(10); var i = _bytesInChunk; var lo = value.toUnsigned(32).toInt(); var hi = (value >> 32).toUnsigned(32).toInt(); while (hi > 0 || lo >= 0x80) { _outputChunk![i++] = 0x80 | (lo & 0x7f); lo = (lo >> 7) | ((hi & 0x7f) << 25); hi >>= 7; } _outputChunk![i++] = lo; _bytesTotal += i - _bytesInChunk; _bytesInChunk = i; } void _writeDouble(double value) { if (value.isNaN) { _writeInt32(0x00000000); _writeInt32(0x7ff80000); return; } _ensureBytes(8); _outputChunkAsByteData!.setFloat64(_bytesInChunk, value, Endian.little); _bytesInChunk += 8; _bytesTotal += 8; } void _writeFloat(double value) { const MIN_FLOAT_DENORM = 1.401298464324817E-45; const MAX_FLOAT = 3.4028234663852886E38; if (value.isNaN) { _writeInt32(0x7fc00000); } else if (value.abs() < MIN_FLOAT_DENORM) { _writeInt32(value.isNegative ? 0x80000000 : 0x00000000); } else if (value.isInfinite || value.abs() > MAX_FLOAT) { _writeInt32(value.isNegative ? 0xff800000 : 0x7f800000); } else { const sz = 4; _ensureBytes(sz); _outputChunkAsByteData!.setFloat32(_bytesInChunk, value, Endian.little); _bytesInChunk += sz; _bytesTotal += sz; } } void _writeInt32(int value) { const sizeInBytes = 4; _ensureBytes(sizeInBytes); _outputChunkAsByteData!.setInt32( _bytesInChunk, value & 0xFFFFFFFF, Endian.little, ); _bytesInChunk += sizeInBytes; _bytesTotal += sizeInBytes; } void _writeInt64(Int64 value) { _writeInt32(value.toUnsigned(32).toInt()); _writeInt32((value >> 32).toUnsigned(32).toInt()); } void _writeValueAs(int valueType, dynamic value) { switch (valueType) { case PbFieldType.BOOL_BIT: _writeVarint32(value ? 1 : 0); case PbFieldType.BYTES_BIT: final List bytes = value; if (bytes is Uint8List) { _writeBytesNoTag(bytes); } else if (bytes.isEmpty) { _writeEmptyBytes(); } else { _writeBytesNoTag(Uint8List.fromList(bytes)); } case PbFieldType.STRING_BIT: final String string = value; if (string.isEmpty) { _writeEmptyBytes(); } else { _writeBytesNoTag(const Utf8Encoder().convert(string)); } case PbFieldType.DOUBLE_BIT: _writeDouble(value); case PbFieldType.FLOAT_BIT: _writeFloat(value); case PbFieldType.ENUM_BIT: final ProtobufEnum enum_ = value; _writeVarint32(enum_.value & 0xffffffff); case PbFieldType.GROUP_BIT: // `value` is `UnknownFieldSet` or `GeneratedMessage`. Test for // `UnknownFieldSet` as it doesn't have subtypes, so the type test will // be fast. if (value is UnknownFieldSet) { // Give the variable a type to not rely on type promotion to // eliminate the dynamic call below. // ignore: omit_local_variable_types final UnknownFieldSet unknownFieldSet = value; unknownFieldSet.writeToCodedBufferWriter(this); } else { final GeneratedMessage message = value; message.writeToCodedBufferWriter(this); } case PbFieldType.INT32_BIT: _writeVarint64(Int64(value)); case PbFieldType.INT64_BIT: _writeVarint64(value); case PbFieldType.SINT32_BIT: _writeVarint32(_encodeZigZag32(value)); case PbFieldType.SINT64_BIT: _writeVarint64(_encodeZigZag64(value)); case PbFieldType.UINT32_BIT: _writeVarint32(value); case PbFieldType.UINT64_BIT: _writeVarint64(value); case PbFieldType.FIXED32_BIT: _writeInt32(value); case PbFieldType.FIXED64_BIT: _writeInt64(value); case PbFieldType.SFIXED32_BIT: _writeInt32(value); case PbFieldType.SFIXED64_BIT: _writeInt64(value); case PbFieldType.MESSAGE_BIT: final mark = _startLengthDelimited(); final GeneratedMessage msg = value; msg.writeToCodedBufferWriter(this); _endLengthDelimited(mark); } } void _writeBytesNoTag(Uint8List value) { writeInt32NoTag(value.length); writeRawBytes(value); } void _writeEmptyBytes() { writeInt32NoTag(0); } void _writeTag(int fieldNumber, int wireFormat) { writeInt32NoTag(makeTag(fieldNumber, wireFormat)); } void _writeValue( int fieldNumber, int valueType, dynamic value, int wireFormat, ) { _writeTag(fieldNumber, wireFormat); _writeValueAs(valueType, value); if (valueType == PbFieldType.GROUP_BIT) { _writeTag(fieldNumber, WIRETYPE_END_GROUP); } } void writeInt32NoTag(int value) { _writeVarint32(value & 0xFFFFFFFF); } /// This function maps a power-of-2 value (2^0 .. 2^31) to a unique value /// in the 0..31 range. /// /// For more details see "Using de Bruijn Sequences to Index a 1 in /// a Computer Word"[1] /// /// Note: this is guaranteed to work after compilation to JavaScript /// where multiplication becomes a floating point multiplication. /// /// [1] http://supertech.csail.mit.edu/papers/debruijn.pdf static int _valueTypeIndex(int powerOf2) { assert(powerOf2 & (powerOf2 - 1) == 0, '$powerOf2 is not a power of 2'); return ((0x077CB531 * powerOf2) >> 27) & 31; } /// Precomputed indices for all FbFieldType._XYZ_BIT values: /// /// _XYZ_BIT_INDEX = _valueTypeIndex(FbFieldType._XYZ_BIT) /// static const _BOOL_BIT_INDEX = 14; static const _BYTES_BIT_INDEX = 29; static const _STRING_BIT_INDEX = 27; static const _DOUBLE_BIT_INDEX = 23; static const _FLOAT_BIT_INDEX = 15; static const _ENUM_BIT_INDEX = 31; static const _GROUP_BIT_INDEX = 30; static const _INT32_BIT_INDEX = 28; static const _INT64_BIT_INDEX = 25; static const _SINT32_BIT_INDEX = 18; static const _SINT64_BIT_INDEX = 5; static const _UINT32_BIT_INDEX = 11; static const _UINT64_BIT_INDEX = 22; static const _FIXED32_BIT_INDEX = 13; static const _FIXED64_BIT_INDEX = 26; static const _SFIXED32_BIT_INDEX = 21; static const _SFIXED64_BIT_INDEX = 10; static const _MESSAGE_BIT_INDEX = 20; /// Mapping from value types to wire-types indexed by _valueTypeIndex(...). static final Uint8List _wireTypes = Uint8List(32) ..[_BOOL_BIT_INDEX] = WIRETYPE_VARINT ..[_BYTES_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED ..[_STRING_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED ..[_DOUBLE_BIT_INDEX] = WIRETYPE_FIXED64 ..[_FLOAT_BIT_INDEX] = WIRETYPE_FIXED32 ..[_ENUM_BIT_INDEX] = WIRETYPE_VARINT ..[_GROUP_BIT_INDEX] = WIRETYPE_START_GROUP ..[_INT32_BIT_INDEX] = WIRETYPE_VARINT ..[_INT64_BIT_INDEX] = WIRETYPE_VARINT ..[_SINT32_BIT_INDEX] = WIRETYPE_VARINT ..[_SINT64_BIT_INDEX] = WIRETYPE_VARINT ..[_UINT32_BIT_INDEX] = WIRETYPE_VARINT ..[_UINT64_BIT_INDEX] = WIRETYPE_VARINT ..[_FIXED32_BIT_INDEX] = WIRETYPE_FIXED32 ..[_FIXED64_BIT_INDEX] = WIRETYPE_FIXED64 ..[_SFIXED32_BIT_INDEX] = WIRETYPE_FIXED32 ..[_SFIXED64_BIT_INDEX] = WIRETYPE_FIXED64 ..[_MESSAGE_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED; } int _encodeZigZag32(int value) => (value << 1) ^ (value >> 31); Int64 _encodeZigZag64(Int64 value) => (value << 1) ^ (value >> 63); ================================================ FILE: protobuf/lib/src/protobuf/consts.dart ================================================ // Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Constant string value of `double.infinity.toString()` and the infinity /// value recognized by `double.parse(..)`. const infinity = 'Infinity'; /// Constant string value of `double.negativeInfinity.toString()` and the /// negative infinity value recognized by `double.parse(..)`. const negativeInfinity = '-Infinity'; /// Constant string value of `double.nan.toString()` and the NaN (not a number) /// value recognized by `double.parse(..)`. const nan = 'NaN'; ================================================ FILE: protobuf/lib/src/protobuf/exceptions.dart ================================================ // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. const _truncatedMessageText = ''' While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could either mean that the input has been truncated or that an embedded message misreported its own length. '''; /// Exception thrown by the binary deserializer when the encoding is malformed. class InvalidProtocolBufferException implements Exception { final String message; InvalidProtocolBufferException._(this.message); @override String toString() => 'InvalidProtocolBufferException: $message'; InvalidProtocolBufferException.invalidEndTag() : this._('Protocol message end-group tag did not match expected tag.'); InvalidProtocolBufferException.invalidTag() : this._('Protocol message contained an invalid tag (zero).'); InvalidProtocolBufferException.invalidWireType() : this._('Protocol message tag had invalid wire type.'); InvalidProtocolBufferException.malformedVarint() : this._('CodedBufferReader encountered a malformed varint.'); InvalidProtocolBufferException.recursionLimitExceeded() : this._(''' Protocol message had too many levels of nesting. May be malicious. Use a CodedBufferReader with a defined recursion depth limit if you need to parse deeply nested messages. '''); InvalidProtocolBufferException.truncatedMessage() : this._(_truncatedMessageText); InvalidProtocolBufferException.truncatedMessageDueToSizeLimit( int originalSize, int truncatedSize, ) : this._('''$_truncatedMessageText Note that the buffer containing the message has $originalSize bytes, but CodedBufferReader was allowed to parse only $truncatedSize bytes. '''); InvalidProtocolBufferException.wrongAnyMessage( String anyTypeName, unpackerTypeName, ) : this._(''' The type of the Any message ($anyTypeName) does not match the given unpacker ($unpackerTypeName). '''); } ================================================ FILE: protobuf/lib/src/protobuf/extension.dart ================================================ // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// An object representing an extension field. class Extension extends FieldInfo { final String extendee; Extension( this.extendee, String name, int tagNumber, int fieldType, { dynamic defaultOrMaker, CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, String? protoName, }) : super( name, tagNumber, null, fieldType, defaultOrMaker: defaultOrMaker, subBuilder: subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName, ); Extension.repeated( this.extendee, String name, int tagNumber, int fieldType, { required CheckFunc? check, CreateBuilderFunc? subBuilder, ValueOfFunc? valueOf, List? enumValues, String? protoName, }) : super.repeated( name, tagNumber, null, fieldType, check, subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName, ); @override int get hashCode => extendee.hashCode * 31 + tagNumber; @override bool operator ==(Object other) { if (other is! Extension) return false; final o = other; return extendee == o.extendee && tagNumber == o.tagNumber; } } ================================================ FILE: protobuf/lib/src/protobuf/extension_field_set.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; class ExtensionFieldSet { final FieldSet _parent; final Map _info; final Map _values; bool _isReadOnly; ExtensionFieldSet(this._parent, {required bool readOnly}) : _info = {}, _values = {}, _isReadOnly = readOnly; ExtensionFieldSet._(this._parent, this._info, this._values) : _isReadOnly = false; Extension? _getInfoOrNull(int tagNumber) => _info[tagNumber]; dynamic _getFieldOrDefault(Extension fi) { if (fi.isRepeated) return _getList(fi); _validateInfo(fi); // TODO(skybrian) seems unnecessary to add info? // I think this was originally here for repeated extensions. _addInfoUnchecked(fi); final value = _getFieldOrNull(fi); if (value == null) { _checkNotInUnknown(fi); return fi.makeDefault!(); } return value; } bool _hasField(int tagNumber) { final value = _values[tagNumber]; if (value == null) return false; if (value is List) return value.isNotEmpty; return true; } /// Ensures that the list exists and an extension is present. /// /// If it doesn't exist, creates the list and saves the extension. /// Suitable for public API and decoders. PbList _ensureRepeatedField(Extension fi) { assert(!_isReadOnly); assert(fi.isRepeated); assert(fi.extendee == '' || fi.extendee == _parent._messageName); final list = _values[fi.tagNumber]; if (list != null) return list; return _addInfoAndCreateList(fi); } PbList _getList(Extension fi) { final value = _values[fi.tagNumber]; if (value != null) return value; _checkNotInUnknown(fi); if (_isReadOnly) return fi._createRepeatedField()..freeze(); return _addInfoAndCreateList(fi); } PbList _addInfoAndCreateList(Extension fi) { _validateInfo(fi); final newList = fi._createRepeatedField(); _addInfoUnchecked(fi); _setFieldUnchecked(fi, newList); return newList; } @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') dynamic _getFieldOrNull(Extension extension) => _values[extension.tagNumber]; void _clearFieldAndInfo(Extension fi) { _clearField(fi); _info.remove(fi.tagNumber); } void _clearField(Extension fi) { _ensureWritable(); _validateInfo(fi); _values.remove(fi.tagNumber); } /// Sets a value for a non-repeated extension that has already been added. /// Does error-checking. void _setField(int tagNumber, value) { final fi = _getInfoOrNull(tagNumber); if (fi == null) { throw ArgumentError( 'tag $tagNumber not defined in $_parent._messageName', ); } if (fi.isRepeated) { throw ArgumentError( _parent._setFieldFailedMessage( fi, value, 'repeating field (use get + .add())', ), ); } _ensureWritable(); _parent._validateField(fi, value); _setFieldUnchecked(fi, value); } /// Sets a non-repeated value and extension. /// Overwrites any existing extension. void _setFieldAndInfo(Extension fi, value) { _ensureWritable(); if (fi.isRepeated) { throw ArgumentError( _parent._setFieldFailedMessage( fi, value, 'repeating field (use get + .add())', ), ); } _validateInfo(fi); _parent._validateField(fi, value); _addInfoUnchecked(fi); _setFieldUnchecked(fi, value); } void _ensureWritable() { if (_isReadOnly) { _throwFrozenMessageModificationError(_parent._messageName); } } void _validateInfo(Extension fi) { if (fi.extendee != _parent._messageName) { throw ArgumentError( 'Extension $fi not legal for message ${_parent._messageName}', ); } } void _addInfoUnchecked(Extension fi) { assert(fi.extendee == _parent._messageName); _info[fi.tagNumber] = fi; } void _setFieldUnchecked(Extension fi, value) { // If there was already an unknown field with the same tag number, // overwrite it. _parent._unknownFields?.clearField(fi.tagNumber); _values[fi.tagNumber] = value; } // Bulk operations Iterable get _tagNumbers => _values.keys; Iterable get _infos => _info.values; bool get _hasValues => _values.isNotEmpty; bool _equalValues(ExtensionFieldSet? other) => other != null && areMapsEqual(_values, other._values); void _clearValues() => _values.clear(); /// Makes a shallow copy of all values from [original] to this. /// /// Repeated fields are copied. /// Extensions cannot contain map fields. void _shallowCopyValues(ExtensionFieldSet original) { for (final tagNumber in original._tagNumbers) { final extension = original._getInfoOrNull(tagNumber)!; _addInfoUnchecked(extension); final value = original._getFieldOrNull(extension); if (value == null) continue; if (extension.isRepeated) { assert(value is PbList); _ensureRepeatedField(extension).addAll(value); } else { _setFieldUnchecked(extension, value); } } } void _markReadOnly() { if (_isReadOnly) return; _isReadOnly = true; for (final field in _info.values) { if (field.isRepeated) { final entriesDynamic = _values[field.tagNumber]; if (entriesDynamic == null) continue; final PbList entries = entriesDynamic; entries.freeze(); } else if (field.isGroupOrMessage) { final entry = _values[field.tagNumber]; if (entry != null) { final GeneratedMessage msg = entry; msg.freeze(); } } } } void _checkNotInUnknown(Extension extension) { final unknownFields = _parent._unknownFields; if (unknownFields != null && unknownFields.hasField(extension.tagNumber)) { throw StateError( 'Trying to get $extension that is present as an unknown field. ' 'Parse the message with this extension in the extension registry or ' 'use `ExtensionRegistry.reparseMessage`.', ); } } ExtensionFieldSet _deepCopy(FieldSet parent) { final newExtensionFieldSet = ExtensionFieldSet._( parent, Map.from(_info), Map.from(_values), ); final newValues = newExtensionFieldSet._values; for (final entry in _values.entries) { final tag = entry.key; final value = entry.value; final fieldInfo = _info[tag]!; if (fieldInfo.isMapField) { final PbMap? map = value; newValues[tag] = map?.deepCopy(); } else if (fieldInfo.isRepeated) { final PbList? list = value; newValues[tag] = list?.deepCopy(); } else if (fieldInfo.isGroupOrMessage) { final GeneratedMessage? message = value; newValues[tag] = message?.deepCopy(); } } return newExtensionFieldSet; } } extension ExtensionFieldSetInternalExtension on ExtensionFieldSet { Map get values => _values; Iterable get tagNumbers => _tagNumbers; Extension? getInfoOrNull(int tagNumber) => _getInfoOrNull(tagNumber); } ================================================ FILE: protobuf/lib/src/protobuf/extension_registry.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// A collection of [Extension] objects, organized by the message type they /// extend. class ExtensionRegistry { final Map> _extensions = >{}; // ignore: constant_identifier_names static const ExtensionRegistry EMPTY = _EmptyExtensionRegistry(); /// Stores an [extension] in the registry. void add(Extension extension) { final map = _extensions.putIfAbsent( extension.extendee, () => {}, ); map[extension.tagNumber] = extension; } /// Stores all [extensions] in the registry. void addAll(Iterable extensions) { extensions.forEach(add); } /// Retrieves an extension from the registry that adds tag number [tagNumber] /// to the [messageName] message type. Extension? getExtension(String messageName, int tagNumber) => _extensions[messageName]?[tagNumber]; /// Creates a shallow copy of [message], with all extensions in `this` parsed /// from the unknown fields of [message] and of every nested submessage. /// /// Extensions already present in [message] will be preserved. /// /// If [message] is frozen, the result will be as well. /// /// Returns the original message if no new extensions are parsed. /// /// Throws an [InvalidProtocolBufferException] if the parsed extensions are /// malformed. /// /// Using this method to retrieve extensions is more expensive overall than /// using an [ExtensionRegistry] with all the needed extensions when doing /// [GeneratedMessage.mergeFromBuffer]. /// /// Example: /// /// `sample.proto` /// ```proto /// syntax = "proto2"; /// /// message Foo { /// extensions 1 to max; /// } /// /// extend Foo { /// optional string val1 = 1; /// optional string val2 = 2; /// } /// ``` /// `main.dart` /// ``` /// import 'package:protobuf/protobuf.dart'; /// import 'package:test/test.dart'; /// import 'src/generated/sample.pb.dart'; /// /// void main() { /// ExtensionRegistry r1 = ExtensionRegistry()..add(Sample.val1); /// ExtensionRegistry r2 = ExtensionRegistry()..add(Sample.val2); /// Foo original = Foo()..setExtension(Sample.val1, 'a')..setExtension(Sample.val2, 'b'); /// Foo withUnknownFields = Foo.fromBuffer(original.writeToBuffer()); /// Foo reparsed1 = r1.reparseMessage(withUnknownFields); /// Foo reparsed2 = r2.reparseMessage(reparsed1); /// expect(withUnknownFields.hasExtension(Sample.val1), isFalse); /// expect(withUnknownFields.hasExtension(Sample.val2), isFalse); /// expect(reparsed1.hasExtension(Sample.val1), isTrue); /// expect(reparsed1.hasExtension(Sample.val2), isFalse); /// expect(reparsed2.hasExtension(Sample.val1), isTrue); /// expect(reparsed2.hasExtension(Sample.val2), isTrue); /// } /// ``` T reparseMessage(T message) => _reparseMessage(message, this); } T _reparseMessage( T message, ExtensionRegistry extensionRegistry, ) { T? result; T ensureResult() { if (result == null) { result ??= message.info_.createEmptyInstance!() as T; result!._fieldSet._shallowCopyValues(message._fieldSet); } return result!; } UnknownFieldSet? resultUnknownFields; UnknownFieldSet ensureUnknownFields() => resultUnknownFields ??= ensureResult()._fieldSet._unknownFields!; final messageUnknownFields = message._fieldSet._unknownFields; if (messageUnknownFields != null) { final codedBufferWriter = CodedBufferWriter(); if (message is $_MessageSet) { final itemList = messageUnknownFields._fields[_messageSetItemsTag]; final parsedItemList = UnknownFieldSetField(); final unparsedItemList = UnknownFieldSetField(); if (itemList != null) { for (final group in itemList.groups) { final typeId = group._fields[_messageSetItemTypeIdTag]!.varints[0].toInt(); if (extensionRegistry.getExtension( message.info_.qualifiedMessageName, typeId, ) == null) { unparsedItemList.addGroup(group); } else { parsedItemList.addGroup(group); } } parsedItemList.writeTo(_messageSetItemsTag, codedBufferWriter); if (unparsedItemList.groups.isEmpty) { messageUnknownFields._fields.remove(_messageSetItemsTag); } else { messageUnknownFields._fields[_messageSetItemsTag] = unparsedItemList; } } } else { extensionRegistry._extensions[message.info_.qualifiedMessageName] ?.forEach((tagNumber, extension) { final unknownField = messageUnknownFields._fields[tagNumber]; if (unknownField != null) { unknownField.writeTo(tagNumber, codedBufferWriter); ensureUnknownFields()._fields.remove(tagNumber); } }); } final buffer = codedBufferWriter.toBuffer(); if (buffer.isNotEmpty) { ensureResult().mergeFromBuffer(buffer, extensionRegistry); } } for (final field in message._fieldSet._meta.byIndex) { PbList? resultEntries; PbList ensureEntries() => resultEntries ??= ensureResult()._fieldSet._values[field.index!]; PbMap? resultMap; PbMap ensureMap() => resultMap ??= ensureResult()._fieldSet._values[field.index!]; if (field.isRepeated) { final messageEntriesDynamic = message._fieldSet._values[field.index!]; if (messageEntriesDynamic == null) continue; final PbList messageEntries = messageEntriesDynamic; if (field.isGroupOrMessage) { for (var i = 0; i < messageEntries.length; i++) { final GeneratedMessage entry = messageEntries[i]; final reparsedEntry = _reparseMessage(entry, extensionRegistry); if (!identical(entry, reparsedEntry)) { ensureEntries()[i] = reparsedEntry; } } } } else if (field is MapFieldInfo) { final messageMapDynamic = message._fieldSet._values[field.index!]; if (messageMapDynamic == null) continue; final PbMap messageMap = messageMapDynamic; if (PbFieldType.isGroupOrMessage(field.valueFieldType)) { for (final key in messageMap.keys) { final GeneratedMessage value = messageMap[key]; final reparsedValue = _reparseMessage(value, extensionRegistry); if (!identical(value, reparsedValue)) { ensureMap()[key] = reparsedValue; } } } } else if (field.isGroupOrMessage) { final messageSubField = message._fieldSet._values[field.index!]; if (messageSubField == null) continue; final reparsedSubField = _reparseMessage( messageSubField, extensionRegistry, ); if (!identical(messageSubField, reparsedSubField)) { ensureResult()._fieldSet._values[field.index!] = reparsedSubField; } } } if (result != null && message.isFrozen) { result!.freeze(); } return result ?? message; } class _EmptyExtensionRegistry implements ExtensionRegistry { const _EmptyExtensionRegistry(); @override Map> get _extensions => const >{}; @override void add(Extension extension) { throw UnsupportedError('Immutable ExtensionRegistry'); } @override void addAll(Iterable extensions) { throw UnsupportedError('Immutable ExtensionRegistry'); } @override Extension? getExtension(String messageName, int tagNumber) => null; @override T reparseMessage(T message) => _reparseMessage(message, this); } ================================================ FILE: protobuf/lib/src/protobuf/field_error.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Returns the error message for an invalid field value, /// or null if it's valid. /// /// For enums, group, and message fields, this check is only approximate, /// because the exact type isn't included in [fieldType]. String? _getFieldError(int fieldType, var value) { switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: if (value is! bool) return 'not type bool'; return null; case PbFieldType.BYTES_BIT: if (value is! List) return 'not List'; return null; case PbFieldType.STRING_BIT: if (value is! String) return 'not type String'; return null; case PbFieldType.FLOAT_BIT: if (value is! double) return 'not type double'; if (!_isFloat32(value)) return 'out of range for float'; return null; case PbFieldType.DOUBLE_BIT: if (value is! double) return 'not type double'; return null; case PbFieldType.ENUM_BIT: if (value is! ProtobufEnum) return 'not type ProtobufEnum'; return null; case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SFIXED32_BIT: if (value is! int) return 'not type int'; if (!_isSigned32(value)) return 'out of range for signed 32-bit int'; return null; case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: if (value is! int) return 'not type int'; if (!_isUnsigned32(value)) return 'out of range for unsigned 32-bit int'; return null; case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: case PbFieldType.SFIXED64_BIT: // We always use the full range of the same Dart type. // It's up to the caller to treat the Int64 as signed or unsigned. // See: https://github.com/google/protobuf.dart/issues/44 if (value is! Int64) return 'not Int64'; return null; case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: if (value is! GeneratedMessage) return 'not a GeneratedMessage'; return null; default: return 'field has unknown type $fieldType'; } } // entry points for generated code /// Returns a function for validating items in a repeated field. /// /// For most types this is a not-null check, except for floats, and signed and /// unsigned 32 bit ints where there also is a range check. /// /// @nodoc CheckFunc? getCheckFunction(int fieldType) { switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: case PbFieldType.BYTES_BIT: case PbFieldType.STRING_BIT: case PbFieldType.DOUBLE_BIT: case PbFieldType.ENUM_BIT: case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: // We always use the full range of the same Dart type. // It's up to the caller to treat the Int64 as signed or unsigned. // See: https://github.com/google/protobuf.dart/issues/44 return null; case PbFieldType.FLOAT_BIT: return _checkFloat; case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SFIXED32_BIT: return _checkSigned32; case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: return _checkUnsigned32; } throw ArgumentError('check function not implemented: $fieldType'); } // check functions for repeated fields void checkNotNull(Object? val) { if (val == null) { throw ArgumentError("Can't add a null to a repeated field"); } } void _checkFloat(Object? val) { if (!_isFloat32(val as double)) throw _createFieldRangeError(val, 'a float'); } void _checkSigned32(Object? val) { if (!_isSigned32(val as int)) { throw _createFieldRangeError(val, 'a signed int32'); } } void _checkUnsigned32(Object? val) { if (!_isUnsigned32(val as int)) { throw _createFieldRangeError(val, 'an unsigned int32'); } } RangeError _createFieldRangeError(num val, String wantedType) => RangeError('Value ($val) is not $wantedType'); bool _isSigned32(int value) => (-2147483648 <= value) && (value <= 2147483647); bool _isUnsigned32(int value) => (0 <= value) && (value <= 4294967295); bool _isFloat32(double value) => value.isNaN || value.isInfinite || (-3.4028234663852886E38 <= value) && (value <= 3.4028234663852886E38); ================================================ FILE: protobuf/lib/src/protobuf/field_info.dart ================================================ // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// An object representing a protobuf message field. class FieldInfo { /// Cached read-only empty list for this field type. For non-repeated fields /// this is always `null`. Otherwise it starts as `null` and gets initialized /// in `readonlyDefault`. PbList? _emptyList; /// Name of this field as the `json_name` reported by protoc. /// /// Example: /// /// ```proto /// message Msg { /// int32 foo_name = 1 [json_name = "barName"]; /// } /// ``` /// /// Here `name` of the field is `barName`. When `json_name` is not specified /// in the proto definition, this is the camelCase version of the field name. /// In the example above, without the `json_name` field option, `name` would /// be `"fooName"`. final String name; /// Name of this field as written in the proto definition. /// /// Example: /// /// ```proto /// message SearchRequest { /// ... /// int32 result_per_page = 3; /// } /// ``` /// /// `protoName` for the `result_per_page` field above is `"result_per_page"`. /// The name typically consist of words separated with underscores. String get protoName { return _protoName ??= _unCamelCase(name); } String? _protoName; /// Field number as specified in the proto definition. /// /// Example: /// /// ```proto /// message SearchRequest { /// ... /// int32 result_per_page = 3; /// } /// ``` /// /// `tagNumber` of `result_per_page` field is 3. final int tagNumber; /// Index of the field in [FieldSet._values] list of this field's message. /// /// The value is `null` for extension fields. final int? index; /// Type of this field. See [PbFieldType]. final int type; /// Constructs the default value of a field. /// /// For repeated fields, only used when the [check] property is `null`. final MakeDefaultFunc? makeDefault; /// Creates an empty message or group when decoding a message. /// /// Only available in fields with message type. final CreateBuilderFunc? subBuilder; /// List of all enum values. /// /// Only available in enum fields. final List? enumValues; /// Default enum value. /// /// Only available in enum fields. final ProtobufEnum? defaultEnumValue; /// Mapping from enum integer values to enum values. /// /// Only available in enum fields. final ValueOfFunc? valueOf; /// Function to verify items when adding to a repeated field. /// /// Only available in repeated fields. final CheckFunc? check; FieldInfo( this.name, this.tagNumber, this.index, this.type, { dynamic defaultOrMaker, this.subBuilder, this.valueOf, this.enumValues, this.defaultEnumValue, String? protoName, }) : makeDefault = findMakeDefault(type, defaultOrMaker), check = null, _protoName = protoName, assert(type != 0), assert( !PbFieldType.isGroupOrMessage(type) || subBuilder != null || PbFieldType.isMapField(type), ), assert(!PbFieldType.isEnum(type) || valueOf != null); // Represents a field that has been removed by a program transformation. FieldInfo.dummy(this.index) : name = '', _protoName = '', tagNumber = 0, type = 0, makeDefault = null, valueOf = null, check = null, enumValues = null, defaultEnumValue = null, subBuilder = null; FieldInfo.repeated( this.name, this.tagNumber, this.index, this.type, this.check, this.subBuilder, { this.valueOf, this.enumValues, this.defaultEnumValue, String? protoName, }) : makeDefault = (() => newPbList(check: check)), _protoName = protoName, assert(PbFieldType.isRepeated(type)), assert(!PbFieldType.isEnum(type) || valueOf != null); static MakeDefaultFunc? findMakeDefault(int type, dynamic defaultOrMaker) { if (defaultOrMaker == null) return PbFieldType.defaultForType(type); if (defaultOrMaker is MakeDefaultFunc) return defaultOrMaker; return () => defaultOrMaker; } /// Whether this represents a dummy field standing in for a field that has /// been removed by a program transformation. bool get _isDummy => tagNumber == 0; bool get isRequired => PbFieldType.isRequired(type); bool get isRepeated => PbFieldType.isRepeated(type); bool get isGroupOrMessage => PbFieldType.isGroupOrMessage(type); bool get isEnum => PbFieldType.isEnum(type); bool get isMapField => PbFieldType.isMapField(type); /// Returns a read-only default value for a field. Unlike /// [GeneratedMessage.getField], doesn't create a repeated field. dynamic get readonlyDefault { if (isRepeated) { return _emptyList ??= newUnmodifiablePbList(); } return makeDefault!(); } /// Returns true if the field's value is okay to transmit. /// That is, it doesn't contain any required fields that aren't initialized. bool _hasRequiredValues(dynamic value) { if (value == null) return !isRequired; // missing is okay if optional if (!PbFieldType.isGroupOrMessage(type)) { return true; // primitive and present } if (!isRepeated) { // A required message: recurse. final GeneratedMessage message = value; return message._fieldSet._hasRequiredValues(); } final List list = value; if (list.isEmpty) return true; // For message types that (recursively) contain no required fields, // short-circuit the loop. if (!list[0]._fieldSet._hasRequiredFields) return true; // Recurse on each item in the list. return list.every((GeneratedMessage m) => m._fieldSet._hasRequiredValues()); } /// Appends the dotted path to each required field that's missing a value. void _appendInvalidFields(List problems, value, String prefix) { if (value == null) { if (isRequired) problems.add('$prefix$name'); } else if (!PbFieldType.isGroupOrMessage(type)) { // primitive and present } else if (!isRepeated) { // Required message/group: recurse. final GeneratedMessage message = value; message._fieldSet._appendInvalidFields(problems, '$prefix$name.'); } else { final List list = value; if (list.isEmpty) return; // For message types that (recursively) contain no required fields, // short-circuit the loop. if (!list[0]._fieldSet._hasRequiredFields) return; // Recurse on each item in the list. var position = 0; for (final message in list) { message._fieldSet._appendInvalidFields( problems, '$prefix$name[$position].', ); position++; } } } /// Creates a repeated field. PbList _createRepeatedField() { assert(isRepeated); return newPbList(check: check); } /// Same as above, but allow a tighter typed [PbList] to be created. PbList _createRepeatedFieldWithType() { assert(isRepeated); return newPbList(check: check); } /// Convenience method to thread this FieldInfo's reified type parameter to /// `FieldSet._ensureRepeatedField`. PbList _ensureRepeatedField(BuilderInfo meta, FieldSet fs) { return fs._ensureRepeatedField(meta, this); } @override String toString() => name; } extension FieldInfoInternalExtension on FieldInfo { List ensureRepeatedField(BuilderInfo meta, FieldSet fs) => _ensureRepeatedField(meta, fs); } final RegExp _upperCase = RegExp('[A-Z]'); String _unCamelCase(String name) { return name.replaceAllMapped( _upperCase, (match) => '_${match.group(0)!.toLowerCase()}', ); } /// A [FieldInfo] subclass for protobuf `map` fields. class MapFieldInfo extends FieldInfo?> { /// Key type of the map. Per proto2 and proto3 specs, this needs to be an /// integer type or `string`, and the type cannot be `repeated`. /// /// The `int` value is interpreted the same way as [FieldInfo.type]. final int keyFieldType; /// Value type of the map. Per proto2 and proto3 specs, this can be any type /// other than `map`, and the type cannot be `repeated`. /// /// The `int` value is interpreted the same way as [FieldInfo.type]. final int valueFieldType; /// Creates a new empty instance of the value type. /// /// `null` if the value type is not a Message type. final CreateBuilderFunc? valueCreator; final BuilderInfo mapEntryBuilderInfo; MapFieldInfo( String name, int tagNumber, int index, int type, this.keyFieldType, this.valueFieldType, this.mapEntryBuilderInfo, this.valueCreator, { ProtobufEnum? defaultEnumValue, String? protoName, }) : assert(PbFieldType.isMapField(type)), super( name, tagNumber, index, type, defaultOrMaker: () => newPbMap(keyFieldType, valueFieldType), defaultEnumValue: defaultEnumValue, protoName: protoName, ) { assert(!PbFieldType.isEnum(type) || valueOf != null); } FieldInfo get valueFieldInfo => mapEntryBuilderInfo.fieldInfo[mapValueFieldNumber]!; PbMap _ensureMapField(BuilderInfo meta, FieldSet fs) { return fs._ensureMapField(meta, this); } PbMap _createMapField() { assert(isMapField); return newPbMap(keyFieldType, valueFieldType); } } extension MapFieldInfoInternalExtension on MapFieldInfo { Map ensureMapField(BuilderInfo meta, FieldSet fs) => _ensureMapField(meta, fs); } ================================================ FILE: protobuf/lib/src/protobuf/field_set.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; @pragma('vm:never-inline') @pragma('wasm:never-inline') void _throwFrozenMessageModificationError( String messageName, [ String? methodName, ]) { if (methodName != null) { throw UnsupportedError( 'Attempted to call $methodName on a read-only message ($messageName)', ); } throw UnsupportedError( 'Attempted to change a read-only message ($messageName)', ); } /// All the data in a [GeneratedMessage]. /// /// These fields and methods are in a separate class to avoid polymorphic /// access due to inheritance. This turns out to be faster when compiled to /// JavaScript. class FieldSet { final GeneratedMessage? _message; /// The value of each non-extension field in a fixed-length array. /// The index of a field can be found in [FieldInfo.index]. /// A null entry indicates that the field has no value. final List _values; /// Contains all the extension fields, or null if there aren't any. ExtensionFieldSet? _extensions; /// Contains all the unknown fields, or null if there aren't any. UnknownFieldSet? _unknownFields; /// Contains unknown data for messages deserialized from json. Map? _unknownJsonData; /// Encodes whether `this` has been frozen, and if so, also memoizes the /// hash code. /// /// Will always be a `bool` or `int`. /// /// If the message is mutable: `false` /// If the message is frozen and no hash code has been computed: `true` /// If the message is frozen and a hash code has been computed: the hash /// code as an `int`. Object _frozenState = false; /// The [BuilderInfo] for the [GeneratedMessage] this [FieldSet] belongs to. /// /// WARNING: Avoid calling this for any performance critical code, instead /// obtain the [BuilderInfo] on the call site. BuilderInfo get _meta => _message!.info_; /// Returns the value of [_frozenState] as if it were a boolean indicator /// for whether `this` is read-only (has been frozen). /// /// If the value is not a `bool`, then it must contain the memoized hash code /// value, in which case the proto must be read-only. bool get _isReadOnly => _frozenState is! bool || _frozenState as bool; /// Returns the value of [_frozenState] if it contains the pre-computed value /// of the hashCode for the frozen field sets. /// /// Computing the hashCode of a proto object can be very expensive for large /// protos. Frozen protos don't allow any mutations, which means the contents /// of the field set should be stable. /// /// If [_frozenState] contains a boolean, the hashCode hasn't been memoized, /// so it will return null. int? get _memoizedHashCode => _frozenState is int ? _frozenState as int : null; /// Maps a `oneof` field index to the tag number which is currently set. If /// the index is not present, the oneof field is unset. final Map? _oneofCases; FieldSet(this._message, BuilderInfo meta) : _values = _makeValueList(meta.byIndex.length), _oneofCases = meta.oneofs.isEmpty ? null : {}; static List _makeValueList(int length) { if (length == 0) return _zeroList; return List.filled(length, null, growable: false); } // Use `List.filled` and not a `[]` to ensure that `_values` always has the // same implementation type. static final List _zeroList = List.filled(0, null, growable: false); // Metadata about multiple fields String get _messageName => _meta.qualifiedMessageName; bool get _hasRequiredFields => _meta.hasRequiredFields; /// The [FieldInfo] for each non-extension field. Iterable get _infos => _meta.fieldInfo.values; /// The [FieldInfo] for each non-extension field in tag order. Iterable get _infosSortedByTag => _meta.sortedByTag; ExtensionFieldSet _ensureExtensions() => _extensions ??= ExtensionFieldSet(this, readOnly: _isReadOnly); UnknownFieldSet _ensureUnknownFields() { if (_unknownFields == null) { if (_isReadOnly) return UnknownFieldSet.emptyUnknownFieldSet; _unknownFields = UnknownFieldSet(); } return _unknownFields!; } // Metadata about single fields /// Returns FieldInfo for a non-extension field, or null if not found. FieldInfo? _nonExtensionInfo(BuilderInfo meta, int? tagNumber) => meta.fieldInfo[tagNumber]; /// Returns FieldInfo for a non-extension field. FieldInfo _nonExtensionInfoByIndex(int index) => _meta.byIndex[index]; /// Returns the FieldInfo for a regular or extension field. /// throws ArgumentException if no info is found. FieldInfo _ensureInfo(int tagNumber) { final fi = _getFieldInfoOrNull(tagNumber); if (fi != null) return fi; throw ArgumentError('tag $tagNumber not defined in $_messageName'); } /// Returns the FieldInfo for a regular or extension field. FieldInfo? _getFieldInfoOrNull(int tagNumber) { final fi = _nonExtensionInfo(_meta, tagNumber); if (fi != null) return fi; return _extensions?._getInfoOrNull(tagNumber); } void _markReadOnly() { if (_isReadOnly) return; _frozenState = true; for (final field in _meta.sortedByTag) { if (field.isRepeated) { final PbList? list = _values[field.index!]; if (list == null) continue; list.freeze(); } else if (field.isMapField) { final PbMap? map = _values[field.index!]; if (map == null) continue; map.freeze(); } else if (field.isGroupOrMessage) { final entry = _values[field.index!]; if (entry != null) { final GeneratedMessage msg = entry; msg.freeze(); } } } _extensions?._markReadOnly(); _unknownFields?._markReadOnly(); } void _ensureWritable() { if (_isReadOnly) { _throwFrozenMessageModificationError(_messageName); } } // Single-field operations /// Gets a field with full error-checking. /// /// Works for both extended and non-extended fields. /// Creates repeated fields (unless read-only). /// Suitable for public API. dynamic _getField(int tagNumber) { final fi = _nonExtensionInfo(_meta, tagNumber); if (fi != null) { final value = _values[fi.index!]; if (value != null) return value; return _getDefault(fi); } final extensions = _extensions; if (extensions != null) { final fi = extensions._getInfoOrNull(tagNumber); if (fi != null) { return extensions._getFieldOrDefault(fi); } } throw ArgumentError('tag $tagNumber not defined in $_messageName'); } dynamic _getDefault(FieldInfo fi) { if (!fi.isRepeated && !fi.isMapField) return fi.makeDefault!(); if (_isReadOnly) return fi.readonlyDefault; final value = fi.makeDefault!(); _setNonExtensionFieldUnchecked(_meta, fi, value); return value; } dynamic _getFieldOrNullByTag(int tagNumber) { final fi = _getFieldInfoOrNull(tagNumber); if (fi == null) return null; return _getFieldOrNull(fi); } /// Returns the field's value or null if not set. /// /// Works for both extended and non-extend fields. /// Works for both repeated and non-repeated fields. dynamic _getFieldOrNull(FieldInfo fi) { if (fi.index != null) return _values[fi.index!]; return _extensions?._getFieldOrNull(fi as Extension); } bool _hasField(int tagNumber) { final fi = _nonExtensionInfo(_meta, tagNumber); if (fi != null) return _$has(fi.index!); return _extensions?._hasField(tagNumber) ?? false; } void _clearField(int tagNumber) { _ensureWritable(); final meta = _meta; final fi = _nonExtensionInfo(meta, tagNumber); if (fi != null) { assert(tagNumber == fi.tagNumber); // Clear a non-extension field _values[fi.index!] = null; final oneofIndex = meta.oneofs[tagNumber]; if (oneofIndex != null) { _oneofCases![oneofIndex] = 0; } return; } final extensions = _extensions; if (extensions != null) { final fi = extensions._getInfoOrNull(tagNumber); if (fi != null) { extensions._clearField(fi); return; } } // neither a regular field nor an extension. // TODO(skybrian) throw? } /// Sets a non-repeated field with error-checking. /// /// Works for both extended and non-extended fields. /// Suitable for public API. void _setField(int tagNumber, Object value) { final meta = _meta; final fi = _nonExtensionInfo(meta, tagNumber); if (fi == null) { final extensions = _extensions; if (extensions == null) { throw ArgumentError('tag $tagNumber not defined in $_messageName'); } extensions._setField(tagNumber, value); return; } if (fi.isRepeated) { throw ArgumentError( _setFieldFailedMessage(fi, value, 'repeating field (use get + .add())'), ); } _validateField(fi, value); _setNonExtensionFieldUnchecked(meta, fi, value); } /// Sets a non-repeated field without validating it. /// /// Works for both extended and non-extended fields. /// Suitable for decoders that do their own validation. void _setFieldUnchecked(BuilderInfo meta, FieldInfo fi, value) { assert(!fi.isRepeated); if (fi.index == null) { _ensureExtensions() .._addInfoUnchecked(fi as Extension) .._setFieldUnchecked(fi, value); } else { _setNonExtensionFieldUnchecked(meta, fi, value); } } /// Returns the list to use for adding to a repeated field. /// /// Works for both extended and non-extended fields. /// Creates and stores the repeated field if it doesn't exist. /// If it's an extension and the list doesn't exist, validates and stores it. /// Suitable for decoders. PbList _ensureRepeatedField(BuilderInfo meta, FieldInfo fi) { assert(!_isReadOnly); assert(fi.isRepeated); if (fi.index == null) { return _ensureExtensions()._ensureRepeatedField(fi as Extension); } final value = _getFieldOrNull(fi); if (value != null) return value; final newValue = fi._createRepeatedField(); _setNonExtensionFieldUnchecked(meta, fi, newValue); return newValue; } PbMap _ensureMapField(BuilderInfo meta, MapFieldInfo fi) { assert(!_isReadOnly); assert(fi.isMapField); assert(fi.index != null); // Map fields are not allowed to be extensions. final value = _getFieldOrNull(fi); if (value != null) return value; final newValue = fi._createMapField(); _setNonExtensionFieldUnchecked(meta, fi, newValue); return newValue; } /// Sets a non-extended field and fires events. void _setNonExtensionFieldUnchecked(BuilderInfo meta, FieldInfo fi, value) { final tag = fi.tagNumber; final oneofIndex = meta.oneofs[tag]; if (oneofIndex != null) { final currentOneofTag = _oneofCases![oneofIndex]; if (currentOneofTag != null) { _clearField(currentOneofTag); } _oneofCases[oneofIndex] = tag; } _values[fi.index!] = value; } // Generated method implementations /// The implementation of a generated getter. T _$get(int index, T? defaultValue) { final value = _values[index]; if (value != null) return value; if (defaultValue != null) return defaultValue; return _getDefault(_nonExtensionInfoByIndex(index)) as T; } /// The implementation of a generated getter for a default value determined by /// the field definition value. Common case for submessages. dynamic type /// pushes the type check to the caller. dynamic _$getND(int index) { final value = _values[index]; if (value != null) return value; return _getDefault(_nonExtensionInfoByIndex(index)); } T _$ensure(int index) { if (!_$has(index)) { final dynamic value = _nonExtensionInfoByIndex(index).subBuilder!(); _$set(index, value); return value; } // The implicit downcast at the return is always correct by construction // from the protoc generator. See `GeneratedMessage.$_getN` for details. return _$getND(index); } /// The implementation of a generated getter for repeated fields. PbList _$getList(int index) { final value = _values[index]; if (value != null) return value; final fi = _nonExtensionInfoByIndex(index) as FieldInfo; assert(fi.isRepeated); if (_isReadOnly) { return fi.readonlyDefault; } final list = fi._createRepeatedFieldWithType(); _setNonExtensionFieldUnchecked(_meta, fi, list); return list; } /// The implementation of a generated getter for map fields. PbMap _$getMap(GeneratedMessage parentMessage, int index) { final value = _values[index]; if (value != null) return value; final fi = _nonExtensionInfoByIndex(index) as MapFieldInfo; assert(fi.isMapField); if (_isReadOnly) { return newUnmodifiablePbMap(fi.keyFieldType, fi.valueFieldType); } final map = fi._createMapField(); _setNonExtensionFieldUnchecked(_meta, fi, map); return map; } /// The implementation of a generated getter for `bool` fields. bool _$getB(int index, bool? defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } return value; } /// The implementation of a generated getter for `bool` fields that default to /// `false`. bool _$getBF(int index) => _values[index] ?? false; /// The implementation of a generated getter for int fields. int _$getI(int index, int? defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } return value; } /// The implementation of a generated getter for `int` fields (int32, uint32, /// fixed32, sfixed32) that default to `0`. int _$getIZ(int index) => _values[index] ?? 0; /// The implementation of a generated getter for String fields. String _$getS(int index, String? defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } return value; } /// The implementation of a generated getter for String fields that default to /// the empty string. String _$getSZ(int index) => _values[index] ?? ''; /// The implementation of a generated getter for Int64 fields. Int64 _$getI64(int index) { var value = _values[index]; value ??= _getDefault(_nonExtensionInfoByIndex(index)); return value; } /// The implementation of a generated 'has' method. bool _$has(int index) { final value = _values[index]; if (value == null) return false; if (value is List) return value.isNotEmpty; return true; } /// The implementation of a generated setter. /// /// In production, does no validation other than a null check. /// Only handles non-repeated, non-extension fields. /// Also, doesn't handle enums or messages which need per-type validation. void _$set(int index, Object? value) { assert(!_nonExtensionInfoByIndex(index).isRepeated); assert(_$check(index, value)); _ensureWritable(); if (value == null) { _$check(index, value); // throw exception for null value } final meta = _meta; final tag = meta.byIndex[index].tagNumber; final oneofIndex = meta.oneofs[tag]; if (oneofIndex != null) { final currentOneofTag = _oneofCases![oneofIndex]; if (currentOneofTag != null) { _clearField(currentOneofTag); } _oneofCases[oneofIndex] = tag; } _values[index] = value; } bool _$check(int index, var newValue) { _validateField(_nonExtensionInfoByIndex(index), newValue); return true; // Allows use in an assertion. } // Bulk operations reading or writing multiple fields void _clear() { _ensureWritable(); if (_unknownFields != null) { _unknownFields!.clear(); } _unknownJsonData = null; if (_values.isNotEmpty) _values.fillRange(0, _values.length, null); _extensions?._clearValues(); _oneofCases?.clear(); } bool _equals(FieldSet o) { if (_meta != o._meta) return false; for (var i = 0; i < _values.length; i++) { if (!_equalFieldValues(_values[i], o._values[i])) return false; } final extensions = _extensions; if (extensions == null || !extensions._hasValues) { // Check if other extensions are logically empty. // (Don't create them unnecessarily.) final oExtensions = o._extensions; if (oExtensions != null && oExtensions._hasValues) { return false; } } else { if (!extensions._equalValues(o._extensions)) return false; } if (_unknownFields == null || _unknownFields!.isEmpty) { // Check if other unknown fields is logically empty. // (Don't create them unnecessarily.) if (o._unknownFields != null && o._unknownFields!.isNotEmpty) { return false; } } else { // Check if the other unknown fields has the same fields. if (_unknownFields != o._unknownFields) return false; } if (_unknownJsonData != null || o._unknownJsonData != null) { if ((_unknownJsonData == null) != (o._unknownJsonData == null)) { return false; } if (!DeepCollectionEquality().equals( _unknownJsonData, o._unknownJsonData, )) { return false; } } return true; } bool _equalFieldValues(Object? left, Object? right) { if (left != null && right != null) return deepEquals(left, right); final val = left ?? right; // Two uninitialized fields are equal. if (val == null) return true; // One field is null. We are comparing an initialized field // with its default value. // An empty repeated field is the same as uninitialized. // This is because accessing a repeated field automatically creates it. // We don't want reading a field to change equality comparisons. if (val is List && val.isEmpty) return true; // An empty map field is the same as uninitialized. // This is because accessing a map field automatically creates it. // We don't want reading a field to change equality comparisons. if (val is PbMap && val.isEmpty) return true; // For now, initialized and uninitialized fields are different. // TODO(skybrian) consider other cases; should we compare with the // default value or not? return false; } /// Calculates a hash code based on the contents of the protobuf. /// /// The hash may change when any field changes (recursively). /// Therefore, protobufs used as map keys shouldn't be changed. /// /// If the protobuf contents have been frozen the hashCode is memoized to /// speed up performance. int get _hashCode { if (_memoizedHashCode != null) { return _memoizedHashCode!; } // Hash with descriptor. var hash = HashUtils.combine(0, _meta.hashCode); // Hash with non-extension fields. final values = _values; for (final fi in _infosSortedByTag) { final value = values[fi.index!]; if (value == null) continue; hash = _hashField(hash, fi, value); } // Hash with extension fields. final extensions = _extensions; if (extensions != null) { final sortedByTagNumbers = sorted(extensions._tagNumbers); for (final tagNumber in sortedByTagNumbers) { final fi = extensions._getInfoOrNull(tagNumber)!; hash = _hashField(hash, fi, extensions._getFieldOrNull(fi)); } } // Hash with unknown fields. hash = HashUtils.combine(hash, _unknownFields?.hashCode ?? 0); if (_unknownJsonData != null) { hash = HashUtils.combine( hash, DeepCollectionEquality().hash(_unknownJsonData), ); } if (_isReadOnly) { _frozenState = hash; } return hash; } // Hashes the value of one field (recursively). static int _hashField(int hash, FieldInfo fi, value) { if (value is List && value.isEmpty) { return hash; // It's either repeated or an empty byte array. } if (value is PbMap && value.isEmpty) { return hash; } hash = HashUtils.combine(hash, fi.tagNumber); if (PbFieldType.isBytes(fi.type)) { // Bytes are represented as a List (Usually with byte-data). // We special case that to match our equality semantics. hash = HashUtils.combine(hash, HashUtils.hashObjects(value)); } else if (!PbFieldType.isEnum(fi.type)) { hash = HashUtils.combine(hash, value.hashCode); } else if (fi.isRepeated) { final PbList list = value; hash = HashUtils.combine( hash, HashUtils.hashObjects( list.map((enm) { final ProtobufEnum enm_ = enm; return enm_.value; }), ), ); } else { final ProtobufEnum enm = value; hash = HashUtils.combine(hash, enm.value); } return hash; } void writeString(StringBuffer out, String indent) { void renderValue(key, value) { if (value is GeneratedMessage) { out.write('$indent$key: {\n'); value._fieldSet.writeString(out, '$indent '); out.write('$indent}\n'); } else if (value is MapEntry) { out.write('$indent$key: {${value.key} : ${value.value}} \n'); } else { out.write('$indent$key: $value\n'); } } void writeFieldValue(fieldValue, String name) { if (fieldValue == null) return; if (fieldValue is PbList) { for (final value in fieldValue) { renderValue(name, value); } } else if (fieldValue is PbMap) { for (final entry in fieldValue.entries) { renderValue(name, entry); } } else { renderValue(name, fieldValue); } } for (final fi in _infosSortedByTag) { writeFieldValue( _values[fi.index!], fi.name == '' ? fi.tagNumber.toString() : fi.name, ); } final extensions = _extensions; if (extensions != null) { extensions._info.keys.toList() ..sort() ..forEach( (int tagNumber) => writeFieldValue( _extensions!._values[tagNumber], '[${_extensions!._info[tagNumber]!.name}]', ), ); } final unknownFields = _unknownFields; if (unknownFields != null) { out.write(unknownFields.toString()); } else { out.write(UnknownFieldSet().toString()); } final unknownJsonData = _unknownJsonData; if (unknownJsonData != null) { out.write(unknownJsonData.toString()); } } /// Writes the text proto string representation of the message. /// Spec: https://protobuf.dev/reference/protobuf/textformat-spec/ void writeTextFormat(StringSink out) { _writeTextFormat(out, 0); } void _writeTextFormat(StringSink out, int initialIndentLevel) { void writeIndent(int indentLevel) { for (var i = 0; i < indentLevel; i++) { out.writeCharCode(32); out.writeCharCode(32); } } void renderValue(String key, dynamic value, int indentLevel) { writeIndent(indentLevel); if (value is GeneratedMessage) { out.write('$key {\n'); value._fieldSet._writeTextFormat(out, indentLevel + 1); writeIndent(indentLevel); out.write('}\n'); } else if (value is MapEntry) { out.write('$key {\n'); renderValue('key', value.key, indentLevel + 1); renderValue('value', value.value, indentLevel + 1); writeIndent(indentLevel); out.write('}\n'); } else if (value is String) { out.write('$key: "${escapeString(value)}"\n'); } else if (value is Map) { out.write('$key {\n'); for (final entry in value.entries) { renderValue(entry.key, entry.value, indentLevel + 1); } writeIndent(indentLevel); out.write('}\n'); // Bytes are represented as a List in Dart protobuf. } else if (value is List) { out.write('$key: "'); escapeBytes(value, out); out.write('"\n'); } else { // Writes the primitive value as a string. out.write('$key: $value\n'); } } void writeFieldValue(String name, dynamic fieldValue) { if (fieldValue is PbList) { for (final value in fieldValue) { renderValue(name, value, initialIndentLevel); } } else if (fieldValue is PbMap) { for (final entry in fieldValue.entries) { renderValue(name, entry, initialIndentLevel); } } else { renderValue(name, fieldValue, initialIndentLevel); } } for (final fi in _infosSortedByTag) { if (_hasField(fi.tagNumber)) { writeFieldValue( fi.name == '' ? fi.tagNumber.toString() : fi.protoName, _values[fi.index!], ); } } final extensions = _extensions; if (extensions != null) { extensions._info.keys.toList() ..sort() ..forEach((int tagNumber) { if (_hasField(tagNumber)) { writeFieldValue( '[${extensions._info[tagNumber]!.name}]', extensions._values[tagNumber], ); } }); } _unknownFields?.writeTextFormat(out, initialIndentLevel); final unknownJsonData = _unknownJsonData; if (unknownJsonData != null) { for (final entry in unknownJsonData.entries) { renderValue(entry.key, entry.value, initialIndentLevel); } } } /// Merges the contents of the [other] into this message. /// /// Singular fields that are set in [other] overwrite the corresponding fields /// in this message. Repeated fields are appended. Singular sub-messages are /// recursively merged. void _mergeFromMessage(FieldSet other) { // TODO(https://github.com/google/protobuf.dart/issues/60): Recognize // when `this` and [other] are the same protobuf (e.g. from cloning). In // this case, we can merge the non-extension fields without field lookups or // validation checks. _ensureWritable(); for (final fi in other._infosSortedByTag) { final value = other._values[fi.index!]; if (value != null) _mergeField(fi, value, isExtension: false); } final otherExtensions = other._extensions; if (otherExtensions != null) { for (final tagNumber in otherExtensions._tagNumbers) { final extension = otherExtensions._getInfoOrNull(tagNumber)!; final value = otherExtensions._getFieldOrNull(extension); _mergeField(extension, value, isExtension: true); } } final otherUnknownFields = other._unknownFields; if (otherUnknownFields != null) { _ensureUnknownFields().mergeFromUnknownFieldSet(otherUnknownFields); } final otherUnknownJsonData = other._unknownJsonData; if (otherUnknownJsonData != null) { final newUnknownJsonData = Map.from( _unknownJsonData ?? {}, ); otherUnknownJsonData.forEach( (key, value) => newUnknownJsonData[key] = value, ); _unknownJsonData = newUnknownJsonData.isEmpty ? null : newUnknownJsonData; } } void _mergeField(FieldInfo otherFi, fieldValue, {required bool isExtension}) { final tagNumber = otherFi.tagNumber; // Determine the FieldInfo to use. // Don't allow regular fields to be overwritten by extensions. final meta = _meta; var fi = _nonExtensionInfo(meta, tagNumber); if (fi == null && isExtension) { // This will overwrite any existing extension field info. fi = otherFi; } if (fi!.isMapField) { if (fieldValue == null) { return; } final MapFieldInfo f = fi as dynamic; final PbMap map = f._ensureMapField(meta, this) as dynamic; if (PbFieldType.isGroupOrMessage(f.valueFieldType)) { final PbMap fieldValueMap = fieldValue; for (final entry in fieldValueMap.entries) { map[entry.key] = entry.value.deepCopy(); } } else { map.addAll(fieldValue); } return; } if (fi.isRepeated) { if (PbFieldType.isGroupOrMessage(otherFi.type)) { // fieldValue must be a PbList of GeneratedMessage. final PbList pbList = fieldValue; final repeatedFields = fi._ensureRepeatedField(meta, this); for (var i = 0; i < pbList.length; ++i) { repeatedFields.add(pbList[i].deepCopy()); } } else { // fieldValue must be at least a PbList. final PbList pbList = fieldValue; fi._ensureRepeatedField(meta, this).addAll(pbList); } return; } if (otherFi.isGroupOrMessage) { final currentFi = isExtension ? _ensureExtensions()._getFieldOrNull(fi as Extension) : _values[fi.index!]; final GeneratedMessage msg = fieldValue; if (currentFi == null) { fieldValue = msg.deepCopy(); } else { final GeneratedMessage currentMsg = currentFi; fieldValue = currentMsg..mergeFromMessage(msg); } } if (isExtension) { _ensureExtensions()._setFieldAndInfo( fi as Extension, fieldValue, ); } else { _validateField(fi, fieldValue); _setNonExtensionFieldUnchecked(meta, fi, fieldValue); } } // Error-checking /// Checks that the message is mutable (not frozen) and the value for the /// field is valid for the field type. /// /// Throws [UnsupportedError] if the message if immutable (frozen). /// /// Throws [ArgumentError] if the field value is not valid for the field /// type. For example, when setting a proto `string` field a Dart `int`. void _validateField(FieldInfo fi, var newValue) { _ensureWritable(); final message = _getFieldError(fi.type, newValue); if (message != null) { throw ArgumentError(_setFieldFailedMessage(fi, newValue, message)); } } String _setFieldFailedMessage(FieldInfo fi, var value, String detail) { return 'Illegal to set field ${fi.name} (${fi.tagNumber}) of $_messageName' ' to value ($value): $detail'; } bool _hasRequiredValues() { if (!_hasRequiredFields) return true; for (final fi in _infos) { final value = _values[fi.index!]; if (!fi._hasRequiredValues(value)) return false; } return _hasRequiredExtensionValues(); } bool _hasRequiredExtensionValues() { final extensions = _extensions; if (extensions == null) return true; for (final fi in extensions._infos) { final value = extensions._getFieldOrNull(fi); if (!fi._hasRequiredValues(value)) return false; } return true; // No problems found. } /// Adds the path to each uninitialized field to the list. void _appendInvalidFields(List problems, String prefix) { if (!_hasRequiredFields) return; for (final fi in _infos) { final value = _values[fi.index!]; fi._appendInvalidFields(problems, value, prefix); } // TODO(skybrian): search extensions as well // https://github.com/google/protobuf.dart/issues/46 } /// Makes a shallow copy of all values from [original] to this. /// /// Map fields and repeated fields are copied. void _shallowCopyValues(FieldSet original) { _values.setRange(0, original._values.length, original._values); final info = _meta; for (var index = 0; index < info.byIndex.length; index++) { final fieldInfo = info.byIndex[index]; if (fieldInfo.isMapField) { final PbMap? map = _values[index]; if (map != null) { _values[index] = (fieldInfo as MapFieldInfo)._createMapField()..addAll(map); } } else if (fieldInfo.isRepeated) { final PbList? list = _values[index]; if (list != null) { _values[index] = fieldInfo._createRepeatedField()..addAll(list); } } } final originalExtensions = original._extensions; if (originalExtensions != null) { _ensureExtensions()._shallowCopyValues(originalExtensions); } final originalUnknownFields = original._unknownFields; if (originalUnknownFields != null) { _ensureUnknownFields()._fields.addAll(originalUnknownFields._fields); } final unknownJsonData = original._unknownJsonData; if (unknownJsonData != null) { _unknownJsonData = Map.from(unknownJsonData); } _oneofCases?.addAll(original._oneofCases!); } // This assumes that [this] is fresh, i.e. no extensions, no values set. // // The reason why this updates [this] instead of returning a new [FieldSet] is // that to start cloning we need to create an empty instance via // `createEmptyInstance`, which already creates an empty [FieldSet], which we // reuse here. void _deepCopyFrom(FieldSet original) { final info = _meta; assert(_values.length == original._values.length); // memcpy the original's values to avoid redundant bounds checks below by // copying scalar fields one by one. _values.setAll(0, original._values); for (var index = 0; index < info.byIndex.length; index++) { final fieldInfo = info.byIndex[index]; if (fieldInfo.isMapField) { final PbMap? originalMap = original._values[index]; if (originalMap == null) continue; _values[index] = originalMap.deepCopy(); } else if (fieldInfo.isRepeated) { final PbList? originalList = original._values[index]; if (originalList == null) continue; _values[index] = originalList.deepCopy(); } else if (fieldInfo.isGroupOrMessage) { final GeneratedMessage? message = original._values[index]; _values[index] = message?.deepCopy(); } // Scalar fields are already copied above with `setAll`. } assert(_extensions == null); final originalExtensions = original._extensions; if (originalExtensions != null) { _extensions = originalExtensions._deepCopy(this); } assert(_unknownFields == null); final originalUnknownFields = original._unknownFields; if (originalUnknownFields != null) { _unknownFields = originalUnknownFields._deepCopy(); } assert(_unknownJsonData == null); final originalUnknownJsonData = original._unknownJsonData; if (originalUnknownJsonData != null) { _unknownJsonData = Map.from(originalUnknownJsonData); } assert(_oneofCases == null || _oneofCases.isEmpty); final originalOneofCases = original._oneofCases; if (originalOneofCases != null) { _oneofCases!.addAll(originalOneofCases); } } bool hasExtension(Extension extension) => _extensions?._getFieldOrNull(extension) != null; dynamic getExtension(Extension extension) => _ensureExtensions()._getFieldOrDefault(extension); void setExtension(Extension extension, Object value) => _ensureExtensions()._setFieldAndInfo(extension, value); void addExtension(Extension extension, Object? value) { _ensureWritable(); if (!extension.isRepeated) { throw ArgumentError( 'Cannot add to a non-repeated field (use setExtension())', ); } _ensureExtensions()._ensureRepeatedField(extension).add(value); } void clearExtension(Extension extension) { _ensureWritable(); _extensions?._clearFieldAndInfo(extension); } } extension FieldSetInternalExtension on FieldSet { Iterable get infos => _infos; Iterable get infosSortedByTag => _infosSortedByTag; List get values => _values; ExtensionFieldSet? get extensions => _extensions; UnknownFieldSet? get unknownFields => _unknownFields; Map? get unknownJsonData => _unknownJsonData; set unknownJsonData(Map? value) => _unknownJsonData = value; BuilderInfo get meta => _meta; GeneratedMessage? get message => _message; String get messageName => _messageName; void ensureWritable() => _ensureWritable(); PbList ensureRepeatedField(BuilderInfo meta, FieldInfo fi) => _ensureRepeatedField(meta, fi); PbMap ensureMapField(BuilderInfo meta, MapFieldInfo fi) => _ensureMapField(meta, fi); void validateField(FieldInfo fi, dynamic newValue) => _validateField(fi, newValue); void setFieldUnchecked(BuilderInfo meta, FieldInfo fi, dynamic value) => _setFieldUnchecked(meta, fi, value); } ================================================ FILE: protobuf/lib/src/protobuf/field_type.dart ================================================ // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: constant_identifier_names,non_constant_identifier_names part of 'internal.dart'; /// Defines constants and functions for dealing with fieldType bits. class PbFieldType { static bool isRepeated(int fieldType) => (fieldType & REPEATED_BIT) != 0; static bool isRequired(int fieldType) => (fieldType & REQUIRED_BIT) != 0; static bool isEnum(int fieldType) => baseType(fieldType) == ENUM_BIT; static bool isBytes(int fieldType) => baseType(fieldType) == BYTES_BIT; static bool isGroupOrMessage(int fieldType) => (fieldType & (GROUP_BIT | MESSAGE_BIT)) != 0; static bool isMapField(int fieldType) => (fieldType & MAP_BIT) != 0; /// Returns the base field type without any of the required, repeated /// and packed bits. static int baseType(int fieldType) => fieldType & ~(REQUIRED_BIT | REPEATED_BIT | PACKED_BIT | MAP_BIT); static MakeDefaultFunc? defaultForType(int type) { switch (type) { case OPTIONAL_BOOL: case REQUIRED_BOOL: return BOOL_FALSE; case OPTIONAL_BYTES: case REQUIRED_BYTES: return BYTES_EMPTY; case OPTIONAL_STRING: case REQUIRED_STRING: return STRING_EMPTY; case OPTIONAL_FLOAT: case REQUIRED_FLOAT: case OPTIONAL_DOUBLE: case REQUIRED_DOUBLE: return DOUBLE_ZERO; case OPTIONAL_INT32: case REQUIRED_INT32: case OPTIONAL_INT64: case REQUIRED_INT64: case OPTIONAL_SINT32: case REQUIRED_SINT32: case OPTIONAL_SINT64: case REQUIRED_SINT64: case OPTIONAL_UINT32: case REQUIRED_UINT32: case OPTIONAL_UINT64: case REQUIRED_UINT64: case OPTIONAL_FIXED32: case REQUIRED_FIXED32: case OPTIONAL_FIXED64: case REQUIRED_FIXED64: case OPTIONAL_SFIXED32: case REQUIRED_SFIXED32: case OPTIONAL_SFIXED64: case REQUIRED_SFIXED64: return INT_ZERO; default: return null; } } // Closures commonly used by initializers. static String STRING_EMPTY() => ''; static List BYTES_EMPTY() => []; static bool BOOL_FALSE() => false; static int INT_ZERO() => 0; static double DOUBLE_ZERO() => 0.0; static const int REQUIRED_BIT = 0x1; static const int REPEATED_BIT = 0x2; static const int PACKED_BIT = 0x4; static const int BOOL_BIT = 0x10; static const int BYTES_BIT = 0x20; static const int STRING_BIT = 0x40; static const int DOUBLE_BIT = 0x80; static const int FLOAT_BIT = 0x100; static const int ENUM_BIT = 0x200; static const int GROUP_BIT = 0x400; static const int INT32_BIT = 0x800; static const int INT64_BIT = 0x1000; static const int SINT32_BIT = 0x2000; static const int SINT64_BIT = 0x4000; static const int UINT32_BIT = 0x8000; static const int UINT64_BIT = 0x10000; static const int FIXED32_BIT = 0x20000; static const int FIXED64_BIT = 0x40000; static const int SFIXED32_BIT = 0x80000; static const int SFIXED64_BIT = 0x100000; static const int MESSAGE_BIT = 0x200000; static const int MAP_BIT = 0x400000; static const int OPTIONAL_BOOL = BOOL_BIT; static const int OPTIONAL_BYTES = BYTES_BIT; static const int OPTIONAL_STRING = STRING_BIT; static const int OPTIONAL_FLOAT = FLOAT_BIT; static const int OPTIONAL_DOUBLE = DOUBLE_BIT; static const int OPTIONAL_ENUM = ENUM_BIT; static const int OPTIONAL_GROUP = GROUP_BIT; static const int OPTIONAL_INT32 = INT32_BIT; static const int OPTIONAL_INT64 = INT64_BIT; static const int OPTIONAL_SINT32 = SINT32_BIT; static const int OPTIONAL_SINT64 = SINT64_BIT; static const int OPTIONAL_UINT32 = UINT32_BIT; static const int OPTIONAL_UINT64 = UINT64_BIT; static const int OPTIONAL_FIXED32 = FIXED32_BIT; static const int OPTIONAL_FIXED64 = FIXED64_BIT; static const int OPTIONAL_SFIXED32 = SFIXED32_BIT; static const int OPTIONAL_SFIXED64 = SFIXED64_BIT; static const int OPTIONAL_MESSAGE = MESSAGE_BIT; static const int REQUIRED_BOOL = REQUIRED_BIT | BOOL_BIT; static const int REQUIRED_BYTES = REQUIRED_BIT | BYTES_BIT; static const int REQUIRED_STRING = REQUIRED_BIT | STRING_BIT; static const int REQUIRED_FLOAT = REQUIRED_BIT | FLOAT_BIT; static const int REQUIRED_DOUBLE = REQUIRED_BIT | DOUBLE_BIT; static const int REQUIRED_ENUM = REQUIRED_BIT | ENUM_BIT; static const int REQUIRED_GROUP = REQUIRED_BIT | GROUP_BIT; static const int REQUIRED_INT32 = REQUIRED_BIT | INT32_BIT; static const int REQUIRED_INT64 = REQUIRED_BIT | INT64_BIT; static const int REQUIRED_SINT32 = REQUIRED_BIT | SINT32_BIT; static const int REQUIRED_SINT64 = REQUIRED_BIT | SINT64_BIT; static const int REQUIRED_UINT32 = REQUIRED_BIT | UINT32_BIT; static const int REQUIRED_UINT64 = REQUIRED_BIT | UINT64_BIT; static const int REQUIRED_FIXED32 = REQUIRED_BIT | FIXED32_BIT; static const int REQUIRED_FIXED64 = REQUIRED_BIT | FIXED64_BIT; static const int REQUIRED_SFIXED32 = REQUIRED_BIT | SFIXED32_BIT; static const int REQUIRED_SFIXED64 = REQUIRED_BIT | SFIXED64_BIT; static const int REQUIRED_MESSAGE = REQUIRED_BIT | MESSAGE_BIT; static const int REPEATED_BOOL = REPEATED_BIT | BOOL_BIT; static const int REPEATED_BYTES = REPEATED_BIT | BYTES_BIT; static const int REPEATED_STRING = REPEATED_BIT | STRING_BIT; static const int REPEATED_FLOAT = REPEATED_BIT | FLOAT_BIT; static const int REPEATED_DOUBLE = REPEATED_BIT | DOUBLE_BIT; static const int REPEATED_ENUM = REPEATED_BIT | ENUM_BIT; static const int REPEATED_GROUP = REPEATED_BIT | GROUP_BIT; static const int REPEATED_INT32 = REPEATED_BIT | INT32_BIT; static const int REPEATED_INT64 = REPEATED_BIT | INT64_BIT; static const int REPEATED_SINT32 = REPEATED_BIT | SINT32_BIT; static const int REPEATED_SINT64 = REPEATED_BIT | SINT64_BIT; static const int REPEATED_UINT32 = REPEATED_BIT | UINT32_BIT; static const int REPEATED_UINT64 = REPEATED_BIT | UINT64_BIT; static const int REPEATED_FIXED32 = REPEATED_BIT | FIXED32_BIT; static const int REPEATED_FIXED64 = REPEATED_BIT | FIXED64_BIT; static const int REPEATED_SFIXED32 = REPEATED_BIT | SFIXED32_BIT; static const int REPEATED_SFIXED64 = REPEATED_BIT | SFIXED64_BIT; static const int REPEATED_MESSAGE = REPEATED_BIT | MESSAGE_BIT; static const int PACKED_BOOL = REPEATED_BIT | PACKED_BIT | BOOL_BIT; static const int PACKED_FLOAT = REPEATED_BIT | PACKED_BIT | FLOAT_BIT; static const int PACKED_DOUBLE = REPEATED_BIT | PACKED_BIT | DOUBLE_BIT; static const int PACKED_ENUM = REPEATED_BIT | PACKED_BIT | ENUM_BIT; static const int PACKED_INT32 = REPEATED_BIT | PACKED_BIT | INT32_BIT; static const int PACKED_INT64 = REPEATED_BIT | PACKED_BIT | INT64_BIT; static const int PACKED_SINT32 = REPEATED_BIT | PACKED_BIT | SINT32_BIT; static const int PACKED_SINT64 = REPEATED_BIT | PACKED_BIT | SINT64_BIT; static const int PACKED_UINT32 = REPEATED_BIT | PACKED_BIT | UINT32_BIT; static const int PACKED_UINT64 = REPEATED_BIT | PACKED_BIT | UINT64_BIT; static const int PACKED_FIXED32 = REPEATED_BIT | PACKED_BIT | FIXED32_BIT; static const int PACKED_FIXED64 = REPEATED_BIT | PACKED_BIT | FIXED64_BIT; static const int PACKED_SFIXED32 = REPEATED_BIT | PACKED_BIT | SFIXED32_BIT; static const int PACKED_SFIXED64 = REPEATED_BIT | PACKED_BIT | SFIXED64_BIT; static const int MAP = MAP_BIT | MESSAGE_BIT; // Short names for use in generated code. // _O_ptional. static const int OB = OPTIONAL_BOOL; static const int OY = OPTIONAL_BYTES; static const int OS = OPTIONAL_STRING; static const int OF = OPTIONAL_FLOAT; static const int OD = OPTIONAL_DOUBLE; static const int OE = OPTIONAL_ENUM; static const int OG = OPTIONAL_GROUP; static const int O3 = OPTIONAL_INT32; static const int O6 = OPTIONAL_INT64; static const int OS3 = OPTIONAL_SINT32; static const int OS6 = OPTIONAL_SINT64; static const int OU3 = OPTIONAL_UINT32; static const int OU6 = OPTIONAL_UINT64; static const int OF3 = OPTIONAL_FIXED32; static const int OF6 = OPTIONAL_FIXED64; static const int OSF3 = OPTIONAL_SFIXED32; static const int OSF6 = OPTIONAL_SFIXED64; static const int OM = OPTIONAL_MESSAGE; // re_Q_uired. static const int QB = REQUIRED_BOOL; static const int QY = REQUIRED_BYTES; static const int QS = REQUIRED_STRING; static const int QF = REQUIRED_FLOAT; static const int QD = REQUIRED_DOUBLE; static const int QE = REQUIRED_ENUM; static const int QG = REQUIRED_GROUP; static const int Q3 = REQUIRED_INT32; static const int Q6 = REQUIRED_INT64; static const int QS3 = REQUIRED_SINT32; static const int QS6 = REQUIRED_SINT64; static const int QU3 = REQUIRED_UINT32; static const int QU6 = REQUIRED_UINT64; static const int QF3 = REQUIRED_FIXED32; static const int QF6 = REQUIRED_FIXED64; static const int QSF3 = REQUIRED_SFIXED32; static const int QSF6 = REQUIRED_SFIXED64; static const int QM = REQUIRED_MESSAGE; // re_P_eated. static const int PB = REPEATED_BOOL; static const int PY = REPEATED_BYTES; static const int PS = REPEATED_STRING; static const int PF = REPEATED_FLOAT; static const int PD = REPEATED_DOUBLE; static const int PE = REPEATED_ENUM; static const int PG = REPEATED_GROUP; static const int P3 = REPEATED_INT32; static const int P6 = REPEATED_INT64; static const int PS3 = REPEATED_SINT32; static const int PS6 = REPEATED_SINT64; static const int PU3 = REPEATED_UINT32; static const int PU6 = REPEATED_UINT64; static const int PF3 = REPEATED_FIXED32; static const int PF6 = REPEATED_FIXED64; static const int PSF3 = REPEATED_SFIXED32; static const int PSF6 = REPEATED_SFIXED64; static const int PM = REPEATED_MESSAGE; // pac_K_ed. static const int KB = PACKED_BOOL; static const int KE = PACKED_ENUM; static const int KF = PACKED_FLOAT; static const int KD = PACKED_DOUBLE; static const int K3 = PACKED_INT32; static const int K6 = PACKED_INT64; static const int KS3 = PACKED_SINT32; static const int KS6 = PACKED_SINT64; static const int KU3 = PACKED_UINT32; static const int KU6 = PACKED_UINT64; static const int KF3 = PACKED_FIXED32; static const int KF6 = PACKED_FIXED64; static const int KSF3 = PACKED_SFIXED32; static const int KSF6 = PACKED_SFIXED64; static const int M = MAP; } ================================================ FILE: protobuf/lib/src/protobuf/generated_message.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: non_constant_identifier_names part of 'internal.dart'; /// Type of an empty message builder. typedef CreateBuilderFunc = GeneratedMessage Function(); /// Type of a function that creates the default value of a protobuf field. typedef MakeDefaultFunc = Function(); /// Type of a function that makes an enum integer value to corresponding /// [ProtobufEnum] value. typedef ValueOfFunc = ProtobufEnum? Function(int value); /// The base class for all protobuf message types. /// /// The protoc plugin generates subclasses providing type-specific properties /// and methods. /// /// Public properties and methods added here should also be added to /// `GeneratedMessage_reservedNames` and should be unlikely to be used in a /// proto file. abstract class GeneratedMessage { // The pragma tells dart2js that the late checks for `__fieldSet` are // unnecessary. The field is always initialized before use, but dart2js can't // see that. One problem is that `this.info_` is called before the // initializing assignment, and potentially one of the many overrides for // `get:info_` could access the field before it is initialized, or call one of // the methods that accesses the field. The code generated for the `get:info_` // methods does not do this, but it is hard to determine from first // principles. @pragma('dart2js:late:trust') late final FieldSet __fieldSet; @pragma('dart2js:prefer-inline') FieldSet get _fieldSet => __fieldSet; GeneratedMessage() { __fieldSet = FieldSet(this, info_); // The following two returns confuse dart2js into avoiding inlining the // constructor *body*. A `@pragma('dart2js:never-inline')` annotation on // the constructor affects inlining of the generative constructor factory, // not the constructor body that is called from all the subclasses. // // TODO(http://dartbug.com/49475): Remove this when there is an annotation // that will give the desired result. return; return; // ignore: dead_code } // Overridden by subclasses. BuilderInfo get info_; /// Creates a deep copy of the fields in this message. @Deprecated( 'Using this can add significant size overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version', ) GeneratedMessage clone(); /// Creates an empty instance of the same message type as this. /// /// This method is useful when you have a value of type [GeneratedMessage] or /// `T extends GeneratedMessage` and you want a new empty message with the /// same message type as the value. If you know the actual message type, it's /// more direct to use the constructor, and this method creates the same /// message as the message's constructor. GeneratedMessage createEmptyInstance(); UnknownFieldSet get unknownFields => _fieldSet._ensureUnknownFields(); /// Make this message read-only. /// /// Marks this message, and any sub-messages, as read-only. GeneratedMessage freeze() { _fieldSet._markReadOnly(); return this; } /// Returns `true` if this message is marked read-only. Otherwise `false`. /// /// Even when `false`, some sub-message could be read-only. /// /// If `true` all sub-messages are frozen. bool get isFrozen => _fieldSet._isReadOnly; /// Creates a writable, shallow copy of this message. /// /// Sub messages will be shared with this message and will still be frozen if /// this message is frozen. /// /// The lists representing repeated fields are copied. But their elements will /// be shared with the corresponding list in `this`. /// /// Similarly for map fields, the maps will be copied, but share the elements. GeneratedMessage toBuilder() { final result = createEmptyInstance(); result._fieldSet._shallowCopyValues(_fieldSet); return result; } /// Apply [updates] to a copy of this message. /// /// Makes a writable shallow copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. @Deprecated( 'Using this can add significant size overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version', ) GeneratedMessage copyWith(void Function(GeneratedMessage) updates) { final builder = toBuilder(); updates(builder); return builder.freeze(); } /// Whether the message has required fields. /// /// Note that proto3 doesn't have required fields, only proto2 does. bool hasRequiredFields() => info_.hasRequiredFields; /// Whether all required fields in the message and embedded messages are set. bool isInitialized() => _fieldSet._hasRequiredValues(); /// Clears all data that was set in this message. /// /// After calling [clear], [getField] will still return default values for /// unset fields. void clear() => _fieldSet._clear(); int? getTagNumber(String fieldName) => info_.tagNumber(fieldName); @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is GeneratedMessage && _fieldSet._equals(other._fieldSet); } /// Calculates a hash code based on the contents of the protobuf. /// /// The hash may change when any field changes (recursively). /// Therefore, protobufs used as map keys shouldn't be changed. @override int get hashCode => _fieldSet._hashCode; /// Returns a [String] representation of this message. /// /// This representation is similar to, but not quite, the Protocol Buffer /// TextFormat. Each field is printed on its own line. Sub-messages are /// indented two spaces farther than their parent messages. /// /// Note that this format is absolutely subject to change, and should only /// ever be used for debugging. @override String toString() => toDebugString(); /// Returns a [String] representation of this message. /// /// This generates the same output as [toString], but can be used by mixins /// to compose debug strings with additional information. String toDebugString() { final out = StringBuffer(); _fieldSet.writeString(out, ''); return out.toString(); } /// Throws a [StateError] if the message has required fields without a value. /// /// This library does not check in any of the methods that required fields in /// have values. Use this method if you need to check that required fields /// have values. void check() { if (!isInitialized()) { final invalidFields = []; _fieldSet._appendInvalidFields(invalidFields, ''); final missingFields = (invalidFields..sort()).join(', '); throw StateError('Message missing required fields: $missingFields'); } } /// Serialize the message as the protobuf binary format. /// /// Unknown field data, data for which there is no metadata for the associated /// field, will only be included if this message was deserialized from the /// same wire format. Uint8List writeToBuffer() { final out = CodedBufferWriter(); writeToCodedBufferWriter(out); return out.toBuffer(); } /// Same as [writeToBuffer], but serializes to the given [CodedBufferWriter]. void writeToCodedBufferWriter(CodedBufferWriter output) => _writeToCodedBufferWriter(_fieldSet, output); /// Same as [mergeFromBuffer], but takes a [CodedBufferReader] input. void mergeFromCodedBufferReader( CodedBufferReader input, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { final meta = _fieldSet._meta; _mergeFromCodedBufferReader(meta, _fieldSet, input, extensionRegistry); } /// Merges serialized protocol buffer data into this message. /// /// For each field in [input] that is already present in this message: /// /// * If it's a repeated field, this appends to the end of our list. /// * Else, if it's a scalar, this overwrites our field. /// * Else, (it's a non-repeated sub-message), this recursively merges into /// the existing sub-message. void mergeFromBuffer( List input, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { final codedInput = CodedBufferReader(input); final meta = _fieldSet._meta; _mergeFromCodedBufferReader(meta, _fieldSet, codedInput, extensionRegistry); codedInput.checkLastTagWas(0); } // JSON support. /// Returns the JSON encoding of this message as a Dart [Map]. /// /// The encoding is described in [GeneratedMessage.writeToJson]. /// /// Unknown field data, data for which there is no metadata for the associated /// field, will only be included if this message was deserialized from the /// same wire format. Map writeToJsonMap() => json_lib.writeToJsonMap(_fieldSet); /// Returns a JSON string that encodes this message. /// /// Each message (top level or nested) is represented as an object delimited /// by curly braces. Within a message, elements are indexed by tag number /// (surrounded by quotes). Repeated elements are represented as arrays. /// /// Boolean values, strings, and floating-point values are represented as /// literals. Values with a 32-bit integer datatype are represented as integer /// literals; values with a 64-bit integer datatype (regardless of their /// actual runtime value) are represented as strings. Enumerated values are /// represented as their integer value. /// /// For the proto3 JSON format use: [toProto3Json]. /// /// Unknown field data, data for which there is no metadata for the associated /// field, will only be included if this message was deserialized from the /// same wire format. String writeToJson() => json_lib.writeToJsonString(_fieldSet); /// Returns an Object representing Proto3 JSON serialization of `this`. /// /// The key for each field is be the camel-cased name of the field. /// /// Well-known types and their special JSON encoding are supported. /// If a well-known type cannot be encoded (eg. a `google.protobuf.Timestamp` /// with negative `nanoseconds`) an error is thrown. /// /// Extensions and unknown fields are not encoded. /// /// The [typeRegistry] is be used for encoding `Any` messages. If an `Any` /// message encoding a type not in [typeRegistry] is encountered, an /// error is thrown. /// /// Unknown field data, data for which there is no metadata for the associated /// field, will not be included. Object? toProto3Json({ TypeRegistry typeRegistry = const TypeRegistry.empty(), }) => _writeToProto3Json(_fieldSet, typeRegistry); /// Merges field values from [json], a JSON object using proto3 encoding. /// /// Well-known types and their special JSON encodings are supported. /// /// Throws [FormatException] if [ignoreUnknownFields] is `false` (the /// default) and an unknown field or enum name is encountered. Otherwise the /// unknown field or enum is ignored. /// /// If [supportNamesWithUnderscores] is `true` (the default) field names in /// the JSON can be represented as either camel-case JSON-names or names with /// underscores. Otherwise only the JSON names are supported. /// /// If [permissiveEnums] is `true` (default `false`) enum values in the JSON /// will be matched without case insensitivity and ignoring `-`s and `_`s. /// This allows JSON values like `camelCase` and `kebab-case` to match the /// enum values `CAMEL_CASE` and `KEBAB_CASE`. /// /// In case of ambiguities between the enum values, the first matching value /// will be used. /// /// The [typeRegistry] is used for decoding `Any` messages. /// /// Throws [FormatException] if an `Any` message type is not in /// [typeRegistry]. /// /// Throws [FormatException] if the JSON not formatted correctly (a String /// where a number was expected etc.). void mergeFromProto3Json( Object? json, { TypeRegistry typeRegistry = const TypeRegistry.empty(), bool ignoreUnknownFields = false, bool supportNamesWithUnderscores = true, bool permissiveEnums = false, }) => _mergeFromProto3Json( json, _fieldSet, typeRegistry, ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums, ); /// Merges field values from [data], a JSON object, encoded as described by /// [GeneratedMessage.writeToJson]. /// /// For the proto3 JSON format use: [mergeFromProto3Json]. void mergeFromJson( String data, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { json_lib.mergeFromJsonString(_fieldSet, data, extensionRegistry); } /// Merges field values from a JSON object represented as a Dart map. /// /// The encoding is described in [GeneratedMessage.writeToJson]. void mergeFromJsonMap( Map json, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { json_lib.mergeFromJsonMap(_fieldSet, json, extensionRegistry); } /// Adds an extension field value to a repeated field. /// /// The backing [List] will be created if necessary. /// If the list already exists, the old extension won't be overwritten. void addExtension(Extension extension, Object? value) => _fieldSet.addExtension(extension, value); /// Clears an extension field and also removes the extension. void clearExtension(Extension extension) => _fieldSet.clearExtension(extension); /// Clears the contents of a given field. /// /// If it's an extension field, the Extension will be kept. /// The tagNumber should be a valid tag or extension. void clearField(int tagNumber) => _fieldSet._clearField(tagNumber); /// For generated code only. /// @nodoc int $_whichOneof(int oneofIndex) => _fieldSet._oneofCases![oneofIndex] ?? 0; bool extensionsAreInitialized() => _fieldSet._hasRequiredExtensionValues(); /// Returns the value of [extension]. /// /// If not set, returns the extension's default value. dynamic getExtension(Extension extension) => _fieldSet.getExtension(extension); /// Returns the value of the field associated with [tagNumber], or the /// default value if it is not set. dynamic getField(int tagNumber) => _fieldSet._getField(tagNumber); /// Returns the value of a field, ignoring any defaults. /// /// For unset or cleared fields, returns null. /// Also returns null for unknown tag numbers. dynamic getFieldOrNull(int tagNumber) => _fieldSet._getFieldOrNullByTag(tagNumber); /// Returns the default value for the given field. /// /// For repeated fields, returns an immutable empty list /// (unlike [getField]). For all other fields, returns /// the same thing that getField() would for a cleared field. dynamic getDefaultForField(int tagNumber) => _fieldSet._ensureInfo(tagNumber).readonlyDefault; /// Returns `true` if a value of [extension] is present. bool hasExtension(Extension extension) => _fieldSet.hasExtension(extension); /// Whether this message has a field associated with [tagNumber]. bool hasField(int tagNumber) => _fieldSet._hasField(tagNumber); /// Merges the contents of the [other] into this message. /// /// Singular fields that are set in [other] overwrite the corresponding fields /// in this message. Repeated fields are appended. Singular sub-messages are /// recursively merged. @pragma('dart2js:noInline') void mergeFromMessage(GeneratedMessage other) => _fieldSet._mergeFromMessage(other._fieldSet); void mergeUnknownFields(UnknownFieldSet unknownFieldSet) => _fieldSet ._ensureUnknownFields() .mergeFromUnknownFieldSet(unknownFieldSet); /// Sets the value of a non-repeated extension field to [value]. void setExtension(Extension extension, Object value) => _fieldSet.setExtension(extension, value); /// Sets the value of a field by its [tagNumber]. /// /// Throws an [ArgumentError] if [value] does not match the type associated /// with [tagNumber]. /// /// Throws an [ArgumentError] if [value] is `null`. /// /// To clear a field of it's current value, use [clearField] instead. @pragma('dart2js:noInline') void setField(int tagNumber, Object value) { _fieldSet._setField(tagNumber, value); } /// For generated code only. /// @nodoc T $_get(int index, T defaultValue) => _fieldSet._$get(index, defaultValue); /// For generated code only. /// @nodoc T $_getN(int index) => _fieldSet._$getND(index); /// For generated code only. /// @nodoc T $_ensure(int index) => _fieldSet._$ensure(index); /// For generated code only. /// @nodoc PbList $_getList(int index) => _fieldSet._$getList(index); /// For generated code only. /// @nodoc PbMap $_getMap(int index) => _fieldSet._$getMap(this, index); /// For generated code only. /// @nodoc bool $_getB(int index, bool defaultValue) => _fieldSet._$getB(index, defaultValue); /// For generated code only. /// @nodoc bool $_getBF(int index) => _fieldSet._$getBF(index); /// For generated code only. /// @nodoc int $_getI(int index, int defaultValue) => _fieldSet._$getI(index, defaultValue); /// For generated code only. /// @nodoc int $_getIZ(int index) => _fieldSet._$getIZ(index); /// For generated code only. /// @nodoc String $_getS(int index, String defaultValue) => _fieldSet._$getS(index, defaultValue); /// For generated code only. /// @nodoc String $_getSZ(int index) => _fieldSet._$getSZ(index); /// For generated code only. /// @nodoc Int64 $_getI64(int index) => _fieldSet._$getI64(index); /// For generated code only. /// @nodoc bool $_has(int index) => _fieldSet._$has(index); /// For generated code only. /// @nodoc void $_setBool(int index, bool value) => _fieldSet._$set(index, value); /// For generated code only. /// @nodoc void $_setBytes(int index, List value) => _fieldSet._$set(index, value); /// For generated code only. /// @nodoc void $_setString(int index, String value) => _fieldSet._$set(index, value); /// For generated code only. /// @nodoc void $_setFloat(int index, double value) { if (!_isFloat32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. /// @nodoc void $_setDouble(int index, double value) => _fieldSet._$set(index, value); /// For generated code only. /// @nodoc void $_setSignedInt32(int index, int value) { if (!_isSigned32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. /// @nodoc void $_setUnsignedInt32(int index, int value) { if (!_isUnsigned32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. /// @nodoc void $_setInt64(int index, Int64 value) => _fieldSet._$set(index, value); /// For generated code only. Separate from [setField] to distinguish /// reflective accesses. /// @nodoc void $_setField(int tagNumber, Object value) => _fieldSet._setField(tagNumber, value); /// For generated code only. Separate from [clearField] to distinguish /// reflective accesses. /// @nodoc void $_clearField(int tagNumber) => _fieldSet._clearField(tagNumber); // Support for generating a read-only default singleton instance. static final Map> _defaultMakers = {}; static T Function() _defaultMakerFor( T Function()? createFn, ) => _getSingletonMaker(createFn!)._frozenSingletonCreator; /// For generated code only. /// @nodoc static T $_defaultFor(T Function() createFn) => _getSingletonMaker(createFn)._frozenSingleton; static _SingletonMaker _getSingletonMaker( T Function() fun, ) { final oldMaker = _defaultMakers[fun]; if (oldMaker != null) { // The CFE will insert an implicit downcast to `_SingletonMaker`. We // avoid making that explicit because implicit downcasts are avoided by // dart2js in production code. return oldMaker as dynamic; } return _defaultMakers[fun] = _SingletonMaker(fun); } } // We use a class that creates singletones instead of a closure function. We do // so because the result of the lookup in [_defaultMakers] has to be downcasted. // A downcast to a generic interface type is much easier to perform at runtime // than a downcast to a generic function type. class _SingletonMaker { final T Function() _creator; _SingletonMaker(this._creator); late final T _frozenSingleton = _creator()..freeze(); // ignore: prefer_function_declarations_over_variables late final T Function() _frozenSingletonCreator = () => _frozenSingleton; } /// The package name of a protobuf message. class PackageName { final String name; const PackageName(this.name); String get prefix => name == '' ? '' : '$name.'; } /// Extensions on [GeneratedMessage]s. extension GeneratedMessageGenericExtensions on T { /// Apply [updates] to a copy of this message. /// /// Throws an [ArgumentError] if `this` is not already frozen. /// /// Makes a writable shallow copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. @UseResult( '[GeneratedMessageGenericExtensions.rebuild] ' 'does not update the message, returns a new message', ) T rebuild(void Function(T) updates) { if (!isFrozen) { throw ArgumentError('Rebuilding only works on frozen messages.'); } final t = toBuilder(); updates(t as T); return t..freeze(); } /// Returns a writable deep copy of this message. @UseResult( '[GeneratedMessageGenericExtensions.deepCopy] ' 'does not update the message, returns a new message', ) T deepCopy() { final newMessage = info_.createEmptyInstance!(); newMessage._fieldSet._deepCopyFrom(_fieldSet); return newMessage as T; } } extension GeneratedMessageInternalExtension on GeneratedMessage { FieldSet get fieldSet => _fieldSet; } extension TextFormatExtension on GeneratedMessage { /// Returns a TextFormat [String] representation of this message. /// /// Spec: https://protobuf.dev/reference/protobuf/textformat-spec/ String toTextFormat() { final out = StringBuffer(); writeTextFormat(out); return out.toString(); } /// Writes a TextFormat [String] representation of this message to [sink]. /// /// Spec: https://protobuf.dev/reference/protobuf/textformat-spec/ void writeTextFormat(StringSink sink) { _fieldSet.writeTextFormat(sink); } } ================================================ FILE: protobuf/lib/src/protobuf/generated_service.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Server side context. class ServerContext { // TODO: Place server specific information in this class. } /// The implementation of a Service API. /// /// The protoc plugin generates subclasses (with names ending with ServiceBase) /// that extend GeneratedService and dispatch requests by method. abstract class GeneratedService { /// Creates a message object that can deserialize a request. GeneratedMessage createRequest(String methodName); /// Dispatches the call. The request object should come from [createRequest]. Future handleCall( ServerContext ctx, String methodName, GeneratedMessage request, ); } ================================================ FILE: protobuf/lib/src/protobuf/internal.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Runtime library for Dart implementation of [protobufs][1]. /// /// [1]: https://developers.google.com/protocol-buffers library; import 'dart:convert' show Utf8Decoder, Utf8Encoder, base64Decode, base64Encode; import 'dart:math' as math; import 'dart:typed_data' show ByteData, Endian, Uint8List; import 'package:collection/collection.dart' show DeepCollectionEquality; import 'package:fixnum/fixnum.dart' show Int64; import 'package:meta/meta.dart' show UseResult; import 'consts.dart'; import 'exceptions.dart'; import 'json/json.dart' as json_lib; import 'json_parsing_context.dart'; import 'mixins/well_known.dart'; import 'pb_list.dart'; import 'pb_map.dart'; import 'permissive_compare.dart'; import 'type_registry.dart'; import 'utils.dart'; export 'annotations.dart' show TagNumber, GrpcServiceName; export 'exceptions.dart' show InvalidProtocolBufferException; export 'pb_list.dart' show PbList; export 'pb_map.dart' show PbMap; export 'type_registry.dart' show TypeRegistry; part 'builder_info.dart'; part 'coded_buffer.dart'; part 'coded_buffer_reader.dart'; part 'coded_buffer_writer.dart'; part 'extension.dart'; part 'extension_field_set.dart'; part 'extension_registry.dart'; part 'field_error.dart'; part 'field_info.dart'; part 'field_set.dart'; part 'field_type.dart'; part 'generated_message.dart'; part 'generated_service.dart'; part 'message_set.dart'; part 'proto3_json.dart'; part 'protobuf_enum.dart'; part 'rpc_client.dart'; part 'unknown_field_set.dart'; part 'unpack.dart'; part 'wire_format.dart'; // TODO(sra): Use `Int64.parse()` when available: // https://github.com/dart-lang/fixnum/issues/18. /// @nodoc Int64 parseLongInt(String text) { if (text.startsWith('0x')) return Int64.parseHex(text.substring(2)); if (text.startsWith('+0x')) return Int64.parseHex(text.substring(3)); if (text.startsWith('-0x')) return -Int64.parseHex(text.substring(3)); return Int64.parseInt(text); } ================================================ FILE: protobuf/lib/src/protobuf/json/json.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show base64Decode, base64Encode; import 'package:fixnum/fixnum.dart' show Int64; import '../consts.dart'; import '../internal.dart'; import '../pb_map.dart'; import '../utils.dart'; // Use json_vm.dart with VM and dart2wasm, json_web.dart with dart2js. // json_web.dart uses JS interop for parsing, and JS interop is too slow on // Wasm. VM's patch performs better in Wasm. export 'json_vm.dart' if (dart.library.html) 'json_web.dart'; Map writeToJsonMap(FieldSet fs) { dynamic convertToMap(dynamic fieldValue, int fieldType) { final baseType = PbFieldType.baseType(fieldType); if (PbFieldType.isRepeated(fieldType)) { final PbList list = fieldValue; return List.from(list.map((e) => convertToMap(e, baseType))); } switch (baseType) { case PbFieldType.BOOL_BIT: case PbFieldType.STRING_BIT: case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: return fieldValue; case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: final value = fieldValue as double; if (value.isNaN) { return nan; } if (value.isInfinite) { return value.isNegative ? negativeInfinity : infinity; } if (fieldValue.toInt() == fieldValue) { return fieldValue.toInt(); } return value; case PbFieldType.BYTES_BIT: // Encode 'bytes' as a base64-encoded string. return base64Encode(fieldValue as List); case PbFieldType.ENUM_BIT: final ProtobufEnum enum_ = fieldValue; return enum_.value; // assume |value| < 2^52 case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: return fieldValue.toString(); case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: final Int64 int_ = fieldValue; return int_.toStringUnsigned(); case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: final GeneratedMessage msg = fieldValue; return msg.writeToJsonMap(); default: throw UnsupportedError('Unknown type $fieldType'); } } List writeMap(PbMap fieldValue, MapFieldInfo fi) => List.from( fieldValue.entries.map( (MapEntry e) => { '$mapKeyFieldNumber': convertToMap(e.key, fi.keyFieldType), '$mapValueFieldNumber': convertToMap(e.value, fi.valueFieldType), }, ), ); final result = {}; for (final fi in fs.infosSortedByTag) { final value = fs.values[fi.index!]; if (value == null || (value is List && value.isEmpty)) { continue; // It's missing, repeated, or an empty byte array. } if (PbFieldType.isMapField(fi.type)) { result['${fi.tagNumber}'] = writeMap( value, fi as MapFieldInfo, ); continue; } result['${fi.tagNumber}'] = convertToMap(value, fi.type); } final extensions = fs.extensions; if (extensions != null) { for (final tagNumber in sorted(extensions.tagNumbers)) { final value = extensions.values[tagNumber]; if (value is List && value.isEmpty) { continue; // It's repeated or an empty byte array. } final fi = extensions.getInfoOrNull(tagNumber)!; result['$tagNumber'] = convertToMap(value, fi.type); } } final unknownJsonData = fs.unknownJsonData; if (unknownJsonData != null) { unknownJsonData.forEach((key, value) { result[key] = value; }); } return result; } // Merge fields from a previously decoded JSON object. // (Called recursively on nested messages.) void mergeFromJsonMap( FieldSet fs, Map json, ExtensionRegistry? registry, ) { fs.ensureWritable(); final keys = json.keys; final meta = fs.meta; for (final key in keys) { var fi = meta.byTagAsString[key]; if (fi == null) { fi = registry?.getExtension(fs.messageName, int.parse(key)); if (fi == null) { (fs.unknownJsonData ??= {})[key] = json[key]; continue; } } if (fi.isMapField) { _appendJsonMap( meta, fs, json[key], fi as MapFieldInfo, registry, ); } else if (fi.isRepeated) { _appendJsonList(meta, fs, json[key], fi, registry); } else { _setJsonField(meta, fs, json[key], fi, registry); } } } void _appendJsonList( BuilderInfo meta, FieldSet fs, List jsonList, FieldInfo fi, ExtensionRegistry? registry, ) { final repeated = fi.ensureRepeatedField(meta, fs); // Micro optimization. Using "for in" generates the following and iterator // alloc: // for (t1 = J.get$iterator$ax(json), t2 = fi.tagNumber, t3 = fi.type, // t4 = J.getInterceptor$ax(repeated); t1.moveNext$0();) for (var i = 0, len = jsonList.length; i < len; i++) { final value = jsonList[i]; var convertedValue = _convertJsonValue( meta, fs, value, fi.tagNumber, fi.type, registry, ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. convertedValue ??= fi.defaultEnumValue; repeated.add(convertedValue); } } void _appendJsonMap( BuilderInfo meta, FieldSet fs, List jsonList, MapFieldInfo fi, ExtensionRegistry? registry, ) { final entryMeta = fi.mapEntryBuilderInfo; final map = fi.ensureMapField(meta, fs); for (final jsonEntryDynamic in jsonList) { final jsonEntry = jsonEntryDynamic as Map; final entryFieldSet = FieldSet(null, entryMeta); final convertedKey = _convertJsonValue( entryMeta, entryFieldSet, jsonEntry['$mapKeyFieldNumber'], mapKeyFieldNumber, fi.keyFieldType, registry, ); var convertedValue = _convertJsonValue( entryMeta, entryFieldSet, jsonEntry['$mapValueFieldNumber'], mapValueFieldNumber, fi.valueFieldType, registry, ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. convertedValue ??= fi.defaultEnumValue; map[convertedKey] = convertedValue; } } void _setJsonField( BuilderInfo meta, FieldSet fs, json, FieldInfo fi, ExtensionRegistry? registry, ) { final value = _convertJsonValue( meta, fs, json, fi.tagNumber, fi.type, registry, ); if (value == null) return; // _convertJsonValue throws exception when it fails to do conversion. // Therefore we run _validateField for debug builds only to validate // correctness of conversion. assert(() { fs.validateField(fi, value); return true; }()); fs.setFieldUnchecked(meta, fi, value); } /// Converts [value] from the JSON format to the Dart data type suitable for /// inserting into the corresponding [GeneratedMessage] field. /// /// Returns the converted value. Returns `null` if it is an unknown enum value, /// in which case the caller should figure out the default enum value to return /// instead. /// /// Throws [ArgumentError] if it cannot convert the value. dynamic _convertJsonValue( BuilderInfo meta, FieldSet fs, value, int tagNumber, int fieldType, ExtensionRegistry? registry, ) { String expectedType; // for exception message switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: if (value is bool) { return value; } else if (value is String) { if (value == 'true') { return true; } else if (value == 'false') { return false; } } else if (value is num) { if (value == 1) { return true; } else if (value == 0) { return false; } } expectedType = 'bool (true, false, "true", "false", 1, 0)'; case PbFieldType.BYTES_BIT: if (value is String) { return base64Decode(value); } expectedType = 'Base64 String'; case PbFieldType.STRING_BIT: if (value is String) { return value; } expectedType = 'String'; case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: // Allow quoted values, although we don't emit them. if (value is double) { return value; } else if (value is num) { return value.toDouble(); } else if (value is String) { return double.parse(value); } expectedType = 'num or stringified num'; case PbFieldType.ENUM_BIT: // Allow quoted values, although we don't emit them. if (value is String) { value = int.parse(value); } if (value is int) { // The following call will return null if the enum value is unknown. // In that case, we want the caller to ignore this value, so we return // null from this method as well. return meta.decodeEnum(tagNumber, registry, value); } expectedType = 'int or stringified int'; case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SFIXED32_BIT: if (value is int) return value; if (value is String) return int.parse(value); expectedType = 'int or stringified int'; case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: int? validatedValue; if (value is int) validatedValue = value; if (value is String) validatedValue = int.parse(value); if (validatedValue != null && validatedValue < 0) { validatedValue += 2 * (1 << 31); } if (validatedValue != null) return validatedValue; expectedType = 'int or stringified int'; case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: case PbFieldType.SFIXED64_BIT: if (value is int) return Int64(value); if (value is String) return Int64.parseInt(value); expectedType = 'int or stringified int'; case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: if (value is Map) { final messageValue = value as Map; final subMessage = meta.makeEmptyMessage(tagNumber, registry); mergeFromJsonMap(subMessage.fieldSet, messageValue, registry); return subMessage; } expectedType = 'nested message or group'; default: throw ArgumentError('Unknown type $fieldType'); } throw ArgumentError('Expected type $expectedType, got $value'); } ================================================ FILE: protobuf/lib/src/protobuf/json/json_vm.dart ================================================ // Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show jsonDecode, jsonEncode; import '../internal.dart'; import 'json.dart'; String writeToJsonString(FieldSet fs) => jsonEncode(writeToJsonMap(fs)); /// Merge fields from a [json] string. void mergeFromJsonString( FieldSet fs, String json, ExtensionRegistry? registry, ) { final jsonMap = jsonDecode(json); if (jsonMap is! Map) { throw ArgumentError.value(json, 'json', 'Does not parse to a JSON object.'); } mergeFromJsonMap(fs, jsonMap, registry); } ================================================ FILE: protobuf/lib/src/protobuf/json/json_web.dart ================================================ // Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert' show base64Decode, base64Encode; import 'dart:js_interop'; import 'dart:js_interop_unsafe'; import 'package:fixnum/fixnum.dart' show Int64; import '../consts.dart'; import '../internal.dart'; import '../pb_map.dart'; import '../utils.dart'; @JS('JSON') extension type _JSON._(JSObject _) implements JSObject { @JS('stringify') external static JSString _stringify(JSObject value); @JS('parse') external static JSAny? _parse(JSString text); } @JS('Number') extension type _Number._(JSObject _) implements JSObject { @JS('isInteger') external static bool _isInteger(JSAny value); } @JS('Object.keys') external JSArray _objectKeys(JSObject obj); @JS('Object.prototype') external JSObject get _objectPrototype; @JS('Object.getPrototypeOf') external JSObject _getPrototypeOf(JSAny obj); extension on JSAny { /// Returns this typed as [T] while omitting the `as` cast. For use after an /// `isA` check. @pragma('dart2js:as:trust') @pragma('dart2js:prefer-inline') T _as() => this as T; } String writeToJsonString(FieldSet fs) { final rawJs = _writeToRawJs(fs); return _JSON._stringify(rawJs).toDart; } JSObject _writeToRawJs(FieldSet fs) { JSAny convertToRawJs(dynamic fieldValue, int fieldType) { final baseType = PbFieldType.baseType(fieldType); if (PbFieldType.isRepeated(fieldType)) { final PbList list = fieldValue; final length = list.length; final jsArray = JSArray.withLength(length); for (var i = 0; i < length; i++) { final entry = list[i]; jsArray[i] = convertToRawJs(entry, baseType); } return jsArray; } switch (baseType) { case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: final int value = fieldValue; return value.toJS; case PbFieldType.BOOL_BIT: final bool value = fieldValue; return value.toJS; case PbFieldType.STRING_BIT: final String value = fieldValue; return value.toJS; case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: final double value = fieldValue; if (value.isNaN) { return nan.toJS; } if (value.isInfinite) { return value.isNegative ? negativeInfinity.toJS : infinity.toJS; } if (value.toInt() == value) { return value.toInt().toJS; } return value.toJS; case PbFieldType.BYTES_BIT: // Encode 'bytes' as a base64-encoded string. final List value = fieldValue; return base64Encode(value).toJS; case PbFieldType.ENUM_BIT: final ProtobufEnum enum_ = fieldValue; return enum_.value.toJS; // assume |value| < 2^52 case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: final Int64 int_ = fieldValue; return int_.toString().toJS; case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: final Int64 int_ = fieldValue; return int_.toStringUnsigned().toJS; case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: final GeneratedMessage msg = fieldValue; return _writeToRawJs(msg.fieldSet); default: throw UnsupportedError('Unknown type $fieldType'); } } JSArray writeMap(PbMap fieldValue, MapFieldInfo fi) { final length = fieldValue.entries.length; final jsArray = JSArray.withLength(length); var index = 0; for (final entry in fieldValue.entries) { final entryJsObj = JSObject(); entryJsObj.setProperty( mapKeyFieldNumber.toJS, convertToRawJs(entry.key, fi.keyFieldType), ); entryJsObj.setProperty( mapValueFieldNumber.toJS, convertToRawJs(entry.value, fi.valueFieldType), ); jsArray[index] = entryJsObj; index++; } return jsArray; } final result = JSObject(); for (final fi in fs.infosSortedByTag) { final value = fs.values[fi.index!]; if (value == null || (value is List && value.isEmpty)) { continue; // It's missing, repeated, or an empty byte array. } if (PbFieldType.isMapField(fi.type)) { result.setProperty( fi.tagNumber.toJS, writeMap(value, fi as MapFieldInfo), ); continue; } result.setProperty(fi.tagNumber.toJS, convertToRawJs(value, fi.type)); } final extensions = fs.extensions; if (extensions != null) { for (final tagNumber in sorted(extensions.tagNumbers)) { final value = extensions.values[tagNumber]; if (value is List && value.isEmpty) { continue; // It's repeated or an empty byte array. } final fi = extensions.getInfoOrNull(tagNumber)!; result.setProperty(tagNumber.toJS, convertToRawJs(value, fi.type)); } } final unknownJsonData = fs.unknownJsonData; if (unknownJsonData != null) { unknownJsonData.forEach((String key, Object? value) { result.setProperty(key.toJS, value.jsify()); }); } return result; } /// Merge fields from a [json] string. void mergeFromJsonString( FieldSet fs, String json, ExtensionRegistry? registry, ) { final JSAny? parsed; try { parsed = _JSON._parse(json.toJS); } catch (e) { throw FormatException(e.toString()); } if (parsed == null || !parsed.isA()) { throw ArgumentError.value(json, 'json', 'Does not parse to a JSON object.'); } _mergeFromRawJsMap(fs, parsed._as(), registry); } void _mergeFromRawJsMap( FieldSet fs, JSObject json, ExtensionRegistry? registry, ) { fs.ensureWritable(); final meta = fs.meta; final keys = _objectKeys(json); final length = keys.length; for (var i = 0; i < length; i++) { final jsKey = keys[i]; final key = jsKey.toDart; var fi = meta.byTagAsString[key]; if (fi == null) { fi = registry?.getExtension(fs.messageName, int.parse(key)); if (fi == null) { (fs.unknownJsonData ??= {})[key] = json.getProperty(jsKey).dartify(); continue; } } if (fi.isMapField) { _appendRawJsMap( meta, fs, json.getProperty>(jsKey), fi as MapFieldInfo, registry, ); } else if (fi.isRepeated) { _appendRawJsList( meta, fs, json.getProperty>(jsKey), fi, registry, ); } else { _setRawJsField(meta, fs, json.getProperty(jsKey), fi, registry); } } } void _appendRawJsList( BuilderInfo meta, FieldSet fs, JSArray jsonList, FieldInfo fi, ExtensionRegistry? registry, ) { final repeated = fi.ensureRepeatedField(meta, fs); // Micro optimization. Using "for in" generates the following and iterator // alloc: // for (t1 = J.get$iterator$ax(json), t2 = fi.tagNumber, t3 = fi.type, // t4 = J.getInterceptor$ax(repeated); t1.moveNext$0();) final length = jsonList.length; for (var i = 0; i < length; i++) { final value = jsonList[i]; var convertedValue = _convertRawJsValue( meta, fs, value, fi.tagNumber, fi.type, registry, ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. convertedValue ??= fi.defaultEnumValue; repeated.add(convertedValue); } } void _appendRawJsMap( BuilderInfo meta, FieldSet fs, JSArray jsonList, MapFieldInfo fi, ExtensionRegistry? registry, ) { final entryMeta = fi.mapEntryBuilderInfo; final map = fi.ensureMapField(meta, fs); final length = jsonList.length; for (var i = 0; i < length; i++) { final value = jsonList[i]; final entryFieldSet = FieldSet(null, entryMeta); final convertedKey = _convertRawJsValue( entryMeta, entryFieldSet, value.getProperty(mapKeyFieldNumber.toJS), mapKeyFieldNumber, fi.keyFieldType, registry, ); var convertedValue = _convertRawJsValue( entryMeta, entryFieldSet, value.getProperty(mapValueFieldNumber.toJS), mapValueFieldNumber, fi.valueFieldType, registry, ); // In the case of an unknown enum value, the converted value may return // null. The default enum value should be used in these cases, which is // stored in the FieldInfo. convertedValue ??= fi.defaultEnumValue; map[convertedKey] = convertedValue; } } void _setRawJsField( BuilderInfo meta, FieldSet fs, JSAny json, FieldInfo fi, ExtensionRegistry? registry, ) { final value = _convertRawJsValue( meta, fs, json, fi.tagNumber, fi.type, registry, ); if (value == null) return; // _convertRawJsValue throws exception when it fails to do conversion. // Therefore we run _validateField for debug builds only to validate // correctness of conversion. assert(() { fs.validateField(fi, value); return true; }()); fs.setFieldUnchecked(meta, fi, value); } /// Converts [value] from the JSON format to the Dart data type suitable for /// inserting into the corresponding [GeneratedMessage] field. /// /// Returns the converted value. Returns `null` if it is an unknown enum value, /// in which case the caller should figure out the default enum value to return /// instead. /// /// Throws [ArgumentError] if it cannot convert the value. Object? _convertRawJsValue( BuilderInfo meta, FieldSet fs, JSAny value, int tagNumber, int fieldType, ExtensionRegistry? registry, ) { String expectedType; // for exception message switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: if (value.isA()) { return value._as().toDart; } else if (value.isA()) { final dartStr = value._as().toDart; if (dartStr == 'true') { return true; } else if (dartStr == 'false') { return false; } } else if (value.isA()) { final dartNum = value._as().toDartDouble; if (dartNum == 1) { return true; } else if (dartNum == 0) { return false; } } expectedType = 'bool (true, false, "true", "false", 1, 0)'; case PbFieldType.BYTES_BIT: if (value.isA()) { return base64Decode(value._as().toDart); } expectedType = 'Base64 String'; case PbFieldType.STRING_BIT: if (value.isA()) { return value._as().toDart; } expectedType = 'String'; case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: // Allow quoted values, although we don't emit them. if (value.isA()) { final jsNum = value._as(); return jsNum.toDartDouble; } else if (value.isA()) { return double.parse(value._as().toDart); } expectedType = 'num or stringified num'; case PbFieldType.ENUM_BIT: // Allow quoted values, although we don't emit them. if (value.isA()) { value = int.parse(value._as().toDart).toJS; } if (_Number._isInteger(value)) { // The following call will return null if the enum value is unknown. // In that case, we want the caller to ignore this value, so we return // null from this method as well. return meta.decodeEnum( tagNumber, registry, value._as().toDartInt, ); } expectedType = 'int or stringified int'; case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SFIXED32_BIT: if (_Number._isInteger(value)) { return value._as().toDartInt; } if (value.isA()) { return int.parse(value._as().toDart); } expectedType = 'int or stringified int'; case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: int? validatedValue; if (_Number._isInteger(value)) { validatedValue = value._as().toDartInt; } if (value.isA()) { validatedValue = int.parse(value._as().toDart); } if (validatedValue != null && validatedValue < 0) { validatedValue += 2 * (1 << 31); } if (validatedValue != null) return validatedValue; expectedType = 'int or stringified int'; case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.UINT64_BIT: case PbFieldType.FIXED64_BIT: case PbFieldType.SFIXED64_BIT: if (_Number._isInteger(value)) { return Int64(value._as().toDartInt); } if (value.isA()) { return Int64.parseInt(value._as().toDart); } expectedType = 'int or stringified int'; case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: if (_getPrototypeOf(value).strictEquals(_objectPrototype).toDart) { final subMessage = meta.makeEmptyMessage(tagNumber, registry); _mergeFromRawJsMap( subMessage.fieldSet, value._as(), registry, ); return subMessage; } expectedType = 'nested message or group'; default: throw ArgumentError( 'Unknown type $fieldType when decoding a ' '${meta.qualifiedMessageName} message field with tag $tagNumber.', ); } throw ArgumentError( 'Expected type $expectedType, got $value when decoding a ' '${meta.qualifiedMessageName} message field with tag $tagNumber.', ); } ================================================ FILE: protobuf/lib/src/protobuf/json_parsing_context.dart ================================================ // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. class JsonParsingContext { // A list of indices into maps and lists pointing to the current root. final List _path = []; final bool ignoreUnknownFields; final bool supportNamesWithUnderscores; final bool permissiveEnums; JsonParsingContext( this.ignoreUnknownFields, this.supportNamesWithUnderscores, this.permissiveEnums, ); void addMapIndex(String index) { _path.add(index); } void addListIndex(int index) { _path.add(index.toString()); } void popIndex() { _path.removeLast(); } /// Creates a [FormatException] indicating the indices to the current path. Exception parseException(String message, Object? source) { final formattedPath = _path.map((s) => '["$s"]').join(); return FormatException( 'Protobuf JSON decoding failed at: root$formattedPath. $message', source, ); } } ================================================ FILE: protobuf/lib/src/protobuf/message_set.dart ================================================ // Copyright (c) 2023, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; const _messageSetItemsTag = 1; const _messageSetItemTypeIdTag = 2; const _messageSetItemMessageTag = 3; /// Overrides binary serialization and deserialization methods to implement the /// message set binary format. /// /// Message set format is very old and only used in Google. When a message has /// this option: /// /// ``` /// option message_set_wire_format = true; /// ``` /// /// The plugin extends the generated message class with this class instead of /// [GeneratedMessage]. /// /// @nodoc abstract class $_MessageSet extends GeneratedMessage { @override void writeToCodedBufferWriter(CodedBufferWriter output) { final extensions = _fieldSet._ensureExtensions(); for (final ext in extensions._values.entries) { final typeId = ext.key; final message = ext.value as GeneratedMessage; output._writeTag(_messageSetItemsTag, WIRETYPE_START_GROUP); output._writeTag(_messageSetItemTypeIdTag, WIRETYPE_VARINT); output._writeVarint32(typeId); output._writeTag(_messageSetItemMessageTag, WIRETYPE_LENGTH_DELIMITED); final mark = output._startLengthDelimited(); message.writeToCodedBufferWriter(output); output._endLengthDelimited(mark); output._writeTag(_messageSetItemsTag, WIRETYPE_END_GROUP); } final unknownFields = _fieldSet._unknownFields; if (unknownFields != null) { unknownFields.writeToCodedBufferWriter(output); } } @override void mergeFromCodedBufferReader( CodedBufferReader input, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { // Parse items. The field for the items looks like: // // repeated group Item items = 1; // // Since message sets are compatible with proto1 items can't be packed. while (true) { final tag = input.readTag(); final tagNumber = getTagFieldNumber(tag); if (tag == 0) { break; // End of input. } if (tagNumber != _messageSetItemsTag) { if (!input.skipField(tag)) { break; // End of group. } else { continue; } } // Parse an item. An item is a message with two fields: // // message Item { // int32 type_id = 2; // Message message = 3; // } // // We can see the fields in any order, so loop until parsing both fields. int? typeId; Uint8List? message; while (true) { final tag = input.readTag(); final tagNumber = getTagFieldNumber(tag); if (tag == 0) { break; // End of input. } if (tagNumber == _messageSetItemTypeIdTag) { typeId = input.readInt32(); if (message != null) { _parseExtension(typeId, message, extensionRegistry); typeId = null; message = null; } } else if (tagNumber == _messageSetItemMessageTag) { message = input.readBytesAsView(); if (typeId != null) { _parseExtension(typeId, message, extensionRegistry); typeId = null; message = null; } } else { // Skip unknown tags. If we're at the end of the group consume the // EGROUP tag. if (!input.skipField(tag)) { break; // End of group. } } } } } @override void mergeFromBuffer( List input, [ ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, ]) { mergeFromCodedBufferReader(CodedBufferReader(input), extensionRegistry); } void _parseExtension( int typeId, Uint8List message, ExtensionRegistry extensionRegistry, ) { final ext = extensionRegistry.getExtension( info_.qualifiedMessageName, typeId, ); if (ext == null) { final messageItem = UnknownFieldSet(); messageItem.addField( _messageSetItemTypeIdTag, UnknownFieldSetField()..varints.add(Int64(typeId)), ); messageItem.addField( _messageSetItemMessageTag, UnknownFieldSetField() ..lengthDelimited.add(Uint8List.fromList(message)), ); final itemListField = _fieldSet._ensureUnknownFields().getField(_messageSetItemsTag) ?? UnknownFieldSetField(); itemListField.addGroup(messageItem); _fieldSet._ensureUnknownFields().addField( _messageSetItemsTag, itemListField, ); } else { setExtension(ext, ext.subBuilder!()..mergeFromBuffer(message)); } } } ================================================ FILE: protobuf/lib/src/protobuf/mixins/map_mixin.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../../../protobuf.dart' show BuilderInfo; /// Note that this class does not claim to implement [Map]. Instead, this needs /// to be specified using a dart_options.imports clause specifying MapMixin as a /// parent mixin to PbMapMixin. /// /// Since PbMapMixin is built in, this is done automatically, so this mixin can /// be enabled by specifying only a dart_options.mixin option. mixin PbMapMixin { // GeneratedMessage properties and methods used by this mixin. BuilderInfo get info_; void clear(); int? getTagNumber(String fieldName); dynamic getField(int tagNumber); void setField(int tagNumber, Object value); dynamic operator [](Object? key) { if (key is! String) return null; final tag = getTagNumber(key); if (tag == null) return null; return getField(tag); } void operator []=(Object? key, Object? val) { final tag = getTagNumber(key as String); if (tag == null) { throw ArgumentError.value( key, 'key', "field '$key' not found in ${info_.qualifiedMessageName}", ); } setField(tag, val!); } Iterable get keys => info_.byName.keys; bool containsKey(Object? key) => info_.byName.containsKey(key); int get length => info_.byName.length; dynamic remove(Object? key) { throw UnsupportedError( 'remove() not supported by ${info_.qualifiedMessageName}', ); } } ================================================ FILE: protobuf/lib/src/protobuf/mixins/well_known.dart ================================================ // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:fixnum/fixnum.dart'; import '../internal.dart'; import '../json_parsing_context.dart'; /// The set of well known protobuf message types which may have customized /// serialization logic. enum WellKnownType { any, timestamp, duration, struct, value, listValue, fieldMask, doubleValue, floatValue, int64Value, uint64Value, int32Value, uint32Value, boolValue, stringValue, bytesValue, } mixin AnyMixin implements GeneratedMessage { String get typeUrl; set typeUrl(String value); List get value; set value(List value); /// Returns `true` if the encoded message matches the type of [instance]. /// /// Can be used with a default instance: /// `any.canUnpackInto(Message.getDefault())` bool canUnpackInto(GeneratedMessage instance) { return canUnpackIntoHelper(instance, typeUrl); } /// Unpacks the message in [value] into [instance]. /// /// Throws a [InvalidProtocolBufferException] if [typeUrl] does not correspond /// to the type of [instance]. /// /// A typical usage would be `any.unpackInto(Message())`. /// /// Returns [instance]. T unpackInto( T instance, { ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, }) { unpackIntoHelper( value, instance, typeUrl, extensionRegistry: extensionRegistry, ); return instance; } /// Updates [target] to be the packed representation of [message]. /// /// The [typeUrl] will be [typeUrlPrefix]/`fullName` where `fullName` is /// the fully qualified name of the type of [message]. static void packIntoAny( AnyMixin target, GeneratedMessage message, { String typeUrlPrefix = 'type.googleapis.com', }) { target.value = message.writeToBuffer(); target.typeUrl = '$typeUrlPrefix/${message.info_.qualifiedMessageName}'; } // From google/protobuf/any.proto: // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": , // "lastName": // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final any = message as AnyMixin; final info = typeRegistry.lookup(_typeNameFromUrl(any.typeUrl)); if (info == null) { throw ArgumentError( 'The type of the Any message (${any.typeUrl}) is not in the given typeRegistry.', ); } final unpacked = info.createEmptyInstance!()..mergeFromBuffer(any.value); return writeToProto3JsonAny(unpacked.fieldSet, any.typeUrl, typeRegistry); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is! Map) { throw context.parseException( 'Expected Any message encoded as {@type,...},', json, ); } final object = json; final typeUrl = object['@type']; if (typeUrl is String) { final any = message as AnyMixin; final info = typeRegistry.lookup(_typeNameFromUrl(typeUrl)); if (info == null) { throw context.parseException( 'Decoding Any of type $typeUrl not in TypeRegistry $typeRegistry', json, ); } final packedMessage = info.createEmptyInstance!(); mergeFromProto3JsonAny( json, packedMessage.fieldSet, typeRegistry, context, ); any.value = packedMessage.writeToBuffer(); any.typeUrl = typeUrl; } else { throw context.parseException('Expected a string', json); } } } String _typeNameFromUrl(String typeUrl) { final index = typeUrl.lastIndexOf('/'); return index < 0 ? '' : typeUrl.substring(index + 1); } mixin TimestampMixin { static final RegExp finalGroupsOfThreeZeroes = RegExp(r'(?:000)*$'); Int64 get seconds; set seconds(Int64 value); int get nanos; set nanos(int value); /// Converts an instance to [DateTime]. /// /// The result is in UTC time zone and has microsecond precision, as /// [DateTime] does not support nanosecond precision. /// /// Use [toLocal] to convert to local time zone, instead of the default UTC. DateTime toDateTime({bool toLocal = false}) => DateTime.fromMicrosecondsSinceEpoch( seconds.toInt() * Duration.microsecondsPerSecond + nanos ~/ 1000, isUtc: !toLocal, ); /// Updates [target] to be the time at [dateTime]. /// /// Time zone information will not be preserved. static void setFromDateTime(TimestampMixin target, DateTime dateTime) { final micros = dateTime.microsecondsSinceEpoch; target.seconds = Int64((micros / Duration.microsecondsPerSecond).floor()); target.nanos = (micros % Duration.microsecondsPerSecond).toInt() * 1000; } static String _twoDigits(int n) { if (n >= 10) return '$n'; return '0$n'; } static final DateTime _minTimestamp = DateTime.utc(1); static final DateTime _maxTimestamp = DateTime.utc(9999, 13, 31, 23, 59, 59); // From google/protobuf/timestamp.proto: // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A proto3 JSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a proto3 JSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final timestamp = message as TimestampMixin; final dateTime = timestamp.toDateTime(); if (timestamp.nanos < 0) { throw ArgumentError( 'Timestamp with negative `nanos`: ${timestamp.nanos}', ); } if (timestamp.nanos > 999999999) { throw ArgumentError( 'Timestamp with `nanos` out of range: ${timestamp.nanos}', ); } if (dateTime.isBefore(_minTimestamp) || dateTime.isAfter(_maxTimestamp)) { throw ArgumentError( 'Timestamp Must be from 0001-01-01T00:00:00Z to ' '9999-12-31T23:59:59Z inclusive. Was: ${dateTime.toIso8601String()}', ); } // Because [DateTime] doesn't have nano-second precision, we cannot use // dateTime.toIso8601String(). final y = '${dateTime.year}'.padLeft(4, '0'); final m = _twoDigits(dateTime.month); final d = _twoDigits(dateTime.day); final h = _twoDigits(dateTime.hour); final min = _twoDigits(dateTime.minute); final sec = _twoDigits(dateTime.second); var secFrac = ''; if (timestamp.nanos > 0) { secFrac = '.${timestamp.nanos.toString().padLeft(9, '0').replaceFirst(finalGroupsOfThreeZeroes, '')}'; } return '$y-$m-${d}T$h:$min:$sec${secFrac}Z'; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is String) { var jsonWithoutFracSec = json; var nanos = 0; final Match? fracSecsMatch = RegExp(r'\.(\d+)').firstMatch(json); if (fracSecsMatch != null) { final fracSecs = fracSecsMatch[1]!; if (fracSecs.length > 9) { throw context.parseException( 'Timestamp can have at most than 9 decimal digits', json, ); } nanos = int.parse(fracSecs.padRight(9, '0')); jsonWithoutFracSec = json.replaceRange( fracSecsMatch.start, fracSecsMatch.end, '', ); } final dateTimeWithoutFractionalSeconds = DateTime.tryParse(jsonWithoutFracSec) ?? (throw context.parseException( 'Timestamp not well formatted. ', json, )); final timestamp = message as TimestampMixin; setFromDateTime(timestamp, dateTimeWithoutFractionalSeconds); timestamp.nanos = nanos; } else { throw context.parseException( 'Expected timestamp represented as String', json, ); } } } mixin DurationMixin { Int64 get seconds; set seconds(Int64 value); int get nanos; set nanos(int value); static final RegExp finalZeroes = RegExp(r'0+$'); static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final duration = message as DurationMixin; final secFrac = duration.nanos // nanos and seconds should always have the same sign. .abs() .toString() .padLeft(9, '0') .replaceFirst(finalZeroes, ''); final secPart = secFrac == '' ? '' : '.$secFrac'; return '${duration.seconds}${secPart}s'; } static final RegExp durationPattern = RegExp(r'(-?\d*)(?:\.(\d*))?s$'); static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { final duration = message as DurationMixin; if (json is String) { final match = durationPattern.matchAsPrefix(json); if (match == null) { throw context.parseException( 'Expected a String of the form `.s`', json, ); } else { final secondsString = match[1]!; final seconds = secondsString == '' ? Int64.ZERO : Int64.parseInt(secondsString); duration.seconds = seconds; final nanos = int.parse((match[2] ?? '').padRight(9, '0')); duration.nanos = seconds < 0 ? -nanos : nanos; } } else { throw context.parseException( 'Expected a String of the form `.s`', json, ); } } } mixin StructMixin implements GeneratedMessage { Map get fields; static const _fieldsFieldTagNumber = 1; // From google/protobuf/struct.proto: // The JSON representation for `Struct` is JSON object. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final struct = message as StructMixin; return struct.fields.map( (key, value) => MapEntry(key, ValueMixin.toProto3JsonHelper(value, typeRegistry)), ); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is Map) { // Check for emptiness to avoid setting `.fields` if there are no // values. if (json.isNotEmpty) { final fields = (message as StructMixin).fields; final valueCreator = (message.info_.fieldInfo[_fieldsFieldTagNumber] as MapFieldInfo) .valueCreator!; json.forEach((key, value) { if (key is! String) { throw context.parseException('Expected String key', json); } final v = valueCreator() as ValueMixin; context.addMapIndex(key); ValueMixin.fromProto3JsonHelper(v, value, typeRegistry, context); context.popIndex(); fields[key] = v; }); } } else { throw context.parseException( 'Expected a JSON object literal (map)', json, ); } } } mixin ValueMixin implements GeneratedMessage { bool hasNullValue(); ProtobufEnum get nullValue; set nullValue(covariant ProtobufEnum value); bool hasNumberValue(); double get numberValue; set numberValue(double v); bool hasStringValue(); String get stringValue; set stringValue(String v); bool hasBoolValue(); bool get boolValue; set boolValue(bool v); bool hasStructValue(); StructMixin get structValue; set structValue(covariant StructMixin v); bool hasListValue(); ListValueMixin get listValue; set listValue(covariant ListValueMixin v); // From google/protobuf/struct.proto: // The JSON representation for `Value` is JSON value static Object? toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final value = message as ValueMixin; // This would ideally be a switch, but we cannot import the enum we are // switching over. if (value.hasNullValue()) { return null; } else if (value.hasNumberValue()) { return value.numberValue; } else if (value.hasStringValue()) { return value.stringValue; } else if (value.hasBoolValue()) { return value.boolValue; } else if (value.hasStructValue()) { return StructMixin.toProto3JsonHelper(value.structValue, typeRegistry); } else if (value.hasListValue()) { return ListValueMixin.toProto3JsonHelper(value.listValue, typeRegistry); } else { throw ArgumentError('Serializing google.protobuf.Value with no value'); } } static void fromProto3JsonHelper( GeneratedMessage message, Object? json, TypeRegistry typeRegistry, JsonParsingContext context, ) { final value = message as ValueMixin; if (json == null) { // Rely on the getter retrieving the default to provide an instance. value.nullValue = value.nullValue; } else if (json is num) { value.numberValue = json.toDouble(); } else if (json is String) { value.stringValue = json; } else if (json is bool) { value.boolValue = json; } else if (json is Map) { // Clone because the default instance is frozen. final structValue = value.structValue.deepCopy(); StructMixin.fromProto3JsonHelper( structValue, json, typeRegistry, context, ); value.structValue = structValue; } else if (json is List) { // Clone because the default instance is frozen. final listValue = value.listValue.deepCopy(); ListValueMixin.fromProto3JsonHelper( listValue, json, typeRegistry, context, ); value.listValue = listValue; } else { throw context.parseException( 'Expected a json-value (Map, List, String, number, bool or null)', json, ); } } } mixin ListValueMixin implements GeneratedMessage { List get values; // From google/protobuf/struct.proto: // The JSON representation for `ListValue` is JSON array. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final list = message as ListValueMixin; return list.values .map((value) => ValueMixin.toProto3JsonHelper(value, typeRegistry)) .toList(); } static const _valueFieldTagNumber = 1; static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { final list = message as ListValueMixin; if (json is List) { final subBuilder = message.info_.subBuilder(_valueFieldTagNumber)!; for (var i = 0; i < json.length; i++) { final Object? element = json[i]; final v = subBuilder() as ValueMixin; context.addListIndex(i); ValueMixin.fromProto3JsonHelper(v, element, typeRegistry, context); context.popIndex(); list.values.add(v); } } else { throw context.parseException('Expected a json-List', json); } } } mixin FieldMaskMixin { List get paths; // From google/protobuf/field_mask.proto: // # JSON Encoding of Field Masks // // In JSON, a field mask is encoded as a single string where paths are // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { final fieldMask = message as FieldMaskMixin; for (final path in fieldMask.paths) { if (path.contains(RegExp('[A-Z]|_[^a-z]'))) { throw ArgumentError( 'Bad fieldmask $path. Does not round-trip to json.', ); } } return fieldMask.paths.map(_toCamelCase).join(','); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is String) { if (json.contains('_')) { throw context.parseException( 'Invalid Character `_` in FieldMask', json, ); } if (json == '') { // The empty string splits to a single value. So this is a special case. return; } (message as FieldMaskMixin).paths.addAll( json.split(',').map(_fromCamelCase), ); } else { throw context.parseException( 'Expected String formatted as FieldMask', json, ); } } static String _toCamelCase(String name) { return name.replaceAllMapped( RegExp('_([a-z])'), (Match m) => m.group(1)!.toUpperCase(), ); } static String _fromCamelCase(String name) { return name.replaceAllMapped( RegExp('[A-Z]'), (Match m) => '_${m.group(0)!.toLowerCase()}', ); } } mixin DoubleValueMixin { double get value; set value(double value); // From google/protobuf/wrappers.proto: // The JSON representation for `DoubleValue` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as DoubleValueMixin).value; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is num) { (message as DoubleValueMixin).value = json.toDouble(); } else if (json is String) { (message as DoubleValueMixin).value = double.tryParse(json) ?? (throw context.parseException( 'Expected string to encode a double', json, )); } else { throw context.parseException( 'Expected a double as a String or number', json, ); } } } mixin FloatValueMixin { double get value; set value(double value); // From google/protobuf/wrappers.proto: // The JSON representation for `FloatValue` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as FloatValueMixin).value; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is num) { (message as FloatValueMixin).value = json.toDouble(); } else if (json is String) { (message as FloatValueMixin).value = double.tryParse(json) ?? (throw context.parseException( 'Expected a float as a String or number', json, )); } else { throw context.parseException( 'Expected a float as a String or number', json, ); } } } mixin Int64ValueMixin { Int64 get value; set value(Int64 value); // From google/protobuf/wrappers.proto: // The JSON representation for `Int64Value` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as Int64ValueMixin).value.toString(); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is int) { (message as Int64ValueMixin).value = Int64(json); } else if (json is String) { try { (message as Int64ValueMixin).value = Int64.parseInt(json); } on FormatException { throw context.parseException('Expected string to encode integer', json); } } else { throw context.parseException( 'Expected an integer encoded as a String or number', json, ); } } } mixin UInt64ValueMixin { Int64 get value; set value(Int64 value); // From google/protobuf/wrappers.proto: // The JSON representation for `UInt64Value` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as UInt64ValueMixin).value.toStringUnsigned(); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is int) { (message as UInt64ValueMixin).value = Int64(json); } else if (json is String) { try { (message as UInt64ValueMixin).value = Int64.parseInt(json); } on FormatException { throw context.parseException( 'Expected string to encode unsigned integer', json, ); } } else { throw context.parseException( 'Expected an unsigned integer as a String or integer', json, ); } } } mixin Int32ValueMixin { int get value; set value(int value); // From google/protobuf/wrappers.proto: // The JSON representation for `Int32Value` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as Int32ValueMixin).value; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is int) { (message as Int32ValueMixin).value = json; } else if (json is String) { (message as Int32ValueMixin).value = int.tryParse(json) ?? (throw context.parseException( 'Expected string to encode integer', json, )); } else { throw context.parseException( 'Expected an integer encoded as a String or number', json, ); } } } mixin UInt32ValueMixin { int get value; set value(int value); static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as UInt32ValueMixin).value; } // From google/protobuf/wrappers.proto: // The JSON representation for `UInt32Value` is JSON number. static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is int) { (message as UInt32ValueMixin).value = json; } else if (json is String) { (message as UInt32ValueMixin).value = int.tryParse(json) ?? (throw context.parseException( 'Expected String to encode an integer', json, )); } else { throw context.parseException( 'Expected an unsigned integer as a String or integer', json, ); } } } mixin BoolValueMixin { bool get value; set value(bool value); // From google/protobuf/wrappers.proto: // The JSON representation for `BoolValue` is JSON `true` and `false` static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as BoolValueMixin).value; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is bool) { (message as BoolValueMixin).value = json; } else { throw context.parseException('Expected a bool', json); } } } mixin StringValueMixin { String get value; set value(String value); // From google/protobuf/wrappers.proto: // The JSON representation for `StringValue` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return (message as StringValueMixin).value; } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is String) { (message as StringValueMixin).value = json; } else { throw context.parseException('Expected a String', json); } } } mixin BytesValueMixin { List get value; set value(List value); // From google/protobuf/wrappers.proto: // The JSON representation for `BytesValue` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry, ) { return base64.encode((message as BytesValueMixin).value); } static void fromProto3JsonHelper( GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is String) { try { (message as BytesValueMixin).value = base64.decode(json); } on FormatException { throw context.parseException( 'Expected bytes encoded as base64 String', json, ); } } else { throw context.parseException( 'Expected bytes encoded as base64 String', json, ); } } } ================================================ FILE: protobuf/lib/src/protobuf/pb_list.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection' show ListBase; import 'dart:math' as math; import 'internal.dart'; import 'utils.dart'; @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbList newPbList({CheckFunc? check}) => PbList._(check: check); @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbList newUnmodifiablePbList({CheckFunc? check}) => PbList._unmodifiable(); /// A [ListBase] implementation used for protobuf `repeated` fields. class PbList extends ListBase { /// The actual list storing the elements. /// /// Note: We want only one [List] implementation class to be stored here to /// make sure the list operations are monomorphic and can be inlined. In /// constructors make sure initializers for this field all return the same /// implementation class. (e.g. `_GrowableList` on the VM) final List _wrappedList; /// A growable list, to be used in `unmodifiable` constructor to avoid /// allocating a list every time. /// /// We can't use `const []` as it makes the `_wrappedList` field polymorphic. static final _emptyList = []; final CheckFunc? _check; bool _isReadOnly = false; bool get isFrozen => _isReadOnly; PbList._({CheckFunc? check}) : _wrappedList = [], _check = check; PbList._unmodifiable() : _wrappedList = _emptyList, _check = null, _isReadOnly = true; @override @pragma('dart2js:never-inline') void add(E element) { _checkModifiable('add'); if (_check != null) { _check(element); } _wrappedList.add(element); } @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void _addUnchecked(E element) { _wrappedList.add(element); } @override @pragma('dart2js:never-inline') void addAll(Iterable iterable) { _checkModifiable('addAll'); if (_check != null) { for (final e in iterable) { _check(e); _addUnchecked(e); } } else { _wrappedList.addAll(iterable); } } @override Iterable get reversed => _wrappedList.reversed; @override void sort([int Function(E a, E b)? compare]) { _checkModifiable('sort'); _wrappedList.sort(compare); } @override void shuffle([math.Random? random]) { _checkModifiable('shuffle'); _wrappedList.shuffle(random); } @override @pragma('dart2js:never-inline') void clear() { _checkModifiable('clear'); _wrappedList.clear(); } @override void insert(int index, E element) { _checkModifiable('insert'); if (_check != null) { _check(element); } _wrappedList.insert(index, element); } @override void insertAll(int index, Iterable iterable) { _checkModifiable('insertAll'); if (_check != null) { _wrappedList.insertAll( index, iterable.map((E e) { _check(e); return e; }), ); } else { _wrappedList.insertAll(index, iterable); } } @override void setAll(int index, Iterable iterable) { _checkModifiable('setAll'); if (_check != null) { _wrappedList.setAll( index, iterable.map((E e) { _check(e); return e; }), ); } else { _wrappedList.setAll(index, iterable); } } @override bool remove(Object? element) { _checkModifiable('remove'); return _wrappedList.remove(element); } @override E removeAt(int index) { _checkModifiable('removeAt'); return _wrappedList.removeAt(index); } @override E removeLast() { _checkModifiable('removeLast'); return _wrappedList.removeLast(); } @override void removeWhere(bool Function(E element) test) { _checkModifiable('removeWhere'); return _wrappedList.removeWhere(test); } @override void retainWhere(bool Function(E element) test) { _checkModifiable('retainWhere'); return _wrappedList.retainWhere(test); } @override void setRange(int start, int end, Iterable iterable, [int skipCount = 0]) { _checkModifiable('setRange'); if (_check != null) { _wrappedList.setRange( start, end, iterable.skip(skipCount).map((E e) { _check(e); return e; }), 0, ); } else { _wrappedList.setRange(start, end, iterable, skipCount); } } @override void removeRange(int start, int end) { _checkModifiable('removeRange'); _wrappedList.removeRange(start, end); } @override void fillRange(int start, int end, [E? fill]) { _checkModifiable('fillRange'); if (_check != null) { _check(fill); } _wrappedList.fillRange(start, end, fill); } @override void replaceRange(int start, int end, Iterable newContents) { _checkModifiable('replaceRange'); if (_check != null) { _wrappedList.replaceRange( start, end, newContents.map((E e) { _check(e); return e; }), ); } else { _wrappedList.replaceRange(start, end, newContents); } } @override int get length => _wrappedList.length; @override bool get isEmpty => _wrappedList.isEmpty; @override bool get isNotEmpty => _wrappedList.isNotEmpty; @override @pragma('dart2js:never-inline') Iterator get iterator => _wrappedList.iterator; @override set length(int newLength) { _checkModifiable('set length'); if (newLength > length) { throw UnsupportedError('Extending protobuf lists is not supported'); } _wrappedList.length = newLength; } @override E operator [](int index) => _wrappedList[index]; @override void operator []=(int index, E value) { _checkModifiable('set element'); if (_check != null) { _check(value); } _wrappedList[index] = value; } @override bool operator ==(Object other) => other is PbList && areListsEqual(other, this); @override int get hashCode => HashUtils.hashObjects(_wrappedList); void freeze() { if (_isReadOnly) { return; } _isReadOnly = true; // Per spec `repeated map<..>` and `repeated repeated ..` are not allowed // so we only check for messages if (_wrappedList.isNotEmpty && _wrappedList[0] is GeneratedMessage) { for (final elem in _wrappedList as Iterable) { elem.freeze(); } } } void _checkModifiable(String methodName) { if (_isReadOnly) { _readOnlyError(methodName); } } static Never _readOnlyError(String methodName) { throw UnsupportedError("'$methodName' on a read-only list"); } PbList _deepCopy() { final newList = PbList._(check: _check); final wrappedList = _wrappedList; final newWrappedList = newList._wrappedList; if (wrappedList.isNotEmpty) { if (wrappedList[0] is GeneratedMessage) { for (final message in wrappedList) { newWrappedList.add((message as GeneratedMessage).deepCopy() as E); } } else { newWrappedList.addAll(wrappedList); } } return newList; } } extension PbListInternalExtension on PbList { @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void checkModifiable(String methodName) => _checkModifiable(methodName); @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') void addUnchecked(E element) => _addUnchecked(element); @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbList deepCopy() => _deepCopy(); } ================================================ FILE: protobuf/lib/src/protobuf/pb_map.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection' show MapBase; import 'internal.dart'; import 'utils.dart'; const mapKeyFieldNumber = 1; const mapValueFieldNumber = 2; @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbMap newPbMap(int keyFieldType, int valueFieldType) => PbMap._( keyFieldType, valueFieldType, getCheckFunction(keyFieldType), getCheckFunction(valueFieldType), ); @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbMap newUnmodifiablePbMap(int keyFieldType, int valueFieldType) => PbMap._unmodifiable(keyFieldType, valueFieldType); /// A [MapBase] implementation used for protobuf `map` fields. class PbMap extends MapBase { /// Key type of the map. Per proto2 and proto3 specs, this needs to be an /// integer type or `string`, and the type cannot be `repeated`. /// /// The `int` value is interpreted the same way as [FieldInfo.type]. final int keyFieldType; /// Value type of the map. Per proto2 and proto3 specs, this can be any type /// other than `map`, and the type cannot be `repeated`. /// /// The `int` value is interpreted the same way as [FieldInfo.type]. final int valueFieldType; /// The actual list storing the elements. /// /// Note: We want only one [Map] implementation class to be stored here to /// make sure the map operations are monomorphic and can be inlined. In /// constructors make sure initializers for this field all return the same /// implementation class. final Map _wrappedMap; bool _isReadOnly = false; final CheckFunc? _checkKey; final CheckFunc? _checkValue; PbMap._( this.keyFieldType, this.valueFieldType, this._checkKey, this._checkValue, ) : _wrappedMap = {}; PbMap._unmodifiable(this.keyFieldType, this.valueFieldType) : _wrappedMap = {}, _isReadOnly = true, _checkKey = null, _checkValue = null; @override V? operator [](Object? key) => _wrappedMap[key]; @override void operator []=(K key, V value) { if (_isReadOnly) { throw UnsupportedError('Attempted to change a read-only map field'); } if (_checkKey != null) { _checkKey(key); } if (_checkValue != null) { _checkValue(value); } _wrappedMap[key] = value; } /// A [PbMap] is equal to another [PbMap] with equal key/value pairs in any /// order. @override bool operator ==(Object other) { if (identical(other, this)) { return true; } if (other is! PbMap) { return false; } if (other.length != length) { return false; } for (final key in keys) { if (other[key] != this[key]) { return false; } } return true; } /// A [PbMap] is equal to another [PbMap] with equal key/value pairs in any /// order. Then, the `hashCode` is guaranteed to be the same. @override int get hashCode { return _wrappedMap.entries.fold( 0, (h, entry) => h ^ HashUtils.hash2(entry.key, entry.value), ); } @override void clear() { if (_isReadOnly) { throw UnsupportedError('Attempted to change a read-only map field'); } _wrappedMap.clear(); } @override Iterable get keys => _wrappedMap.keys; @override V? remove(Object? key) { if (_isReadOnly) { throw UnsupportedError('Attempted to change a read-only map field'); } return _wrappedMap.remove(key); } PbMap freeze() { _isReadOnly = true; if (PbFieldType.isGroupOrMessage(valueFieldType)) { for (final subMessage in values as Iterable) { subMessage.freeze(); } } return this; } PbMap _deepCopy() { final newMap = PbMap._( keyFieldType, valueFieldType, _checkKey, _checkValue, ); final wrappedMap = _wrappedMap; final newWrappedMap = newMap._wrappedMap; if (PbFieldType.isGroupOrMessage(valueFieldType)) { for (final entry in wrappedMap.entries) { newWrappedMap[entry.key] = (entry.value as GeneratedMessage).deepCopy() as V; } } else { newWrappedMap.addAll(wrappedMap); } return newMap; } } extension PbMapInternalExtension on PbMap { @pragma('dart2js:tryInline') @pragma('vm:prefer-inline') @pragma('wasm:prefer-inline') PbMap deepCopy() => _deepCopy(); } ================================================ FILE: protobuf/lib/src/protobuf/permissive_compare.dart ================================================ // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Returns true if [a] and [b] are the same ignoring case and all instances of /// `-` and `_`. /// /// This is specialized code for comparing enum names. /// Works only for ascii strings containing letters and `_` and `-`. bool permissiveCompare(String a, String b) { const dash = 45; const underscore = 95; var i = 0; var j = 0; while (true) { int ca, cb; do { ca = i < a.length ? a.codeUnitAt(i++) : -1; } while (ca == dash || ca == underscore); do { cb = j < b.length ? b.codeUnitAt(j++) : -1; } while (cb == dash || cb == underscore); if (ca == cb) { if (ca == -1) return true; // Both at end continue; } if (ca ^ cb != 0x20 || !_isAsciiLetter(ca)) { return false; } } } bool _isAsciiLetter(int char) { const lowerA = 97; const lowerZ = 122; const capitalA = 65; char |= lowerA ^ capitalA; return lowerA <= char && char <= lowerZ; } ================================================ FILE: protobuf/lib/src/protobuf/proto3_json.dart ================================================ // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; // Public because this is called from the mixins library. Object writeToProto3JsonAny( FieldSet fs, String typeUrl, TypeRegistry typeRegistry, ) { final result = _writeToProto3Json(fs, typeRegistry); final wellKnownType = fs._meta._wellKnownType; if (wellKnownType != null) { switch (wellKnownType) { case WellKnownType.any: case WellKnownType.timestamp: case WellKnownType.duration: case WellKnownType.struct: case WellKnownType.value: case WellKnownType.listValue: case WellKnownType.fieldMask: case WellKnownType.doubleValue: case WellKnownType.floatValue: case WellKnownType.int64Value: case WellKnownType.uint64Value: case WellKnownType.int32Value: case WellKnownType.uint32Value: case WellKnownType.boolValue: case WellKnownType.stringValue: case WellKnownType.bytesValue: return {'@type': typeUrl, 'value': result}; } } (result as Map)['@type'] = typeUrl; return result; } Object? _writeToProto3Json(FieldSet fs, TypeRegistry typeRegistry) { String? convertToMapKey(dynamic key, int keyType) { final baseType = PbFieldType.baseType(keyType); assert(!PbFieldType.isRepeated(keyType)); switch (baseType) { case PbFieldType.BOOL_BIT: return key ? 'true' : 'false'; case PbFieldType.STRING_BIT: return key; case PbFieldType.UINT64_BIT: return (key as Int64).toStringUnsigned(); case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: case PbFieldType.FIXED64_BIT: return key.toString(); default: throw StateError('Not a valid key type $keyType'); } } Object? valueToProto3Json(dynamic fieldValue, int? fieldType) { if (fieldValue == null) return null; if (PbFieldType.isGroupOrMessage(fieldType!)) { return _writeToProto3Json( (fieldValue as GeneratedMessage)._fieldSet, typeRegistry, ); } else if (PbFieldType.isEnum(fieldType)) { return (fieldValue as ProtobufEnum).name; } else { final baseType = PbFieldType.baseType(fieldType); switch (baseType) { case PbFieldType.BOOL_BIT: return fieldValue as bool; case PbFieldType.STRING_BIT: return fieldValue; case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: return fieldValue; case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: case PbFieldType.FIXED64_BIT: return fieldValue.toString(); case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: final double value = fieldValue; if (value.isNaN) { return nan; } if (value.isInfinite) { return value.isNegative ? negativeInfinity : infinity; } if (value.toInt() == fieldValue) { return value.toInt(); } return value; case PbFieldType.UINT64_BIT: return (fieldValue as Int64).toStringUnsigned(); case PbFieldType.BYTES_BIT: return base64Encode(fieldValue); default: throw StateError( 'Invariant violation: unexpected value type $fieldType', ); } } } final meta = fs._meta; final wellKnownType = meta._wellKnownType; if (wellKnownType != null) { switch (wellKnownType) { case WellKnownType.any: return AnyMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.timestamp: return TimestampMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.duration: return DurationMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.struct: return StructMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.value: return ValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.listValue: return ListValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.fieldMask: return FieldMaskMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.doubleValue: return DoubleValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.floatValue: return FloatValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.int64Value: return Int64ValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.uint64Value: return UInt64ValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.int32Value: return Int32ValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.uint32Value: return UInt32ValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.boolValue: return BoolValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.stringValue: return StringValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); case WellKnownType.bytesValue: return BytesValueMixin.toProto3JsonHelper(fs._message!, typeRegistry); } // [WellKnownType] could be used to for messages which have special // encodings in other codecs. The set of messages which special encodings in // proto3json is handled here, so we intentionally fall through to the // default message handling rather than throwing. } final result = {}; for (final fieldInfo in fs._infosSortedByTag) { final value = fs._values[fieldInfo.index!]; if (value == null || (value is List && value.isEmpty)) { continue; // It's missing, repeated, or an empty byte array. } dynamic jsonValue; if (fieldInfo.isMapField) { jsonValue = (value as PbMap).map((key, entryValue) { final mapEntryInfo = fieldInfo as MapFieldInfo; return MapEntry( convertToMapKey(key, mapEntryInfo.keyFieldType), valueToProto3Json(entryValue, mapEntryInfo.valueFieldType), ); }); } else if (fieldInfo.isRepeated) { jsonValue = (value as PbList) .map((element) => valueToProto3Json(element, fieldInfo.type)) .toList(); } else { jsonValue = valueToProto3Json(value, fieldInfo.type); } result[fieldInfo.name] = jsonValue; } // Extensions and unknown fields are not encoded by proto3 JSON. return result; } /// TODO(paulberry): find a better home for this? extension _FindFirst on Iterable { E? findFirst(bool Function(E) test) { for (final element in this) { if (test(element)) return element; } return null; } } // Public because this is called from the mixins library. void mergeFromProto3JsonAny( Object? json, FieldSet fieldSet, TypeRegistry typeRegistry, JsonParsingContext context, ) { if (json is! Map) { throw context.parseException('Expected JSON object', json); } final wellKnownType = fieldSet._meta._wellKnownType; if (wellKnownType != null) { switch (wellKnownType) { case WellKnownType.any: case WellKnownType.timestamp: case WellKnownType.duration: case WellKnownType.struct: case WellKnownType.value: case WellKnownType.listValue: case WellKnownType.fieldMask: case WellKnownType.doubleValue: case WellKnownType.floatValue: case WellKnownType.int64Value: case WellKnownType.uint64Value: case WellKnownType.int32Value: case WellKnownType.uint32Value: case WellKnownType.boolValue: case WellKnownType.stringValue: case WellKnownType.bytesValue: final value = json['value']; return _mergeFromProto3JsonWithContext( value, fieldSet, typeRegistry, context, ); } } // TODO(sigurdm): avoid cloning [object] here. final withoutType = Map.from(json)..remove('@type'); return _mergeFromProto3JsonWithContext( withoutType, fieldSet, typeRegistry, context, ); } /// Merge a JSON object representing a message in proto3 JSON format ([json]) /// to [fieldSet]. void _mergeFromProto3Json( Object? json, FieldSet fieldSet, TypeRegistry typeRegistry, bool ignoreUnknownFields, bool supportNamesWithUnderscores, bool permissiveEnums, ) { final context = JsonParsingContext( ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums, ); return _mergeFromProto3JsonWithContext(json, fieldSet, typeRegistry, context); } /// Merge a JSON object representing a message in proto3 JSON format ([json]) /// to [fieldSet]. void _mergeFromProto3JsonWithContext( Object? json, FieldSet fieldSet, TypeRegistry typeRegistry, JsonParsingContext context, ) { fieldSet._ensureWritable(); void recursionHelper(Object? json, FieldSet fieldSet) { // Convert a JSON object to proto object. Returns `null` on unknown enum // values when [ignoreUnknownFields] is [true]. Object? convertProto3JsonValue(Object value, FieldInfo fieldInfo) { final fieldType = fieldInfo.type; switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: if (value is bool) { return value; } throw context.parseException('Expected bool value', json); case PbFieldType.BYTES_BIT: if (value is String) { try { return base64Decode(value); } on FormatException { throw context.parseException( 'Expected bytes encoded as base64 String', json, ); } } throw context.parseException( 'Expected bytes encoded as base64 String', value, ); case PbFieldType.STRING_BIT: if (value is String) { return value; } throw context.parseException('Expected String value', value); case PbFieldType.FLOAT_BIT: case PbFieldType.DOUBLE_BIT: if (value is double) { return value; } else if (value is num) { return value.toDouble(); } else if (value is String) { return double.tryParse(value) ?? (throw context.parseException( 'Expected String to encode a double', value, )); } throw context.parseException( 'Expected a double represented as a String or number', value, ); case PbFieldType.ENUM_BIT: if (value is String) { // TODO(sigurdm): Do we want to avoid linear search here? Measure... final result = context.permissiveEnums ? fieldInfo.enumValues!.findFirst( (e) => permissiveCompare(e.name, value), ) : fieldInfo.enumValues!.findFirst((e) => e.name == value); if ((result != null) || context.ignoreUnknownFields) return result; throw context.parseException('Unknown enum value', value); } else if (value is int) { return fieldInfo.valueOf!(value) ?? (context.ignoreUnknownFields ? null : (throw context.parseException( 'Unknown enum value', value, ))); } throw context.parseException( 'Expected enum as a string or integer', value, ); case PbFieldType.UINT32_BIT: case PbFieldType.FIXED32_BIT: int result; if (value is int) { result = value; } else if (value is String) { result = Proto3ParseUtils.tryParse32Bit(value, context); } else { throw context.parseException( 'Expected int or stringified int', value, ); } return Proto3ParseUtils.check32BitUnsigned(result, context); case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SFIXED32_BIT: int result; if (value is int) { result = value; } else if (value is String) { result = Proto3ParseUtils.tryParse32Bit(value, context); } else { throw context.parseException( 'Expected int or stringified int', value, ); } Proto3ParseUtils.check32BitSigned(result, context); return result; case PbFieldType.UINT64_BIT: Int64 result; if (value is int) { result = Int64(value); } else if (value is String) { result = Proto3ParseUtils.tryParse64Bit(json, value, context); } else { throw context.parseException( 'Expected int or stringified int', value, ); } return result; case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.FIXED64_BIT: case PbFieldType.SFIXED64_BIT: if (value is int) return Int64(value); if (value is String) { try { return Int64.parseInt(value); } on FormatException { throw context.parseException( 'Expected int or stringified int', value, ); } } throw context.parseException( 'Expected int or stringified int', value, ); case PbFieldType.GROUP_BIT: case PbFieldType.MESSAGE_BIT: final subMessage = fieldInfo.subBuilder!(); recursionHelper(value, subMessage._fieldSet); return subMessage; default: throw StateError('Unknown type $fieldType'); } } Object decodeMapKey(String key, int fieldType) { switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: switch (key) { case 'true': return true; case 'false': return false; default: throw context.parseException( 'Wrong boolean key, should be one of ("true", "false")', key, ); } case PbFieldType.STRING_BIT: return key; case PbFieldType.UINT64_BIT: // TODO(sigurdm): We do not throw on negative values here. // That would probably require going via bignum. return Proto3ParseUtils.tryParse64Bit(json, key, context); case PbFieldType.INT64_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.SFIXED64_BIT: case PbFieldType.FIXED64_BIT: return Proto3ParseUtils.tryParse64Bit(json, key, context); case PbFieldType.INT32_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: return Proto3ParseUtils.check32BitSigned( Proto3ParseUtils.tryParse32Bit(key, context), context, ); case PbFieldType.UINT32_BIT: return Proto3ParseUtils.check32BitUnsigned( Proto3ParseUtils.tryParse32Bit(key, context), context, ); default: throw StateError('Not a valid key type $fieldType'); } } if (json == null) { // `null` represents the default value. Do nothing more. return; } final meta = fieldSet._meta; final wellKnownType = meta._wellKnownType; if (wellKnownType != null) { switch (wellKnownType) { case WellKnownType.any: AnyMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.timestamp: TimestampMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.duration: DurationMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.struct: StructMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.value: ValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.listValue: ListValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.fieldMask: FieldMaskMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.doubleValue: DoubleValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.floatValue: FloatValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.int64Value: Int64ValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.uint64Value: UInt64ValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.int32Value: Int32ValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.uint32Value: UInt32ValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.boolValue: BoolValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.stringValue: StringValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; case WellKnownType.bytesValue: BytesValueMixin.fromProto3JsonHelper( fieldSet._message!, json, typeRegistry, context, ); return; } // [WellKnownType] could be used to for messages which have special // encodings in other codecs. The set of messages which special encodings // in proto3json is handled here, so we intentionally fall through to the // default message handling rather than throwing. } if (json is Map) { final byName = meta.byName; json.forEach((key, Object? value) { if (value == null) { return; } if (key is! String) { throw context.parseException('Key was not a String', key); } context.addMapIndex(key); var fieldInfo = byName[key]; if (fieldInfo == null && context.supportNamesWithUnderscores) { // We don't optimize for field names with underscores, instead do a // linear search for the index. fieldInfo = byName.values.findFirst( (FieldInfo info) => info.protoName == key, ); } if (fieldInfo == null) { if (context.ignoreUnknownFields) { return; } else { throw context.parseException('Unknown field name \'$key\'', key); } } if (PbFieldType.isMapField(fieldInfo.type)) { if (value is Map) { final mapFieldInfo = fieldInfo as MapFieldInfo; final Map fieldValues = fieldSet._ensureMapField(meta, fieldInfo); value.forEach((subKey, subValue) { if (subKey is! String) { throw context.parseException('Expected a String key', subKey); } context.addMapIndex(subKey); final key = decodeMapKey(subKey, mapFieldInfo.keyFieldType); final value = convertProto3JsonValue( subValue, mapFieldInfo.valueFieldInfo, ); if (value != null) { fieldValues[key] = value; } context.popIndex(); }); } else { throw context.parseException('Expected a map', value); } } else if (PbFieldType.isRepeated(fieldInfo.type)) { if (value is List) { final values = fieldSet._ensureRepeatedField(meta, fieldInfo); for (var i = 0; i < value.length; i++) { final entry = value[i]; context.addListIndex(i); final parsedValue = convertProto3JsonValue(entry, fieldInfo); if (parsedValue != null) { values.add(parsedValue); } context.popIndex(); } } else { throw context.parseException('Expected a list', value); } } else if (PbFieldType.isGroupOrMessage(fieldInfo.type)) { // TODO(sigurdm) consider a cleaner separation between parsing and // merging. final parsedSubMessage = convertProto3JsonValue(value, fieldInfo) as GeneratedMessage; final GeneratedMessage? original = fieldSet._values[fieldInfo.index!]; if (original == null) { fieldSet._setNonExtensionFieldUnchecked( meta, fieldInfo, parsedSubMessage, ); } else { original.mergeFromMessage(parsedSubMessage); } } else { final parsedValue = convertProto3JsonValue(value, fieldInfo); if (parsedValue == null) { // Unknown enum if (!context.ignoreUnknownFields) { throw context.parseException('Unknown enum value', value); } } else { fieldSet._setFieldUnchecked(meta, fieldInfo, parsedValue); } } context.popIndex(); }); } else { throw context.parseException('Expected JSON object', json); } } recursionHelper(json, fieldSet); } ================================================ FILE: protobuf/lib/src/protobuf/protobuf_enum.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: non_constant_identifier_names part of 'internal.dart'; /// A base class for all proto enum types. /// /// All proto `enum` classes inherit from [ProtobufEnum]. For example, given /// the following enum defined in a proto file: /// /// message MyMessage { /// enum Color { /// RED = 0; /// GREEN = 1; /// BLUE = 2; /// }; /// // ... /// } /// /// the generated Dart file will include a `MyMessage_Color` class that extends /// `ProtobufEnum`. It will also include a `const MyMessage_Color` for each of /// the three values defined. Here are some examples: /// /// ``` /// MyMessage_Color.RED // => a MyMessage_Color instance /// MyMessage_Color.GREEN.value // => 1 /// MyMessage_Color.GREEN.name // => "GREEN" /// ``` class ProtobufEnum { /// This enum's integer value, as specified in the .proto file. final int value; /// This enum's name, as specified in the .proto file. final String name; /// Creates a new constant [ProtobufEnum] using [value] and [name]. const ProtobufEnum(this.value, this.name); /// This function is for generated code. /// /// Creates a Map for all of the [ProtobufEnum]s in [enumValues], mapping each /// [ProtobufEnum]'s [value] to the [ProtobufEnum]. /// /// @nodoc static Map initByValue(List enumValues) { final byValue = {}; for (final enumValue in enumValues) { byValue[enumValue.value] = enumValue; } return byValue; } /// This function is for generated code. /// /// @nodoc static List $_initByValueList( List enumValues, int maxEnumValue, ) { final byValue = List.filled(maxEnumValue + 1, null); for (final enumValue in enumValues) { byValue[enumValue.value] = enumValue; } return byValue; } /// Returns this enum's [name] or the [value] if names are not represented. @override String toString() => name == '' ? value.toString() : name; } ================================================ FILE: protobuf/lib/src/protobuf/rpc_client.dart ================================================ // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Client side context for [RpcClient]s. class ClientContext { /// The desired timeout of the RPC call. final Duration? timeout; ClientContext({this.timeout}); } /// Client-side transport for making calls to a service. /// /// Subclasses implement whatever serialization and networking is needed /// to make a call. They should serialize the request to binary or JSON as /// appropriate and merge the response into the supplied emptyResponse /// before returning it. /// /// The protoc plugin generates a client-side stub for each service that /// takes an RpcClient as a constructor parameter. abstract class RpcClient { /// Sends a request to a server and returns the reply. /// /// The implementation should serialize the request as binary or JSON, as /// appropriate. It should merge the reply into [emptyResponse] and /// return it. Future invoke( ClientContext? ctx, String serviceName, String methodName, GeneratedMessage request, T emptyResponse, ); } ================================================ FILE: protobuf/lib/src/protobuf/type_registry.dart ================================================ // Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../../protobuf.dart'; /// A TypeRegistry is used to resolve Any messages in the proto3 JSON conversion. /// /// You must provide a TypeRegistry containing all message types used in /// Any message fields, or the JSON conversion will fail because data /// in Any message fields is unrecognizable. You don't need to supply a /// TypeRegistry if you don't use Any message fields. class TypeRegistry { final Map _mapping; /// Constructs a new TypeRegistry recognizing the given types of messages. /// /// You can use an empty message of the given type to represent the type. Eg: /// /// ```dart /// TypeRegistry([Foo(), Bar()]); /// ``` TypeRegistry(Iterable types) : _mapping = Map.fromEntries( types.map( (message) => MapEntry(message.info_.qualifiedMessageName, message.info_), ), ); const TypeRegistry.empty() : _mapping = const {}; BuilderInfo? lookup(String qualifiedName) { return _mapping[qualifiedName]; } } ================================================ FILE: protobuf/lib/src/protobuf/unknown_field_set.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// A set of unknown fields in a [GeneratedMessage]. class UnknownFieldSet { static final UnknownFieldSet emptyUnknownFieldSet = UnknownFieldSet().._markReadOnly(); final Map _fields; UnknownFieldSet() : _fields = {}; UnknownFieldSet._(this._fields); UnknownFieldSet._clone(UnknownFieldSet unknownFieldSet) : _fields = {} { mergeFromUnknownFieldSet(unknownFieldSet); } UnknownFieldSet clone() => UnknownFieldSet._clone(this); bool get isEmpty => _fields.isEmpty; bool get isNotEmpty => _fields.isNotEmpty; bool _isReadOnly = false; Map asMap() => Map.from(_fields); void clear() { _ensureWritable('clear'); _fields.clear(); } void clearField(int tagNumber) { _ensureWritable('clearField'); _fields.remove(tagNumber); } UnknownFieldSetField? getField(int tagNumber) => _fields[tagNumber]; bool hasField(int tagNumber) => _fields.containsKey(tagNumber); void addField(int number, UnknownFieldSetField field) { _ensureWritable('addField'); _checkFieldNumber(number); _fields[number] = field; } void mergeField(int number, UnknownFieldSetField field) { _ensureWritable('mergeField'); _getField(number) ..varints.addAll(field.varints) ..fixed32s.addAll(field.fixed32s) ..fixed64s.addAll(field.fixed64s) ..lengthDelimited.addAll(field.lengthDelimited) ..groups.addAll(field.groups); } bool mergeFieldFromBuffer(int tag, CodedBufferReader input) { _ensureWritable('mergeFieldFromBuffer'); final number = getTagFieldNumber(tag); switch (getTagWireType(tag)) { case WIRETYPE_VARINT: mergeVarintField(number, input.readInt64()); return true; case WIRETYPE_FIXED64: mergeFixed64Field(number, input.readFixed64()); return true; case WIRETYPE_LENGTH_DELIMITED: mergeLengthDelimitedField(number, input.readBytes()); return true; case WIRETYPE_START_GROUP: final subGroup = input.readUnknownFieldSetGroup(number); mergeGroupField(number, subGroup); return true; case WIRETYPE_END_GROUP: return false; case WIRETYPE_FIXED32: mergeFixed32Field(number, input.readFixed32()); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } void mergeFromCodedBufferReader(CodedBufferReader input) { _ensureWritable('mergeFromCodedBufferReader'); while (true) { final tag = input.readTag(); if (tag == 0 || !mergeFieldFromBuffer(tag, input)) { break; } } } void mergeFromUnknownFieldSet(UnknownFieldSet other) { _ensureWritable('mergeFromUnknownFieldSet'); for (final key in other._fields.keys) { mergeField(key, other._fields[key]!); } } void _checkFieldNumber(int number) { if (number == 0) { throw ArgumentError('Zero is not a valid field number.'); } } void mergeFixed32Field(int number, int value) { _ensureWritable('mergeFixed32Field'); _getField(number).addFixed32(value); } void mergeFixed64Field(int number, Int64 value) { _ensureWritable('mergeFixed64Field'); _getField(number).addFixed64(value); } void mergeGroupField(int number, UnknownFieldSet value) { _ensureWritable('mergeGroupField'); _getField(number).addGroup(value); } void mergeLengthDelimitedField(int number, List value) { _ensureWritable('mergeLengthDelimitedField'); _getField(number).addLengthDelimited(value); } void mergeVarintField(int number, Int64 value) { _ensureWritable('mergeVarintField'); _getField(number).addVarint(value); } UnknownFieldSetField _getField(int number) { _checkFieldNumber(number); if (_isReadOnly) assert(_fields.containsKey(number)); return _fields.putIfAbsent(number, UnknownFieldSetField.new); } @override bool operator ==(Object other) { if (other is! UnknownFieldSet) return false; final o = other; return areMapsEqual(o._fields, _fields); } @override int get hashCode { var hash = 0; _fields.forEach((int number, Object value) { hash = 0x1fffffff & ((37 * hash) + number); hash = 0x1fffffff & ((53 * hash) + value.hashCode); }); return hash; } @override String toString() => _toString(''); String _toString(String indent) { final stringBuffer = StringBuffer(); for (final tag in sorted(_fields.keys)) { final field = _fields[tag]!; for (final value in field.values) { if (value is UnknownFieldSet) { stringBuffer ..write('$indent$tag: {\n') ..write(value._toString('$indent ')) ..write('$indent}\n'); } else { stringBuffer.write('$indent$tag: $value\n'); } } } return stringBuffer.toString(); } void writeTextFormat(StringSink out, int indentLevel) { for (final tag in sorted(_fields.keys)) { final field = _fields[tag]!; _writeUnknownFieldSetField(out, tag, field, indentLevel); } } void _writeUnknownFieldSetField( StringSink out, int tag, UnknownFieldSetField field, int indentLevel, ) { void writeIndent(StringSink out, int indentLevel) { for (var i = 0; i < indentLevel; i++) { out.writeCharCode(32); out.writeCharCode(32); } } for (final value in field.varints) { writeIndent(out, indentLevel); out.write('$tag: '); final bi = value.toInt64(); out.write(bi.toStringUnsigned()); out.write('\n'); } for (final value in field.fixed32s) { writeIndent(out, indentLevel); out.write( '$tag: 0x${value.toUnsigned(32).toRadixString(16).padLeft(8, '0')}\n', ); } for (final value in field.fixed64s) { writeIndent(out, indentLevel); out.write('$tag: '); out.write('0x${value.toRadixStringUnsigned(16).padLeft(16, '0')}\n'); } for (final value in field.lengthDelimited) { writeIndent(out, indentLevel); out.write('$tag: '); try { final ufs = UnknownFieldSet() ..mergeFromCodedBufferReader(CodedBufferReader(value)); out.write('{\n'); ufs.writeTextFormat(out, indentLevel + 1); writeIndent(out, indentLevel); out.write('}\n'); } on InvalidProtocolBufferException { out.write('"'); escapeBytes(value, out); out.write('"\n'); } } for (final value in field.groups) { writeIndent(out, indentLevel); out.write('$tag {\n'); value.writeTextFormat(out, indentLevel + 1); writeIndent(out, indentLevel); out.write('}\n'); } } void writeToCodedBufferWriter(CodedBufferWriter output) { for (final entry in _fields.entries) { entry.value.writeTo(entry.key, output); } } void _markReadOnly() { if (_isReadOnly) return; for (final f in _fields.values) { f._markReadOnly(); } _isReadOnly = true; } void _ensureWritable(String methodName) { if (_isReadOnly) { _throwFrozenMessageModificationError('UnknownFieldSet', methodName); } } UnknownFieldSet _deepCopy() { Map newFields = {}; for (final entry in _fields.entries) { final key = entry.key; final value = entry.value; newFields[key] = value._deepCopy(); } return UnknownFieldSet._(newFields); } } /// An unknown field in a [UnknownFieldSet]. class UnknownFieldSetField { List> _lengthDelimited = >[]; List _varints = []; List _fixed32s = []; List _fixed64s = []; List _groups = []; List> get lengthDelimited => _lengthDelimited; List get varints => _varints; List get fixed32s => _fixed32s; List get fixed64s => _fixed64s; List get groups => _groups; UnknownFieldSetField() : _lengthDelimited = >[], _varints = [], _fixed32s = [], _fixed64s = [], _groups = []; UnknownFieldSetField._( this._lengthDelimited, this._varints, this._fixed32s, this._fixed64s, this._groups, ); bool _isReadOnly = false; void _markReadOnly() { if (_isReadOnly) return; _isReadOnly = true; _lengthDelimited = List.unmodifiable(_lengthDelimited); _varints = List.unmodifiable(_varints); _fixed32s = List.unmodifiable(_fixed32s); _fixed64s = List.unmodifiable(_fixed64s); _groups = List.unmodifiable(_groups); } @override bool operator ==(Object other) { if (other is! UnknownFieldSetField) return false; final o = other; if (lengthDelimited.length != o.lengthDelimited.length) return false; for (var i = 0; i < lengthDelimited.length; i++) { if (!areListsEqual(o.lengthDelimited[i], lengthDelimited[i])) { return false; } } if (!areListsEqual(o.varints, varints)) return false; if (!areListsEqual(o.fixed32s, fixed32s)) return false; if (!areListsEqual(o.fixed64s, fixed64s)) return false; if (!areListsEqual(o.groups, groups)) return false; return true; } @override int get hashCode { var hash = 0; for (final value in lengthDelimited) { for (var i = 0; i < value.length; i++) { hash = 0x1fffffff & (hash + value[i]); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); hash = hash ^ (hash >> 6); } hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); hash = 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } for (final value in varints) { hash = 0x1fffffff & (hash + (7 * value.hashCode)); } for (final value in fixed32s) { hash = 0x1fffffff & (hash + (37 * value.hashCode)); } for (final value in fixed64s) { hash = 0x1fffffff & (hash + (53 * value.hashCode)); } for (final value in groups) { hash = 0x1fffffff & (hash + value.hashCode); } return hash; } List get values => [ ...lengthDelimited, ...varints, ...fixed32s, ...fixed64s, ...groups, ]; void writeTo(int fieldNumber, CodedBufferWriter output) { void write(int type, value) { output.writeField(fieldNumber, type, value); } write(PbFieldType.REPEATED_UINT64, varints); write(PbFieldType.REPEATED_FIXED32, fixed32s); write(PbFieldType.REPEATED_FIXED64, fixed64s); write(PbFieldType.REPEATED_BYTES, lengthDelimited); write(PbFieldType.REPEATED_GROUP, groups); } void addGroup(UnknownFieldSet value) { groups.add(value); } void addLengthDelimited(List value) { lengthDelimited.add(value); } void addFixed32(int value) { fixed32s.add(value); } void addFixed64(Int64 value) { fixed64s.add(value); } void addVarint(Int64 value) { varints.add(value); } UnknownFieldSetField _deepCopy() { final newLengthDelimited = List>.from(_lengthDelimited); final newVarints = List.from(_varints); final newFixed32s = List.from(_fixed32s); final newFixed64s = List.from(_fixed64s); final newGroups = []; for (final group in _groups) { newGroups.add(group._deepCopy()); } return UnknownFieldSetField._( newLengthDelimited, newVarints, newFixed32s, newFixed64s, newGroups, ); } } ================================================ FILE: protobuf/lib/src/protobuf/unpack.dart ================================================ // Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of 'internal.dart'; /// Unpacks the message in [value] into [instance]. /// /// Throws a [InvalidProtocolBufferException] if [typeUrl] does not correspond /// with the type of [instance]. /// /// This is a helper method for `Any.unpackInto`. /// /// @nodoc void unpackIntoHelper( List value, T instance, String typeUrl, { ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY, }) { // From "google/protobuf/any.proto": // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". if (!canUnpackIntoHelper(instance, typeUrl)) { final typeName = instance.info_.qualifiedMessageName; throw InvalidProtocolBufferException.wrongAnyMessage( _typeNameFromUrl(typeUrl), typeName, ); } instance.mergeFromBuffer(value, extensionRegistry); } /// Returns `true` if the type of [instance] is described by /// `typeUrl`. /// /// This is a helper method for `Any.canUnpackInto`. /// /// @nodoc bool canUnpackIntoHelper(GeneratedMessage instance, String typeUrl) { return instance.info_.qualifiedMessageName == _typeNameFromUrl(typeUrl); } String _typeNameFromUrl(String typeUrl) { final index = typeUrl.lastIndexOf('/'); return index == -1 ? '' : typeUrl.substring(index + 1); } ================================================ FILE: protobuf/lib/src/protobuf/utils.dart ================================================ // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:fixnum/fixnum.dart' show Int64; import 'internal.dart'; import 'json_parsing_context.dart'; /// Type of a function that checks items added to `PbList` and `PbMap`. /// /// Throws [ArgumentError] or [RangeError] when the item is not valid. typedef CheckFunc = void Function(E? x); // TODO(antonm): reconsider later if PbList should take care of equality. bool deepEquals(Object? lhs, Object? rhs) { // Some GeneratedMessages implement Map, so test this first. if (lhs is GeneratedMessage) return lhs == rhs; if (rhs is GeneratedMessage) return false; if ((lhs is List) && (rhs is List)) return areListsEqual(lhs, rhs); if ((lhs is Map) && (rhs is Map)) return areMapsEqual(lhs, rhs); return lhs == rhs; } bool areListsEqual(List lhs, List rhs) { if (lhs.length != rhs.length) return false; for (var i = 0; i < lhs.length; i++) { if (!deepEquals(lhs[i], rhs[i])) return false; } return true; } bool areMapsEqual(Map lhs, Map rhs) { if (lhs.length != rhs.length) return false; return lhs.keys.every((key) => deepEquals(lhs[key], rhs[key])); } List sorted(Iterable list) => List.from(list)..sort(); /// Escapes slash, double quotes, and newlines in [s] with \ as needed /// for a TextFormat string. /// /// This is a copy of the official Java implementation: https://github.com/protocolbuffers/protobuf/blob/main/java/core/src/main/java/com/google/protobuf/TextFormat.java#L632 String escapeString(String s) { return s .replaceAll('\\', '\\\\') .replaceAll('"', '\\"') .replaceAll('\n', '\\n'); } /// Appends the characters of [bytes] to [out] while escaping them as needed /// for a TextFormat string. /// /// See TextFormat spec in https://protobuf.dev/reference/protobuf/textformat-spec/ /// This is a copy of the official Java implementation: https://github.com/protocolbuffers/protobuf/blob/main/java/core/src/main/java/com/google/protobuf/TextFormatEscaper.java#L40 void escapeBytes(List bytes, StringSink out) { for (final byte in bytes) { // Only ASCII characters between 0x20 (space) and 0x7e (tilde) are // printable. Other byte values must be escaped. switch (byte) { case 0x07: out.write(r'\a'); case 0x08: out.write(r'\b'); case 0x0c: out.write(r'\f'); case 0x0a: out.write(r'\n'); case 0x0d: out.write(r'\r'); case 0x09: out.write(r'\t'); case 0x0b: out.write(r'\v'); default: if (byte >= 0x20 && byte < 0x7f) { if (byte == 0x22 /* " */ || byte == 0x5c /* \ */ ) { out.write(r'\'); } out.writeCharCode(byte); } else { out.write(r'\'); out.write(((byte >> 6) & 3).toString()); out.write(((byte >> 3) & 7).toString()); out.write((byte & 7).toString()); } } } } class HashUtils { // Jenkins hash functions copied from // https://github.com/google/quiver-dart/blob/master/lib/src/core/hash.dart. static int combine(int hash, int value) { hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int _finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } /// Generates a hash code for multiple [objects]. static int hashObjects(Iterable objects) => _finish(objects.fold(0, (h, i) => combine(h, i.hashCode))); /// Generates a hash code for two objects. static int hash2(dynamic a, dynamic b) => _finish(combine(combine(0, a.hashCode), b.hashCode)); } class Proto3ParseUtils { static int tryParse32Bit(String s, JsonParsingContext context) { return int.tryParse(s) ?? (throw context.parseException('expected integer', s)); } static int check32BitSigned(int n, JsonParsingContext context) { if (n < -2147483648 || n > 2147483647) { throw context.parseException('expected 32 bit signed integer', n); } return n; } static int check32BitUnsigned(int n, JsonParsingContext context) { if (n < 0 || n > 0xFFFFFFFF) { throw context.parseException('expected 32 bit unsigned integer', n); } return n; } static Int64 tryParse64Bit( Object? json, String s, JsonParsingContext context, ) { try { return Int64.parseInt(s); } on FormatException { throw context.parseException('expected integer', json); } } } ================================================ FILE: protobuf/lib/src/protobuf/wire_format.dart ================================================ // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // ignore_for_file: constant_identifier_names part of 'internal.dart'; const int _TAG_TYPE_BITS = 3; const int _TAG_TYPE_MASK = (1 << _TAG_TYPE_BITS) - 1; /// @nodoc const int WIRETYPE_VARINT = 0; /// @nodoc const int WIRETYPE_FIXED64 = 1; /// @nodoc const int WIRETYPE_LENGTH_DELIMITED = 2; /// @nodoc const int WIRETYPE_START_GROUP = 3; /// @nodoc const int WIRETYPE_END_GROUP = 4; /// @nodoc const int WIRETYPE_FIXED32 = 5; /// @nodoc int getTagFieldNumber(int tag) => tag >> _TAG_TYPE_BITS; /// @nodoc int getTagWireType(int tag) => tag & _TAG_TYPE_MASK; /// @nodoc int makeTag(int fieldNumber, int tag) => (fieldNumber << _TAG_TYPE_BITS) | tag; /// Returns true if the wireType can be merged into the given fieldType. bool _wireTypeMatches(int fieldType, int wireType) { switch (PbFieldType.baseType(fieldType)) { case PbFieldType.BOOL_BIT: case PbFieldType.ENUM_BIT: case PbFieldType.INT32_BIT: case PbFieldType.INT64_BIT: case PbFieldType.SINT32_BIT: case PbFieldType.SINT64_BIT: case PbFieldType.UINT32_BIT: case PbFieldType.UINT64_BIT: return wireType == WIRETYPE_VARINT || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType.FLOAT_BIT: case PbFieldType.FIXED32_BIT: case PbFieldType.SFIXED32_BIT: return wireType == WIRETYPE_FIXED32 || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType.DOUBLE_BIT: case PbFieldType.FIXED64_BIT: case PbFieldType.SFIXED64_BIT: return wireType == WIRETYPE_FIXED64 || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType.BYTES_BIT: case PbFieldType.STRING_BIT: case PbFieldType.MESSAGE_BIT: return wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType.GROUP_BIT: return wireType == WIRETYPE_START_GROUP; default: return false; } } ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/any.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/any.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/src/protobuf/mixins/well_known.dart' as $mixin; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// `Any` contains an arbitrary serialized protocol buffer message along with a /// URL that describes the type of the serialized message. /// /// Protobuf library provides support to pack/unpack Any values in the form /// of utility functions or additional generated methods of the Any type. /// /// Example 1: Pack and unpack a message in C++. /// /// Foo foo = ...; /// Any any; /// any.PackFrom(foo); /// ... /// if (any.UnpackTo(&foo)) { /// ... /// } /// /// Example 2: Pack and unpack a message in 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()); /// } /// /// Example 3: Pack and unpack a message in Python. /// /// foo = Foo(...) /// any = Any() /// any.Pack(foo) /// ... /// if any.Is(Foo.DESCRIPTOR): /// any.Unpack(foo) /// ... /// /// Example 4: Pack and unpack a message in Go /// /// foo := &pb.Foo{...} /// any, err := anypb.New(foo) /// if err != nil { /// ... /// } /// ... /// foo := &pb.Foo{} /// if err := any.UnmarshalTo(foo); err != nil { /// ... /// } /// /// The pack methods provided by protobuf library will by default use /// 'type.googleapis.com/full.type.name' as the type URL and the unpack /// methods only use the fully qualified type name after the last '/' /// in the type URL, for example "foo.bar.com/x/y.z" will yield type /// name "y.z". /// /// JSON /// ==== /// The JSON representation of an `Any` value uses the regular /// representation of the deserialized, embedded message, with an /// additional field `@type` which contains the type URL. Example: /// /// package google.profile; /// message Person { /// string first_name = 1; /// string last_name = 2; /// } /// /// { /// "@type": "type.googleapis.com/google.profile.Person", /// "firstName": , /// "lastName": /// } /// /// If the embedded message type is well-known and has a custom JSON /// representation, that representation will be embedded adding a field /// `value` which holds the custom JSON in addition to the `@type` /// field. Example (for message [google.protobuf.Duration][]): /// /// { /// "@type": "type.googleapis.com/google.protobuf.Duration", /// "value": "1.212s" /// } class Any extends $pb.GeneratedMessage with $mixin.AnyMixin { factory Any({ $core.String? typeUrl, $core.List<$core.int>? value, }) { final result = create(); if (typeUrl != null) result.typeUrl = typeUrl; if (value != null) result.value = value; return result; } Any._(); factory Any.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Any.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Any', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.any) ..aOS(1, _omitFieldNames ? '' : 'typeUrl') ..a<$core.List<$core.int>>( 2, _omitFieldNames ? '' : 'value', $pb.PbFieldType.OY) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Any clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Any copyWith(void Function(Any) updates) => super.copyWith((message) => updates(message as Any)) as Any; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Any create() => Any._(); @$core.override Any createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Any getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Any? _defaultInstance; /// A URL/resource name that uniquely identifies the type of the serialized /// protocol buffer message. This string must contain at least /// one "/" character. The last segment of the URL's path must represent /// the fully qualified name of the type (as in /// `path/google.protobuf.Duration`). The name should be in a canonical form /// (e.g., leading "." is not accepted). /// /// In practice, teams usually precompile into the binary all types that they /// expect it to use in the context of Any. However, for URLs which use the /// scheme `http`, `https`, or no scheme, one can optionally set up a type /// server that maps type URLs to message definitions as follows: /// /// * If no scheme is provided, `https` is assumed. /// * An HTTP GET on the URL must yield a [google.protobuf.Type][] /// value in binary format, or produce an error. /// * Applications are allowed to cache lookup results based on the /// URL, or have them precompiled into a binary to avoid any /// lookup. Therefore, binary compatibility needs to be preserved /// on changes to types. (Use versioned type names to manage /// breaking changes.) /// /// Note: this functionality is not currently available in the official /// protobuf release, and it is not used for type URLs beginning with /// type.googleapis.com. As of May 2023, there are no widely used type server /// implementations and no plans to implement one. /// /// Schemes other than `http`, `https` (or the empty scheme) might be /// used with implementation specific semantics. @$pb.TagNumber(1) $core.String get typeUrl => $_getSZ(0); @$pb.TagNumber(1) set typeUrl($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasTypeUrl() => $_has(0); @$pb.TagNumber(1) void clearTypeUrl() => $_clearField(1); /// Must be a valid serialized protocol buffer of the above specified type. @$pb.TagNumber(2) $core.List<$core.int> get value => $_getN(1); @$pb.TagNumber(2) set value($core.List<$core.int> value) => $_setBytes(1, value); @$pb.TagNumber(2) $core.bool hasValue() => $_has(1); @$pb.TagNumber(2) void clearValue() => $_clearField(2); /// Creates a new [Any] encoding [message]. /// /// The [typeUrl] will be [typeUrlPrefix]/`fullName` where `fullName` is /// the fully qualified name of the type of [message]. static Any pack($pb.GeneratedMessage message, {$core.String typeUrlPrefix = 'type.googleapis.com'}) { final result = create(); $mixin.AnyMixin.packIntoAny(result, message, typeUrlPrefix: typeUrlPrefix); return result; } } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/any.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/any.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use anyDescriptor instead') const Any$json = { '1': 'Any', '2': [ {'1': 'type_url', '3': 1, '4': 1, '5': 9, '10': 'typeUrl'}, {'1': 'value', '3': 2, '4': 1, '5': 12, '10': 'value'}, ], }; /// Descriptor for `Any`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List anyDescriptor = $convert.base64Decode( 'CgNBbnkSGQoIdHlwZV91cmwYASABKAlSB3R5cGVVcmwSFAoFdmFsdWUYAiABKAxSBXZhbHVl'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/api.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/api.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/well_known_types/google/protobuf/source_context.pb.dart' as $1; import 'package:protobuf/well_known_types/google/protobuf/type.pb.dart' as $0; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// Api is a light-weight descriptor for an API Interface. /// /// Interfaces are also described as "protocol buffer services" in some contexts, /// such as by the "service" keyword in a .proto file, but they are different /// from API Services, which represent a concrete implementation of an interface /// as opposed to simply a description of methods and bindings. They are also /// sometimes simply referred to as "APIs" in other contexts, such as the name of /// this message itself. See https://cloud.google.com/apis/design/glossary for /// detailed terminology. /// /// New usages of this message as an alternative to ServiceDescriptorProto are /// strongly discouraged. This message does not reliability preserve all /// information necessary to model the schema and preserve semantics. Instead /// make use of FileDescriptorSet which preserves the necessary information. class Api extends $pb.GeneratedMessage { factory Api({ $core.String? name, $core.Iterable? methods, $core.Iterable<$0.Option>? options, $core.String? version, $1.SourceContext? sourceContext, $core.Iterable? mixins, $0.Syntax? syntax, $core.String? edition, }) { final result = create(); if (name != null) result.name = name; if (methods != null) result.methods.addAll(methods); if (options != null) result.options.addAll(options); if (version != null) result.version = version; if (sourceContext != null) result.sourceContext = sourceContext; if (mixins != null) result.mixins.addAll(mixins); if (syntax != null) result.syntax = syntax; if (edition != null) result.edition = edition; return result; } Api._(); factory Api.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Api.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Api', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'name') ..pPM(2, _omitFieldNames ? '' : 'methods', subBuilder: Method.create) ..pPM<$0.Option>(3, _omitFieldNames ? '' : 'options', subBuilder: $0.Option.create) ..aOS(4, _omitFieldNames ? '' : 'version') ..aOM<$1.SourceContext>(5, _omitFieldNames ? '' : 'sourceContext', subBuilder: $1.SourceContext.create) ..pPM(6, _omitFieldNames ? '' : 'mixins', subBuilder: Mixin.create) ..aE<$0.Syntax>(7, _omitFieldNames ? '' : 'syntax', enumValues: $0.Syntax.values) ..aOS(8, _omitFieldNames ? '' : 'edition') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Api clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Api copyWith(void Function(Api) updates) => super.copyWith((message) => updates(message as Api)) as Api; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Api create() => Api._(); @$core.override Api createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Api getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Api? _defaultInstance; /// The fully qualified name of this interface, including package name /// followed by the interface's simple name. @$pb.TagNumber(1) $core.String get name => $_getSZ(0); @$pb.TagNumber(1) set name($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasName() => $_has(0); @$pb.TagNumber(1) void clearName() => $_clearField(1); /// The methods of this interface, in unspecified order. @$pb.TagNumber(2) $pb.PbList get methods => $_getList(1); /// Any metadata attached to the interface. @$pb.TagNumber(3) $pb.PbList<$0.Option> get options => $_getList(2); /// A version string for this interface. If specified, must have the form /// `major-version.minor-version`, as in `1.10`. If the minor version is /// omitted, it defaults to zero. If the entire version field is empty, the /// major version is derived from the package name, as outlined below. If the /// field is not empty, the version in the package name will be verified to be /// consistent with what is provided here. /// /// The versioning schema uses [semantic /// versioning](http://semver.org) where the major version number /// indicates a breaking change and the minor version an additive, /// non-breaking change. Both version numbers are signals to users /// what to expect from different versions, and should be carefully /// chosen based on the product plan. /// /// The major version is also reflected in the package name of the /// interface, which must end in `v`, as in /// `google.feature.v1`. For major versions 0 and 1, the suffix can /// be omitted. Zero major versions must only be used for /// experimental, non-GA interfaces. @$pb.TagNumber(4) $core.String get version => $_getSZ(3); @$pb.TagNumber(4) set version($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasVersion() => $_has(3); @$pb.TagNumber(4) void clearVersion() => $_clearField(4); /// Source context for the protocol buffer service represented by this /// message. @$pb.TagNumber(5) $1.SourceContext get sourceContext => $_getN(4); @$pb.TagNumber(5) set sourceContext($1.SourceContext value) => $_setField(5, value); @$pb.TagNumber(5) $core.bool hasSourceContext() => $_has(4); @$pb.TagNumber(5) void clearSourceContext() => $_clearField(5); @$pb.TagNumber(5) $1.SourceContext ensureSourceContext() => $_ensure(4); /// Included interfaces. See [Mixin][]. @$pb.TagNumber(6) $pb.PbList get mixins => $_getList(5); /// The source syntax of the service. @$pb.TagNumber(7) $0.Syntax get syntax => $_getN(6); @$pb.TagNumber(7) set syntax($0.Syntax value) => $_setField(7, value); @$pb.TagNumber(7) $core.bool hasSyntax() => $_has(6); @$pb.TagNumber(7) void clearSyntax() => $_clearField(7); /// The source edition string, only valid when syntax is SYNTAX_EDITIONS. @$pb.TagNumber(8) $core.String get edition => $_getSZ(7); @$pb.TagNumber(8) set edition($core.String value) => $_setString(7, value); @$pb.TagNumber(8) $core.bool hasEdition() => $_has(7); @$pb.TagNumber(8) void clearEdition() => $_clearField(8); } /// Method represents a method of an API interface. /// /// New usages of this message as an alternative to MethodDescriptorProto are /// strongly discouraged. This message does not reliability preserve all /// information necessary to model the schema and preserve semantics. Instead /// make use of FileDescriptorSet which preserves the necessary information. class Method extends $pb.GeneratedMessage { factory Method({ $core.String? name, $core.String? requestTypeUrl, $core.bool? requestStreaming, $core.String? responseTypeUrl, $core.bool? responseStreaming, $core.Iterable<$0.Option>? options, @$core.Deprecated('This field is deprecated.') $0.Syntax? syntax, @$core.Deprecated('This field is deprecated.') $core.String? edition, }) { final result = create(); if (name != null) result.name = name; if (requestTypeUrl != null) result.requestTypeUrl = requestTypeUrl; if (requestStreaming != null) result.requestStreaming = requestStreaming; if (responseTypeUrl != null) result.responseTypeUrl = responseTypeUrl; if (responseStreaming != null) result.responseStreaming = responseStreaming; if (options != null) result.options.addAll(options); if (syntax != null) result.syntax = syntax; if (edition != null) result.edition = edition; return result; } Method._(); factory Method.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Method.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Method', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'name') ..aOS(2, _omitFieldNames ? '' : 'requestTypeUrl') ..aOB(3, _omitFieldNames ? '' : 'requestStreaming') ..aOS(4, _omitFieldNames ? '' : 'responseTypeUrl') ..aOB(5, _omitFieldNames ? '' : 'responseStreaming') ..pPM<$0.Option>(6, _omitFieldNames ? '' : 'options', subBuilder: $0.Option.create) ..aE<$0.Syntax>(7, _omitFieldNames ? '' : 'syntax', enumValues: $0.Syntax.values) ..aOS(8, _omitFieldNames ? '' : 'edition') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Method clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Method copyWith(void Function(Method) updates) => super.copyWith((message) => updates(message as Method)) as Method; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Method create() => Method._(); @$core.override Method createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Method getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Method? _defaultInstance; /// The simple name of this method. @$pb.TagNumber(1) $core.String get name => $_getSZ(0); @$pb.TagNumber(1) set name($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasName() => $_has(0); @$pb.TagNumber(1) void clearName() => $_clearField(1); /// A URL of the input message type. @$pb.TagNumber(2) $core.String get requestTypeUrl => $_getSZ(1); @$pb.TagNumber(2) set requestTypeUrl($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasRequestTypeUrl() => $_has(1); @$pb.TagNumber(2) void clearRequestTypeUrl() => $_clearField(2); /// If true, the request is streamed. @$pb.TagNumber(3) $core.bool get requestStreaming => $_getBF(2); @$pb.TagNumber(3) set requestStreaming($core.bool value) => $_setBool(2, value); @$pb.TagNumber(3) $core.bool hasRequestStreaming() => $_has(2); @$pb.TagNumber(3) void clearRequestStreaming() => $_clearField(3); /// The URL of the output message type. @$pb.TagNumber(4) $core.String get responseTypeUrl => $_getSZ(3); @$pb.TagNumber(4) set responseTypeUrl($core.String value) => $_setString(3, value); @$pb.TagNumber(4) $core.bool hasResponseTypeUrl() => $_has(3); @$pb.TagNumber(4) void clearResponseTypeUrl() => $_clearField(4); /// If true, the response is streamed. @$pb.TagNumber(5) $core.bool get responseStreaming => $_getBF(4); @$pb.TagNumber(5) set responseStreaming($core.bool value) => $_setBool(4, value); @$pb.TagNumber(5) $core.bool hasResponseStreaming() => $_has(4); @$pb.TagNumber(5) void clearResponseStreaming() => $_clearField(5); /// Any metadata attached to the method. @$pb.TagNumber(6) $pb.PbList<$0.Option> get options => $_getList(5); /// The source syntax of this method. /// /// This field should be ignored, instead the syntax should be inherited from /// Api. This is similar to Field and EnumValue. @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(7) $0.Syntax get syntax => $_getN(6); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(7) set syntax($0.Syntax value) => $_setField(7, value); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(7) $core.bool hasSyntax() => $_has(6); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(7) void clearSyntax() => $_clearField(7); /// The source edition string, only valid when syntax is SYNTAX_EDITIONS. /// /// This field should be ignored, instead the edition should be inherited from /// Api. This is similar to Field and EnumValue. @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(8) $core.String get edition => $_getSZ(7); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(8) set edition($core.String value) => $_setString(7, value); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(8) $core.bool hasEdition() => $_has(7); @$core.Deprecated('This field is deprecated.') @$pb.TagNumber(8) void clearEdition() => $_clearField(8); } /// Declares an API Interface to be included in this interface. The including /// interface must redeclare all the methods from the included interface, but /// documentation and options are inherited as follows: /// /// - If after comment and whitespace stripping, the documentation /// string of the redeclared method is empty, it will be inherited /// from the original method. /// /// - Each annotation belonging to the service config (http, /// visibility) which is not set in the redeclared method will be /// inherited. /// /// - If an http annotation is inherited, the path pattern will be /// modified as follows. Any version prefix will be replaced by the /// version of the including interface plus the [root][] path if /// specified. /// /// Example of a simple mixin: /// /// package google.acl.v1; /// service AccessControl { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v1/{resource=**}:getAcl"; /// } /// } /// /// package google.storage.v2; /// service Storage { /// rpc GetAcl(GetAclRequest) returns (Acl); /// /// // Get a data record. /// rpc GetData(GetDataRequest) returns (Data) { /// option (google.api.http).get = "/v2/{resource=**}"; /// } /// } /// /// Example of a mixin configuration: /// /// apis: /// - name: google.storage.v2.Storage /// mixins: /// - name: google.acl.v1.AccessControl /// /// The mixin construct implies that all methods in `AccessControl` are /// also declared with same name and request/response types in /// `Storage`. A documentation generator or annotation processor will /// see the effective `Storage.GetAcl` method after inheriting /// documentation and annotations as follows: /// /// service Storage { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v2/{resource=**}:getAcl"; /// } /// ... /// } /// /// Note how the version in the path pattern changed from `v1` to `v2`. /// /// If the `root` field in the mixin is specified, it should be a /// relative path under which inherited HTTP paths are placed. Example: /// /// apis: /// - name: google.storage.v2.Storage /// mixins: /// - name: google.acl.v1.AccessControl /// root: acls /// /// This implies the following inherited HTTP annotation: /// /// service Storage { /// // Get the underlying ACL object. /// rpc GetAcl(GetAclRequest) returns (Acl) { /// option (google.api.http).get = "/v2/acls/{resource=**}:getAcl"; /// } /// ... /// } class Mixin extends $pb.GeneratedMessage { factory Mixin({ $core.String? name, $core.String? root, }) { final result = create(); if (name != null) result.name = name; if (root != null) result.root = root; return result; } Mixin._(); factory Mixin.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Mixin.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Mixin', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'name') ..aOS(2, _omitFieldNames ? '' : 'root') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Mixin clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Mixin copyWith(void Function(Mixin) updates) => super.copyWith((message) => updates(message as Mixin)) as Mixin; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Mixin create() => Mixin._(); @$core.override Mixin createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Mixin getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Mixin? _defaultInstance; /// The fully qualified name of the interface which is included. @$pb.TagNumber(1) $core.String get name => $_getSZ(0); @$pb.TagNumber(1) set name($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasName() => $_has(0); @$pb.TagNumber(1) void clearName() => $_clearField(1); /// If non-empty specifies a path under which inherited HTTP paths /// are rooted. @$pb.TagNumber(2) $core.String get root => $_getSZ(1); @$pb.TagNumber(2) set root($core.String value) => $_setString(1, value); @$pb.TagNumber(2) $core.bool hasRoot() => $_has(1); @$pb.TagNumber(2) void clearRoot() => $_clearField(2); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/api.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/api.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use apiDescriptor instead') const Api$json = { '1': 'Api', '2': [ {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'}, { '1': 'methods', '3': 2, '4': 3, '5': 11, '6': '.google.protobuf.Method', '10': 'methods' }, { '1': 'options', '3': 3, '4': 3, '5': 11, '6': '.google.protobuf.Option', '10': 'options' }, {'1': 'version', '3': 4, '4': 1, '5': 9, '10': 'version'}, { '1': 'source_context', '3': 5, '4': 1, '5': 11, '6': '.google.protobuf.SourceContext', '10': 'sourceContext' }, { '1': 'mixins', '3': 6, '4': 3, '5': 11, '6': '.google.protobuf.Mixin', '10': 'mixins' }, { '1': 'syntax', '3': 7, '4': 1, '5': 14, '6': '.google.protobuf.Syntax', '10': 'syntax' }, {'1': 'edition', '3': 8, '4': 1, '5': 9, '10': 'edition'}, ], }; /// Descriptor for `Api`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List apiDescriptor = $convert.base64Decode( 'CgNBcGkSEgoEbmFtZRgBIAEoCVIEbmFtZRIxCgdtZXRob2RzGAIgAygLMhcuZ29vZ2xlLnByb3' 'RvYnVmLk1ldGhvZFIHbWV0aG9kcxIxCgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVm' 'Lk9wdGlvblIHb3B0aW9ucxIYCgd2ZXJzaW9uGAQgASgJUgd2ZXJzaW9uEkUKDnNvdXJjZV9jb2' '50ZXh0GAUgASgLMh4uZ29vZ2xlLnByb3RvYnVmLlNvdXJjZUNvbnRleHRSDXNvdXJjZUNvbnRl' 'eHQSLgoGbWl4aW5zGAYgAygLMhYuZ29vZ2xlLnByb3RvYnVmLk1peGluUgZtaXhpbnMSLwoGc3' 'ludGF4GAcgASgOMhcuZ29vZ2xlLnByb3RvYnVmLlN5bnRheFIGc3ludGF4EhgKB2VkaXRpb24Y' 'CCABKAlSB2VkaXRpb24='); @$core.Deprecated('Use methodDescriptor instead') const Method$json = { '1': 'Method', '2': [ {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'}, {'1': 'request_type_url', '3': 2, '4': 1, '5': 9, '10': 'requestTypeUrl'}, { '1': 'request_streaming', '3': 3, '4': 1, '5': 8, '10': 'requestStreaming' }, {'1': 'response_type_url', '3': 4, '4': 1, '5': 9, '10': 'responseTypeUrl'}, { '1': 'response_streaming', '3': 5, '4': 1, '5': 8, '10': 'responseStreaming' }, { '1': 'options', '3': 6, '4': 3, '5': 11, '6': '.google.protobuf.Option', '10': 'options' }, { '1': 'syntax', '3': 7, '4': 1, '5': 14, '6': '.google.protobuf.Syntax', '8': {'3': true}, '10': 'syntax', }, { '1': 'edition', '3': 8, '4': 1, '5': 9, '8': {'3': true}, '10': 'edition', }, ], }; /// Descriptor for `Method`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List methodDescriptor = $convert.base64Decode( 'CgZNZXRob2QSEgoEbmFtZRgBIAEoCVIEbmFtZRIoChByZXF1ZXN0X3R5cGVfdXJsGAIgASgJUg' '5yZXF1ZXN0VHlwZVVybBIrChFyZXF1ZXN0X3N0cmVhbWluZxgDIAEoCFIQcmVxdWVzdFN0cmVh' 'bWluZxIqChFyZXNwb25zZV90eXBlX3VybBgEIAEoCVIPcmVzcG9uc2VUeXBlVXJsEi0KEnJlc3' 'BvbnNlX3N0cmVhbWluZxgFIAEoCFIRcmVzcG9uc2VTdHJlYW1pbmcSMQoHb3B0aW9ucxgGIAMo' 'CzIXLmdvb2dsZS5wcm90b2J1Zi5PcHRpb25SB29wdGlvbnMSMwoGc3ludGF4GAcgASgOMhcuZ2' '9vZ2xlLnByb3RvYnVmLlN5bnRheEICGAFSBnN5bnRheBIcCgdlZGl0aW9uGAggASgJQgIYAVIH' 'ZWRpdGlvbg=='); @$core.Deprecated('Use mixinDescriptor instead') const Mixin$json = { '1': 'Mixin', '2': [ {'1': 'name', '3': 1, '4': 1, '5': 9, '10': 'name'}, {'1': 'root', '3': 2, '4': 1, '5': 9, '10': 'root'}, ], }; /// Descriptor for `Mixin`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List mixinDescriptor = $convert.base64Decode( 'CgVNaXhpbhISCgRuYW1lGAEgASgJUgRuYW1lEhIKBHJvb3QYAiABKAlSBHJvb3Q='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/duration.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/duration.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/src/protobuf/mixins/well_known.dart' as $mixin; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// A Duration represents a signed, fixed-length span of time represented /// as a count of seconds and fractions of seconds at nanosecond /// resolution. It is independent of any calendar and concepts like "day" /// or "month". It is related to Timestamp in that the difference between /// two Timestamp values is a Duration and it can be added or subtracted /// from a Timestamp. Range is approximately +-10,000 years. /// /// # Examples /// /// Example 1: Compute Duration from two Timestamps in pseudo code. /// /// Timestamp start = ...; /// Timestamp end = ...; /// Duration duration = ...; /// /// duration.seconds = end.seconds - start.seconds; /// duration.nanos = end.nanos - start.nanos; /// /// if (duration.seconds < 0 && duration.nanos > 0) { /// duration.seconds += 1; /// duration.nanos -= 1000000000; /// } else if (duration.seconds > 0 && duration.nanos < 0) { /// duration.seconds -= 1; /// duration.nanos += 1000000000; /// } /// /// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. /// /// Timestamp start = ...; /// Duration duration = ...; /// Timestamp end = ...; /// /// end.seconds = start.seconds + duration.seconds; /// end.nanos = start.nanos + duration.nanos; /// /// if (end.nanos < 0) { /// end.seconds -= 1; /// end.nanos += 1000000000; /// } else if (end.nanos >= 1000000000) { /// end.seconds += 1; /// end.nanos -= 1000000000; /// } /// /// Example 3: Compute Duration from datetime.timedelta in Python. /// /// td = datetime.timedelta(days=3, minutes=10) /// duration = Duration() /// duration.FromTimedelta(td) /// /// # JSON Mapping /// /// In JSON format, the Duration type is encoded as a string rather than an /// object, where the string ends in the suffix "s" (indicating seconds) and /// is preceded by the number of seconds, with nanoseconds expressed as /// fractional seconds. For example, 3 seconds with 0 nanoseconds should be /// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should /// be expressed in JSON format as "3.000000001s", and 3 seconds and 1 /// microsecond should be expressed in JSON format as "3.000001s". class Duration extends $pb.GeneratedMessage with $mixin.DurationMixin { factory Duration({ $fixnum.Int64? seconds, $core.int? nanos, }) { final result = create(); if (seconds != null) result.seconds = seconds; if (nanos != null) result.nanos = nanos; return result; } Duration._(); factory Duration.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Duration.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Duration', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.duration) ..aInt64(1, _omitFieldNames ? '' : 'seconds') ..aI(2, _omitFieldNames ? '' : 'nanos') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Duration clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Duration copyWith(void Function(Duration) updates) => super.copyWith((message) => updates(message as Duration)) as Duration; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Duration create() => Duration._(); @$core.override Duration createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Duration getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Duration? _defaultInstance; /// Signed seconds of the span of time. Must be from -315,576,000,000 /// to +315,576,000,000 inclusive. Note: these bounds are computed from: /// 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years @$pb.TagNumber(1) $fixnum.Int64 get seconds => $_getI64(0); @$pb.TagNumber(1) set seconds($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasSeconds() => $_has(0); @$pb.TagNumber(1) void clearSeconds() => $_clearField(1); /// Signed fractions of a second at nanosecond resolution of the span /// of time. Durations less than one second are represented with a 0 /// `seconds` field and a positive or negative `nanos` field. For durations /// of one second or more, a non-zero value for the `nanos` field must be /// of the same sign as the `seconds` field. Must be from -999,999,999 /// to +999,999,999 inclusive. @$pb.TagNumber(2) $core.int get nanos => $_getIZ(1); @$pb.TagNumber(2) set nanos($core.int value) => $_setSignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasNanos() => $_has(1); @$pb.TagNumber(2) void clearNanos() => $_clearField(2); /// Converts the [Duration] to [$core.Duration]. /// /// This is a lossy conversion, as [$core.Duration] is limited to [int] /// microseconds and also does not support nanosecond precision. $core.Duration toDart() => $core.Duration( seconds: seconds.toInt(), microseconds: nanos ~/ 1000, ); /// Creates a new instance from [$core.Duration]. static Duration fromDart($core.Duration duration) => Duration() ..seconds = $fixnum.Int64(duration.inSeconds) ..nanos = (duration.inMicroseconds % $core.Duration.microsecondsPerSecond) * 1000; } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/duration.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/duration.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use durationDescriptor instead') const Duration$json = { '1': 'Duration', '2': [ {'1': 'seconds', '3': 1, '4': 1, '5': 3, '10': 'seconds'}, {'1': 'nanos', '3': 2, '4': 1, '5': 5, '10': 'nanos'}, ], }; /// Descriptor for `Duration`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List durationDescriptor = $convert.base64Decode( 'CghEdXJhdGlvbhIYCgdzZWNvbmRzGAEgASgDUgdzZWNvbmRzEhQKBW5hbm9zGAIgASgFUgVuYW' '5vcw=='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/empty.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/empty.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// A generic empty message that you can re-use to avoid defining duplicated /// empty messages in your APIs. A typical example is to use it as the request /// or the response type of an API method. For instance: /// /// service Foo { /// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); /// } class Empty extends $pb.GeneratedMessage { factory Empty() => create(); Empty._(); factory Empty.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Empty.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Empty', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Empty clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Empty copyWith(void Function(Empty) updates) => super.copyWith((message) => updates(message as Empty)) as Empty; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Empty create() => Empty._(); @$core.override Empty createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Empty getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Empty? _defaultInstance; } const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/empty.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/empty.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use emptyDescriptor instead') const Empty$json = { '1': 'Empty', }; /// Descriptor for `Empty`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List emptyDescriptor = $convert.base64Decode('CgVFbXB0eQ=='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/field_mask.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/field_mask.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/src/protobuf/mixins/well_known.dart' as $mixin; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// `FieldMask` represents a set of symbolic field paths, for example: /// /// paths: "f.a" /// paths: "f.b.d" /// /// Here `f` represents a field in some root message, `a` and `b` /// fields in the message found in `f`, and `d` a field found in the /// message in `f.b`. /// /// Field masks are used to specify a subset of fields that should be /// returned by a get operation or modified by an update operation. /// Field masks also have a custom JSON encoding (see below). /// /// # Field Masks in Projections /// /// When used in the context of a projection, a response message or /// sub-message is filtered by the API to only contain those fields as /// specified in the mask. For example, if the mask in the previous /// example is applied to a response message as follows: /// /// f { /// a : 22 /// b { /// d : 1 /// x : 2 /// } /// y : 13 /// } /// z: 8 /// /// The result will not contain specific values for fields x,y and z /// (their value will be set to the default, and omitted in proto text /// output): /// /// /// f { /// a : 22 /// b { /// d : 1 /// } /// } /// /// A repeated field is not allowed except at the last position of a /// paths string. /// /// If a FieldMask object is not present in a get operation, the /// operation applies to all fields (as if a FieldMask of all fields /// had been specified). /// /// Note that a field mask does not necessarily apply to the /// top-level response message. In case of a REST get operation, the /// field mask applies directly to the response, but in case of a REST /// list operation, the mask instead applies to each individual message /// in the returned resource list. In case of a REST custom method, /// other definitions may be used. Where the mask applies will be /// clearly documented together with its declaration in the API. In /// any case, the effect on the returned resource/resources is required /// behavior for APIs. /// /// # Field Masks in Update Operations /// /// A field mask in update operations specifies which fields of the /// targeted resource are going to be updated. The API is required /// to only change the values of the fields as specified in the mask /// and leave the others untouched. If a resource is passed in to /// describe the updated values, the API ignores the values of all /// fields not covered by the mask. /// /// If a repeated field is specified for an update operation, new values will /// be appended to the existing repeated field in the target resource. Note that /// a repeated field is only allowed in the last position of a `paths` string. /// /// If a sub-message is specified in the last position of the field mask for an /// update operation, then new value will be merged into the existing sub-message /// in the target resource. /// /// For example, given the target message: /// /// f { /// b { /// d: 1 /// x: 2 /// } /// c: [1] /// } /// /// And an update message: /// /// f { /// b { /// d: 10 /// } /// c: [2] /// } /// /// then if the field mask is: /// /// paths: ["f.b", "f.c"] /// /// then the result will be: /// /// f { /// b { /// d: 10 /// x: 2 /// } /// c: [1, 2] /// } /// /// An implementation may provide options to override this default behavior for /// repeated and message fields. /// /// In order to reset a field's value to the default, the field must /// be in the mask and set to the default value in the provided resource. /// Hence, in order to reset all fields of a resource, provide a default /// instance of the resource and set all fields in the mask, or do /// not provide a mask as described below. /// /// If a field mask is not present on update, the operation applies to /// all fields (as if a field mask of all fields has been specified). /// Note that in the presence of schema evolution, this may mean that /// fields the client does not know and has therefore not filled into /// the request will be reset to their default. If this is unwanted /// behavior, a specific service may require a client to always specify /// a field mask, producing an error if not. /// /// As with get operations, the location of the resource which /// describes the updated values in the request message depends on the /// operation kind. In any case, the effect of the field mask is /// required to be honored by the API. /// /// ## Considerations for HTTP REST /// /// The HTTP kind of an update operation which uses a field mask must /// be set to PATCH instead of PUT in order to satisfy HTTP semantics /// (PUT must only be used for full updates). /// /// # JSON Encoding of Field Masks /// /// In JSON, a field mask is encoded as a single string where paths are /// separated by a comma. Fields name in each path are converted /// to/from lower-camel naming conventions. /// /// As an example, consider the following message declarations: /// /// message Profile { /// User user = 1; /// Photo photo = 2; /// } /// message User { /// string display_name = 1; /// string address = 2; /// } /// /// In proto a field mask for `Profile` may look as such: /// /// mask { /// paths: "user.display_name" /// paths: "photo" /// } /// /// In JSON, the same mask is represented as below: /// /// { /// mask: "user.displayName,photo" /// } /// /// # Field Masks and Oneof Fields /// /// Field masks treat fields in oneofs just as regular fields. Consider the /// following message: /// /// message SampleMessage { /// oneof test_oneof { /// string name = 4; /// SubMessage sub_message = 9; /// } /// } /// /// The field mask can be: /// /// mask { /// paths: "name" /// } /// /// Or: /// /// mask { /// paths: "sub_message" /// } /// /// Note that oneof type names ("test_oneof" in this case) cannot be used in /// paths. /// /// ## Field Mask Verification /// /// The implementation of any API method which has a FieldMask type field in the /// request should verify the included field paths, and return an /// `INVALID_ARGUMENT` error if any path is unmappable. class FieldMask extends $pb.GeneratedMessage with $mixin.FieldMaskMixin { factory FieldMask({ $core.Iterable<$core.String>? paths, }) { final result = create(); if (paths != null) result.paths.addAll(paths); return result; } FieldMask._(); factory FieldMask.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory FieldMask.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'FieldMask', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.fieldMask) ..pPS(1, _omitFieldNames ? '' : 'paths') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') FieldMask clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') FieldMask copyWith(void Function(FieldMask) updates) => super.copyWith((message) => updates(message as FieldMask)) as FieldMask; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static FieldMask create() => FieldMask._(); @$core.override FieldMask createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static FieldMask getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static FieldMask? _defaultInstance; /// The set of field mask paths. @$pb.TagNumber(1) $pb.PbList<$core.String> get paths => $_getList(0); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/field_mask.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/field_mask.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use fieldMaskDescriptor instead') const FieldMask$json = { '1': 'FieldMask', '2': [ {'1': 'paths', '3': 1, '4': 3, '5': 9, '10': 'paths'}, ], }; /// Descriptor for `FieldMask`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List fieldMaskDescriptor = $convert.base64Decode('CglGaWVsZE1hc2sSFAoFcGF0aHMYASADKAlSBXBhdGhz'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/source_context.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/source_context.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// `SourceContext` represents information about the source of a /// protobuf element, like the file in which it is defined. class SourceContext extends $pb.GeneratedMessage { factory SourceContext({ $core.String? fileName, }) { final result = create(); if (fileName != null) result.fileName = fileName; return result; } SourceContext._(); factory SourceContext.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory SourceContext.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'SourceContext', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create) ..aOS(1, _omitFieldNames ? '' : 'fileName') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SourceContext clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') SourceContext copyWith(void Function(SourceContext) updates) => super.copyWith((message) => updates(message as SourceContext)) as SourceContext; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static SourceContext create() => SourceContext._(); @$core.override SourceContext createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static SourceContext getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static SourceContext? _defaultInstance; /// The path-qualified name of the .proto file that contained the associated /// protobuf element. For example: `"google/protobuf/source_context.proto"`. @$pb.TagNumber(1) $core.String get fileName => $_getSZ(0); @$pb.TagNumber(1) set fileName($core.String value) => $_setString(0, value); @$pb.TagNumber(1) $core.bool hasFileName() => $_has(0); @$pb.TagNumber(1) void clearFileName() => $_clearField(1); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/source_context.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/source_context.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use sourceContextDescriptor instead') const SourceContext$json = { '1': 'SourceContext', '2': [ {'1': 'file_name', '3': 1, '4': 1, '5': 9, '10': 'fileName'}, ], }; /// Descriptor for `SourceContext`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List sourceContextDescriptor = $convert.base64Decode( 'Cg1Tb3VyY2VDb250ZXh0EhsKCWZpbGVfbmFtZRgBIAEoCVIIZmlsZU5hbWU='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/struct.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/struct.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/src/protobuf/mixins/well_known.dart' as $mixin; import 'package:protobuf/well_known_types/google/protobuf/struct.pbenum.dart'; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'package:protobuf/well_known_types/google/protobuf/struct.pbenum.dart'; /// `Struct` represents a structured data value, consisting of fields /// which map to dynamically typed values. In some languages, `Struct` /// might be supported by a native representation. For example, in /// scripting languages like JS a struct is represented as an /// object. The details of that representation are described together /// with the proto support for the language. /// /// The JSON representation for `Struct` is JSON object. class Struct extends $pb.GeneratedMessage with $mixin.StructMixin { factory Struct({ $core.Iterable<$core.MapEntry<$core.String, Value>>? fields, }) { final result = create(); if (fields != null) result.fields.addEntries(fields); return result; } Struct._(); factory Struct.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Struct.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Struct', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.struct) ..m<$core.String, Value>(1, _omitFieldNames ? '' : 'fields', entryClassName: 'Struct.FieldsEntry', keyFieldType: $pb.PbFieldType.OS, valueFieldType: $pb.PbFieldType.OM, valueCreator: Value.create, valueDefaultOrMaker: Value.getDefault, packageName: const $pb.PackageName('google.protobuf')) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Struct clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Struct copyWith(void Function(Struct) updates) => super.copyWith((message) => updates(message as Struct)) as Struct; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Struct create() => Struct._(); @$core.override Struct createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Struct getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Struct? _defaultInstance; /// Unordered map of dynamically typed values. @$pb.TagNumber(1) $pb.PbMap<$core.String, Value> get fields => $_getMap(0); } enum Value_Kind { nullValue, numberValue, stringValue, boolValue, structValue, listValue, notSet } /// `Value` represents a dynamically typed value which can be either /// null, a number, a string, a boolean, a recursive struct value, or a /// list of values. A producer of value is expected to set one of these /// variants. Absence of any variant indicates an error. /// /// The JSON representation for `Value` is JSON value. class Value extends $pb.GeneratedMessage with $mixin.ValueMixin { factory Value({ NullValue? nullValue, $core.double? numberValue, $core.String? stringValue, $core.bool? boolValue, Struct? structValue, ListValue? listValue, }) { final result = create(); if (nullValue != null) result.nullValue = nullValue; if (numberValue != null) result.numberValue = numberValue; if (stringValue != null) result.stringValue = stringValue; if (boolValue != null) result.boolValue = boolValue; if (structValue != null) result.structValue = structValue; if (listValue != null) result.listValue = listValue; return result; } Value._(); factory Value.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Value.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static const $core.Map<$core.int, Value_Kind> _Value_KindByTag = { 1: Value_Kind.nullValue, 2: Value_Kind.numberValue, 3: Value_Kind.stringValue, 4: Value_Kind.boolValue, 5: Value_Kind.structValue, 6: Value_Kind.listValue, 0: Value_Kind.notSet }; static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Value', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.value) ..oo(0, [1, 2, 3, 4, 5, 6]) ..aE(1, _omitFieldNames ? '' : 'nullValue', enumValues: NullValue.values) ..aD(2, _omitFieldNames ? '' : 'numberValue') ..aOS(3, _omitFieldNames ? '' : 'stringValue') ..aOB(4, _omitFieldNames ? '' : 'boolValue') ..aOM(5, _omitFieldNames ? '' : 'structValue', subBuilder: Struct.create) ..aOM(6, _omitFieldNames ? '' : 'listValue', subBuilder: ListValue.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Value clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Value copyWith(void Function(Value) updates) => super.copyWith((message) => updates(message as Value)) as Value; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Value create() => Value._(); @$core.override Value createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Value getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Value? _defaultInstance; @$pb.TagNumber(1) @$pb.TagNumber(2) @$pb.TagNumber(3) @$pb.TagNumber(4) @$pb.TagNumber(5) @$pb.TagNumber(6) Value_Kind whichKind() => _Value_KindByTag[$_whichOneof(0)]!; @$pb.TagNumber(1) @$pb.TagNumber(2) @$pb.TagNumber(3) @$pb.TagNumber(4) @$pb.TagNumber(5) @$pb.TagNumber(6) void clearKind() => $_clearField($_whichOneof(0)); /// Represents a null value. @$pb.TagNumber(1) NullValue get nullValue => $_getN(0); @$pb.TagNumber(1) set nullValue(NullValue value) => $_setField(1, value); @$pb.TagNumber(1) $core.bool hasNullValue() => $_has(0); @$pb.TagNumber(1) void clearNullValue() => $_clearField(1); /// Represents a double value. @$pb.TagNumber(2) $core.double get numberValue => $_getN(1); @$pb.TagNumber(2) set numberValue($core.double value) => $_setDouble(1, value); @$pb.TagNumber(2) $core.bool hasNumberValue() => $_has(1); @$pb.TagNumber(2) void clearNumberValue() => $_clearField(2); /// Represents a string value. @$pb.TagNumber(3) $core.String get stringValue => $_getSZ(2); @$pb.TagNumber(3) set stringValue($core.String value) => $_setString(2, value); @$pb.TagNumber(3) $core.bool hasStringValue() => $_has(2); @$pb.TagNumber(3) void clearStringValue() => $_clearField(3); /// Represents a boolean value. @$pb.TagNumber(4) $core.bool get boolValue => $_getBF(3); @$pb.TagNumber(4) set boolValue($core.bool value) => $_setBool(3, value); @$pb.TagNumber(4) $core.bool hasBoolValue() => $_has(3); @$pb.TagNumber(4) void clearBoolValue() => $_clearField(4); /// Represents a structured value. @$pb.TagNumber(5) Struct get structValue => $_getN(4); @$pb.TagNumber(5) set structValue(Struct value) => $_setField(5, value); @$pb.TagNumber(5) $core.bool hasStructValue() => $_has(4); @$pb.TagNumber(5) void clearStructValue() => $_clearField(5); @$pb.TagNumber(5) Struct ensureStructValue() => $_ensure(4); /// Represents a repeated `Value`. @$pb.TagNumber(6) ListValue get listValue => $_getN(5); @$pb.TagNumber(6) set listValue(ListValue value) => $_setField(6, value); @$pb.TagNumber(6) $core.bool hasListValue() => $_has(5); @$pb.TagNumber(6) void clearListValue() => $_clearField(6); @$pb.TagNumber(6) ListValue ensureListValue() => $_ensure(5); } /// `ListValue` is a wrapper around a repeated field of values. /// /// The JSON representation for `ListValue` is JSON array. class ListValue extends $pb.GeneratedMessage with $mixin.ListValueMixin { factory ListValue({ $core.Iterable? values, }) { final result = create(); if (values != null) result.values.addAll(values); return result; } ListValue._(); factory ListValue.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory ListValue.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'ListValue', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.listValue) ..pPM(1, _omitFieldNames ? '' : 'values', subBuilder: Value.create) ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListValue clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') ListValue copyWith(void Function(ListValue) updates) => super.copyWith((message) => updates(message as ListValue)) as ListValue; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static ListValue create() => ListValue._(); @$core.override ListValue createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static ListValue getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static ListValue? _defaultInstance; /// Repeated field of dynamically typed values. @$pb.TagNumber(1) $pb.PbList get values => $_getList(0); } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/struct.pbenum.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/struct.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; /// `NullValue` is a singleton enumeration to represent the null value for the /// `Value` type union. /// /// The JSON representation for `NullValue` is JSON `null`. class NullValue extends $pb.ProtobufEnum { /// Null value. static const NullValue NULL_VALUE = NullValue._(0, _omitEnumNames ? '' : 'NULL_VALUE'); static const $core.List values = [ NULL_VALUE, ]; static final $core.List _byValue = $pb.ProtobufEnum.$_initByValueList(values, 0); static NullValue? valueOf($core.int value) => value < 0 || value >= _byValue.length ? null : _byValue[value]; const NullValue._(super.value, super.name); } const $core.bool _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/struct.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/struct.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use nullValueDescriptor instead') const NullValue$json = { '1': 'NullValue', '2': [ {'1': 'NULL_VALUE', '2': 0}, ], }; /// Descriptor for `NullValue`. Decode as a `google.protobuf.EnumDescriptorProto`. final $typed_data.Uint8List nullValueDescriptor = $convert.base64Decode('CglOdWxsVmFsdWUSDgoKTlVMTF9WQUxVRRAA'); @$core.Deprecated('Use structDescriptor instead') const Struct$json = { '1': 'Struct', '2': [ { '1': 'fields', '3': 1, '4': 3, '5': 11, '6': '.google.protobuf.Struct.FieldsEntry', '10': 'fields' }, ], '3': [Struct_FieldsEntry$json], }; @$core.Deprecated('Use structDescriptor instead') const Struct_FieldsEntry$json = { '1': 'FieldsEntry', '2': [ {'1': 'key', '3': 1, '4': 1, '5': 9, '10': 'key'}, { '1': 'value', '3': 2, '4': 1, '5': 11, '6': '.google.protobuf.Value', '10': 'value' }, ], '7': {'7': true}, }; /// Descriptor for `Struct`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List structDescriptor = $convert.base64Decode( 'CgZTdHJ1Y3QSOwoGZmllbGRzGAEgAygLMiMuZ29vZ2xlLnByb3RvYnVmLlN0cnVjdC5GaWVsZH' 'NFbnRyeVIGZmllbGRzGlEKC0ZpZWxkc0VudHJ5EhAKA2tleRgBIAEoCVIDa2V5EiwKBXZhbHVl' 'GAIgASgLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlUgV2YWx1ZToCOAE='); @$core.Deprecated('Use valueDescriptor instead') const Value$json = { '1': 'Value', '2': [ { '1': 'null_value', '3': 1, '4': 1, '5': 14, '6': '.google.protobuf.NullValue', '9': 0, '10': 'nullValue' }, {'1': 'number_value', '3': 2, '4': 1, '5': 1, '9': 0, '10': 'numberValue'}, {'1': 'string_value', '3': 3, '4': 1, '5': 9, '9': 0, '10': 'stringValue'}, {'1': 'bool_value', '3': 4, '4': 1, '5': 8, '9': 0, '10': 'boolValue'}, { '1': 'struct_value', '3': 5, '4': 1, '5': 11, '6': '.google.protobuf.Struct', '9': 0, '10': 'structValue' }, { '1': 'list_value', '3': 6, '4': 1, '5': 11, '6': '.google.protobuf.ListValue', '9': 0, '10': 'listValue' }, ], '8': [ {'1': 'kind'}, ], }; /// Descriptor for `Value`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List valueDescriptor = $convert.base64Decode( 'CgVWYWx1ZRI7CgpudWxsX3ZhbHVlGAEgASgOMhouZ29vZ2xlLnByb3RvYnVmLk51bGxWYWx1ZU' 'gAUgludWxsVmFsdWUSIwoMbnVtYmVyX3ZhbHVlGAIgASgBSABSC251bWJlclZhbHVlEiMKDHN0' 'cmluZ192YWx1ZRgDIAEoCUgAUgtzdHJpbmdWYWx1ZRIfCgpib29sX3ZhbHVlGAQgASgISABSCW' 'Jvb2xWYWx1ZRI8CgxzdHJ1Y3RfdmFsdWUYBSABKAsyFy5nb29nbGUucHJvdG9idWYuU3RydWN0' 'SABSC3N0cnVjdFZhbHVlEjsKCmxpc3RfdmFsdWUYBiABKAsyGi5nb29nbGUucHJvdG9idWYuTG' 'lzdFZhbHVlSABSCWxpc3RWYWx1ZUIGCgRraW5k'); @$core.Deprecated('Use listValueDescriptor instead') const ListValue$json = { '1': 'ListValue', '2': [ { '1': 'values', '3': 1, '4': 3, '5': 11, '6': '.google.protobuf.Value', '10': 'values' }, ], }; /// Descriptor for `ListValue`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List listValueDescriptor = $convert.base64Decode( 'CglMaXN0VmFsdWUSLgoGdmFsdWVzGAEgAygLMhYuZ29vZ2xlLnByb3RvYnVmLlZhbHVlUgZ2YW' 'x1ZXM='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/timestamp.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/timestamp.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:fixnum/fixnum.dart' as $fixnum; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/src/protobuf/mixins/well_known.dart' as $mixin; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; /// A Timestamp represents a point in time independent of any time zone or local /// calendar, encoded as a count of seconds and fractions of seconds at /// nanosecond resolution. The count is relative to an epoch at UTC midnight on /// January 1, 1970, in the proleptic Gregorian calendar which extends the /// Gregorian calendar backwards to year one. /// /// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap /// second table is needed for interpretation, using a [24-hour linear /// smear](https://developers.google.com/time/smear). /// /// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By /// restricting to that range, we ensure that we can convert to and from [RFC /// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. /// /// # Examples /// /// Example 1: Compute Timestamp from POSIX `time()`. /// /// Timestamp timestamp; /// timestamp.set_seconds(time(NULL)); /// timestamp.set_nanos(0); /// /// Example 2: Compute Timestamp from POSIX `gettimeofday()`. /// /// struct timeval tv; /// gettimeofday(&tv, NULL); /// /// Timestamp timestamp; /// timestamp.set_seconds(tv.tv_sec); /// timestamp.set_nanos(tv.tv_usec * 1000); /// /// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. /// /// FILETIME ft; /// GetSystemTimeAsFileTime(&ft); /// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; /// /// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z /// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. /// Timestamp timestamp; /// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); /// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); /// /// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. /// /// long millis = System.currentTimeMillis(); /// /// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) /// .setNanos((int) ((millis % 1000) * 1000000)).build(); /// /// Example 5: Compute Timestamp from Java `Instant.now()`. /// /// Instant now = Instant.now(); /// /// Timestamp timestamp = /// Timestamp.newBuilder().setSeconds(now.getEpochSecond()) /// .setNanos(now.getNano()).build(); /// /// Example 6: Compute Timestamp from current time in Python. /// /// timestamp = Timestamp() /// timestamp.GetCurrentTime() /// /// # JSON Mapping /// /// In JSON format, the Timestamp type is encoded as a string in the /// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the /// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" /// where {year} is always expressed using four digits while {month}, {day}, /// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional /// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), /// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone /// is required. A ProtoJSON serializer should always use UTC (as indicated by /// "Z") when printing the Timestamp type and a ProtoJSON parser should be /// able to accept both UTC and other timezones (as indicated by an offset). /// /// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past /// 01:30 UTC on January 15, 2017. /// /// In JavaScript, one can convert a Date object to this format using the /// standard /// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) /// method. In Python, a standard `datetime.datetime` object can be converted /// to this format using /// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with /// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use /// the Joda Time's [`ISODateTimeFormat.dateTime()`]( /// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() /// ) to obtain a formatter capable of generating timestamps in this format. class Timestamp extends $pb.GeneratedMessage with $mixin.TimestampMixin { factory Timestamp({ $fixnum.Int64? seconds, $core.int? nanos, }) { final result = create(); if (seconds != null) result.seconds = seconds; if (nanos != null) result.nanos = nanos; return result; } Timestamp._(); factory Timestamp.fromBuffer($core.List<$core.int> data, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(data, registry); factory Timestamp.fromJson($core.String json, [$pb.ExtensionRegistry registry = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(json, registry); static final $pb.BuilderInfo _i = $pb.BuilderInfo( _omitMessageNames ? '' : 'Timestamp', package: const $pb.PackageName(_omitMessageNames ? '' : 'google.protobuf'), createEmptyInstance: create, wellKnownType: $mixin.WellKnownType.timestamp) ..aInt64(1, _omitFieldNames ? '' : 'seconds') ..aI(2, _omitFieldNames ? '' : 'nanos') ..hasRequiredFields = false; @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Timestamp clone() => deepCopy(); @$core.Deprecated('See https://github.com/google/protobuf.dart/issues/998.') Timestamp copyWith(void Function(Timestamp) updates) => super.copyWith((message) => updates(message as Timestamp)) as Timestamp; @$core.override $pb.BuilderInfo get info_ => _i; @$core.pragma('dart2js:noInline') static Timestamp create() => Timestamp._(); @$core.override Timestamp createEmptyInstance() => create(); @$core.pragma('dart2js:noInline') static Timestamp getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor(create); static Timestamp? _defaultInstance; /// Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must /// be between -62135596800 and 253402300799 inclusive (which corresponds to /// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z). @$pb.TagNumber(1) $fixnum.Int64 get seconds => $_getI64(0); @$pb.TagNumber(1) set seconds($fixnum.Int64 value) => $_setInt64(0, value); @$pb.TagNumber(1) $core.bool hasSeconds() => $_has(0); @$pb.TagNumber(1) void clearSeconds() => $_clearField(1); /// Non-negative fractions of a second at nanosecond resolution. This field is /// the nanosecond portion of the duration, not an alternative to seconds. /// Negative second values with fractions must still have non-negative nanos /// values that count forward in time. Must be between 0 and 999,999,999 /// inclusive. @$pb.TagNumber(2) $core.int get nanos => $_getIZ(1); @$pb.TagNumber(2) set nanos($core.int value) => $_setSignedInt32(1, value); @$pb.TagNumber(2) $core.bool hasNanos() => $_has(1); @$pb.TagNumber(2) void clearNanos() => $_clearField(2); /// Creates a new instance from [dateTime]. /// /// Time zone information will not be preserved. static Timestamp fromDateTime($core.DateTime dateTime) { final result = create(); $mixin.TimestampMixin.setFromDateTime(result, dateTime); return result; } } const $core.bool _omitFieldNames = $core.bool.fromEnvironment('protobuf.omit_field_names'); const $core.bool _omitMessageNames = $core.bool.fromEnvironment('protobuf.omit_message_names'); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/timestamp.pbjson.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/timestamp.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports // ignore_for_file: unused_import import 'dart:convert' as $convert; import 'dart:core' as $core; import 'dart:typed_data' as $typed_data; @$core.Deprecated('Use timestampDescriptor instead') const Timestamp$json = { '1': 'Timestamp', '2': [ {'1': 'seconds', '3': 1, '4': 1, '5': 3, '10': 'seconds'}, {'1': 'nanos', '3': 2, '4': 1, '5': 5, '10': 'nanos'}, ], }; /// Descriptor for `Timestamp`. Decode as a `google.protobuf.DescriptorProto`. final $typed_data.Uint8List timestampDescriptor = $convert.base64Decode( 'CglUaW1lc3RhbXASGAoHc2Vjb25kcxgBIAEoA1IHc2Vjb25kcxIUCgVuYW5vcxgCIAEoBVIFbm' 'Fub3M='); ================================================ FILE: protobuf/lib/well_known_types/google/protobuf/type.pb.dart ================================================ // This is a generated file - do not edit. // // Generated from google/protobuf/type.proto. // @dart = 3.3 // ignore_for_file: annotate_overrides, camel_case_types, comment_references // ignore_for_file: constant_identifier_names // ignore_for_file: curly_braces_in_flow_control_structures // ignore_for_file: deprecated_member_use_from_same_package, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_relative_imports import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/well_known_types/google/protobuf/any.pb.dart' as $1; import 'package:protobuf/well_known_types/google/protobuf/source_context.pb.dart' as $0; import 'package:protobuf/well_known_types/google/protobuf/type.pbenum.dart'; export 'package:protobuf/protobuf.dart' show GeneratedMessageGenericExtensions; export 'package:protobuf/well_known_types/google/protobuf/type.pbenum.dart'; /// A protocol buffer message type. /// /// New usages of this message as an alternative to DescriptorProto are strongly /// discouraged. This message does not reliability preserve all information /// necessary to model the schema and preserve semantics. Instead make use of /// FileDescriptorSet which preserves the necessary information. class Type extends $pb.GeneratedMessage { factory Type({ $core.String? name, $core.Iterable? fields, $core.Iterable<$core.String>? oneofs, $core.Iterable