diff options
author | Treehugger Robot <treehugger-gerrit@google.com> | 2023-04-12 21:05:56 +0000 |
---|---|---|
committer | Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com> | 2023-04-12 21:05:56 +0000 |
commit | 45f0bf3bf0b816709a0685db2ee6b6381a2683e5 (patch) | |
tree | 971c49e3e23c1508cd5d3449db1162011f57ccc6 | |
parent | c09e48776e55c179c7f8970cbcc01dc826239b10 (diff) | |
parent | 7341fcb74547dbbda375b990fc31e87eb4067e87 (diff) | |
download | protobuf-45f0bf3bf0b816709a0685db2ee6b6381a2683e5.tar.gz |
Merge "Upgrade protobuf to 3.2.0" am: 7dc275cd70 am: 9b9bcfecdd am: 7341fcb745android14-dev
Original change: https://android-review.googlesource.com/c/platform/external/rust/crates/protobuf/+/2520001
Change-Id: I382314fb421087ddca1e190af79a75da4496a2d0
Signed-off-by: Automerger Merge Worker <android-build-automerger-merge-worker@system.gserviceaccount.com>
172 files changed, 25002 insertions, 22360 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index ca74a42..bf5e7a5 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,6 +1,6 @@ { "git": { - "sha1": "ec31ce829473039ac598ca6fdcb245cbd6fa82ba" + "sha1": "7155092f3df112159d55132081937e1fe5c30490" }, "path_in_vcs": "protobuf" }
\ No newline at end of file @@ -27,51 +27,27 @@ genrule { rust_library { name: "libprotobuf", - // has rustc warnings host_supported: true, crate_name: "protobuf", cargo_env_compat: true, - cargo_pkg_version: "2.27.1", + cargo_pkg_version: "3.2.0", srcs: [ "src/lib.rs", ":copy_protobuf_build_out", ], - edition: "2018", + edition: "2021", features: ["bytes"], rustlibs: [ "libbytes", + "libonce_cell", + "libprotobuf_support", + "libthiserror", ], apex_available: [ "//apex_available:platform", - "com.android.btservices", - "com.android.compos", - "com.android.virt", + "//apex_available:anyapex", ], product_available: true, vendor_available: true, min_sdk_version: "29", } - -rust_library_host { - name: "libprotobuf_with_serde", - // has rustc warnings - crate_name: "protobuf", - cargo_env_compat: true, - cargo_pkg_version: "2.27.1", - srcs: [ - "src/lib.rs", - ":copy_protobuf_build_out", - ], - edition: "2018", - features: [ - "serde", - "serde_derive", - "with-serde", - ], - rustlibs: [ - "libserde", - ], - proc_macros: ["libserde_derive"], - product_available: true, - vendor_available: true, -} @@ -10,15 +10,16 @@ # See Cargo.toml.orig for the original contents. [package] -edition = "2018" +edition = "2021" name = "protobuf" -version = "2.27.1" +version = "3.2.0" authors = ["Stepan Koltsov <stepan.koltsov@gmail.com>"] description = """ Rust implementation of Google protocol buffers """ homepage = "https://github.com/stepancheg/rust-protobuf/" documentation = "https://github.com/stepancheg/rust-protobuf/blob/master/README.md" +readme = "README.md" license = "MIT" repository = "https://github.com/stepancheg/rust-protobuf/" @@ -26,25 +27,21 @@ repository = "https://github.com/stepancheg/rust-protobuf/" all-features = true [lib] -doctest = false bench = false [dependencies.bytes] -version = "1.0" +version = "1.1" optional = true -[dependencies.serde] -version = "1.0" -features = ["derive"] -optional = true +[dependencies.once_cell] +version = "1.9.0" -[dependencies.serde_derive] -version = "1.0" -optional = true +[dependencies.protobuf-support] +version = "=3.2.0" + +[dependencies.thiserror] +version = "1.0.30" [features] +default = [] with-bytes = ["bytes"] -with-serde = [ - "serde", - "serde_derive", -] diff --git a/Cargo.toml.orig b/Cargo.toml.orig index c1be2f7..7b40d37 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,9 +1,9 @@ [package] name = "protobuf" -version = "2.27.1" +version = "3.2.0" authors = ["Stepan Koltsov <stepan.koltsov@gmail.com>"] -edition = "2018" +edition = "2021" license = "MIT" homepage = "https://github.com/stepancheg/rust-protobuf/" repository = "https://github.com/stepancheg/rust-protobuf/" @@ -13,17 +13,18 @@ Rust implementation of Google protocol buffers """ [lib] -doctest = false bench = false [features] with-bytes = ["bytes"] -with-serde = ["serde", "serde_derive"] +default = [] [dependencies] -bytes = { version = "1.0", optional = true } -serde = { version = "1.0", features = ["derive"], optional = true } -serde_derive = { version = "1.0", optional = true } +bytes = { version = "1.1", optional = true } +thiserror = "1.0.30" +once_cell = "1.9.0" + +protobuf-support = { path = "../protobuf-support", version = "=3.2.0" } [package.metadata.docs.rs] all-features = true @@ -1,3 +1,7 @@ +# This project was upgraded with external_updater. +# Usage: tools/external_updater/updater.sh update rust/crates/protobuf +# For more info, check https://cs.android.com/android/platform/superproject/+/master:tools/external_updater/README.md + name: "protobuf" description: "Rust implementation of Google protocol buffers" third_party { @@ -7,13 +11,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/protobuf/protobuf-2.27.1.crate" + value: "https://static.crates.io/crates/protobuf/protobuf-3.2.0.crate" } - version: "2.27.1" + version: "3.2.0" license_type: NOTICE last_upgrade_date { - year: 2022 - month: 3 - day: 1 + year: 2023 + month: 4 + day: 3 } } @@ -2,94 +2,31 @@ # Library to read and write protocol buffers data -# Version 2 is stable +## Features -Currently developed branch of rust-protobuf [is 3](https://docs.rs/protobuf/%3E=3.0.0-alpha). -It has the same spirit as version 2, but contains numerous improvements like: -* runtime reflection for mutability, not just for access -* protobuf text format and JSON parsing (which rely on reflection) -* dynamic message support: work with protobuf data without generating code from schema +This crate has one feature, which is `with-bytes`. -Stable version of rust-protobuf will be supported until version 3 released. +`with-bytes` enables `protobuf` crate support for +[`bytes` crate](https://github.com/tokio-rs/bytes): +when parsing bytes or strings from `bytes::Bytes`, +`protobuf` will be able to reference the input instead of allocating subarrays. -[Tracking issue for version 3](https://github.com/stepancheg/rust-protobuf/issues/518). +Note, codegen also need to be instructed to generate `Bytes` or `Chars` for +`bytes` or `string` protobuf types instead of default `Vec<u8>` or `String`, +just enabling option on this crate is not enough. -# How to generate rust code +See `Customize` struct in [`protobuf-codegen` crate](https://docs.rs/protobuf-codegen). -There are several ways to generate rust code from `.proto` files +## Accompanying crates -## Invoke `protoc` programmatically with protoc-rust crate (recommended) - -Have a look at readme in [protoc-rust crate](https://docs.rs/protoc-rust/=2). - -## Use pure rust protobuf parser and code generator - -Readme should be in -[protobuf-codegen-pure crate](https://docs.rs/protobuf-codegen-pure/=2). - -## Use protoc-gen-rust plugin - -Readme is [here](https://docs.rs/protobuf-codegen/=2). - -## Generated code - -Have a look at generated files (for current development version), -used internally in rust-protobuf: - -* [descriptor.rs](https://github.com/stepancheg/rust-protobuf/blob/master/protobuf/src/descriptor.rs) - for [descriptor.proto](https://github.com/stepancheg/rust-protobuf/blob/master/protoc-bin-vendored/include/google/protobuf/descriptor.proto) - (that is part of Google protobuf) - -# Copy on write - -Rust-protobuf can be used with [bytes crate](https://github.com/tokio-rs/bytes). - -To enable `Bytes` you need to: - -1. Enable `with-bytes` feature in rust-protobuf: - -```rust -[dependencies] -protobuf = { version = "~2.0", features = ["with-bytes"] } -``` - -2. Enable bytes option - -with `Customize` when codegen is invoked programmatically: - -```rust -protoc_rust::run(protoc_rust::Args { - ... - customize: Customize { - carllerche_bytes_for_bytes: Some(true), - carllerche_bytes_for_string: Some(true), - ..Default::default() - }, -}); -``` - -or in `.proto` file: - -```rust -import "rustproto.proto"; - -option (rustproto.carllerche_bytes_for_bytes_all) = true; -option (rustproto.carllerche_bytes_for_string_all) = true; -``` - -With these options enabled, fields of type `bytes` or `string` are -generated as `Bytes` or `Chars` respectively. When `CodedInputStream` is constructed -from `Bytes` object, fields of these types get subslices of original `Bytes` object, -instead of being allocated on heap. - -# Accompanying crates - -* [`protoc-rust`](https://docs.rs/protoc-rust/=2) - and [`protobuf-codegen-pure`](https://docs.rs/protobuf-codegen-pure/=2) +* [`protobuf-json-mapping`](https://docs.rs/protobuf-json-mapping) + implements JSON parsing and serialization for protobuf messages. +* [`protobuf-codegen`](https://docs.rs/protobuf-codegen) can be used to rust code from `.proto` crates. -* [`protobuf-codegen`](https://docs.rs/protobuf-codegen/=2) for `protoc-gen-rust` protoc plugin. -* [`protoc`](https://docs.rs/protoc/=2) crate can be used to invoke `protoc` programmatically. -* [`protoc-bin-vendored`](https://docs.rs/protoc-bin-vendored/=2) contains `protoc` command - packed into the crate. +* [`protoc-bin-vendored`](https://docs.rs/protoc-bin-vendored) + contains `protoc` command packed into the crate. +* [`protobuf-parse`](https://docs.rs/protobuf-parse) contains + `.proto` file parser. Rarely need to be used directly, + but can be used for mechanical processing of `.proto` files. <!-- cargo-sync-readme end --> diff --git a/benches/coded_input_stream.rs b/benches/coded_input_stream.rs index d1795e5..10831da 100644 --- a/benches/coded_input_stream.rs +++ b/benches/coded_input_stream.rs @@ -102,3 +102,34 @@ fn read_varint_1(b: &mut Bencher) { assert_eq!(1000, count); }) } + +fn xorshift(mut x: u64) -> u64 { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x +} + +#[bench] +fn read_varint_large(b: &mut Bencher) { + let mut v = Vec::new(); + { + let mut v = protobuf::CodedOutputStream::vec(&mut v); + let mut rng = 1; + for _ in 0..1000 { + // one or two byte varints + v.write_raw_varint64(rng).unwrap(); + rng = xorshift(rng); + } + v.flush().expect("flush"); + } + b.iter(|| { + let mut is = CodedInputStream::from_bytes(test::black_box(&v)); + let mut count = 0; + while !is.eof().expect("eof") { + test::black_box(is.read_raw_varint64().expect("read")); + count += 1; + } + assert_eq!(1000, count); + }) +} diff --git a/benches/coded_output_stream.rs b/benches/coded_output_stream.rs index 9edf95c..8aed4d8 100644 --- a/benches/coded_output_stream.rs +++ b/benches/coded_output_stream.rs @@ -48,3 +48,18 @@ fn bench_buffer_bytes(b: &mut Bencher) { v }); } + +#[bench] +fn bench_write_raw_varint_32(b: &mut Bencher) { + let mut v = Vec::with_capacity(10_000); + b.iter(|| { + v.clear(); + { + let mut os = CodedOutputStream::new(&mut v); + for i in 0..1000 { + os.write_raw_varint32(i * 139 % 1000).unwrap(); + } + } + v.len() + }) +} diff --git a/benches/write.rs b/benches/write.rs new file mode 100644 index 0000000..3b49831 --- /dev/null +++ b/benches/write.rs @@ -0,0 +1,23 @@ +// `cargo test --benches` and `#[feature(test)]` work only in nightly +#![cfg(rustc_nightly)] +#![feature(test)] + +extern crate test; + +use protobuf::well_known_types::struct_::value; +use protobuf::well_known_types::struct_::Struct; +use protobuf::well_known_types::struct_::Value; +use protobuf::Message; +use test::Bencher; + +#[bench] +fn write_to_bytes(b: &mut Bencher) { + let mut value = Value::new(); + value.kind = Some(value::Kind::NumberValue(10.0)); + let mut value2 = Value::new(); + value2.kind = Some(value::Kind::BoolValue(true)); + let mut s = Struct::new(); + s.fields.insert("foo".to_owned(), value); + s.fields.insert("bar".to_owned(), value2); + b.iter(|| s.write_to_bytes()); +} @@ -1,4 +1,5 @@ use std::env; +use std::env::VarError; use std::fs::File; use std::io::Read; use std::io::Write; @@ -16,7 +17,7 @@ fn version_is_nightly(version: &str) -> bool { version.contains("nightly") } -fn main() { +fn cfg_rust_version() { let rustc = env::var("RUSTC").expect("RUSTC unset"); let mut child = process::Command::new(rustc) @@ -39,8 +40,16 @@ fn main() { if version_is_nightly(&rustc_version) { println!("cargo:rustc-cfg=rustc_nightly"); } +} - write_version(); +fn cfg_serde() { + match env::var("CARGO_FEATURE_WITH_SERDE") { + Ok(_) => { + println!("cargo:rustc-cfg=serde"); + } + Err(VarError::NotUnicode(..)) => panic!(), + Err(VarError::NotPresent) => {} + } } fn out_dir() -> PathBuf { @@ -76,3 +85,9 @@ fn write_version() { writeln!(file, "pub const {}: () = ();", version_ident).unwrap(); file.flush().unwrap(); } + +fn main() { + cfg_rust_version(); + cfg_serde(); + write_version(); +} diff --git a/cargo2android.json b/cargo2android.json index cafe7cd..e6792f4 100644 --- a/cargo2android.json +++ b/cargo2android.json @@ -1,24 +1,12 @@ { "apex-available": [ "//apex_available:platform", - "com.android.btservices", - "com.android.compos", - "com.android.virt" + "//apex_available:anyapex" ], "copy-out": true, "dependencies": true, "device": true, "features": "bytes", - "variants": [ - { - "suffix": "" - }, - { - "suffix": "_with_serde", - "features": "with-serde", - "device": false - } - ], "min-sdk-version": "29", "run": true -}
\ No newline at end of file +} diff --git a/cargo_1.out b/cargo_1.out new file mode 100644 index 0000000..23d4847 --- /dev/null +++ b/cargo_1.out @@ -0,0 +1,4 @@ +### Running: /usr/local/google/home/jeffv/android/aosp/development/scripts/../../prebuilts/rust/linux-x86/1.68.0/bin/cargo -v clean --target-dir target.tmp >> ./cargo_1.out 2>&1 + Removing /tmp/tmpbssc9a1g/protobuf-3.2.0/target.tmp +### Running: /usr/local/google/home/jeffv/android/aosp/development/scripts/../../prebuilts/rust/linux-x86/1.68.0/bin/cargo -v build --target x86_64-unknown-linux-gnu --no-default-features --features with-serde --target-dir target.tmp >> ./cargo_1.out 2>&1 +error: none of the selected packages contains these features: with-serde diff --git a/out/version.rs b/out/version.rs index 18bbac5..4ede33b 100644 --- a/out/version.rs +++ b/out/version.rs @@ -1,7 +1,7 @@ /// protobuf crate version -pub const VERSION: &'static str = "2.27.1"; +pub const VERSION: &'static str = "3.2.0"; /// This symbol is used by codegen #[doc(hidden)] -pub const VERSION_IDENT: &'static str = "VERSION_2_27_1"; +pub const VERSION_IDENT: &'static str = "VERSION_3_2_0"; /// This symbol can be referenced to assert that proper version of crate is used -pub const VERSION_2_27_1: () = (); +pub const VERSION_3_2_0: () = (); diff --git a/regenerate.sh b/regenerate.sh index 0173496..37ec4bc 100755 --- a/regenerate.sh +++ b/regenerate.sh @@ -16,9 +16,11 @@ case "$protoc_ver" in esac cargo build --manifest-path=../protobuf-codegen/Cargo.toml -cargo build --manifest-path=../protoc-bin-vendored/Cargo.toml --bin protoc-bin-which +cargo build --manifest-path=../protoc-bin/Cargo.toml --bin protoc-bin-print-paths -PROTOC=$(cargo run --manifest-path=../protoc-bin-vendored/Cargo.toml --bin protoc-bin-which) +eval "$(cargo run --manifest-path=../protoc-bin/Cargo.toml --bin protoc-bin-print-paths)" + +test -n "$PROTOC" where_am_i=$( cd .. @@ -40,35 +42,20 @@ esac "$PROTOC" \ --plugin=protoc-gen-rust="$where_am_i/target/debug/protoc-gen-rust$exe_suffix" \ --rust_out tmp-generated \ - --rust_opt 'serde_derive=true inside_protobuf=true' \ + --rust_opt 'inside_protobuf=true gen_mod_rs=false' \ -I../proto \ - -I../protoc-bin-vendored/include \ - ../protoc-bin-vendored/include/google/protobuf/*.proto \ - ../protoc-bin-vendored/include/google/protobuf/compiler/* \ - ../proto/rustproto.proto - -mv tmp-generated/descriptor.rs tmp-generated/plugin.rs tmp-generated/rustproto.rs src/ + ../proto/google/protobuf/*.proto \ + ../proto/google/protobuf/compiler/*.proto \ + ../proto/rustproto.proto \ + ../proto/doctest_pb.proto + +mv \ + tmp-generated/descriptor.rs \ + tmp-generated/plugin.rs \ + tmp-generated/rustproto.rs \ + tmp-generated/doctest_pb.rs \ + src/ +mv tmp-generated/well_known_types_mod.rs src/well_known_types/mod.rs mv tmp-generated/*.rs src/well_known_types/ -( - cd src/well_known_types - exec >mod.rs - echo "// This file is generated. Do not edit" - echo '//! Generated code for "well known types"' - echo "//!" - echo "//! [This document](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf) describes these types." - - mod_list() { - # shellcheck disable=SC2010 - ls | grep -v mod.rs | sed -e 's,\.rs$,,' - } - - echo - mod_list | sed -e 's,^,mod ,; s,$,;,' - - echo - mod_list | while read -r mod; do - echo "pub use self::$mod::*;" - done -) # vim: set ts=4 sw=4 et: diff --git a/src/any.rs b/src/any.rs deleted file mode 100644 index 31ddd82..0000000 --- a/src/any.rs +++ /dev/null @@ -1,114 +0,0 @@ -use crate::parse_from_bytes; -use crate::reflect::MessageDescriptor; -use crate::well_known_types::Any; -use crate::Message; -use crate::ProtobufResult; - -impl Any { - fn type_url(type_url_prefix: &str, descriptor: &MessageDescriptor) -> String { - format!("{}/{}", type_url_prefix, descriptor.full_name()) - } - - fn get_type_name_from_type_url(type_url: &str) -> Option<&str> { - match type_url.rfind('/') { - Some(i) => Some(&type_url[i + 1..]), - None => None, - } - } - - /// Pack any message into `well_known_types::Any` value. - /// - /// # Examples - /// - /// ``` - /// # use protobuf::Message; - /// # use protobuf::ProtobufResult; - /// use protobuf::well_known_types::Any; - /// - /// # fn the_test<MyMessage: Message>(message: &MyMessage) -> ProtobufResult<()> { - /// let message: &MyMessage = message; - /// let any = Any::pack(message)?; - /// assert!(any.is::<MyMessage>()); - /// # Ok(()) - /// # } - /// ``` - pub fn pack<M: Message>(message: &M) -> ProtobufResult<Any> { - Any::pack_dyn(message) - } - - /// Pack any message into `well_known_types::Any` value. - /// - /// # Examples - /// - /// ``` - /// use protobuf::Message; - /// # use protobuf::ProtobufResult; - /// use protobuf::well_known_types::Any; - /// - /// # fn the_test(message: &dyn Message) -> ProtobufResult<()> { - /// let message: &dyn Message = message; - /// let any = Any::pack_dyn(message)?; - /// assert!(any.is_dyn(message.descriptor())); - /// # Ok(()) - /// # } - /// ``` - pub fn pack_dyn(message: &dyn Message) -> ProtobufResult<Any> { - Any::pack_with_type_url_prefix(message, "type.googleapis.com") - } - - fn pack_with_type_url_prefix( - message: &dyn Message, - type_url_prefix: &str, - ) -> ProtobufResult<Any> { - Ok(Any { - type_url: Any::type_url(type_url_prefix, message.descriptor()), - value: message.write_to_bytes()?, - ..Default::default() - }) - } - - /// Check if `Any` contains a message of given type. - pub fn is<M: Message>(&self) -> bool { - self.is_dyn(M::descriptor_static()) - } - - /// Check if `Any` contains a message of given type. - pub fn is_dyn(&self, descriptor: &MessageDescriptor) -> bool { - match Any::get_type_name_from_type_url(&self.type_url) { - Some(type_name) => type_name == descriptor.full_name(), - None => false, - } - } - - /// Extract a message from this `Any`. - /// - /// # Returns - /// - /// * `Ok(None)` when message type mismatch - /// * `Err` when parse failed - pub fn unpack<M: Message>(&self) -> ProtobufResult<Option<M>> { - if !self.is::<M>() { - return Ok(None); - } - Ok(Some(parse_from_bytes(&self.value)?)) - } - - /// Extract a message from this `Any`. - /// - /// # Returns - /// - /// * `Ok(None)` when message type mismatch - /// * `Err` when parse failed - pub fn unpack_dyn( - &self, - descriptor: &MessageDescriptor, - ) -> ProtobufResult<Option<Box<dyn Message>>> { - if !self.is_dyn(descriptor) { - return Ok(None); - } - let mut message = descriptor.new_instance(); - message.merge_from_bytes(&self.value)?; - message.check_initialized()?; - Ok(Some(message)) - } -} diff --git a/src/byteorder.rs b/src/byteorder.rs new file mode 100644 index 0000000..364af6e --- /dev/null +++ b/src/byteorder.rs @@ -0,0 +1,2 @@ +/// Expose cfg as constant to be able to typecheck both versions. +pub(crate) const LITTLE_ENDIAN: bool = cfg!(target_endian = "little"); diff --git a/src/cached_size.rs b/src/cached_size.rs index 350ddac..3919b99 100644 --- a/src/cached_size.rs +++ b/src/cached_size.rs @@ -1,15 +1,27 @@ +use std::hash::Hash; +use std::hash::Hasher; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; /// Cached size field used in generated code. +/// /// It is always equal to itself to simplify generated code. /// (Generated code can use `#[derive(Eq)]`). +/// +/// This type should rarely be used directly. #[derive(Debug, Default)] pub struct CachedSize { size: AtomicUsize, } impl CachedSize { + /// Create a new `CachedSize` object. + pub const fn new() -> CachedSize { + CachedSize { + size: AtomicUsize::new(0), + } + } + /// Get cached size pub fn get(&self) -> u32 { self.size.load(Ordering::Relaxed) as u32 @@ -36,3 +48,9 @@ impl PartialEq<CachedSize> for CachedSize { } impl Eq for CachedSize {} + +impl Hash for CachedSize { + fn hash<H: Hasher>(&self, _state: &mut H) { + // ignore cached size in cache computation + } +} diff --git a/src/chars.rs b/src/chars.rs index 49c02d7..9a2109e 100644 --- a/src/chars.rs +++ b/src/chars.rs @@ -1,13 +1,12 @@ #![cfg(feature = "bytes")] +use std::borrow::Borrow; use std::fmt; use std::ops::Deref; use std::str; use bytes::Bytes; -use crate::clear::Clear; - /// Thin wrapper around `Bytes` which guarantees that bytes are valid UTF-8 string. /// Should be API-compatible to `String`. #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -15,10 +14,15 @@ pub struct Chars(Bytes); impl Chars { /// New empty object. - pub fn new() -> Chars { + pub const fn new() -> Chars { Chars(Bytes::new()) } + /// Clear the buffer. + pub fn clear(&mut self) { + self.0.clear(); + } + /// Try convert from `Bytes` pub fn from_bytes(bytes: Bytes) -> Result<Chars, str::Utf8Error> { str::from_utf8(&bytes)?; @@ -71,9 +75,9 @@ impl Deref for Chars { } } -impl Clear for Chars { - fn clear(&mut self) { - self.0.clear(); +impl Borrow<str> for Chars { + fn borrow(&self) -> &str { + &*self } } @@ -96,6 +100,7 @@ mod test { use super::Chars; #[test] + #[cfg_attr(miri, ignore)] // bytes violates SB, see https://github.com/tokio-rs/bytes/issues/522 fn test_display_and_debug() { let s = "test"; let string: String = s.into(); diff --git a/src/clear.rs b/src/clear.rs deleted file mode 100644 index 712c492..0000000 --- a/src/clear.rs +++ /dev/null @@ -1,33 +0,0 @@ -#[cfg(feature = "bytes")] -use bytes::Bytes; - -/// anything that can be cleared -pub trait Clear { - /// Clear this make, make it equivalent to newly created object. - fn clear(&mut self); -} - -impl<T> Clear for Option<T> { - fn clear(&mut self) { - self.take(); - } -} - -impl Clear for String { - fn clear(&mut self) { - String::clear(self); - } -} - -impl<T> Clear for Vec<T> { - fn clear(&mut self) { - Vec::clear(self); - } -} - -#[cfg(feature = "bytes")] -impl Clear for Bytes { - fn clear(&mut self) { - Bytes::clear(self); - } -} diff --git a/src/coded_input_stream.rs b/src/coded_input_stream.rs deleted file mode 100644 index a49563c..0000000 --- a/src/coded_input_stream.rs +++ /dev/null @@ -1,976 +0,0 @@ -#![doc(hidden)] - -//! `CodedInputStream` and `CodedOutputStream` implementations - -use std::io; -use std::io::BufRead; -use std::io::Read; -use std::mem; -use std::mem::MaybeUninit; -use std::slice; - -#[cfg(feature = "bytes")] -use bytes::Bytes; - -use crate::buf_read_iter::BufReadIter; -#[cfg(feature = "bytes")] -use crate::chars::Chars; -use crate::enums::ProtobufEnum; -use crate::error::ProtobufError; -use crate::error::ProtobufResult; -use crate::error::WireError; -use crate::message::Message; -use crate::misc::maybe_ununit_array_assume_init; -use crate::unknown::UnknownValue; -use crate::wire_format; -use crate::zigzag::decode_zig_zag_32; -use crate::zigzag::decode_zig_zag_64; - -/// Default recursion level limit. 100 is the default value of C++'s implementation. -const DEFAULT_RECURSION_LIMIT: u32 = 100; - -/// Max allocated vec when reading length-delimited from unknown input stream -pub(crate) const READ_RAW_BYTES_MAX_ALLOC: usize = 10_000_000; - -/// Buffered read with handy utilities. -pub struct CodedInputStream<'a> { - source: BufReadIter<'a>, - recursion_level: u32, - recursion_limit: u32, -} - -impl<'a> CodedInputStream<'a> { - /// Wrap a `Read`. - /// - /// Note resulting `CodedInputStream` is buffered even if `Read` is not. - pub fn new(read: &'a mut dyn Read) -> CodedInputStream<'a> { - CodedInputStream::from_buf_read_iter(BufReadIter::from_read(read)) - } - - /// Create from `BufRead`. - /// - /// `CodedInputStream` will utilize `BufRead` buffer. - pub fn from_buffered_reader(buf_read: &'a mut dyn BufRead) -> CodedInputStream<'a> { - CodedInputStream::from_buf_read_iter(BufReadIter::from_buf_read(buf_read)) - } - - /// Read from byte slice - pub fn from_bytes(bytes: &'a [u8]) -> CodedInputStream<'a> { - CodedInputStream::from_buf_read_iter(BufReadIter::from_byte_slice(bytes)) - } - - /// Read from `Bytes`. - /// - /// `CodedInputStream` operations like - /// [`read_carllerche_bytes`](crate::CodedInputStream::read_carllerche_bytes) - /// will return a shared copy of this bytes object. - #[cfg(feature = "bytes")] - pub fn from_carllerche_bytes(bytes: &'a Bytes) -> CodedInputStream<'a> { - CodedInputStream::from_buf_read_iter(BufReadIter::from_bytes(bytes)) - } - - fn from_buf_read_iter(source: BufReadIter<'a>) -> CodedInputStream<'a> { - CodedInputStream { - source: source, - recursion_level: 0, - recursion_limit: DEFAULT_RECURSION_LIMIT, - } - } - - /// Set the recursion limit. - pub fn set_recursion_limit(&mut self, limit: u32) { - self.recursion_limit = limit; - } - - #[inline] - pub(crate) fn incr_recursion(&mut self) -> ProtobufResult<()> { - if self.recursion_level >= self.recursion_limit { - return Err(ProtobufError::WireError(WireError::OverRecursionLimit)); - } - self.recursion_level += 1; - Ok(()) - } - - #[inline] - pub(crate) fn decr_recursion(&mut self) { - self.recursion_level -= 1; - } - - /// How many bytes processed - pub fn pos(&self) -> u64 { - self.source.pos() - } - - /// How many bytes until current limit - pub fn bytes_until_limit(&self) -> u64 { - self.source.bytes_until_limit() - } - - /// Read bytes into given `buf`. - #[inline] - fn read_exact_uninit(&mut self, buf: &mut [MaybeUninit<u8>]) -> ProtobufResult<()> { - self.source.read_exact(buf) - } - - /// Read bytes into given `buf`. - /// - /// Return `0` on EOF. - // TODO: overload with `Read::read` - pub fn read(&mut self, buf: &mut [u8]) -> ProtobufResult<()> { - // SAFETY: same layout - let buf = unsafe { - slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut MaybeUninit<u8>, buf.len()) - }; - self.read_exact_uninit(buf) - } - - /// Read exact number of bytes as `Bytes` object. - /// - /// This operation returns a shared view if `CodedInputStream` is - /// constructed with `Bytes` parameter. - #[cfg(feature = "bytes")] - fn read_raw_callerche_bytes(&mut self, count: usize) -> ProtobufResult<Bytes> { - self.source.read_exact_bytes(count) - } - - /// Read one byte - #[inline(always)] - pub fn read_raw_byte(&mut self) -> ProtobufResult<u8> { - self.source.read_byte() - } - - /// Push new limit, return previous limit. - pub fn push_limit(&mut self, limit: u64) -> ProtobufResult<u64> { - self.source.push_limit(limit) - } - - /// Restore previous limit. - pub fn pop_limit(&mut self, old_limit: u64) { - self.source.pop_limit(old_limit); - } - - /// Are we at EOF? - #[inline(always)] - pub fn eof(&mut self) -> ProtobufResult<bool> { - self.source.eof() - } - - /// Check we are at EOF. - /// - /// Return error if we are not at EOF. - pub fn check_eof(&mut self) -> ProtobufResult<()> { - let eof = self.eof()?; - if !eof { - return Err(ProtobufError::WireError(WireError::UnexpectedEof)); - } - Ok(()) - } - - fn read_raw_varint64_slow(&mut self) -> ProtobufResult<u64> { - let mut r: u64 = 0; - let mut i = 0; - loop { - if i == 10 { - return Err(ProtobufError::WireError(WireError::IncorrectVarint)); - } - let b = self.read_raw_byte()?; - // TODO: may overflow if i == 9 - r = r | (((b & 0x7f) as u64) << (i * 7)); - i += 1; - if b < 0x80 { - return Ok(r); - } - } - } - - /// Read varint - #[inline(always)] - pub fn read_raw_varint64(&mut self) -> ProtobufResult<u64> { - 'slow: loop { - let ret; - let consume; - - loop { - let rem = self.source.remaining_in_buf(); - - if rem.len() >= 1 { - // most varints are in practice fit in 1 byte - if rem[0] < 0x80 { - ret = rem[0] as u64; - consume = 1; - } else { - // handle case of two bytes too - if rem.len() >= 2 && rem[1] < 0x80 { - ret = (rem[0] & 0x7f) as u64 | (rem[1] as u64) << 7; - consume = 2; - } else if rem.len() >= 10 { - // Read from array when buf at at least 10 bytes, - // max len for varint. - let mut r: u64 = 0; - let mut i: usize = 0; - { - let rem = rem; - loop { - if i == 10 { - return Err(ProtobufError::WireError( - WireError::IncorrectVarint, - )); - } - - let b = if true { - // skip range check - unsafe { *rem.get_unchecked(i) } - } else { - rem[i] - }; - - // TODO: may overflow if i == 9 - r = r | (((b & 0x7f) as u64) << (i * 7)); - i += 1; - if b < 0x80 { - break; - } - } - } - consume = i; - ret = r; - } else { - break 'slow; - } - } - } else { - break 'slow; - } - break; - } - - self.source.consume(consume); - return Ok(ret); - } - - self.read_raw_varint64_slow() - } - - /// Read varint - #[inline(always)] - pub fn read_raw_varint32(&mut self) -> ProtobufResult<u32> { - self.read_raw_varint64().map(|v| v as u32) - } - - /// Read little-endian 32-bit integer - pub fn read_raw_little_endian32(&mut self) -> ProtobufResult<u32> { - let mut bytes = [MaybeUninit::uninit(); 4]; - self.read_exact_uninit(&mut bytes)?; - // SAFETY: `read_exact` guarantees that the buffer is filled. - let bytes = unsafe { maybe_ununit_array_assume_init(bytes) }; - Ok(u32::from_le_bytes(bytes)) - } - - /// Read little-endian 64-bit integer - pub fn read_raw_little_endian64(&mut self) -> ProtobufResult<u64> { - let mut bytes = [MaybeUninit::uninit(); 8]; - self.read_exact_uninit(&mut bytes)?; - // SAFETY: `read_exact` guarantees that the buffer is filled. - let bytes = unsafe { maybe_ununit_array_assume_init(bytes) }; - Ok(u64::from_le_bytes(bytes)) - } - - /// Read tag - #[inline] - pub fn read_tag(&mut self) -> ProtobufResult<wire_format::Tag> { - let v = self.read_raw_varint32()?; - match wire_format::Tag::new(v) { - Some(tag) => Ok(tag), - None => Err(ProtobufError::WireError(WireError::IncorrectTag(v))), - } - } - - /// Read tag, return it is pair (field number, wire type) - #[inline] - pub fn read_tag_unpack(&mut self) -> ProtobufResult<(u32, wire_format::WireType)> { - self.read_tag().map(|t| t.unpack()) - } - - /// Read `double` - pub fn read_double(&mut self) -> ProtobufResult<f64> { - let bits = self.read_raw_little_endian64()?; - unsafe { Ok(mem::transmute::<u64, f64>(bits)) } - } - - /// Read `float` - pub fn read_float(&mut self) -> ProtobufResult<f32> { - let bits = self.read_raw_little_endian32()?; - unsafe { Ok(mem::transmute::<u32, f32>(bits)) } - } - - /// Read `int64` - pub fn read_int64(&mut self) -> ProtobufResult<i64> { - self.read_raw_varint64().map(|v| v as i64) - } - - /// Read `int32` - pub fn read_int32(&mut self) -> ProtobufResult<i32> { - self.read_raw_varint32().map(|v| v as i32) - } - - /// Read `uint64` - pub fn read_uint64(&mut self) -> ProtobufResult<u64> { - self.read_raw_varint64() - } - - /// Read `uint32` - pub fn read_uint32(&mut self) -> ProtobufResult<u32> { - self.read_raw_varint32() - } - - /// Read `sint64` - pub fn read_sint64(&mut self) -> ProtobufResult<i64> { - self.read_uint64().map(decode_zig_zag_64) - } - - /// Read `sint32` - pub fn read_sint32(&mut self) -> ProtobufResult<i32> { - self.read_uint32().map(decode_zig_zag_32) - } - - /// Read `fixed64` - pub fn read_fixed64(&mut self) -> ProtobufResult<u64> { - self.read_raw_little_endian64() - } - - /// Read `fixed32` - pub fn read_fixed32(&mut self) -> ProtobufResult<u32> { - self.read_raw_little_endian32() - } - - /// Read `sfixed64` - pub fn read_sfixed64(&mut self) -> ProtobufResult<i64> { - self.read_raw_little_endian64().map(|v| v as i64) - } - - /// Read `sfixed32` - pub fn read_sfixed32(&mut self) -> ProtobufResult<i32> { - self.read_raw_little_endian32().map(|v| v as i32) - } - - /// Read `bool` - pub fn read_bool(&mut self) -> ProtobufResult<bool> { - self.read_raw_varint32().map(|v| v != 0) - } - - /// Read `enum` as `ProtobufEnum` - pub fn read_enum<E: ProtobufEnum>(&mut self) -> ProtobufResult<E> { - let i = self.read_int32()?; - match ProtobufEnum::from_i32(i) { - Some(e) => Ok(e), - None => Err(ProtobufError::WireError(WireError::InvalidEnumValue(i))), - } - } - - /// Read `repeated` packed `double` - pub fn read_repeated_packed_double_into( - &mut self, - target: &mut Vec<f64>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 4) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_double()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read `repeated` packed `float` - pub fn read_repeated_packed_float_into(&mut self, target: &mut Vec<f32>) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 4) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_float()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read `repeated` packed `int64` - pub fn read_repeated_packed_int64_into(&mut self, target: &mut Vec<i64>) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len as u64)?; - while !self.eof()? { - target.push(self.read_int64()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `int32` - pub fn read_repeated_packed_int32_into(&mut self, target: &mut Vec<i32>) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_int32()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `uint64` - pub fn read_repeated_packed_uint64_into( - &mut self, - target: &mut Vec<u64>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_uint64()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `uint32` - pub fn read_repeated_packed_uint32_into( - &mut self, - target: &mut Vec<u32>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_uint32()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `sint64` - pub fn read_repeated_packed_sint64_into( - &mut self, - target: &mut Vec<i64>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_sint64()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `sint32` - pub fn read_repeated_packed_sint32_into( - &mut self, - target: &mut Vec<i32>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_sint32()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `fixed64` - pub fn read_repeated_packed_fixed64_into( - &mut self, - target: &mut Vec<u64>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 8) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_fixed64()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `fixed32` - pub fn read_repeated_packed_fixed32_into( - &mut self, - target: &mut Vec<u32>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 4) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_fixed32()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `sfixed64` - pub fn read_repeated_packed_sfixed64_into( - &mut self, - target: &mut Vec<i64>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 8) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_sfixed64()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `sfixed32` - pub fn read_repeated_packed_sfixed32_into( - &mut self, - target: &mut Vec<i32>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - target.reserve((len / 4) as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_sfixed32()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `bool` - pub fn read_repeated_packed_bool_into(&mut self, target: &mut Vec<bool>) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - - // regular bool value is 1-byte size - target.reserve(len as usize); - - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_bool()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read repeated packed `enum` into `ProtobufEnum` - pub fn read_repeated_packed_enum_into<E: ProtobufEnum>( - &mut self, - target: &mut Vec<E>, - ) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - while !self.eof()? { - target.push(self.read_enum()?); - } - self.pop_limit(old_limit); - Ok(()) - } - - /// Read `UnknownValue` - pub fn read_unknown( - &mut self, - wire_type: wire_format::WireType, - ) -> ProtobufResult<UnknownValue> { - match wire_type { - wire_format::WireTypeVarint => { - self.read_raw_varint64().map(|v| UnknownValue::Varint(v)) - } - wire_format::WireTypeFixed64 => self.read_fixed64().map(|v| UnknownValue::Fixed64(v)), - wire_format::WireTypeFixed32 => self.read_fixed32().map(|v| UnknownValue::Fixed32(v)), - wire_format::WireTypeLengthDelimited => { - let len = self.read_raw_varint32()?; - self.read_raw_bytes(len) - .map(|v| UnknownValue::LengthDelimited(v)) - } - _ => Err(ProtobufError::WireError(WireError::UnexpectedWireType( - wire_type, - ))), - } - } - - /// Skip field - pub fn skip_field(&mut self, wire_type: wire_format::WireType) -> ProtobufResult<()> { - self.read_unknown(wire_type).map(|_| ()) - } - - /// Read raw bytes into the supplied vector. The vector will be resized as needed and - /// overwritten. - pub fn read_raw_bytes_into(&mut self, count: u32, target: &mut Vec<u8>) -> ProtobufResult<()> { - self.source.read_exact_to_vec(count as usize, target) - } - - /// Read exact number of bytes - pub fn read_raw_bytes(&mut self, count: u32) -> ProtobufResult<Vec<u8>> { - let mut r = Vec::new(); - self.read_raw_bytes_into(count, &mut r)?; - Ok(r) - } - - /// Skip exact number of bytes - pub fn skip_raw_bytes(&mut self, count: u32) -> ProtobufResult<()> { - // TODO: make it more efficient - self.read_raw_bytes(count).map(|_| ()) - } - - /// Read `bytes` field, length delimited - pub fn read_bytes(&mut self) -> ProtobufResult<Vec<u8>> { - let mut r = Vec::new(); - self.read_bytes_into(&mut r)?; - Ok(r) - } - - /// Read `bytes` field, length delimited - #[cfg(feature = "bytes")] - pub fn read_carllerche_bytes(&mut self) -> ProtobufResult<Bytes> { - let len = self.read_raw_varint32()?; - self.read_raw_callerche_bytes(len as usize) - } - - /// Read `string` field, length delimited - #[cfg(feature = "bytes")] - pub fn read_carllerche_chars(&mut self) -> ProtobufResult<Chars> { - let bytes = self.read_carllerche_bytes()?; - Ok(Chars::from_bytes(bytes)?) - } - - /// Read `bytes` field, length delimited - pub fn read_bytes_into(&mut self, target: &mut Vec<u8>) -> ProtobufResult<()> { - let len = self.read_raw_varint32()?; - self.read_raw_bytes_into(len, target)?; - Ok(()) - } - - /// Read `string` field, length delimited - pub fn read_string(&mut self) -> ProtobufResult<String> { - let mut r = String::new(); - self.read_string_into(&mut r)?; - Ok(r) - } - - /// Read `string` field, length delimited - pub fn read_string_into(&mut self, target: &mut String) -> ProtobufResult<()> { - target.clear(); - // take target's buffer - let mut vec = mem::replace(target, String::new()).into_bytes(); - self.read_bytes_into(&mut vec)?; - - let s = match String::from_utf8(vec) { - Ok(t) => t, - Err(_) => return Err(ProtobufError::WireError(WireError::Utf8Error)), - }; - *target = s; - Ok(()) - } - - /// Read message, do not check if message is initialized - pub fn merge_message<M: Message>(&mut self, message: &mut M) -> ProtobufResult<()> { - let len = self.read_raw_varint64()?; - let old_limit = self.push_limit(len)?; - message.merge_from(self)?; - self.pop_limit(old_limit); - Ok(()) - } - - /// Read message - pub fn read_message<M: Message>(&mut self) -> ProtobufResult<M> { - let mut r: M = Message::new(); - self.merge_message(&mut r)?; - r.check_initialized()?; - Ok(r) - } -} - -impl<'a> Read for CodedInputStream<'a> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.source.read(buf).map_err(Into::into) - } -} - -impl<'a> BufRead for CodedInputStream<'a> { - fn fill_buf(&mut self) -> io::Result<&[u8]> { - self.source.fill_buf().map_err(Into::into) - } - - fn consume(&mut self, amt: usize) { - self.source.consume(amt) - } -} - -/// Helper internal utility, should not be used directly -#[doc(hidden)] -pub trait WithCodedInputStream { - fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>; -} - -impl<'a> WithCodedInputStream for &'a mut (dyn Read + 'a) { - fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>, - { - let mut is = CodedInputStream::new(self); - let r = cb(&mut is)?; - is.check_eof()?; - Ok(r) - } -} - -impl<'a> WithCodedInputStream for &'a mut (dyn BufRead + 'a) { - fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>, - { - let mut is = CodedInputStream::from_buffered_reader(self); - let r = cb(&mut is)?; - is.check_eof()?; - Ok(r) - } -} - -impl<'a> WithCodedInputStream for &'a [u8] { - fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>, - { - let mut is = CodedInputStream::from_bytes(self); - let r = cb(&mut is)?; - is.check_eof()?; - Ok(r) - } -} - -#[cfg(feature = "bytes")] -impl<'a> WithCodedInputStream for &'a Bytes { - fn with_coded_input_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedInputStream) -> ProtobufResult<T>, - { - let mut is = CodedInputStream::from_carllerche_bytes(self); - let r = cb(&mut is)?; - is.check_eof()?; - Ok(r) - } -} - -#[cfg(test)] -mod test { - - use std::fmt::Debug; - use std::io; - use std::io::BufRead; - use std::io::Read; - - use super::CodedInputStream; - use super::READ_RAW_BYTES_MAX_ALLOC; - use crate::error::ProtobufError; - use crate::error::ProtobufResult; - use crate::hex::decode_hex; - - fn test_read_partial<F>(hex: &str, mut callback: F) - where - F: FnMut(&mut CodedInputStream), - { - let d = decode_hex(hex); - let mut reader = io::Cursor::new(d); - let mut is = CodedInputStream::from_buffered_reader(&mut reader as &mut dyn BufRead); - assert_eq!(0, is.pos()); - callback(&mut is); - } - - fn test_read<F>(hex: &str, mut callback: F) - where - F: FnMut(&mut CodedInputStream), - { - let len = decode_hex(hex).len(); - test_read_partial(hex, |reader| { - callback(reader); - assert!(reader.eof().expect("eof")); - assert_eq!(len as u64, reader.pos()); - }); - } - - fn test_read_v<F, V>(hex: &str, v: V, mut callback: F) - where - F: FnMut(&mut CodedInputStream) -> ProtobufResult<V>, - V: PartialEq + Debug, - { - test_read(hex, |reader| { - assert_eq!(v, callback(reader).unwrap()); - }); - } - - #[test] - fn test_input_stream_read_raw_byte() { - test_read("17", |is| { - assert_eq!(23, is.read_raw_byte().unwrap()); - }); - } - - #[test] - fn test_input_stream_read_raw_varint() { - test_read_v("07", 7, |reader| reader.read_raw_varint32()); - test_read_v("07", 7, |reader| reader.read_raw_varint64()); - - test_read_v("96 01", 150, |reader| reader.read_raw_varint32()); - test_read_v("96 01", 150, |reader| reader.read_raw_varint64()); - - test_read_v( - "ff ff ff ff ff ff ff ff ff 01", - 0xffffffffffffffff, - |reader| reader.read_raw_varint64(), - ); - - test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| { - reader.read_raw_varint32() - }); - test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| { - reader.read_raw_varint64() - }); - } - - #[test] - fn test_input_stream_read_raw_vaint_malformed() { - // varint cannot have length > 10 - test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| { - let result = reader.read_raw_varint64(); - match result { - // TODO: make an enum variant - Err(ProtobufError::WireError(..)) => (), - _ => panic!(), - } - }); - test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| { - let result = reader.read_raw_varint32(); - match result { - // TODO: make an enum variant - Err(ProtobufError::WireError(..)) => (), - _ => panic!(), - } - }); - } - - #[test] - fn test_input_stream_read_raw_varint_unexpected_eof() { - test_read_partial("96 97", |reader| { - let result = reader.read_raw_varint32(); - match result { - Err(ProtobufError::WireError(..)) => (), - _ => panic!(), - } - }); - } - - #[test] - fn test_input_stream_read_raw_varint_pos() { - test_read_partial("95 01 98", |reader| { - assert_eq!(149, reader.read_raw_varint32().unwrap()); - assert_eq!(2, reader.pos()); - }); - } - - #[test] - fn test_input_stream_read_int32() { - test_read_v("02", 2, |reader| reader.read_int32()); - } - - #[test] - fn test_input_stream_read_float() { - test_read_v("95 73 13 61", 17e19, |is| is.read_float()); - } - - #[test] - fn test_input_stream_read_double() { - test_read_v("40 d5 ab 68 b3 07 3d 46", 23e29, |is| is.read_double()); - } - - #[test] - fn test_input_stream_skip_raw_bytes() { - test_read("", |reader| { - reader.skip_raw_bytes(0).unwrap(); - }); - test_read("aa bb", |reader| { - reader.skip_raw_bytes(2).unwrap(); - }); - test_read("aa bb cc dd ee ff", |reader| { - reader.skip_raw_bytes(6).unwrap(); - }); - } - - #[test] - fn test_input_stream_read_raw_bytes() { - test_read("", |reader| { - assert_eq!( - Vec::from(&b""[..]), - reader.read_raw_bytes(0).expect("read_raw_bytes") - ); - }) - } - - #[test] - fn test_input_stream_limits() { - test_read("aa bb cc", |is| { - let old_limit = is.push_limit(1).unwrap(); - assert_eq!(1, is.bytes_until_limit()); - let r1 = is.read_raw_bytes(1).unwrap(); - assert_eq!(&[0xaa as u8], &r1[..]); - is.pop_limit(old_limit); - let r2 = is.read_raw_bytes(2).unwrap(); - assert_eq!(&[0xbb as u8, 0xcc], &r2[..]); - }); - } - - #[test] - fn test_input_stream_io_read() { - test_read("aa bb cc", |is| { - let mut buf = [0; 3]; - assert_eq!(Read::read(is, &mut buf).expect("io::Read"), 3); - assert_eq!(buf, [0xaa, 0xbb, 0xcc]); - }); - } - - #[test] - fn test_input_stream_io_bufread() { - test_read("aa bb cc", |is| { - assert_eq!( - BufRead::fill_buf(is).expect("io::BufRead::fill_buf"), - &[0xaa, 0xbb, 0xcc] - ); - BufRead::consume(is, 3); - }); - } - - #[test] - fn test_input_stream_read_raw_bytes_into_huge() { - let mut v = Vec::new(); - for i in 0..READ_RAW_BYTES_MAX_ALLOC + 1000 { - v.push((i % 10) as u8); - } - - let mut slice: &[u8] = v.as_slice(); - - let mut is = CodedInputStream::new(&mut slice); - - let mut buf = Vec::new(); - - is.read_raw_bytes_into(READ_RAW_BYTES_MAX_ALLOC as u32 + 10, &mut buf) - .expect("read"); - - assert_eq!(READ_RAW_BYTES_MAX_ALLOC + 10, buf.len()); - - buf.clear(); - - is.read_raw_bytes_into(1000 - 10, &mut buf).expect("read"); - - assert_eq!(1000 - 10, buf.len()); - - assert!(is.eof().expect("eof")); - } -} diff --git a/src/buf_read_iter.rs b/src/coded_input_stream/buf_read_iter.rs index ff1fce2..94109f2 100644 --- a/src/buf_read_iter.rs +++ b/src/coded_input_stream/buf_read_iter.rs @@ -4,7 +4,6 @@ use std::io::BufReader; use std::io::Read; use std::mem; use std::mem::MaybeUninit; -use std::u64; #[cfg(feature = "bytes")] use bytes::buf::UninitSlice; @@ -15,30 +14,19 @@ use bytes::Bytes; #[cfg(feature = "bytes")] use bytes::BytesMut; -use crate::buf_read_or_reader::BufReadOrReader; +use crate::coded_input_stream::buf_read_or_reader::BufReadOrReader; +use crate::coded_input_stream::input_buf::InputBuf; +use crate::coded_input_stream::input_source::InputSource; use crate::coded_input_stream::READ_RAW_BYTES_MAX_ALLOC; +use crate::error::ProtobufError; use crate::error::WireError; -use crate::misc::maybe_uninit_write_slice; -use crate::misc::vec_spare_capacity_mut; -use crate::ProtobufError; -use crate::ProtobufResult; // If an input stream is constructed with a `Read`, we create a // `BufReader` with an internal buffer of this size. const INPUT_STREAM_BUFFER_SIZE: usize = 4096; -const USE_UNSAFE_FOR_SPEED: bool = true; - const NO_LIMIT: u64 = u64::MAX; -/// Hold all possible combinations of input source -enum InputSource<'a> { - Read(BufReadOrReader<'a>), - Slice(&'a [u8]), - #[cfg(feature = "bytes")] - Bytes(&'a Bytes), -} - /// Dangerous implementation of `BufRead`. /// /// Unsafe wrapper around BufRead which assumes that `BufRead` buf is @@ -53,11 +41,10 @@ enum InputSource<'a> { /// It is important for `CodedInputStream` performance that small reads /// (e. g. 4 bytes reads) do not involve virtual calls or switches. /// This is achievable with `BufReadIter`. +#[derive(Debug)] pub(crate) struct BufReadIter<'a> { input_source: InputSource<'a>, - buf: &'a [u8], - pos_within_buf: usize, - limit_within_buf: usize, + buf: InputBuf<'a>, pos_of_buf_start: u64, limit: u64, } @@ -65,56 +52,48 @@ pub(crate) struct BufReadIter<'a> { impl<'a> Drop for BufReadIter<'a> { fn drop(&mut self) { match self.input_source { - InputSource::Read(ref mut buf_read) => buf_read.consume(self.pos_within_buf), + InputSource::Read(ref mut buf_read) => buf_read.consume(self.buf.pos_within_buf()), _ => {} } } } -impl<'ignore> BufReadIter<'ignore> { - pub(crate) fn from_read<'a>(read: &'a mut dyn Read) -> BufReadIter<'a> { +impl<'a> BufReadIter<'a> { + pub(crate) fn from_read(read: &'a mut dyn Read) -> BufReadIter<'a> { BufReadIter { input_source: InputSource::Read(BufReadOrReader::BufReader(BufReader::with_capacity( INPUT_STREAM_BUFFER_SIZE, read, ))), - buf: &[], - pos_within_buf: 0, - limit_within_buf: 0, + buf: InputBuf::empty(), pos_of_buf_start: 0, limit: NO_LIMIT, } } - pub(crate) fn from_buf_read<'a>(buf_read: &'a mut dyn BufRead) -> BufReadIter<'a> { + pub(crate) fn from_buf_read(buf_read: &'a mut dyn BufRead) -> BufReadIter<'a> { BufReadIter { input_source: InputSource::Read(BufReadOrReader::BufRead(buf_read)), - buf: &[], - pos_within_buf: 0, - limit_within_buf: 0, + buf: InputBuf::empty(), pos_of_buf_start: 0, limit: NO_LIMIT, } } - pub(crate) fn from_byte_slice<'a>(bytes: &'a [u8]) -> BufReadIter<'a> { + pub(crate) fn from_byte_slice(bytes: &'a [u8]) -> BufReadIter<'a> { BufReadIter { input_source: InputSource::Slice(bytes), - buf: bytes, - pos_within_buf: 0, - limit_within_buf: bytes.len(), + buf: InputBuf::from_bytes(bytes), pos_of_buf_start: 0, limit: NO_LIMIT, } } #[cfg(feature = "bytes")] - pub(crate) fn from_bytes<'a>(bytes: &'a Bytes) -> BufReadIter<'a> { + pub(crate) fn from_bytes(bytes: &'a Bytes) -> BufReadIter<'a> { BufReadIter { input_source: InputSource::Bytes(bytes), - buf: &bytes, - pos_within_buf: 0, - limit_within_buf: bytes.len(), + buf: InputBuf::from_bytes(&bytes), pos_of_buf_start: 0, limit: NO_LIMIT, } @@ -122,36 +101,31 @@ impl<'ignore> BufReadIter<'ignore> { #[inline] fn assertions(&self) { - debug_assert!(self.pos_within_buf <= self.limit_within_buf); - debug_assert!(self.limit_within_buf <= self.buf.len()); - debug_assert!(self.pos_of_buf_start + self.pos_within_buf as u64 <= self.limit); + debug_assert!(self.pos() <= self.limit); + self.buf.assertions(); } #[inline(always)] pub(crate) fn pos(&self) -> u64 { - self.pos_of_buf_start + self.pos_within_buf as u64 + self.pos_of_buf_start + self.buf.pos_within_buf() as u64 } /// Recompute `limit_within_buf` after update of `limit` #[inline] fn update_limit_within_buf(&mut self) { - if self.pos_of_buf_start + (self.buf.len() as u64) <= self.limit { - self.limit_within_buf = self.buf.len(); - } else { - self.limit_within_buf = (self.limit - self.pos_of_buf_start) as usize; - } - + assert!(self.limit >= self.pos_of_buf_start); + self.buf.update_limit(self.limit - self.pos_of_buf_start); self.assertions(); } - pub(crate) fn push_limit(&mut self, limit: u64) -> ProtobufResult<u64> { + pub(crate) fn push_limit(&mut self, limit: u64) -> crate::Result<u64> { let new_limit = match self.pos().checked_add(limit) { Some(new_limit) => new_limit, - None => return Err(ProtobufError::WireError(WireError::Other)), + None => return Err(ProtobufError::WireError(WireError::LimitOverflow).into()), }; if new_limit > self.limit { - return Err(ProtobufError::WireError(WireError::Other)); + return Err(ProtobufError::WireError(WireError::LimitIncrease).into()); } let prev_limit = mem::replace(&mut self.limit, new_limit); @@ -170,22 +144,19 @@ impl<'ignore> BufReadIter<'ignore> { self.update_limit_within_buf(); } - #[inline] + #[inline(always)] pub(crate) fn remaining_in_buf(&self) -> &[u8] { - if USE_UNSAFE_FOR_SPEED { - unsafe { - &self - .buf - .get_unchecked(self.pos_within_buf..self.limit_within_buf) - } - } else { - &self.buf[self.pos_within_buf..self.limit_within_buf] - } + self.buf.remaining_in_buf() + } + + #[inline] + pub(crate) fn consume(&mut self, amt: usize) { + self.buf.consume(amt); } #[inline(always)] pub(crate) fn remaining_in_buf_len(&self) -> usize { - self.limit_within_buf - self.pos_within_buf + self.remaining_in_buf().len() } #[inline(always)] @@ -193,66 +164,48 @@ impl<'ignore> BufReadIter<'ignore> { if self.limit == NO_LIMIT { NO_LIMIT } else { - self.limit - (self.pos_of_buf_start + self.pos_within_buf as u64) + self.limit - self.pos() } } #[inline(always)] - pub(crate) fn eof(&mut self) -> ProtobufResult<bool> { - if self.pos_within_buf == self.limit_within_buf { - Ok(self.fill_buf()?.is_empty()) - } else { + pub(crate) fn eof(&mut self) -> crate::Result<bool> { + if self.remaining_in_buf_len() != 0 { Ok(false) + } else { + Ok(self.fill_buf()?.is_empty()) } } - #[inline(always)] - pub(crate) fn read_byte(&mut self) -> ProtobufResult<u8> { - if self.pos_within_buf == self.limit_within_buf { - self.do_fill_buf()?; - if self.remaining_in_buf_len() == 0 { - return Err(ProtobufError::WireError(WireError::UnexpectedEof)); - } + fn read_byte_slow(&mut self) -> crate::Result<u8> { + self.fill_buf_slow()?; + + if let Some(b) = self.buf.read_byte() { + return Ok(b); } - let r = if USE_UNSAFE_FOR_SPEED { - unsafe { *self.buf.get_unchecked(self.pos_within_buf) } - } else { - self.buf[self.pos_within_buf] - }; - self.pos_within_buf += 1; - Ok(r) + Err(WireError::UnexpectedEof.into()) } - /// Read at most `max` bytes, append to `Vec`. - /// - /// Returns 0 when EOF or limit reached. - fn read_to_vec(&mut self, vec: &mut Vec<u8>, max: usize) -> ProtobufResult<usize> { - let len = { - let rem = self.fill_buf()?; + #[inline(always)] + pub(crate) fn read_byte(&mut self) -> crate::Result<u8> { + if let Some(b) = self.buf.read_byte() { + return Ok(b); + } - let len = cmp::min(rem.len(), max); - vec.extend_from_slice(&rem[..len]); - len - }; - self.pos_within_buf += len; - Ok(len) + self.read_byte_slow() } #[cfg(feature = "bytes")] - pub(crate) fn read_exact_bytes(&mut self, len: usize) -> ProtobufResult<Bytes> { + pub(crate) fn read_exact_bytes(&mut self, len: usize) -> crate::Result<Bytes> { if let InputSource::Bytes(bytes) = self.input_source { - let end = match self.pos_within_buf.checked_add(len) { - Some(end) => end, - None => return Err(ProtobufError::WireError(WireError::UnexpectedEof)), - }; - - if end > self.limit_within_buf { - return Err(ProtobufError::WireError(WireError::UnexpectedEof)); + if len > self.remaining_in_buf_len() { + return Err(ProtobufError::WireError(WireError::UnexpectedEof).into()); } + let end = self.buf.pos_within_buf() + len; - let r = bytes.slice(self.pos_within_buf..end); - self.pos_within_buf += len; + let r = bytes.slice(self.buf.pos_within_buf()..end); + self.buf.consume(len); Ok(r) } else { if len >= READ_RAW_BYTES_MAX_ALLOC { @@ -280,67 +233,78 @@ impl<'ignore> BufReadIter<'ignore> { } /// Returns 0 when EOF or limit reached. - pub(crate) fn read(&mut self, buf: &mut [u8]) -> ProtobufResult<usize> { - self.fill_buf()?; - - let rem = &self.buf[self.pos_within_buf..self.limit_within_buf]; + pub(crate) fn read(&mut self, buf: &mut [u8]) -> crate::Result<usize> { + let rem = self.fill_buf()?; let len = cmp::min(rem.len(), buf.len()); buf[..len].copy_from_slice(&rem[..len]); - self.pos_within_buf += len; + self.buf.consume(len); + Ok(len) + } + + fn consume_buf(&mut self) -> crate::Result<()> { + match &mut self.input_source { + InputSource::Read(read) => { + read.consume(self.buf.pos_within_buf()); + self.pos_of_buf_start += self.buf.pos_within_buf() as u64; + self.buf = InputBuf::empty(); + self.assertions(); + Ok(()) + } + _ => Err(WireError::UnexpectedEof.into()), + } + } + + /// Read at most `max` bytes. + /// + /// Returns 0 when EOF or limit reached. + fn read_to_vec(&mut self, vec: &mut Vec<u8>, max: usize) -> crate::Result<usize> { + let rem = self.fill_buf()?; + + let len = cmp::min(rem.len(), max); + vec.extend_from_slice(&rem[..len]); + self.buf.consume(len); Ok(len) } - fn read_exact_slow(&mut self, buf: &mut [MaybeUninit<u8>]) -> ProtobufResult<()> { + fn read_exact_slow(&mut self, buf: &mut [MaybeUninit<u8>]) -> crate::Result<()> { if self.bytes_until_limit() < buf.len() as u64 { - return Err(ProtobufError::WireError(WireError::UnexpectedEof)); + return Err(ProtobufError::WireError(WireError::UnexpectedEof).into()); } - let consume = self.pos_within_buf; - self.pos_of_buf_start += self.pos_within_buf as u64; - self.pos_within_buf = 0; - self.buf = &[]; - self.limit_within_buf = 0; + self.consume_buf()?; - match self.input_source { - InputSource::Read(ref mut buf_read) => { - buf_read.consume(consume); + match &mut self.input_source { + InputSource::Read(buf_read) => { buf_read.read_exact_uninit(buf)?; + self.pos_of_buf_start += buf.len() as u64; + self.assertions(); + Ok(()) } - _ => { - return Err(ProtobufError::WireError(WireError::UnexpectedEof)); - } + _ => unreachable!(), } - - self.pos_of_buf_start += buf.len() as u64; - - self.assertions(); - - Ok(()) } #[inline] - pub(crate) fn read_exact(&mut self, buf: &mut [MaybeUninit<u8>]) -> ProtobufResult<()> { + pub(crate) fn read_exact(&mut self, buf: &mut [MaybeUninit<u8>]) -> crate::Result<()> { if self.remaining_in_buf_len() >= buf.len() { - let buf_len = buf.len(); - maybe_uninit_write_slice( - buf, - &self.buf[self.pos_within_buf..self.pos_within_buf + buf_len], - ); - self.pos_within_buf += buf_len; + self.buf.read_bytes(buf); return Ok(()); } self.read_exact_slow(buf) } - /// Read exact number of bytes into `Vec`. - /// - /// `Vec` is cleared in the beginning. - pub fn read_exact_to_vec(&mut self, count: usize, target: &mut Vec<u8>) -> ProtobufResult<()> { + /// Read raw bytes into the supplied vector. The vector will be resized as needed and + /// overwritten. + pub(crate) fn read_exact_to_vec( + &mut self, + count: usize, + target: &mut Vec<u8>, + ) -> crate::Result<()> { // TODO: also do some limits when reading from unlimited source if count as u64 > self.bytes_until_limit() { - return Err(ProtobufError::WireError(WireError::TruncatedMessage)); + return Err(ProtobufError::WireError(WireError::TruncatedMessage).into()); } target.clear(); @@ -351,24 +315,23 @@ impl<'ignore> BufReadIter<'ignore> { target.reserve(READ_RAW_BYTES_MAX_ALLOC); while target.len() < count { - let need_to_read = count - target.len(); - if need_to_read <= target.len() { - target.reserve_exact(need_to_read); + if count - target.len() <= target.len() { + target.reserve_exact(count - target.len()); } else { target.reserve(1); } - let max = cmp::min(target.capacity() - target.len(), need_to_read); + let max = cmp::min(target.capacity() - target.len(), count - target.len()); let read = self.read_to_vec(target, max)?; if read == 0 { - return Err(ProtobufError::WireError(WireError::TruncatedMessage)); + return Err(ProtobufError::WireError(WireError::TruncatedMessage).into()); } } } else { target.reserve_exact(count); unsafe { - self.read_exact(&mut vec_spare_capacity_mut(target)[..count])?; + self.read_exact(&mut target.spare_capacity_mut()[..count])?; target.set_len(count); } } @@ -378,56 +341,68 @@ impl<'ignore> BufReadIter<'ignore> { Ok(()) } - fn do_fill_buf(&mut self) -> ProtobufResult<()> { - debug_assert!(self.pos_within_buf == self.limit_within_buf); + pub(crate) fn skip_bytes(&mut self, count: u32) -> crate::Result<()> { + if count as usize <= self.remaining_in_buf_len() { + self.buf.consume(count as usize); + return Ok(()); + } + + if count as u64 > self.bytes_until_limit() { + return Err(WireError::TruncatedMessage.into()); + } + + self.consume_buf()?; - // Limit is reached, do not fill buf, because otherwise - // synchronous read from `CodedInputStream` may block. + match &mut self.input_source { + InputSource::Read(read) => { + read.skip_bytes(count as usize)?; + self.pos_of_buf_start += count as u64; + self.assertions(); + Ok(()) + } + _ => unreachable!(), + } + } + + fn fill_buf_slow(&mut self) -> crate::Result<()> { + self.assertions(); if self.limit == self.pos() { return Ok(()); } - let consume = self.buf.len(); - self.pos_of_buf_start += self.buf.len() as u64; - self.buf = &[]; - self.pos_within_buf = 0; - self.limit_within_buf = 0; + match self.input_source { + InputSource::Read(..) => {} + _ => return Ok(()), + } + + self.consume_buf()?; match self.input_source { InputSource::Read(ref mut buf_read) => { - buf_read.consume(consume); - self.buf = unsafe { mem::transmute(buf_read.fill_buf()?) }; + self.buf = unsafe { InputBuf::from_bytes_ignore_lifetime(buf_read.fill_buf()?) }; + self.update_limit_within_buf(); + Ok(()) } _ => { - return Ok(()); + unreachable!(); } } - - self.update_limit_within_buf(); - - Ok(()) } #[inline(always)] - pub(crate) fn fill_buf(&mut self) -> ProtobufResult<&[u8]> { - if self.pos_within_buf == self.limit_within_buf { - self.do_fill_buf()?; + pub(crate) fn fill_buf(&mut self) -> crate::Result<&[u8]> { + let rem = self.buf.remaining_in_buf(); + if !rem.is_empty() { + return Ok(rem); } - Ok(if USE_UNSAFE_FOR_SPEED { - unsafe { - self.buf - .get_unchecked(self.pos_within_buf..self.limit_within_buf) - } - } else { - &self.buf[self.pos_within_buf..self.limit_within_buf] - }) - } + if self.limit == self.pos() { + return Ok(&[]); + } - #[inline(always)] - pub(crate) fn consume(&mut self, amt: usize) { - assert!(amt <= self.limit_within_buf - self.pos_within_buf); - self.pos_within_buf += amt; + self.fill_buf_slow()?; + + Ok(self.buf.remaining_in_buf()) } } @@ -448,6 +423,7 @@ mod test_bytes { } #[test] + #[cfg_attr(miri, ignore)] // bytes violates SB, see https://github.com/tokio-rs/bytes/issues/522 fn read_exact_bytes_from_slice() { let bytes = make_long_string(100); let mut bri = BufReadIter::from_byte_slice(&bytes[..]); @@ -456,6 +432,7 @@ mod test_bytes { } #[test] + #[cfg_attr(miri, ignore)] // bytes violates SB, see https://github.com/tokio-rs/bytes/issues/522 fn read_exact_bytes_from_bytes() { let bytes = Bytes::from(make_long_string(100)); let mut bri = BufReadIter::from_bytes(&bytes); diff --git a/src/buf_read_or_reader.rs b/src/coded_input_stream/buf_read_or_reader.rs index 6a47c76..d27d6ed 100644 --- a/src/buf_read_or_reader.rs +++ b/src/coded_input_stream/buf_read_or_reader.rs @@ -1,6 +1,7 @@ //! `BufRead` pointer or `BufReader` owned. use std::cmp; +use std::fmt; use std::io; use std::io::BufRead; use std::io::BufReader; @@ -15,6 +16,15 @@ pub(crate) enum BufReadOrReader<'a> { BufRead(&'a mut dyn BufRead), } +impl<'a> fmt::Debug for BufReadOrReader<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + BufReadOrReader::BufReader(..) => write!(f, "BufReader(...)"), + BufReadOrReader::BufRead(..) => write!(f, "BufRead(...)"), + } + } +} + impl<'a> Read for BufReadOrReader<'a> { fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> { match self { @@ -66,6 +76,23 @@ impl<'a> BufReadOrReader<'a> { } Ok(()) } + + pub(crate) fn skip_bytes(&mut self, count: usize) -> Result<(), io::Error> { + let mut rem = count; + while rem != 0 { + let buf = self.fill_buf()?; + if buf.is_empty() { + return Err(io::Error::new( + io::ErrorKind::UnexpectedEof, + "Unexpected end of file", + )); + } + let consume = cmp::min(buf.len(), rem); + self.consume(consume); + rem -= consume; + } + Ok(()) + } } impl<'a> BufRead for BufReadOrReader<'a> { diff --git a/src/coded_input_stream/input_buf.rs b/src/coded_input_stream/input_buf.rs new file mode 100644 index 0000000..d5d6252 --- /dev/null +++ b/src/coded_input_stream/input_buf.rs @@ -0,0 +1,82 @@ +use std::cmp; +use std::mem::MaybeUninit; + +use crate::misc::maybe_uninit_write_slice; + +#[derive(Debug)] +pub(crate) struct InputBuf<'a> { + // Invariants: `0 <= pos_within_buf <= limit_within_buf <= buf.len()`. + buf: &'a [u8], + pos_within_buf: usize, + limit_within_buf: usize, +} + +impl<'a> InputBuf<'a> { + #[inline] + pub(crate) fn assertions(&self) { + debug_assert!(self.pos_within_buf <= self.limit_within_buf); + debug_assert!(self.limit_within_buf <= self.buf.len()); + } + + pub(crate) fn empty() -> InputBuf<'a> { + InputBuf { + buf: &[], + pos_within_buf: 0, + limit_within_buf: 0, + } + } + + pub(crate) fn from_bytes(buf: &'a [u8]) -> InputBuf<'a> { + InputBuf { + buf, + pos_within_buf: 0, + limit_within_buf: buf.len(), + } + } + + pub(crate) unsafe fn from_bytes_ignore_lifetime(buf: &[u8]) -> InputBuf<'a> { + let buf = &*(buf as *const [u8]); + Self::from_bytes(buf) + } + + pub(crate) fn update_limit(&mut self, limit: u64) { + let limit_within_buf = cmp::min(self.buf.len() as u64, limit); + assert!(limit_within_buf >= self.pos_within_buf as u64); + self.limit_within_buf = limit_within_buf as usize; + } + + pub(crate) fn pos_within_buf(&self) -> usize { + self.pos_within_buf + } + + #[inline(always)] + pub(crate) fn remaining_in_buf(&self) -> &'a [u8] { + // SAFETY: Invariants. + unsafe { + self.buf + .get_unchecked(self.pos_within_buf..self.limit_within_buf) + } + } + + #[inline(always)] + pub(crate) fn consume(&mut self, amt: usize) { + assert!(amt <= self.remaining_in_buf().len()); + self.pos_within_buf += amt; + } + + #[inline(always)] + pub(crate) fn read_byte(&mut self) -> Option<u8> { + let r = self.remaining_in_buf().first().copied(); + if let Some(..) = r { + self.pos_within_buf += 1; + } + r + } + + pub(crate) fn read_bytes<'b>(&mut self, dest: &'b mut [MaybeUninit<u8>]) -> &'b mut [u8] { + // This panics if this has not enough data. + let r = maybe_uninit_write_slice(dest, &self.remaining_in_buf()[..dest.len()]); + self.pos_within_buf += r.len(); + r + } +} diff --git a/src/coded_input_stream/input_source.rs b/src/coded_input_stream/input_source.rs new file mode 100644 index 0000000..5f36475 --- /dev/null +++ b/src/coded_input_stream/input_source.rs @@ -0,0 +1,13 @@ +#[cfg(feature = "bytes")] +use bytes::Bytes; + +use crate::coded_input_stream::buf_read_or_reader::BufReadOrReader; + +/// Hold all possible combinations of input source +#[derive(Debug)] +pub(crate) enum InputSource<'a> { + Read(BufReadOrReader<'a>), + Slice(&'a [u8]), + #[cfg(feature = "bytes")] + Bytes(&'a Bytes), +} diff --git a/src/coded_input_stream/mod.rs b/src/coded_input_stream/mod.rs new file mode 100644 index 0000000..a979df1 --- /dev/null +++ b/src/coded_input_stream/mod.rs @@ -0,0 +1,985 @@ +mod buf_read_iter; +mod buf_read_or_reader; +mod input_buf; +mod input_source; + +use std::io; +use std::io::BufRead; +use std::io::Read; +use std::mem; +use std::mem::MaybeUninit; + +#[cfg(feature = "bytes")] +use ::bytes::Bytes; + +#[cfg(feature = "bytes")] +use crate::chars::Chars; +use crate::coded_input_stream::buf_read_iter::BufReadIter; +use crate::enums::Enum; +use crate::error::ProtobufError; +use crate::error::WireError; +use crate::misc::maybe_ununit_array_assume_init; +use crate::reflect::types::ProtobufTypeBool; +use crate::reflect::types::ProtobufTypeDouble; +use crate::reflect::types::ProtobufTypeFixed; +use crate::reflect::types::ProtobufTypeFixed32; +use crate::reflect::types::ProtobufTypeFixed64; +use crate::reflect::types::ProtobufTypeFloat; +use crate::reflect::types::ProtobufTypeInt32; +use crate::reflect::types::ProtobufTypeInt64; +use crate::reflect::types::ProtobufTypeSfixed32; +use crate::reflect::types::ProtobufTypeSfixed64; +use crate::reflect::types::ProtobufTypeSint32; +use crate::reflect::types::ProtobufTypeSint64; +use crate::reflect::types::ProtobufTypeTrait; +use crate::reflect::types::ProtobufTypeUint32; +use crate::reflect::types::ProtobufTypeUint64; +use crate::reflect::MessageDescriptor; +use crate::unknown::UnknownValue; +use crate::varint::decode::decode_varint32; +use crate::varint::decode::decode_varint64; +use crate::varint::MAX_VARINT_ENCODED_LEN; +use crate::wire_format; +use crate::wire_format::WireType; +use crate::zigzag::decode_zig_zag_32; +use crate::zigzag::decode_zig_zag_64; +use crate::EnumOrUnknown; +use crate::Message; +use crate::MessageDyn; + +// Default recursion level limit. 100 is the default value of C++'s implementation. +const DEFAULT_RECURSION_LIMIT: u32 = 100; + +// Max allocated vec when reading length-delimited from unknown input stream +pub(crate) const READ_RAW_BYTES_MAX_ALLOC: usize = 10_000_000; + +/// Buffered read with handy utilities. +#[derive(Debug)] +pub struct CodedInputStream<'a> { + source: BufReadIter<'a>, + recursion_level: u32, + recursion_limit: u32, +} + +impl<'a> CodedInputStream<'a> { + /// Wrap a `Read`. + /// + /// Note resulting `CodedInputStream` is buffered. + /// + /// If `Read` is buffered, the resulting stream will be double buffered, + /// consider using [`from_buf_read`](Self::from_buf_read) instead. + pub fn new(read: &'a mut dyn Read) -> CodedInputStream<'a> { + CodedInputStream::from_buf_read_iter(BufReadIter::from_read(read)) + } + + /// Create from `BufRead`. + /// + /// `CodedInputStream` will utilize `BufRead` buffer. + pub fn from_buf_read(buf_read: &'a mut dyn BufRead) -> CodedInputStream<'a> { + CodedInputStream::from_buf_read_iter(BufReadIter::from_buf_read(buf_read)) + } + + /// Read from byte slice + pub fn from_bytes(bytes: &'a [u8]) -> CodedInputStream<'a> { + CodedInputStream::from_buf_read_iter(BufReadIter::from_byte_slice(bytes)) + } + + /// Read from `Bytes`. + /// + /// `CodedInputStream` operations like + /// [`read_tokio_bytes`](crate::CodedInputStream::read_tokio_bytes) + /// will return a shared copy of this bytes object. + #[cfg(feature = "bytes")] + pub fn from_tokio_bytes(bytes: &'a Bytes) -> CodedInputStream<'a> { + CodedInputStream::from_buf_read_iter(BufReadIter::from_bytes(bytes)) + } + + fn from_buf_read_iter(source: BufReadIter<'a>) -> CodedInputStream<'a> { + CodedInputStream { + source, + recursion_level: 0, + recursion_limit: DEFAULT_RECURSION_LIMIT, + } + } + + /// Set the recursion limit. + pub fn set_recursion_limit(&mut self, limit: u32) { + self.recursion_limit = limit; + } + + #[inline] + pub(crate) fn incr_recursion(&mut self) -> crate::Result<()> { + if self.recursion_level >= self.recursion_limit { + return Err(ProtobufError::WireError(WireError::OverRecursionLimit).into()); + } + self.recursion_level += 1; + Ok(()) + } + + #[inline] + pub(crate) fn decr_recursion(&mut self) { + self.recursion_level -= 1; + } + + /// How many bytes processed + pub fn pos(&self) -> u64 { + self.source.pos() + } + + /// How many bytes until current limit + pub fn bytes_until_limit(&self) -> u64 { + self.source.bytes_until_limit() + } + + /// Read bytes into given `buf`. + #[inline] + pub fn read_exact(&mut self, buf: &mut [MaybeUninit<u8>]) -> crate::Result<()> { + self.source.read_exact(buf) + } + + /// Read exact number of bytes as `Bytes` object. + /// + /// This operation returns a shared view if `CodedInputStream` is + /// constructed with `Bytes` parameter. + #[cfg(feature = "bytes")] + fn read_raw_tokio_bytes(&mut self, count: usize) -> crate::Result<Bytes> { + self.source.read_exact_bytes(count) + } + + /// Read one byte + #[inline(always)] + pub fn read_raw_byte(&mut self) -> crate::Result<u8> { + self.source.read_byte() + } + + /// Push new limit, return previous limit. + pub fn push_limit(&mut self, limit: u64) -> crate::Result<u64> { + self.source.push_limit(limit) + } + + /// Restore previous limit. + pub fn pop_limit(&mut self, old_limit: u64) { + self.source.pop_limit(old_limit); + } + + /// Are we at EOF? + #[inline(always)] + pub fn eof(&mut self) -> crate::Result<bool> { + self.source.eof() + } + + /// Check we are at EOF. + /// + /// Return error if we are not at EOF. + pub fn check_eof(&mut self) -> crate::Result<()> { + let eof = self.eof()?; + if !eof { + return Err(ProtobufError::WireError(WireError::UnexpectedEof).into()); + } + Ok(()) + } + + fn read_raw_varint64_slow(&mut self) -> crate::Result<u64> { + let mut r: u64 = 0; + let mut i = 0; + loop { + if i == MAX_VARINT_ENCODED_LEN { + return Err(ProtobufError::WireError(WireError::IncorrectVarint).into()); + } + let b = self.read_raw_byte()?; + if i == 9 && (b & 0x7f) > 1 { + return Err(ProtobufError::WireError(WireError::IncorrectVarint).into()); + } + r = r | (((b & 0x7f) as u64) << (i * 7)); + i += 1; + if b < 0x80 { + return Ok(r); + } + } + } + + fn read_raw_varint32_slow(&mut self) -> crate::Result<u32> { + let v = self.read_raw_varint64_slow()?; + if v > u32::MAX as u64 { + return Err(ProtobufError::WireError(WireError::U32Overflow(v)).into()); + } + Ok(v as u32) + } + + /// Read varint + #[inline] + pub fn read_raw_varint64(&mut self) -> crate::Result<u64> { + let rem = self.source.remaining_in_buf(); + + match decode_varint64(rem)? { + Some((r, c)) => { + self.source.consume(c); + Ok(r) + } + None => self.read_raw_varint64_slow(), + } + } + + /// Read varint + #[inline] + pub fn read_raw_varint32(&mut self) -> crate::Result<u32> { + let rem = self.source.remaining_in_buf(); + + match decode_varint32(rem)? { + Some((r, c)) => { + self.source.consume(c); + Ok(r) + } + None => self.read_raw_varint32_slow(), + } + } + + #[inline] + fn read_raw_varint32_or_eof(&mut self) -> crate::Result<Option<u32>> { + let rem = self.source.remaining_in_buf(); + let v = decode_varint32(rem)?; + match v { + Some((r, c)) => { + self.source.consume(c); + Ok(Some(r)) + } + None => { + if self.eof()? { + Ok(None) + } else { + let v = self.read_raw_varint32_slow()?; + Ok(Some(v)) + } + } + } + } + + /// Read little-endian 32-bit integer + pub fn read_raw_little_endian32(&mut self) -> crate::Result<u32> { + let mut bytes = [MaybeUninit::uninit(); 4]; + self.read_exact(&mut bytes)?; + // SAFETY: `read_exact` guarantees that the buffer is filled. + let bytes = unsafe { maybe_ununit_array_assume_init(bytes) }; + Ok(u32::from_le_bytes(bytes)) + } + + /// Read little-endian 64-bit integer + pub fn read_raw_little_endian64(&mut self) -> crate::Result<u64> { + let mut bytes = [MaybeUninit::uninit(); 8]; + self.read_exact(&mut bytes)?; + // SAFETY: `read_exact` guarantees that the buffer is filled. + let bytes = unsafe { maybe_ununit_array_assume_init(bytes) }; + Ok(u64::from_le_bytes(bytes)) + } + + /// Read tag number as `u32` or None if EOF is reached. + #[inline] + pub fn read_raw_tag_or_eof(&mut self) -> crate::Result<Option<u32>> { + self.read_raw_varint32_or_eof() + } + + /// Read tag + #[inline] + pub(crate) fn read_tag(&mut self) -> crate::Result<wire_format::Tag> { + let v = self.read_raw_varint32()?; + wire_format::Tag::new(v) + } + + /// Read tag, return it is pair (field number, wire type) + #[inline] + pub(crate) fn read_tag_unpack(&mut self) -> crate::Result<(u32, WireType)> { + self.read_tag().map(|t| t.unpack()) + } + + /// Read `double` + pub fn read_double(&mut self) -> crate::Result<f64> { + let bits = self.read_raw_little_endian64()?; + Ok(f64::from_bits(bits)) + } + + /// Read `float` + pub fn read_float(&mut self) -> crate::Result<f32> { + let bits = self.read_raw_little_endian32()?; + Ok(f32::from_bits(bits)) + } + + /// Read `int64` + pub fn read_int64(&mut self) -> crate::Result<i64> { + self.read_raw_varint64().map(|v| v as i64) + } + + /// Read `int32` + pub fn read_int32(&mut self) -> crate::Result<i32> { + let v = self.read_int64()?; + i32::try_from(v).map_err(|_| WireError::I32Overflow(v).into()) + } + + /// Read `uint64` + pub fn read_uint64(&mut self) -> crate::Result<u64> { + self.read_raw_varint64() + } + + /// Read `uint32` + pub fn read_uint32(&mut self) -> crate::Result<u32> { + self.read_raw_varint32() + } + + /// Read `sint64` + pub fn read_sint64(&mut self) -> crate::Result<i64> { + self.read_uint64().map(decode_zig_zag_64) + } + + /// Read `sint32` + pub fn read_sint32(&mut self) -> crate::Result<i32> { + self.read_uint32().map(decode_zig_zag_32) + } + + /// Read `fixed64` + pub fn read_fixed64(&mut self) -> crate::Result<u64> { + self.read_raw_little_endian64() + } + + /// Read `fixed32` + pub fn read_fixed32(&mut self) -> crate::Result<u32> { + self.read_raw_little_endian32() + } + + /// Read `sfixed64` + pub fn read_sfixed64(&mut self) -> crate::Result<i64> { + self.read_raw_little_endian64().map(|v| v as i64) + } + + /// Read `sfixed32` + pub fn read_sfixed32(&mut self) -> crate::Result<i32> { + self.read_raw_little_endian32().map(|v| v as i32) + } + + /// Read `bool` + pub fn read_bool(&mut self) -> crate::Result<bool> { + self.read_raw_varint64().map(|v| v != 0) + } + + pub(crate) fn read_enum_value(&mut self) -> crate::Result<i32> { + self.read_int32() + } + + /// Read `enum` as `ProtobufEnum` + pub fn read_enum<E: Enum>(&mut self) -> crate::Result<E> { + let i = self.read_enum_value()?; + match Enum::from_i32(i) { + Some(e) => Ok(e), + None => Err(ProtobufError::WireError(WireError::InvalidEnumValue(E::NAME, i)).into()), + } + } + + /// Read `enum` as `ProtobufEnumOrUnknown` + pub fn read_enum_or_unknown<E: Enum>(&mut self) -> crate::Result<EnumOrUnknown<E>> { + Ok(EnumOrUnknown::from_i32(self.read_int32()?)) + } + + fn read_repeated_packed_fixed_into<T: ProtobufTypeFixed>( + &mut self, + target: &mut Vec<T::ProtobufValue>, + ) -> crate::Result<()> { + let len_bytes = self.read_raw_varint64()?; + + let reserve = if len_bytes <= READ_RAW_BYTES_MAX_ALLOC as u64 { + (len_bytes as usize) / (T::ENCODED_SIZE as usize) + } else { + // prevent OOM on malformed input + // probably should truncate + READ_RAW_BYTES_MAX_ALLOC / (T::ENCODED_SIZE as usize) + }; + + target.reserve(reserve); + + let old_limit = self.push_limit(len_bytes)?; + while !self.eof()? { + target.push(T::read(self)?); + } + self.pop_limit(old_limit); + Ok(()) + } + + fn read_repeated_packed_into<T: ProtobufTypeTrait>( + &mut self, + target: &mut Vec<T::ProtobufValue>, + ) -> crate::Result<()> { + let len_bytes = self.read_raw_varint64()?; + + // value is at least 1 bytes, so this is lower bound of element count + let reserve = if len_bytes <= READ_RAW_BYTES_MAX_ALLOC as u64 { + len_bytes as usize + } else { + // prevent OOM on malformed input + READ_RAW_BYTES_MAX_ALLOC + }; + + target.reserve(reserve); + + let old_limit = self.push_limit(len_bytes)?; + while !self.eof()? { + target.push(T::read(self)?); + } + self.pop_limit(old_limit); + Ok(()) + } + + /// Read repeated packed `double` + pub fn read_repeated_packed_double_into(&mut self, target: &mut Vec<f64>) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeDouble>(target) + } + + /// Read repeated packed `float` + pub fn read_repeated_packed_float_into(&mut self, target: &mut Vec<f32>) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeFloat>(target) + } + + /// Read repeated packed `int64` + pub fn read_repeated_packed_int64_into(&mut self, target: &mut Vec<i64>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeInt64>(target) + } + + /// Read repeated packed `int32` + pub fn read_repeated_packed_int32_into(&mut self, target: &mut Vec<i32>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeInt32>(target) + } + + /// Read repeated packed `uint64` + pub fn read_repeated_packed_uint64_into(&mut self, target: &mut Vec<u64>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeUint64>(target) + } + + /// Read repeated packed `uint32` + pub fn read_repeated_packed_uint32_into(&mut self, target: &mut Vec<u32>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeUint32>(target) + } + + /// Read repeated packed `sint64` + pub fn read_repeated_packed_sint64_into(&mut self, target: &mut Vec<i64>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeSint64>(target) + } + + /// Read repeated packed `sint32` + pub fn read_repeated_packed_sint32_into(&mut self, target: &mut Vec<i32>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeSint32>(target) + } + + /// Read repeated packed `fixed64` + pub fn read_repeated_packed_fixed64_into( + &mut self, + target: &mut Vec<u64>, + ) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeFixed64>(target) + } + + /// Read repeated packed `fixed32` + pub fn read_repeated_packed_fixed32_into( + &mut self, + target: &mut Vec<u32>, + ) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeFixed32>(target) + } + + /// Read repeated packed `sfixed64` + pub fn read_repeated_packed_sfixed64_into( + &mut self, + target: &mut Vec<i64>, + ) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeSfixed64>(target) + } + + /// Read repeated packed `sfixed32` + pub fn read_repeated_packed_sfixed32_into( + &mut self, + target: &mut Vec<i32>, + ) -> crate::Result<()> { + self.read_repeated_packed_fixed_into::<ProtobufTypeSfixed32>(target) + } + + /// Read repeated packed `bool` + pub fn read_repeated_packed_bool_into(&mut self, target: &mut Vec<bool>) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeBool>(target) + } + + /// Read repeated packed enum values into the vector. + pub(crate) fn read_repeated_packed_enum_values_into( + &mut self, + target: &mut Vec<i32>, + ) -> crate::Result<()> { + self.read_repeated_packed_into::<ProtobufTypeInt32>(target) + } + + fn skip_group(&mut self) -> crate::Result<()> { + while !self.eof()? { + let wire_type = self.read_tag_unpack()?.1; + if wire_type == WireType::EndGroup { + break; + } + self.skip_field(wire_type)?; + } + Ok(()) + } + + /// Read `UnknownValue` + pub fn read_unknown(&mut self, wire_type: WireType) -> crate::Result<UnknownValue> { + match wire_type { + WireType::Varint => self.read_raw_varint64().map(|v| UnknownValue::Varint(v)), + WireType::Fixed64 => self.read_fixed64().map(|v| UnknownValue::Fixed64(v)), + WireType::Fixed32 => self.read_fixed32().map(|v| UnknownValue::Fixed32(v)), + WireType::LengthDelimited => { + let len = self.read_raw_varint32()?; + self.read_raw_bytes(len) + .map(|v| UnknownValue::LengthDelimited(v)) + } + WireType::StartGroup => { + self.skip_group()?; + // We do not support groups, so just return something. + Ok(UnknownValue::LengthDelimited(Vec::new())) + } + WireType::EndGroup => { + Err(ProtobufError::WireError(WireError::UnexpectedWireType(wire_type)).into()) + } + } + } + + /// Skip field. + pub fn skip_field(&mut self, wire_type: WireType) -> crate::Result<()> { + match wire_type { + WireType::Varint => self.read_raw_varint64().map(|_| ()), + WireType::Fixed64 => self.read_fixed64().map(|_| ()), + WireType::Fixed32 => self.read_fixed32().map(|_| ()), + WireType::LengthDelimited => { + let len = self.read_raw_varint32()?; + self.skip_raw_bytes(len) + } + WireType::StartGroup => self.skip_group(), + WireType::EndGroup => { + Err(ProtobufError::WireError(WireError::UnexpectedWireType(wire_type)).into()) + } + } + } + + /// Read raw bytes into the supplied vector. The vector will be resized as needed and + /// overwritten. + pub fn read_raw_bytes_into(&mut self, count: u32, target: &mut Vec<u8>) -> crate::Result<()> { + self.source.read_exact_to_vec(count as usize, target) + } + + /// Read exact number of bytes + pub fn read_raw_bytes(&mut self, count: u32) -> crate::Result<Vec<u8>> { + let mut r = Vec::new(); + self.read_raw_bytes_into(count, &mut r)?; + Ok(r) + } + + /// Skip exact number of bytes + pub fn skip_raw_bytes(&mut self, count: u32) -> crate::Result<()> { + self.source.skip_bytes(count) + } + + /// Read `bytes` field, length delimited + pub fn read_bytes(&mut self) -> crate::Result<Vec<u8>> { + let mut r = Vec::new(); + self.read_bytes_into(&mut r)?; + Ok(r) + } + + /// Read `bytes` field, length delimited + #[cfg(feature = "bytes")] + pub fn read_tokio_bytes(&mut self) -> crate::Result<Bytes> { + let len = self.read_raw_varint32()?; + self.read_raw_tokio_bytes(len as usize) + } + + /// Read `string` field, length delimited + #[cfg(feature = "bytes")] + pub fn read_tokio_chars(&mut self) -> crate::Result<Chars> { + let bytes = self.read_tokio_bytes()?; + Ok(Chars::from_bytes(bytes).map_err(ProtobufError::Utf8)?) + } + + /// Read `bytes` field, length delimited + pub fn read_bytes_into(&mut self, target: &mut Vec<u8>) -> crate::Result<()> { + let len = self.read_raw_varint32()?; + self.read_raw_bytes_into(len, target)?; + Ok(()) + } + + /// Read `string` field, length delimited + pub fn read_string(&mut self) -> crate::Result<String> { + let mut r = String::new(); + self.read_string_into(&mut r)?; + Ok(r) + } + + /// Read `string` field, length delimited + pub fn read_string_into(&mut self, target: &mut String) -> crate::Result<()> { + target.clear(); + // take target's buffer + let mut vec = mem::replace(target, String::new()).into_bytes(); + self.read_bytes_into(&mut vec)?; + + let s = match String::from_utf8(vec) { + Ok(t) => t, + Err(_) => return Err(ProtobufError::WireError(WireError::Utf8Error).into()), + }; + *target = s; + Ok(()) + } + + /// Read message, do not check if message is initialized + pub fn merge_message<M: Message>(&mut self, message: &mut M) -> crate::Result<()> { + self.incr_recursion()?; + struct DecrRecursion<'a, 'b>(&'a mut CodedInputStream<'b>); + impl<'a, 'b> Drop for DecrRecursion<'a, 'b> { + fn drop(&mut self) { + self.0.decr_recursion(); + } + } + + let mut decr = DecrRecursion(self); + + let len = decr.0.read_raw_varint64()?; + let old_limit = decr.0.push_limit(len)?; + message.merge_from(&mut decr.0)?; + decr.0.pop_limit(old_limit); + Ok(()) + } + + /// Like `merge_message`, but for dynamic messages. + pub fn merge_message_dyn(&mut self, message: &mut dyn MessageDyn) -> crate::Result<()> { + let len = self.read_raw_varint64()?; + let old_limit = self.push_limit(len)?; + message.merge_from_dyn(self)?; + self.pop_limit(old_limit); + Ok(()) + } + + /// Read message + pub fn read_message<M: Message>(&mut self) -> crate::Result<M> { + let mut r: M = Message::new(); + self.merge_message(&mut r)?; + r.check_initialized()?; + Ok(r) + } + + /// Read message. + pub fn read_message_dyn( + &mut self, + descriptor: &MessageDescriptor, + ) -> crate::Result<Box<dyn MessageDyn>> { + let mut r = descriptor.new_instance(); + self.merge_message_dyn(&mut *r)?; + r.check_initialized_dyn()?; + Ok(r) + } +} + +impl<'a> Read for CodedInputStream<'a> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.source.read(buf).map_err(Into::into) + } +} + +impl<'a> BufRead for CodedInputStream<'a> { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + self.source.fill_buf().map_err(Into::into) + } + + fn consume(&mut self, amt: usize) { + self.source.consume(amt) + } +} + +#[cfg(test)] +mod test { + + use std::fmt::Debug; + use std::io; + use std::io::BufRead; + use std::io::Read; + + use super::CodedInputStream; + use super::READ_RAW_BYTES_MAX_ALLOC; + use crate::error::ProtobufError; + use crate::hex::decode_hex; + use crate::wire_format::Tag; + use crate::wire_format::WireType; + use crate::CodedOutputStream; + + fn test_read_partial<F>(hex: &str, mut callback: F) + where + F: FnMut(&mut CodedInputStream), + { + let d = decode_hex(hex); + // Test with buffered reader. + { + let mut reader = io::Cursor::new(&d); + let mut is = CodedInputStream::from_buf_read(&mut reader as &mut dyn BufRead); + assert_eq!(0, is.pos()); + callback(&mut is); + } + // Test from bytes. + { + let mut is = CodedInputStream::from_bytes(&d); + assert_eq!(0, is.pos()); + callback(&mut is); + } + } + + fn test_read<F>(hex: &str, mut callback: F) + where + F: FnMut(&mut CodedInputStream), + { + let len = decode_hex(hex).len(); + test_read_partial(hex, |reader| { + callback(reader); + assert!(reader.eof().expect("eof")); + assert_eq!(len as u64, reader.pos()); + }); + } + + fn test_read_v<F, V>(hex: &str, v: V, mut callback: F) + where + F: FnMut(&mut CodedInputStream) -> crate::Result<V>, + V: PartialEq + Debug, + { + test_read(hex, |reader| { + assert_eq!(v, callback(reader).unwrap()); + }); + } + + #[test] + fn test_input_stream_read_raw_byte() { + test_read("17", |is| { + assert_eq!(23, is.read_raw_byte().unwrap()); + }); + } + + #[test] + fn test_input_stream_read_raw_varint() { + test_read_v("07", 7, |reader| reader.read_raw_varint32()); + test_read_v("07", 7, |reader| reader.read_raw_varint64()); + + test_read_v("96 01", 150, |reader| reader.read_raw_varint32()); + test_read_v("96 01", 150, |reader| reader.read_raw_varint64()); + + test_read_v( + "ff ff ff ff ff ff ff ff ff 01", + 0xffffffffffffffff, + |reader| reader.read_raw_varint64(), + ); + + test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| { + reader.read_raw_varint32() + }); + test_read_v("ff ff ff ff 0f", 0xffffffff, |reader| { + reader.read_raw_varint64() + }); + } + + #[test] + fn test_input_stream_read_raw_varint_out_of_range() { + test_read_partial("ff ff ff ff ff ff ff ff ff 02", |is| { + assert!(is.read_raw_varint64().is_err()); + }); + test_read_partial("ff ff ff ff ff ff ff ff ff 02", |is| { + assert!(is.read_raw_varint32().is_err()); + }); + } + + #[test] + fn test_input_stream_read_raw_varint_too_long() { + // varint cannot have length > 10 + test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| { + let error = reader.read_raw_varint64().unwrap_err().0; + match *error { + ProtobufError::WireError(..) => (), + _ => panic!(), + } + }); + test_read_partial("ff ff ff ff ff ff ff ff ff ff 01", |reader| { + let error = reader.read_raw_varint32().unwrap_err().0; + match *error { + ProtobufError::WireError(..) => (), + _ => panic!(), + } + }); + } + + #[test] + fn test_input_stream_read_raw_varint_unexpected_eof() { + test_read_partial("96 97", |reader| { + let error = reader.read_raw_varint32().unwrap_err().0; + match *error { + ProtobufError::WireError(..) => (), + _ => panic!(), + } + }); + } + + #[test] + fn test_input_stream_read_raw_varint_pos() { + test_read_partial("95 01 98", |reader| { + assert_eq!(149, reader.read_raw_varint32().unwrap()); + assert_eq!(2, reader.pos()); + }); + } + + #[test] + fn test_input_stream_read_int32() { + test_read_v("02", 2, |reader| reader.read_int32()); + } + + #[test] + fn test_input_stream_read_float() { + test_read_v("95 73 13 61", 17e19, |is| is.read_float()); + } + + #[test] + fn test_input_stream_read_double() { + test_read_v("40 d5 ab 68 b3 07 3d 46", 23e29, |is| is.read_double()); + } + + #[test] + fn test_input_stream_skip_raw_bytes() { + test_read("", |reader| { + reader.skip_raw_bytes(0).unwrap(); + }); + test_read("aa bb", |reader| { + reader.skip_raw_bytes(2).unwrap(); + }); + test_read("aa bb cc dd ee ff", |reader| { + reader.skip_raw_bytes(6).unwrap(); + }); + } + + #[test] + fn test_input_stream_read_raw_bytes() { + test_read("", |reader| { + assert_eq!( + Vec::from(&b""[..]), + reader.read_raw_bytes(0).expect("read_raw_bytes") + ); + }) + } + + #[test] + fn test_input_stream_limits() { + test_read("aa bb cc", |is| { + let old_limit = is.push_limit(1).unwrap(); + assert_eq!(1, is.bytes_until_limit()); + let r1 = is.read_raw_bytes(1).unwrap(); + assert_eq!(&[0xaa as u8], &r1[..]); + is.pop_limit(old_limit); + let r2 = is.read_raw_bytes(2).unwrap(); + assert_eq!(&[0xbb as u8, 0xcc], &r2[..]); + }); + } + + #[test] + fn test_input_stream_io_read() { + test_read("aa bb cc", |is| { + let mut buf = [0; 3]; + assert_eq!(Read::read(is, &mut buf).expect("io::Read"), 3); + assert_eq!(buf, [0xaa, 0xbb, 0xcc]); + }); + } + + #[test] + fn test_input_stream_io_bufread() { + test_read("aa bb cc", |is| { + assert_eq!( + BufRead::fill_buf(is).expect("io::BufRead::fill_buf"), + &[0xaa, 0xbb, 0xcc] + ); + BufRead::consume(is, 3); + }); + } + + #[test] + #[cfg_attr(miri, ignore)] // Miri is too slow for this test. + fn test_input_stream_read_raw_bytes_into_huge() { + let mut v = Vec::new(); + for i in 0..READ_RAW_BYTES_MAX_ALLOC + 1000 { + v.push((i % 10) as u8); + } + + let mut slice: &[u8] = v.as_slice(); + + let mut is = CodedInputStream::new(&mut slice); + + let mut buf = Vec::new(); + + is.read_raw_bytes_into(READ_RAW_BYTES_MAX_ALLOC as u32 + 10, &mut buf) + .expect("read"); + + assert_eq!(READ_RAW_BYTES_MAX_ALLOC + 10, buf.len()); + + buf.clear(); + + is.read_raw_bytes_into(1000 - 10, &mut buf).expect("read"); + + assert_eq!(1000 - 10, buf.len()); + + assert!(is.eof().expect("eof")); + } + + // Copy of this test: https://tinyurl.com/34hfavtz + #[test] + fn test_skip_group() { + // Create an output stream with a group in: + // Field 1: string "field 1" + // Field 2: group containing: + // Field 1: fixed int32 value 100 + // Field 2: string "ignore me" + // Field 3: nested group containing + // Field 1: fixed int64 value 1000 + // Field 3: string "field 3" + + let mut vec = Vec::new(); + let mut os = CodedOutputStream::new(&mut vec); + os.write_tag(1, WireType::LengthDelimited).unwrap(); + os.write_string_no_tag("field 1").unwrap(); + + // The outer group... + os.write_tag(2, WireType::StartGroup).unwrap(); + os.write_tag(1, WireType::Fixed32).unwrap(); + os.write_fixed32_no_tag(100).unwrap(); + os.write_tag(3, WireType::LengthDelimited).unwrap(); + os.write_string_no_tag("ignore me").unwrap(); + // The nested group... + os.write_tag(3, WireType::StartGroup).unwrap(); + os.write_tag(1, WireType::Fixed64).unwrap(); + os.write_fixed64_no_tag(1000).unwrap(); + // Note: Not sure the field number is relevant for end group... + os.write_tag(3, WireType::EndGroup).unwrap(); + + // End the outer group + os.write_tag(2, WireType::EndGroup).unwrap(); + + os.write_tag(3, WireType::LengthDelimited).unwrap(); + os.write_string_no_tag("field 3").unwrap(); + os.flush().unwrap(); + drop(os); + + let mut input = CodedInputStream::from_bytes(&vec); + // Now act like a generated client + assert_eq!( + Tag::make(1, WireType::LengthDelimited), + input.read_tag().unwrap() + ); + assert_eq!("field 1", &input.read_string().unwrap()); + assert_eq!( + Tag::make(2, WireType::StartGroup), + input.read_tag().unwrap() + ); + input.skip_field(WireType::StartGroup).unwrap(); + assert_eq!( + Tag::make(3, WireType::LengthDelimited), + input.read_tag().unwrap() + ); + assert_eq!("field 3", input.read_string().unwrap()); + } +} diff --git a/src/coded_output_stream.rs b/src/coded_output_stream.rs deleted file mode 100644 index 2bbe0a3..0000000 --- a/src/coded_output_stream.rs +++ /dev/null @@ -1,756 +0,0 @@ -use std::io; -use std::io::Write; -use std::mem; -use std::mem::MaybeUninit; -use std::ptr; -use std::slice; - -use crate::misc::maybe_uninit_write; -use crate::misc::maybe_uninit_write_slice; -use crate::misc::vec_spare_capacity_mut; -use crate::varint; -use crate::wire_format; -use crate::zigzag::encode_zig_zag_32; -use crate::zigzag::encode_zig_zag_64; -use crate::Message; -use crate::ProtobufEnum; -use crate::ProtobufError; -use crate::ProtobufResult; -use crate::UnknownFields; -use crate::UnknownValueRef; - -/// Equal to the default buffer size of `BufWriter`, so when -/// `CodedOutputStream` wraps `BufWriter`, it often skips double buffering. -const OUTPUT_STREAM_BUFFER_SIZE: usize = 8 * 1024; - -#[doc(hidden)] -pub trait WithCodedOutputStream { - fn with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>; -} - -impl<'a> WithCodedOutputStream for &'a mut (dyn Write + 'a) { - fn with_coded_output_stream<T, F>(self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>, - { - let mut os = CodedOutputStream::new(self); - let r = cb(&mut os)?; - os.flush()?; - Ok(r) - } -} - -impl<'a> WithCodedOutputStream for &'a mut Vec<u8> { - fn with_coded_output_stream<T, F>(mut self, cb: F) -> ProtobufResult<T> - where - F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<T>, - { - let mut os = CodedOutputStream::vec(&mut self); - let r = cb(&mut os)?; - os.flush()?; - Ok(r) - } -} - -#[doc(hidden)] -pub fn with_coded_output_stream_to_bytes<F>(cb: F) -> ProtobufResult<Vec<u8>> -where - F: FnOnce(&mut CodedOutputStream) -> ProtobufResult<()>, -{ - let mut v = Vec::new(); - v.with_coded_output_stream(cb)?; - Ok(v) -} - -/// Output buffer/writer for `CodedOutputStream`. -enum OutputTarget<'a> { - Write(&'a mut dyn Write, Vec<u8>), - Vec(&'a mut Vec<u8>), - /// The buffer is passed as `&[u8]` to `CodedOutputStream` constructor - /// and immediately converted to `buffer` field of `CodedOutputStream`, - /// it is not needed to be stored here. - /// Lifetime parameter of `CodedOutputStream` guarantees the buffer is valid - /// during the lifetime of `CodedOutputStream`. - Bytes, -} - -/// Buffered write with handy utilities -pub struct CodedOutputStream<'a> { - target: OutputTarget<'a>, - // Actual buffer is owned by `OutputTarget`, - // and here we alias the buffer so access to the buffer is branchless: - // access does not require switch by actual target type: `&[], `Vec`, `Write` etc. - // We don't access the actual buffer in `OutputTarget` except when - // we initialize `buffer` field here. - buffer: *mut [MaybeUninit<u8>], - // within buffer - position: usize, -} - -impl<'a> CodedOutputStream<'a> { - /// Construct from given `Write`. - /// - /// `CodedOutputStream` is buffered even if `Write` is not - pub fn new(writer: &'a mut dyn Write) -> CodedOutputStream<'a> { - let buffer_len = OUTPUT_STREAM_BUFFER_SIZE; - - let mut buffer_storage = Vec::with_capacity(buffer_len); - - // SAFETY: we are not using the `buffer_storage` - // except for initializing the `buffer` field. - // See `buffer` field documentation. - let buffer = vec_spare_capacity_mut(&mut buffer_storage); - let buffer: *mut [MaybeUninit<u8>] = buffer; - - CodedOutputStream { - target: OutputTarget::Write(writer, buffer_storage), - buffer, - position: 0, - } - } - - /// `CodedOutputStream` which writes directly to bytes. - /// - /// Attempt to write more than bytes capacity results in error. - pub fn bytes(bytes: &'a mut [u8]) -> CodedOutputStream<'a> { - // SAFETY: it is safe to cast from &mut [u8] to &mut [MaybeUninit<u8>]. - let buffer = - ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut MaybeUninit<u8>, bytes.len()); - CodedOutputStream { - target: OutputTarget::Bytes, - buffer, - position: 0, - } - } - - /// `CodedOutputStream` which writes directly to `Vec<u8>`. - /// - /// Caller should call `flush` at the end to guarantee vec contains - /// all written data. - pub fn vec(vec: &'a mut Vec<u8>) -> CodedOutputStream<'a> { - let buffer: *mut [MaybeUninit<u8>] = &mut []; - CodedOutputStream { - target: OutputTarget::Vec(vec), - buffer, - position: 0, - } - } - - /// Check if EOF is reached. - /// - /// # Panics - /// - /// If underlying write has no EOF - pub fn check_eof(&self) { - match self.target { - OutputTarget::Bytes => { - assert_eq!(self.buffer().len() as u64, self.position as u64); - } - OutputTarget::Write(..) | OutputTarget::Vec(..) => { - panic!("must not be called with Writer or Vec"); - } - } - } - - #[inline(always)] - fn buffer(&self) -> &[MaybeUninit<u8>] { - // SAFETY: see the `buffer` field documentation about invariants. - unsafe { &*(self.buffer as *mut [MaybeUninit<u8>]) } - } - - #[inline(always)] - fn filled_buffer_impl<'s>(buffer: *mut [MaybeUninit<u8>], position: usize) -> &'s [u8] { - // SAFETY: this function is safe assuming `buffer` and `position` - // are `self.buffer` and `safe.position`: - // * `CodedOutputStream` has invariant that `position <= buffer.len()`. - // * `buffer` is filled up to `position`. - unsafe { slice::from_raw_parts_mut(buffer as *mut u8, position) } - } - - fn refresh_buffer(&mut self) -> ProtobufResult<()> { - match self.target { - OutputTarget::Write(ref mut write, _) => { - write.write_all(Self::filled_buffer_impl(self.buffer, self.position))?; - self.position = 0; - } - OutputTarget::Vec(ref mut vec) => unsafe { - let vec_len = vec.len(); - assert!(vec_len + self.position <= vec.capacity()); - vec.set_len(vec_len + self.position); - vec.reserve(1); - self.buffer = vec_spare_capacity_mut(vec); - self.position = 0; - }, - OutputTarget::Bytes => { - return Err(ProtobufError::IoError(io::Error::new( - io::ErrorKind::Other, - "given slice is too small to serialize the message", - ))); - } - } - Ok(()) - } - - /// Flush the buffer to underlying write - pub fn flush(&mut self) -> ProtobufResult<()> { - match self.target { - OutputTarget::Bytes => Ok(()), - OutputTarget::Write(..) | OutputTarget::Vec(..) => { - // TODO: must not reserve additional in Vec - self.refresh_buffer() - } - } - } - - /// Write a byte - pub fn write_raw_byte(&mut self, byte: u8) -> ProtobufResult<()> { - if self.position as usize == self.buffer().len() { - self.refresh_buffer()?; - } - unsafe { maybe_uninit_write(&mut (&mut *self.buffer)[self.position as usize], byte) }; - self.position += 1; - Ok(()) - } - - /// Write bytes - pub fn write_raw_bytes(&mut self, bytes: &[u8]) -> ProtobufResult<()> { - if bytes.len() <= self.buffer().len() - self.position { - let bottom = self.position as usize; - let top = bottom + (bytes.len() as usize); - // SAFETY: see the `buffer` field documentation about invariants. - let buffer = unsafe { &mut (&mut *self.buffer)[bottom..top] }; - maybe_uninit_write_slice(buffer, bytes); - self.position += bytes.len(); - return Ok(()); - } - - self.refresh_buffer()?; - - assert!(self.position == 0); - - if self.position + bytes.len() < self.buffer().len() { - // SAFETY: see the `buffer` field documentation about invariants. - let buffer = - unsafe { &mut (&mut *self.buffer)[self.position..self.position + bytes.len()] }; - maybe_uninit_write_slice(buffer, bytes); - self.position += bytes.len(); - return Ok(()); - } - - match self.target { - OutputTarget::Bytes => { - unreachable!(); - } - OutputTarget::Write(ref mut write, _) => { - write.write_all(bytes)?; - } - OutputTarget::Vec(ref mut vec) => { - vec.extend(bytes); - self.buffer = vec_spare_capacity_mut(vec) - } - } - Ok(()) - } - - /// Write a tag - pub fn write_tag( - &mut self, - field_number: u32, - wire_type: wire_format::WireType, - ) -> ProtobufResult<()> { - self.write_raw_varint32(wire_format::Tag::make(field_number, wire_type).value()) - } - - /// Write varint - pub fn write_raw_varint32(&mut self, value: u32) -> ProtobufResult<()> { - if self.buffer().len() - self.position >= 5 { - // fast path - let len = unsafe { - varint::encode_varint32(value, &mut (&mut *self.buffer)[self.position..]) - }; - self.position += len; - Ok(()) - } else { - // slow path - let buf = &mut [0u8; 5]; - let len = varint::encode_varint32(value, unsafe { - slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut MaybeUninit<u8>, buf.len()) - }); - self.write_raw_bytes(&buf[..len]) - } - } - - /// Write varint - pub fn write_raw_varint64(&mut self, value: u64) -> ProtobufResult<()> { - if self.buffer().len() - self.position >= 10 { - // fast path - let len = unsafe { - varint::encode_varint64(value, &mut (&mut *self.buffer)[self.position..]) - }; - self.position += len; - Ok(()) - } else { - // slow path - let buf = &mut [0u8; 10]; - let len = varint::encode_varint64(value, unsafe { - slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut MaybeUninit<u8>, buf.len()) - }); - self.write_raw_bytes(&buf[..len]) - } - } - - /// Write 32-bit integer little endian - pub fn write_raw_little_endian32(&mut self, value: u32) -> ProtobufResult<()> { - let bytes = unsafe { mem::transmute::<_, [u8; 4]>(value.to_le()) }; - self.write_raw_bytes(&bytes) - } - - /// Write 64-bit integer little endian - pub fn write_raw_little_endian64(&mut self, value: u64) -> ProtobufResult<()> { - let bytes = unsafe { mem::transmute::<_, [u8; 8]>(value.to_le()) }; - self.write_raw_bytes(&bytes) - } - - /// Write `float` - pub fn write_float_no_tag(&mut self, value: f32) -> ProtobufResult<()> { - let bits = unsafe { mem::transmute::<f32, u32>(value) }; - self.write_raw_little_endian32(bits) - } - - /// Write `double` - pub fn write_double_no_tag(&mut self, value: f64) -> ProtobufResult<()> { - let bits = unsafe { mem::transmute::<f64, u64>(value) }; - self.write_raw_little_endian64(bits) - } - - /// Write `float` field - pub fn write_float(&mut self, field_number: u32, value: f32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed32)?; - self.write_float_no_tag(value)?; - Ok(()) - } - - /// Write `double` field - pub fn write_double(&mut self, field_number: u32, value: f64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed64)?; - self.write_double_no_tag(value)?; - Ok(()) - } - - /// Write varint - pub fn write_uint64_no_tag(&mut self, value: u64) -> ProtobufResult<()> { - self.write_raw_varint64(value) - } - - /// Write varint - pub fn write_uint32_no_tag(&mut self, value: u32) -> ProtobufResult<()> { - self.write_raw_varint32(value) - } - - /// Write varint - pub fn write_int64_no_tag(&mut self, value: i64) -> ProtobufResult<()> { - self.write_raw_varint64(value as u64) - } - - /// Write varint - pub fn write_int32_no_tag(&mut self, value: i32) -> ProtobufResult<()> { - self.write_raw_varint64(value as u64) - } - - /// Write zigzag varint - pub fn write_sint64_no_tag(&mut self, value: i64) -> ProtobufResult<()> { - self.write_uint64_no_tag(encode_zig_zag_64(value)) - } - - /// Write zigzag varint - pub fn write_sint32_no_tag(&mut self, value: i32) -> ProtobufResult<()> { - self.write_uint32_no_tag(encode_zig_zag_32(value)) - } - - /// Write `fixed64` - pub fn write_fixed64_no_tag(&mut self, value: u64) -> ProtobufResult<()> { - self.write_raw_little_endian64(value) - } - - /// Write `fixed32` - pub fn write_fixed32_no_tag(&mut self, value: u32) -> ProtobufResult<()> { - self.write_raw_little_endian32(value) - } - - /// Write `sfixed64` - pub fn write_sfixed64_no_tag(&mut self, value: i64) -> ProtobufResult<()> { - self.write_raw_little_endian64(value as u64) - } - - /// Write `sfixed32` - pub fn write_sfixed32_no_tag(&mut self, value: i32) -> ProtobufResult<()> { - self.write_raw_little_endian32(value as u32) - } - - /// Write `bool` - pub fn write_bool_no_tag(&mut self, value: bool) -> ProtobufResult<()> { - self.write_raw_varint32(if value { 1 } else { 0 }) - } - - /// Write `enum` - pub fn write_enum_no_tag(&mut self, value: i32) -> ProtobufResult<()> { - self.write_int32_no_tag(value) - } - - /// Write `enum` - pub fn write_enum_obj_no_tag<E>(&mut self, value: E) -> ProtobufResult<()> - where - E: ProtobufEnum, - { - self.write_enum_no_tag(value.value()) - } - - /// Write unknown value - pub fn write_unknown_no_tag(&mut self, unknown: UnknownValueRef) -> ProtobufResult<()> { - match unknown { - UnknownValueRef::Fixed64(fixed64) => self.write_raw_little_endian64(fixed64), - UnknownValueRef::Fixed32(fixed32) => self.write_raw_little_endian32(fixed32), - UnknownValueRef::Varint(varint) => self.write_raw_varint64(varint), - UnknownValueRef::LengthDelimited(bytes) => self.write_bytes_no_tag(bytes), - } - } - - /// Write `uint64` field - pub fn write_uint64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_uint64_no_tag(value)?; - Ok(()) - } - - /// Write `uint32` field - pub fn write_uint32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_uint32_no_tag(value)?; - Ok(()) - } - - /// Write `int64` field - pub fn write_int64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_int64_no_tag(value)?; - Ok(()) - } - - /// Write `int32` field - pub fn write_int32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_int32_no_tag(value)?; - Ok(()) - } - - /// Write `sint64` field - pub fn write_sint64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_sint64_no_tag(value)?; - Ok(()) - } - - /// Write `sint32` field - pub fn write_sint32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_sint32_no_tag(value)?; - Ok(()) - } - - /// Write `fixed64` field - pub fn write_fixed64(&mut self, field_number: u32, value: u64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed64)?; - self.write_fixed64_no_tag(value)?; - Ok(()) - } - - /// Write `fixed32` field - pub fn write_fixed32(&mut self, field_number: u32, value: u32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed32)?; - self.write_fixed32_no_tag(value)?; - Ok(()) - } - - /// Write `sfixed64` field - pub fn write_sfixed64(&mut self, field_number: u32, value: i64) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed64)?; - self.write_sfixed64_no_tag(value)?; - Ok(()) - } - - /// Write `sfixed32` field - pub fn write_sfixed32(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeFixed32)?; - self.write_sfixed32_no_tag(value)?; - Ok(()) - } - - /// Write `bool` field - pub fn write_bool(&mut self, field_number: u32, value: bool) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_bool_no_tag(value)?; - Ok(()) - } - - /// Write `enum` field - pub fn write_enum(&mut self, field_number: u32, value: i32) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeVarint)?; - self.write_enum_no_tag(value)?; - Ok(()) - } - - /// Write `enum` field - pub fn write_enum_obj<E>(&mut self, field_number: u32, value: E) -> ProtobufResult<()> - where - E: ProtobufEnum, - { - self.write_enum(field_number, value.value()) - } - - /// Write unknown field - pub fn write_unknown( - &mut self, - field_number: u32, - value: UnknownValueRef, - ) -> ProtobufResult<()> { - self.write_tag(field_number, value.wire_type())?; - self.write_unknown_no_tag(value)?; - Ok(()) - } - - /// Write unknown fields - pub fn write_unknown_fields(&mut self, fields: &UnknownFields) -> ProtobufResult<()> { - for (number, values) in fields { - for value in values { - self.write_unknown(number, value)?; - } - } - Ok(()) - } - - /// Write bytes - pub fn write_bytes_no_tag(&mut self, bytes: &[u8]) -> ProtobufResult<()> { - self.write_raw_varint32(bytes.len() as u32)?; - self.write_raw_bytes(bytes)?; - Ok(()) - } - - /// Write string - pub fn write_string_no_tag(&mut self, s: &str) -> ProtobufResult<()> { - self.write_bytes_no_tag(s.as_bytes()) - } - - /// Write message - pub fn write_message_no_tag<M: Message>(&mut self, msg: &M) -> ProtobufResult<()> { - msg.write_length_delimited_to(self) - } - - /// Write `bytes` field - pub fn write_bytes(&mut self, field_number: u32, bytes: &[u8]) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?; - self.write_bytes_no_tag(bytes)?; - Ok(()) - } - - /// Write `string` field - pub fn write_string(&mut self, field_number: u32, s: &str) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?; - self.write_string_no_tag(s)?; - Ok(()) - } - - /// Write `message` field - pub fn write_message<M: Message>(&mut self, field_number: u32, msg: &M) -> ProtobufResult<()> { - self.write_tag(field_number, wire_format::WireTypeLengthDelimited)?; - self.write_message_no_tag(msg)?; - Ok(()) - } -} - -impl<'a> Write for CodedOutputStream<'a> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.write_raw_bytes(buf)?; - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - CodedOutputStream::flush(self).map_err(Into::into) - } -} - -#[cfg(test)] -mod test { - use std::io::Write; - use std::iter; - - use crate::coded_output_stream::CodedOutputStream; - use crate::hex::decode_hex; - use crate::hex::encode_hex; - use crate::wire_format; - use crate::ProtobufResult; - - fn test_write<F>(expected: &str, mut gen: F) - where - F: FnMut(&mut CodedOutputStream) -> ProtobufResult<()>, - { - let expected_bytes = decode_hex(expected); - - // write to Write - { - let mut v = Vec::new(); - { - let mut os = CodedOutputStream::new(&mut v as &mut dyn Write); - gen(&mut os).unwrap(); - os.flush().unwrap(); - } - assert_eq!(encode_hex(&expected_bytes), encode_hex(&v)); - } - - // write to &[u8] - { - let mut r = Vec::with_capacity(expected_bytes.len()); - r.resize(expected_bytes.len(), 0); - { - let mut os = CodedOutputStream::bytes(&mut r); - gen(&mut os).unwrap(); - os.check_eof(); - } - assert_eq!(encode_hex(&expected_bytes), encode_hex(&r)); - } - - // write to Vec<u8> - { - let mut r = Vec::new(); - r.extend(&[11, 22, 33, 44, 55, 66, 77]); - { - let mut os = CodedOutputStream::vec(&mut r); - gen(&mut os).unwrap(); - os.flush().unwrap(); - } - - r.drain(..7); - assert_eq!(encode_hex(&expected_bytes), encode_hex(&r)); - } - } - - #[test] - fn test_output_stream_write_raw_byte() { - test_write("a1", |os| os.write_raw_byte(0xa1)); - } - - #[test] - fn test_output_stream_write_tag() { - test_write("08", |os| os.write_tag(1, wire_format::WireTypeVarint)); - } - - #[test] - fn test_output_stream_write_raw_bytes() { - test_write("00 ab", |os| os.write_raw_bytes(&[0x00, 0xab])); - - let expected = iter::repeat("01 02 03 04") - .take(2048) - .collect::<Vec<_>>() - .join(" "); - test_write(&expected, |os| { - for _ in 0..2048 { - os.write_raw_bytes(&[0x01, 0x02, 0x03, 0x04])?; - } - - Ok(()) - }); - } - - #[test] - fn test_output_stream_write_raw_varint32() { - test_write("96 01", |os| os.write_raw_varint32(150)); - test_write("ff ff ff ff 0f", |os| os.write_raw_varint32(0xffffffff)); - } - - #[test] - fn test_output_stream_write_raw_varint64() { - test_write("96 01", |os| os.write_raw_varint64(150)); - test_write("ff ff ff ff ff ff ff ff ff 01", |os| { - os.write_raw_varint64(0xffffffffffffffff) - }); - } - - #[test] - fn test_output_stream_write_int32_no_tag() { - test_write("ff ff ff ff ff ff ff ff ff 01", |os| { - os.write_int32_no_tag(-1) - }); - } - - #[test] - fn test_output_stream_write_int64_no_tag() { - test_write("ff ff ff ff ff ff ff ff ff 01", |os| { - os.write_int64_no_tag(-1) - }); - } - - #[test] - fn test_output_stream_write_raw_little_endian32() { - test_write("f1 e2 d3 c4", |os| os.write_raw_little_endian32(0xc4d3e2f1)); - } - - #[test] - fn test_output_stream_write_float_no_tag() { - test_write("95 73 13 61", |os| os.write_float_no_tag(17e19)); - } - - #[test] - fn test_output_stream_write_double_no_tag() { - test_write("40 d5 ab 68 b3 07 3d 46", |os| { - os.write_double_no_tag(23e29) - }); - } - - #[test] - fn test_output_stream_write_raw_little_endian64() { - test_write("f1 e2 d3 c4 b5 a6 07 f8", |os| { - os.write_raw_little_endian64(0xf807a6b5c4d3e2f1) - }); - } - - #[test] - fn test_output_stream_io_write() { - let expected = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77]; - - // write to Write - { - let mut v = Vec::new(); - { - let mut os = CodedOutputStream::new(&mut v as &mut dyn Write); - Write::write(&mut os, &expected).expect("io::Write::write"); - Write::flush(&mut os).expect("io::Write::flush"); - } - assert_eq!(expected, *v); - } - - // write to &[u8] - { - let mut v = Vec::with_capacity(expected.len()); - v.resize(expected.len(), 0); - { - let mut os = CodedOutputStream::bytes(&mut v); - Write::write(&mut os, &expected).expect("io::Write::write"); - Write::flush(&mut os).expect("io::Write::flush"); - os.check_eof(); - } - assert_eq!(expected, *v); - } - - // write to Vec<u8> - { - let mut v = Vec::new(); - { - let mut os = CodedOutputStream::vec(&mut v); - Write::write(&mut os, &expected).expect("io::Write::write"); - Write::flush(&mut os).expect("io::Write::flush"); - } - assert_eq!(expected, *v); - } - } -} diff --git a/src/coded_output_stream/buffer.rs b/src/coded_output_stream/buffer.rs new file mode 100644 index 0000000..ec4c62f --- /dev/null +++ b/src/coded_output_stream/buffer.rs @@ -0,0 +1,110 @@ +use std::fmt; +use std::fmt::Formatter; +use std::mem::MaybeUninit; +use std::slice; + +use crate::misc::maybe_uninit_write_slice; + +pub(crate) struct OutputBuffer { + // Actual buffer is owned by `OutputTarget`, + // and here we alias the buffer so access to the buffer is branchless: + // access does not require switch by actual target type: `&[], `Vec`, `Write` etc. + // We don't access the actual buffer in `OutputTarget` except when + // we initialize `buffer` field here. + buffer: *mut [MaybeUninit<u8>], + /// Position within the buffer. + /// Always correct. + pos_within_buf: usize, +} + +impl fmt::Debug for OutputBuffer { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("OutputBuffer") + .field("buffer.len", &self.buffer().len()) + .field("pos_within_buf", &self.pos_within_buf) + .finish() + } +} + +impl OutputBuffer { + #[inline] + pub(crate) fn new(buffer: *mut [MaybeUninit<u8>]) -> OutputBuffer { + Self { + buffer, + pos_within_buf: 0, + } + } + + /// Whole buffer: written data + unwritten data. + #[inline] + pub(crate) fn buffer(&self) -> &[MaybeUninit<u8>] { + unsafe { &*self.buffer } + } + + #[inline] + fn buffer_mut(&mut self) -> &mut [MaybeUninit<u8>] { + unsafe { &mut *self.buffer } + } + + #[inline] + pub(crate) fn pos_within_buf(&self) -> usize { + self.pos_within_buf + } + + #[inline] + pub(crate) fn filled(&self) -> &[u8] { + // SAFETY: This type invariant is data is filled up to `pos_within_buf`. + unsafe { slice::from_raw_parts_mut(self.buffer as *mut u8, self.pos_within_buf) } + } + + #[inline] + pub(crate) fn unfilled(&mut self) -> &mut [MaybeUninit<u8>] { + // SAFETY: This type invariant is `pos_within_buf` is smaller than buffer length. + let pos_within_buf = self.pos_within_buf; + unsafe { self.buffer_mut().get_unchecked_mut(pos_within_buf..) } + } + + #[inline] + pub(crate) fn unfilled_len(&self) -> usize { + self.buffer().len() - self.pos_within_buf + } + + #[inline] + pub(crate) unsafe fn advance(&mut self, n: usize) { + debug_assert!(n <= self.unfilled_len()); + self.pos_within_buf += n; + } + + #[inline] + pub(crate) fn rewind(&mut self) { + self.pos_within_buf = 0; + } + + #[inline] + pub(crate) fn replace_buffer_keep_pos(&mut self, buffer: *mut [MaybeUninit<u8>]) { + unsafe { + assert!(self.pos_within_buf <= (&*buffer).len()); + } + self.buffer = buffer; + } + + #[inline] + pub(crate) unsafe fn write_byte(&mut self, b: u8) { + debug_assert!(self.unfilled_len() >= 1); + // SAFETY: caller is responsible for ensuring that byte fits in the buffer. + let pos_within_buf = self.pos_within_buf; + self.buffer_mut().get_unchecked_mut(pos_within_buf).write(b); + self.pos_within_buf += 1; + } + + #[inline] + pub(crate) unsafe fn write_bytes(&mut self, bytes: &[u8]) { + debug_assert!(self.unfilled_len() >= bytes.len()); + let bottom = self.pos_within_buf as usize; + let top = bottom + (bytes.len() as usize); + // SAFETY: caller is responsible for ensuring that `bytes` fits in the buffer. + let buffer = self.buffer_mut().get_unchecked_mut(bottom..top); + maybe_uninit_write_slice(buffer, bytes); + self.pos_within_buf += bytes.len(); + } +} diff --git a/src/coded_output_stream/mod.rs b/src/coded_output_stream/mod.rs new file mode 100644 index 0000000..5010df9 --- /dev/null +++ b/src/coded_output_stream/mod.rs @@ -0,0 +1,1225 @@ +mod buffer; +mod output_target; +pub(crate) mod with; + +use std::io; +use std::io::Write; +use std::mem::MaybeUninit; +use std::ptr; +use std::slice; + +use crate::byteorder::LITTLE_ENDIAN; +use crate::coded_output_stream::buffer::OutputBuffer; +use crate::coded_output_stream::output_target::OutputTarget; +use crate::error::ProtobufError; +use crate::rt::packed::vec_packed_enum_or_unknown_data_size; +use crate::rt::packed::vec_packed_fixed_data_size; +use crate::rt::packed::vec_packed_varint_data_size; +use crate::rt::packed::vec_packed_varint_zigzag_data_size; +use crate::varint::encode::encode_varint32; +use crate::varint::encode::encode_varint64; +use crate::varint::encode::encoded_varint64_len; +use crate::varint::MAX_VARINT_ENCODED_LEN; +use crate::wire_format; +use crate::wire_format::check_message_size; +use crate::wire_format::WireType; +use crate::wire_format::MAX_MESSAGE_SIZE; +use crate::zigzag::encode_zig_zag_32; +use crate::zigzag::encode_zig_zag_64; +use crate::Enum; +use crate::EnumOrUnknown; +use crate::Message; +use crate::MessageDyn; +use crate::MessageFull; +use crate::UnknownFields; +use crate::UnknownValueRef; + +// Equal to the default buffer size of `BufWriter`, so when +// `CodedOutputStream` wraps `BufWriter`, it often skips double buffering. +const OUTPUT_STREAM_BUFFER_SIZE: usize = 8 * 1024; + +/// Buffered write with handy utilities +#[derive(Debug)] +pub struct CodedOutputStream<'a> { + target: OutputTarget<'a>, + buffer: OutputBuffer, + /// Absolute position of the buffer start. + pos_of_buffer_start: u64, +} + +impl<'a> CodedOutputStream<'a> { + /// Construct from given `Write`. + /// + /// `CodedOutputStream` is buffered even if `Write` is not + pub fn new(writer: &'a mut dyn Write) -> CodedOutputStream<'a> { + let buffer_len = OUTPUT_STREAM_BUFFER_SIZE; + + let mut buffer_storage = Vec::with_capacity(buffer_len); + + // SAFETY: we are not using the `buffer_storage` + // except for initializing the `buffer` field. + // See `buffer` field documentation. + let buffer = OutputBuffer::new(buffer_storage.spare_capacity_mut()); + + CodedOutputStream { + target: OutputTarget::Write(writer, buffer_storage), + buffer, + pos_of_buffer_start: 0, + } + } + + /// `CodedOutputStream` which writes directly to bytes. + /// + /// Attempt to write more than bytes capacity results in error. + pub fn bytes(bytes: &'a mut [u8]) -> CodedOutputStream<'a> { + // SAFETY: it is safe to cast from &mut [u8] to &mut [MaybeUninit<u8>]. + let buffer = + ptr::slice_from_raw_parts_mut(bytes.as_mut_ptr() as *mut MaybeUninit<u8>, bytes.len()); + let buffer = OutputBuffer::new(buffer); + CodedOutputStream { + target: OutputTarget::Bytes, + buffer, + pos_of_buffer_start: 0, + } + } + + /// `CodedOutputStream` which writes directly to `Vec<u8>`. + pub fn vec(vec: &'a mut Vec<u8>) -> CodedOutputStream<'a> { + let buffer = OutputBuffer::new(vec.spare_capacity_mut()); + CodedOutputStream { + target: OutputTarget::Vec(vec), + buffer, + pos_of_buffer_start: 0, + } + } + + pub(crate) fn reserve_additional( + &mut self, + additional: u32, + message: &str, + ) -> crate::Result<()> { + if additional as usize <= self.buffer.unfilled_len() { + return Ok(()); + } + match &mut self.target { + OutputTarget::Write(..) => Ok(()), + OutputTarget::Vec(v) => { + let reserve = (additional as usize) + .checked_add(self.buffer.pos_within_buf()) + .unwrap(); + v.reserve(reserve); + // `pos_within_buf` remains unchanged. + self.buffer.replace_buffer_keep_pos(v.spare_capacity_mut()); + Ok(()) + } + OutputTarget::Bytes => { + Err(ProtobufError::BufferHasNotEnoughCapacity(message.to_owned()).into()) + } + } + } + + pub(crate) fn reserve_additional_for_length_delimited( + &mut self, + size: u32, + message: &str, + ) -> crate::Result<()> { + debug_assert!( + size <= MAX_MESSAGE_SIZE as u32, + "Caller of this function is responsible to guarantee \ + that message size does not exceed; size: {}, MAX_MESSAGE_SIZE: {}", + size, + MAX_MESSAGE_SIZE, + ); + let reserve = size + encoded_varint64_len(size as u64) as u32; + self.reserve_additional(reserve, message) + } + + /// Total number of bytes written to this stream. + /// + /// This number may be larger than the actual number of bytes written to the underlying stream, + /// if the buffer was not flushed. + /// + /// The number may be inaccurate if there was an error during the write. + pub fn total_bytes_written(&self) -> u64 { + self.pos_of_buffer_start + self.buffer.pos_within_buf() as u64 + } + + /// Check if EOF is reached. + /// + /// # Panics + /// + /// If underlying write has no EOF + pub fn check_eof(&self) { + match self.target { + OutputTarget::Bytes => { + assert_eq!( + self.buffer.buffer().len() as u64, + self.buffer.pos_within_buf() as u64 + ); + } + OutputTarget::Write(..) | OutputTarget::Vec(..) => { + panic!("must not be called with Writer or Vec"); + } + } + } + + fn refresh_buffer(&mut self) -> crate::Result<()> { + match self.target { + OutputTarget::Write(ref mut write, _) => { + write.write_all(self.buffer.filled())?; + self.pos_of_buffer_start += self.buffer.pos_within_buf() as u64; + self.buffer.rewind(); + } + OutputTarget::Vec(ref mut vec) => unsafe { + let vec_len = vec.len(); + assert!(vec_len + self.buffer.pos_within_buf() <= vec.capacity()); + vec.set_len(vec_len + self.buffer.pos_within_buf()); + vec.reserve(1); + self.pos_of_buffer_start += self.buffer.pos_within_buf() as u64; + self.buffer = OutputBuffer::new(vec.spare_capacity_mut()); + }, + OutputTarget::Bytes => { + return Err(ProtobufError::IoError(io::Error::new( + io::ErrorKind::Other, + "given slice is too small to serialize the message", + )) + .into()); + } + } + Ok(()) + } + + /// Flush to buffer to the underlying buffer. + /// Note that `CodedOutputStream` does `flush` in the destructor, + /// however, if `flush` in destructor fails, then destructor panics + /// and program terminates. So it's advisable to explicitly call flush + /// before destructor. + pub fn flush(&mut self) -> crate::Result<()> { + match &mut self.target { + OutputTarget::Bytes => Ok(()), + OutputTarget::Vec(vec) => { + let vec_len = vec.len(); + assert!(vec_len + self.buffer.pos_within_buf() <= vec.capacity()); + unsafe { + vec.set_len(vec_len + self.buffer.pos_within_buf()); + } + self.pos_of_buffer_start += self.buffer.pos_within_buf() as u64; + self.buffer = OutputBuffer::new(vec.spare_capacity_mut()); + Ok(()) + } + OutputTarget::Write(..) => self.refresh_buffer(), + } + } + + /// Write a byte + pub fn write_raw_byte(&mut self, byte: u8) -> crate::Result<()> { + if self.buffer.unfilled_len() == 0 { + self.refresh_buffer()?; + } + unsafe { self.buffer.write_byte(byte) }; + Ok(()) + } + + /// Write bytes + pub fn write_raw_bytes(&mut self, bytes: &[u8]) -> crate::Result<()> { + if bytes.len() <= self.buffer.unfilled_len() { + // SAFETY: we've just checked that there's enough space in the buffer. + unsafe { self.buffer.write_bytes(bytes) }; + return Ok(()); + } + + self.refresh_buffer()?; + + assert!(self.buffer.pos_within_buf() == 0); + + if bytes.len() <= self.buffer.unfilled_len() { + // SAFETY: we've just checked that there's enough space in the buffer. + unsafe { self.buffer.write_bytes(bytes) }; + return Ok(()); + } + + match self.target { + OutputTarget::Bytes => { + unreachable!(); + } + OutputTarget::Write(ref mut write, _) => { + write.write_all(bytes)?; + } + OutputTarget::Vec(ref mut vec) => { + assert!(self.buffer.pos_within_buf() == 0); + vec.extend(bytes); + self.buffer = OutputBuffer::new(vec.spare_capacity_mut()); + self.pos_of_buffer_start += bytes.len() as u64; + } + } + Ok(()) + } + + /// Write a tag + pub fn write_tag(&mut self, field_number: u32, wire_type: WireType) -> crate::Result<()> { + self.write_raw_varint32(wire_format::Tag::make(field_number, wire_type).value()) + } + + /// Write varint + pub fn write_raw_varint32(&mut self, value: u32) -> crate::Result<()> { + if self.buffer.unfilled_len() >= 5 { + // fast path + unsafe { + let len = encode_varint32(value, self.buffer.unfilled()); + self.buffer.advance(len); + }; + Ok(()) + } else { + // slow path + let buf = &mut [0u8; 5]; + let len = encode_varint32(value, unsafe { + slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut MaybeUninit<u8>, buf.len()) + }); + self.write_raw_bytes(&buf[..len]) + } + } + + /// Write varint + pub fn write_raw_varint64(&mut self, value: u64) -> crate::Result<()> { + if self.buffer.unfilled_len() >= MAX_VARINT_ENCODED_LEN { + // fast path + unsafe { + let len = encode_varint64(value, self.buffer.unfilled()); + self.buffer.advance(len); + }; + Ok(()) + } else { + // slow path + let buf = &mut [0u8; MAX_VARINT_ENCODED_LEN]; + let len = encode_varint64(value, unsafe { + slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut MaybeUninit<u8>, buf.len()) + }); + self.write_raw_bytes(&buf[..len]) + } + } + + /// Write 32-bit integer little endian + pub fn write_raw_little_endian32(&mut self, value: u32) -> crate::Result<()> { + self.write_raw_bytes(&value.to_le_bytes()) + } + + /// Write 64-bit integer little endian + pub fn write_raw_little_endian64(&mut self, value: u64) -> crate::Result<()> { + self.write_raw_bytes(&value.to_le_bytes()) + } + + /// Write `float` + pub fn write_float_no_tag(&mut self, value: f32) -> crate::Result<()> { + self.write_raw_little_endian32(value.to_bits()) + } + + /// Write `double` + pub fn write_double_no_tag(&mut self, value: f64) -> crate::Result<()> { + self.write_raw_little_endian64(value.to_bits()) + } + + /// Write `float` field + pub fn write_float(&mut self, field_number: u32, value: f32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed32)?; + self.write_float_no_tag(value)?; + Ok(()) + } + + /// Write `double` field + pub fn write_double(&mut self, field_number: u32, value: f64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed64)?; + self.write_double_no_tag(value)?; + Ok(()) + } + + /// Write varint + pub fn write_uint64_no_tag(&mut self, value: u64) -> crate::Result<()> { + self.write_raw_varint64(value) + } + + /// Write varint + pub fn write_uint32_no_tag(&mut self, value: u32) -> crate::Result<()> { + self.write_raw_varint32(value) + } + + /// Write varint + pub fn write_int64_no_tag(&mut self, value: i64) -> crate::Result<()> { + self.write_raw_varint64(value as u64) + } + + /// Write varint + pub fn write_int32_no_tag(&mut self, value: i32) -> crate::Result<()> { + self.write_raw_varint64(value as u64) + } + + /// Write zigzag varint + pub fn write_sint64_no_tag(&mut self, value: i64) -> crate::Result<()> { + self.write_uint64_no_tag(encode_zig_zag_64(value)) + } + + /// Write zigzag varint + pub fn write_sint32_no_tag(&mut self, value: i32) -> crate::Result<()> { + self.write_uint32_no_tag(encode_zig_zag_32(value)) + } + + /// Write `fixed64` + pub fn write_fixed64_no_tag(&mut self, value: u64) -> crate::Result<()> { + self.write_raw_little_endian64(value) + } + + /// Write `fixed32` + pub fn write_fixed32_no_tag(&mut self, value: u32) -> crate::Result<()> { + self.write_raw_little_endian32(value) + } + + /// Write `sfixed64` + pub fn write_sfixed64_no_tag(&mut self, value: i64) -> crate::Result<()> { + self.write_raw_little_endian64(value as u64) + } + + /// Write `sfixed32` + pub fn write_sfixed32_no_tag(&mut self, value: i32) -> crate::Result<()> { + self.write_raw_little_endian32(value as u32) + } + + /// Write `bool` + pub fn write_bool_no_tag(&mut self, value: bool) -> crate::Result<()> { + self.write_raw_varint32(if value { 1 } else { 0 }) + } + + /// Write `enum` + pub fn write_enum_no_tag(&mut self, value: i32) -> crate::Result<()> { + self.write_int32_no_tag(value) + } + + /// Write `enum` + pub fn write_enum_obj_no_tag<E>(&mut self, value: E) -> crate::Result<()> + where + E: Enum, + { + self.write_enum_no_tag(value.value()) + } + + /// Write `enum` + pub fn write_enum_or_unknown_no_tag<E>(&mut self, value: EnumOrUnknown<E>) -> crate::Result<()> + where + E: Enum, + { + self.write_enum_no_tag(value.value()) + } + + /// Write unknown value + pub fn write_unknown_no_tag(&mut self, unknown: UnknownValueRef) -> crate::Result<()> { + match unknown { + UnknownValueRef::Fixed64(fixed64) => self.write_raw_little_endian64(fixed64), + UnknownValueRef::Fixed32(fixed32) => self.write_raw_little_endian32(fixed32), + UnknownValueRef::Varint(varint) => self.write_raw_varint64(varint), + UnknownValueRef::LengthDelimited(bytes) => self.write_bytes_no_tag(bytes), + } + } + + /// Write `uint64` field + pub fn write_uint64(&mut self, field_number: u32, value: u64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_uint64_no_tag(value)?; + Ok(()) + } + + /// Write `uint32` field + pub fn write_uint32(&mut self, field_number: u32, value: u32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_uint32_no_tag(value)?; + Ok(()) + } + + /// Write `int64` field + pub fn write_int64(&mut self, field_number: u32, value: i64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_int64_no_tag(value)?; + Ok(()) + } + + /// Write `int32` field + pub fn write_int32(&mut self, field_number: u32, value: i32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_int32_no_tag(value)?; + Ok(()) + } + + /// Write `sint64` field + pub fn write_sint64(&mut self, field_number: u32, value: i64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_sint64_no_tag(value)?; + Ok(()) + } + + /// Write `sint32` field + pub fn write_sint32(&mut self, field_number: u32, value: i32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_sint32_no_tag(value)?; + Ok(()) + } + + /// Write `fixed64` field + pub fn write_fixed64(&mut self, field_number: u32, value: u64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed64)?; + self.write_fixed64_no_tag(value)?; + Ok(()) + } + + /// Write `fixed32` field + pub fn write_fixed32(&mut self, field_number: u32, value: u32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed32)?; + self.write_fixed32_no_tag(value)?; + Ok(()) + } + + /// Write `sfixed64` field + pub fn write_sfixed64(&mut self, field_number: u32, value: i64) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed64)?; + self.write_sfixed64_no_tag(value)?; + Ok(()) + } + + /// Write `sfixed32` field + pub fn write_sfixed32(&mut self, field_number: u32, value: i32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Fixed32)?; + self.write_sfixed32_no_tag(value)?; + Ok(()) + } + + /// Write `bool` field + pub fn write_bool(&mut self, field_number: u32, value: bool) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_bool_no_tag(value)?; + Ok(()) + } + + /// Write `enum` field + pub fn write_enum(&mut self, field_number: u32, value: i32) -> crate::Result<()> { + self.write_tag(field_number, WireType::Varint)?; + self.write_enum_no_tag(value)?; + Ok(()) + } + + /// Write `enum` field + pub fn write_enum_obj<E>(&mut self, field_number: u32, value: E) -> crate::Result<()> + where + E: Enum, + { + self.write_enum(field_number, value.value()) + } + + /// Write `enum` field + pub fn write_enum_or_unknown<E>( + &mut self, + field_number: u32, + value: EnumOrUnknown<E>, + ) -> crate::Result<()> + where + E: Enum, + { + self.write_enum(field_number, value.value()) + } + + /// Write unknown field + pub fn write_unknown( + &mut self, + field_number: u32, + value: UnknownValueRef, + ) -> crate::Result<()> { + self.write_tag(field_number, value.wire_type())?; + self.write_unknown_no_tag(value)?; + Ok(()) + } + + /// Write unknown fields + pub fn write_unknown_fields(&mut self, fields: &UnknownFields) -> crate::Result<()> { + for (number, value) in fields { + self.write_unknown(number, value)?; + } + Ok(()) + } + + /// Write unknown fields sorting them by name + // TODO: make unknown fields deterministic and remove this. + pub(crate) fn write_unknown_fields_sorted( + &mut self, + fields: &UnknownFields, + ) -> crate::Result<()> { + let mut fields: Vec<_> = fields.iter().collect(); + fields.sort_by_key(|(n, _)| *n); + for (number, value) in fields { + self.write_unknown(number, value)?; + } + Ok(()) + } + + /// Write bytes + pub fn write_bytes_no_tag(&mut self, bytes: &[u8]) -> crate::Result<()> { + self.write_raw_varint32(bytes.len() as u32)?; + self.write_raw_bytes(bytes)?; + Ok(()) + } + + /// Write string + pub fn write_string_no_tag(&mut self, s: &str) -> crate::Result<()> { + self.write_bytes_no_tag(s.as_bytes()) + } + + /// Write message + pub fn write_message_no_tag<M: Message>(&mut self, msg: &M) -> crate::Result<()> { + msg.write_length_delimited_to(self) + } + + /// Write dynamic message + pub fn write_message_no_tag_dyn(&mut self, msg: &dyn MessageDyn) -> crate::Result<()> { + let size = msg.compute_size_dyn(); + let size = check_message_size(size)?; + self.write_raw_varint32(size)?; + msg.write_to_dyn(self)?; + Ok(()) + } + + /// Write `bytes` field + pub fn write_bytes(&mut self, field_number: u32, bytes: &[u8]) -> crate::Result<()> { + self.write_tag(field_number, WireType::LengthDelimited)?; + self.write_bytes_no_tag(bytes)?; + Ok(()) + } + + /// Write `string` field + pub fn write_string(&mut self, field_number: u32, s: &str) -> crate::Result<()> { + self.write_tag(field_number, WireType::LengthDelimited)?; + self.write_string_no_tag(s)?; + Ok(()) + } + + /// Write repeated packed float values. + pub fn write_repeated_packed_float_no_tag(&mut self, values: &[f32]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute floats to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 4) }; + self.write_raw_bytes(bytes) + } else { + for v in values { + self.write_float_no_tag(*v)?; + } + Ok(()) + } + } + + /// Write field header and data for repeated packed float. + pub fn write_repeated_packed_float( + &mut self, + field_number: u32, + values: &[f32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_float_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed double values. + pub fn write_repeated_packed_double_no_tag(&mut self, values: &[f64]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute doubles to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 8) }; + self.write_raw_bytes(bytes) + } else { + for v in values { + self.write_double_no_tag(*v)?; + } + Ok(()) + } + } + + /// Write field header and data for repeated packed double. + pub fn write_repeated_packed_double( + &mut self, + field_number: u32, + values: &[f64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_double_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed fixed32 values. + pub fn write_repeated_packed_fixed32_no_tag(&mut self, values: &[u32]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute integer to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 4) }; + self.write_raw_bytes(bytes)?; + } else { + for v in values { + self.write_fixed32_no_tag(*v)?; + } + } + Ok(()) + } + + /// Write field header and data for repeated packed fixed32. + pub fn write_repeated_packed_fixed32( + &mut self, + field_number: u32, + values: &[u32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_fixed32_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed fixed64 values. + pub fn write_repeated_packed_fixed64_no_tag(&mut self, values: &[u64]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute integer to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 8) }; + self.write_raw_bytes(bytes)?; + } else { + for v in values { + self.write_fixed64_no_tag(*v)?; + } + } + Ok(()) + } + + /// Write field header and data for repeated packed fixed64. + pub fn write_repeated_packed_fixed64( + &mut self, + field_number: u32, + values: &[u64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_fixed64_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed sfixed32 values. + pub fn write_repeated_packed_sfixed32_no_tag(&mut self, values: &[i32]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute integer to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 4) }; + self.write_raw_bytes(bytes)?; + } else { + for v in values { + self.write_sfixed32_no_tag(*v)?; + } + } + Ok(()) + } + + /// Write field header and data for repeated packed sfixed32. + pub fn write_repeated_packed_sfixed32( + &mut self, + field_number: u32, + values: &[i32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_sfixed32_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed sfixed64 values. + pub fn write_repeated_packed_sfixed64_no_tag(&mut self, values: &[i64]) -> crate::Result<()> { + if LITTLE_ENDIAN { + // SAFETY: it is safe to transmute integer to bytes. + let bytes = + unsafe { slice::from_raw_parts(values.as_ptr() as *const u8, values.len() * 8) }; + self.write_raw_bytes(bytes)?; + } else { + for v in values { + self.write_sfixed64_no_tag(*v)?; + } + } + Ok(()) + } + + /// Write field header and data for repeated packed sfixed64. + pub fn write_repeated_packed_sfixed64( + &mut self, + field_number: u32, + values: &[i64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_sfixed64_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed int32 values. + pub fn write_repeated_packed_int32_no_tag(&mut self, values: &[i32]) -> crate::Result<()> { + for v in values { + self.write_int32_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed int32. + pub fn write_repeated_packed_int32( + &mut self, + field_number: u32, + values: &[i32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_int32_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed int64 values. + pub fn write_repeated_packed_int64_no_tag(&mut self, values: &[i64]) -> crate::Result<()> { + for v in values { + self.write_int64_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed int64. + pub fn write_repeated_packed_int64( + &mut self, + field_number: u32, + values: &[i64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_int64_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed uint32 values. + pub fn write_repeated_packed_uint32_no_tag(&mut self, values: &[u32]) -> crate::Result<()> { + for v in values { + self.write_uint32_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed uint32. + pub fn write_repeated_packed_uint32( + &mut self, + field_number: u32, + values: &[u32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_uint32_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed uint64 values. + pub fn write_repeated_packed_uint64_no_tag(&mut self, values: &[u64]) -> crate::Result<()> { + for v in values { + self.write_uint64_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed uint64. + pub fn write_repeated_packed_uint64( + &mut self, + field_number: u32, + values: &[u64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_uint64_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed sint32 values. + pub fn write_repeated_packed_sint32_no_tag(&mut self, values: &[i32]) -> crate::Result<()> { + for v in values { + self.write_sint32_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed sint32. + pub fn write_repeated_packed_sint32( + &mut self, + field_number: u32, + values: &[i32], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_zigzag_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_sint32_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed sint64 values. + pub fn write_repeated_packed_sint64_no_tag(&mut self, values: &[i64]) -> crate::Result<()> { + for v in values { + self.write_sint64_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed sint64. + pub fn write_repeated_packed_sint64( + &mut self, + field_number: u32, + values: &[i64], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_varint_zigzag_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_sint64_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed bool values. + pub fn write_repeated_packed_bool_no_tag(&mut self, values: &[bool]) -> crate::Result<()> { + for v in values { + self.write_bool_no_tag(*v)?; + } + Ok(()) + } + + /// Write field header and data for repeated packed bool. + pub fn write_repeated_packed_bool( + &mut self, + field_number: u32, + values: &[bool], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_fixed_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_bool_no_tag(values)?; + Ok(()) + } + + /// Write repeated packed enum values. + #[inline] + pub fn write_repeated_packed_enum_or_unknown_no_tag<E: Enum>( + &mut self, + values: &[EnumOrUnknown<E>], + ) -> crate::Result<()> { + self.write_repeated_packed_int32_no_tag(EnumOrUnknown::cast_to_values(values)) + } + + /// Write field header and data for repeated packed enum. + pub fn write_repeated_packed_enum_or_unknown<E: Enum>( + &mut self, + field_number: u32, + values: &[EnumOrUnknown<E>], + ) -> crate::Result<()> { + if values.is_empty() { + return Ok(()); + } + self.write_tag(field_number, WireType::LengthDelimited)?; + let data_size = vec_packed_enum_or_unknown_data_size(values); + self.write_raw_varint32(data_size as u32)?; + self.write_repeated_packed_enum_or_unknown_no_tag(values)?; + Ok(()) + } + + /// Write `message` field + pub fn write_message<M: MessageFull>( + &mut self, + field_number: u32, + msg: &M, + ) -> crate::Result<()> { + self.write_tag(field_number, WireType::LengthDelimited)?; + self.write_message_no_tag(msg)?; + Ok(()) + } + + /// Write dynamic `message` field + pub fn write_message_dyn( + &mut self, + field_number: u32, + msg: &dyn MessageDyn, + ) -> crate::Result<()> { + self.write_tag(field_number, WireType::LengthDelimited)?; + self.write_message_no_tag_dyn(msg)?; + Ok(()) + } +} + +impl<'a> Write for CodedOutputStream<'a> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.write_raw_bytes(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + CodedOutputStream::flush(self).map_err(Into::into) + } +} + +impl<'a> Drop for CodedOutputStream<'a> { + fn drop(&mut self) { + // This may panic + CodedOutputStream::flush(self).expect("failed to flush"); + } +} + +#[cfg(test)] +mod test { + use std::iter; + + use super::*; + use crate::hex::decode_hex; + use crate::hex::encode_hex; + + fn test_write<F>(expected: &str, mut gen: F) + where + F: FnMut(&mut CodedOutputStream) -> crate::Result<()>, + { + let expected_bytes = decode_hex(expected); + + // write to Write + { + let mut v = Vec::new(); + { + let mut os = CodedOutputStream::new(&mut v as &mut dyn Write); + gen(&mut os).unwrap(); + os.flush().unwrap(); + } + assert_eq!(encode_hex(&expected_bytes), encode_hex(&v)); + } + + // write to &[u8] + { + let mut r = Vec::with_capacity(expected_bytes.len()); + r.resize(expected_bytes.len(), 0); + { + let mut os = CodedOutputStream::bytes(&mut r); + gen(&mut os).unwrap(); + os.check_eof(); + } + assert_eq!(encode_hex(&expected_bytes), encode_hex(&r)); + } + + // write to Vec<u8> + { + let mut r = Vec::new(); + r.extend(&[11, 22, 33, 44, 55, 66, 77]); + { + let mut os = CodedOutputStream::vec(&mut r); + gen(&mut os).unwrap(); + os.flush().unwrap(); + } + + r.drain(..7); + assert_eq!(encode_hex(&expected_bytes), encode_hex(&r)); + } + } + + #[test] + fn test_output_stream_write_raw_byte() { + test_write("a1", |os| os.write_raw_byte(0xa1)); + } + + #[test] + fn test_output_stream_write_tag() { + test_write("08", |os| os.write_tag(1, WireType::Varint)); + } + + #[test] + #[cfg_attr(miri, ignore)] // Miri is too slow for this test. + fn test_output_stream_write_raw_bytes() { + test_write("00 ab", |os| os.write_raw_bytes(&[0x00, 0xab])); + + let expected = iter::repeat("01 02 03 04") + .take(2048) + .collect::<Vec<_>>() + .join(" "); + test_write(&expected, |os| { + for _ in 0..2048 { + os.write_raw_bytes(&[0x01, 0x02, 0x03, 0x04])?; + } + + Ok(()) + }); + } + + #[test] + fn test_output_stream_write_raw_varint32() { + test_write("96 01", |os| os.write_raw_varint32(150)); + test_write("ff ff ff ff 0f", |os| os.write_raw_varint32(0xffffffff)); + } + + #[test] + fn test_output_stream_write_raw_varint64() { + test_write("96 01", |os| os.write_raw_varint64(150)); + test_write("ff ff ff ff ff ff ff ff ff 01", |os| { + os.write_raw_varint64(0xffffffffffffffff) + }); + } + + #[test] + fn test_output_stream_write_int32_no_tag() { + test_write("ff ff ff ff ff ff ff ff ff 01", |os| { + os.write_int32_no_tag(-1) + }); + } + + #[test] + fn test_output_stream_write_int64_no_tag() { + test_write("ff ff ff ff ff ff ff ff ff 01", |os| { + os.write_int64_no_tag(-1) + }); + } + + #[test] + fn test_output_stream_write_raw_little_endian32() { + test_write("f1 e2 d3 c4", |os| os.write_raw_little_endian32(0xc4d3e2f1)); + } + + #[test] + fn test_output_stream_write_float_no_tag() { + test_write("95 73 13 61", |os| os.write_float_no_tag(17e19)); + } + + #[test] + fn test_output_stream_write_double_no_tag() { + test_write("40 d5 ab 68 b3 07 3d 46", |os| { + os.write_double_no_tag(23e29) + }); + } + + #[test] + fn test_output_stream_write_raw_little_endian64() { + test_write("f1 e2 d3 c4 b5 a6 07 f8", |os| { + os.write_raw_little_endian64(0xf807a6b5c4d3e2f1) + }); + } + + #[test] + fn test_output_stream_io_write() { + let expected = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77]; + + // write to Write + { + let mut v = Vec::new(); + { + let mut os = CodedOutputStream::new(&mut v as &mut dyn Write); + Write::write(&mut os, &expected).expect("io::Write::write"); + Write::flush(&mut os).expect("io::Write::flush"); + } + assert_eq!(expected, *v); + } + + // write to &[u8] + { + let mut v = Vec::with_capacity(expected.len()); + v.resize(expected.len(), 0); + { + let mut os = CodedOutputStream::bytes(&mut v); + Write::write(&mut os, &expected).expect("io::Write::write"); + Write::flush(&mut os).expect("io::Write::flush"); + os.check_eof(); + } + assert_eq!(expected, *v); + } + + // write to Vec<u8> + { + let mut v = Vec::new(); + { + let mut os = CodedOutputStream::vec(&mut v); + Write::write(&mut os, &expected).expect("io::Write::write"); + Write::flush(&mut os).expect("io::Write::flush"); + } + assert_eq!(expected, *v); + } + } + + #[test] + fn flush_for_vec_does_not_allocate_more() { + let mut v = Vec::with_capacity(10); + { + let mut os = CodedOutputStream::vec(&mut v); + for i in 0..10 { + os.write_raw_byte(i as u8).unwrap(); + } + os.flush().unwrap(); + } + assert_eq!(10, v.len()); + // Previously, this allocated more data in buf. + assert_eq!(10, v.capacity()); + } + + #[test] + fn total_bytes_written_to_bytes() { + let mut buf = vec![0; 10]; + let mut stream = CodedOutputStream::bytes(&mut buf); + assert_eq!(0, stream.total_bytes_written()); + stream.write_raw_bytes(&[11, 22]).unwrap(); + assert_eq!(2, stream.total_bytes_written()); + stream.write_raw_bytes(&[33, 44, 55]).unwrap(); + assert_eq!(5, stream.total_bytes_written()); + } + + #[test] + fn total_bytes_written_to_vec() { + let mut buf = Vec::new(); + let mut stream = CodedOutputStream::vec(&mut buf); + for i in 0..100 { + stream.write_raw_bytes(&[0, 1, 2]).unwrap(); + assert_eq!((i + 1) * 3, stream.total_bytes_written()); + } + } +} diff --git a/src/coded_output_stream/output_target.rs b/src/coded_output_stream/output_target.rs new file mode 100644 index 0000000..c60c1aa --- /dev/null +++ b/src/coded_output_stream/output_target.rs @@ -0,0 +1,32 @@ +use std::fmt; +use std::io::Write; + +/// Output buffer/writer for `CodedOutputStream`. +pub(crate) enum OutputTarget<'a> { + Write(&'a mut dyn Write, Vec<u8>), + Vec(&'a mut Vec<u8>), + /// The buffer is passed as `&[u8]` to `CodedOutputStream` constructor + /// and immediately converted to `buffer` field of `CodedOutputStream`, + /// it is not needed to be stored here. + /// Lifetime parameter of `CodedOutputStream` guarantees the buffer is valid + /// during the lifetime of `CodedOutputStream`. + Bytes, +} + +impl<'a> fmt::Debug for OutputTarget<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + OutputTarget::Write(_w, vec) => f + .debug_struct("Write") + .field("buf_len", &vec.len()) + .field("buf_cap", &vec.capacity()) + .finish_non_exhaustive(), + OutputTarget::Vec(vec) => f + .debug_struct("Vec") + .field("len", &vec.len()) + .field("cap", &vec.capacity()) + .finish_non_exhaustive(), + OutputTarget::Bytes => f.debug_tuple("Bytes").finish(), + } + } +} diff --git a/src/coded_output_stream/with.rs b/src/coded_output_stream/with.rs new file mode 100644 index 0000000..b41d71a --- /dev/null +++ b/src/coded_output_stream/with.rs @@ -0,0 +1,33 @@ +use std::io::Write; + +use crate::CodedOutputStream; + +pub(crate) trait WithCodedOutputStream { + fn with_coded_output_stream<T, F>(self, cb: F) -> crate::Result<T> + where + F: FnOnce(&mut CodedOutputStream) -> crate::Result<T>; +} + +impl<'a> WithCodedOutputStream for &'a mut (dyn Write + 'a) { + fn with_coded_output_stream<T, F>(self, cb: F) -> crate::Result<T> + where + F: FnOnce(&mut CodedOutputStream) -> crate::Result<T>, + { + let mut os = CodedOutputStream::new(self); + let r = cb(&mut os)?; + os.flush()?; + Ok(r) + } +} + +impl<'a> WithCodedOutputStream for &'a mut Vec<u8> { + fn with_coded_output_stream<T, F>(mut self, cb: F) -> crate::Result<T> + where + F: FnOnce(&mut CodedOutputStream) -> crate::Result<T>, + { + let mut os = CodedOutputStream::vec(&mut self); + let r = cb(&mut os)?; + os.flush()?; + Ok(r) + } +} diff --git a/src/compiler_plugin.rs b/src/compiler_plugin.rs deleted file mode 100644 index 122eeb3..0000000 --- a/src/compiler_plugin.rs +++ /dev/null @@ -1,53 +0,0 @@ -// TODO: move into separate crate -#![doc(hidden)] - -use std::io::stdin; -use std::io::stdout; -use std::str; - -use crate::descriptor::FileDescriptorProto; -use crate::plugin::*; -use crate::Message; - -pub struct GenRequest<'a> { - pub file_descriptors: &'a [FileDescriptorProto], - pub files_to_generate: &'a [String], - pub parameter: &'a str, -} - -pub struct GenResult { - pub name: String, - pub content: Vec<u8>, -} - -pub fn plugin_main<F>(gen: F) -where - F: Fn(&[FileDescriptorProto], &[String]) -> Vec<GenResult>, -{ - plugin_main_2(|r| gen(r.file_descriptors, r.files_to_generate)) -} - -pub fn plugin_main_2<F>(gen: F) -where - F: Fn(&GenRequest) -> Vec<GenResult>, -{ - let req = CodeGeneratorRequest::parse_from_reader(&mut stdin()).unwrap(); - let result = gen(&GenRequest { - file_descriptors: &req.get_proto_file(), - files_to_generate: &req.get_file_to_generate(), - parameter: req.get_parameter(), - }); - let mut resp = CodeGeneratorResponse::new(); - resp.set_file( - result - .iter() - .map(|file| { - let mut r = CodeGeneratorResponse_File::new(); - r.set_name(file.name.to_string()); - r.set_content(str::from_utf8(file.content.as_ref()).unwrap().to_string()); - r - }) - .collect(), - ); - resp.write_to_writer(&mut stdout()).unwrap(); -} diff --git a/src/descriptor.rs b/src/descriptor.rs index 7ca155d..9179a17 100644 --- a/src/descriptor.rs +++ b/src/descriptor.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,20 +16,22 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/descriptor.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// The protocol compiler can output a FileDescriptorSet containing the .proto +/// files it parses. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FileDescriptorSet) pub struct FileDescriptorSet { // message fields - pub file: crate::RepeatedField<FileDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorSet.file) + pub file: ::std::vec::Vec<FileDescriptorProto>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FileDescriptorSet.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FileDescriptorSet { @@ -42,33 +45,25 @@ impl FileDescriptorSet { ::std::default::Default::default() } - // repeated .google.protobuf.FileDescriptorProto file = 1; - - - pub fn get_file(&self) -> &[FileDescriptorProto] { - &self.file - } - pub fn clear_file(&mut self) { - self.file.clear(); - } - - // Param is passed by value, moved - pub fn set_file(&mut self, v: crate::RepeatedField<FileDescriptorProto>) { - self.file = v; - } - - // Mutable pointer to the field. - pub fn mut_file(&mut self) -> &mut crate::RepeatedField<FileDescriptorProto> { - &mut self.file - } - - // Take field - pub fn take_file(&mut self) -> crate::RepeatedField<FileDescriptorProto> { - ::std::mem::replace(&mut self.file, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "file", + |m: &FileDescriptorSet| { &m.file }, + |m: &mut FileDescriptorSet| { &mut m.file }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FileDescriptorSet>( + "FileDescriptorSet", + fields, + oneofs, + ) } } impl crate::Message for FileDescriptorSet { + const NAME: &'static str = "FileDescriptorSet"; + fn is_initialized(&self) -> bool { for v in &self.file { if !v.is_initialized() { @@ -78,15 +73,14 @@ impl crate::Message for FileDescriptorSet { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.file)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.file.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -95,120 +89,111 @@ impl crate::Message for FileDescriptorSet { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.file { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.file { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(1, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FileDescriptorSet { FileDescriptorSet::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<FileDescriptorProto>>( - "file", - |m: &FileDescriptorSet| { &m.file }, - |m: &mut FileDescriptorSet| { &mut m.file }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FileDescriptorSet>( - "FileDescriptorSet", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.file.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static FileDescriptorSet { - static instance: crate::rt::LazyV2<FileDescriptorSet> = crate::rt::LazyV2::INIT; - instance.get(FileDescriptorSet::new) + static instance: FileDescriptorSet = FileDescriptorSet { + file: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for FileDescriptorSet { - fn clear(&mut self) { - self.file.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for FileDescriptorSet { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FileDescriptorSet").unwrap()).clone() } } -impl ::std::fmt::Debug for FileDescriptorSet { +impl ::std::fmt::Display for FileDescriptorSet { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for FileDescriptorSet { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a complete .proto file. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FileDescriptorProto) pub struct FileDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - package: crate::SingularField<::std::string::String>, - pub dependency: crate::RepeatedField<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.package) + pub package: ::std::option::Option<::std::string::String>, + /// Names of files imported by this file. + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.dependency) + pub dependency: ::std::vec::Vec<::std::string::String>, + /// Indexes of the public imported files in the dependency list above. + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.public_dependency) pub public_dependency: ::std::vec::Vec<i32>, + /// Indexes of the weak imported files in the dependency list. + /// For Google-internal migration only. Do not use. + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.weak_dependency) pub weak_dependency: ::std::vec::Vec<i32>, - pub message_type: crate::RepeatedField<DescriptorProto>, - pub enum_type: crate::RepeatedField<EnumDescriptorProto>, - pub service: crate::RepeatedField<ServiceDescriptorProto>, - pub extension: crate::RepeatedField<FieldDescriptorProto>, - pub options: crate::SingularPtrField<FileOptions>, - pub source_code_info: crate::SingularPtrField<SourceCodeInfo>, - syntax: crate::SingularField<::std::string::String>, + /// All top-level definitions in this file. + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.message_type) + pub message_type: ::std::vec::Vec<DescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.enum_type) + pub enum_type: ::std::vec::Vec<EnumDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.service) + pub service: ::std::vec::Vec<ServiceDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.extension) + pub extension: ::std::vec::Vec<FieldDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.options) + pub options: crate::MessageField<FileOptions>, + /// This field contains optional information about the original source code. + /// You may safely remove this entire field without harming runtime + /// functionality of the descriptors -- the information is needed only by + /// development tools. + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.source_code_info) + pub source_code_info: crate::MessageField<SourceCodeInfo>, + /// The syntax of the proto file. + /// The supported values are "proto2" and "proto3". + // @@protoc_insertion_point(field:google.protobuf.FileDescriptorProto.syntax) + pub syntax: ::std::option::Option<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FileDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FileDescriptorProto { @@ -224,15 +209,15 @@ impl FileDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -241,14 +226,14 @@ impl FileDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -260,15 +245,15 @@ impl FileDescriptorProto { // optional string package = 2; - - pub fn get_package(&self) -> &str { + pub fn package(&self) -> &str { match self.package.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_package(&mut self) { - self.package.clear(); + self.package = ::std::option::Option::None; } pub fn has_package(&self) -> bool { @@ -277,14 +262,14 @@ impl FileDescriptorProto { // Param is passed by value, moved pub fn set_package(&mut self, v: ::std::string::String) { - self.package = crate::SingularField::some(v); + self.package = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_package(&mut self) -> &mut ::std::string::String { if self.package.is_none() { - self.package.set_default(); + self.package = ::std::option::Option::Some(::std::string::String::new()); } self.package.as_mut().unwrap() } @@ -294,258 +279,17 @@ impl FileDescriptorProto { self.package.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated string dependency = 3; - - - pub fn get_dependency(&self) -> &[::std::string::String] { - &self.dependency - } - pub fn clear_dependency(&mut self) { - self.dependency.clear(); - } - - // Param is passed by value, moved - pub fn set_dependency(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.dependency = v; - } - - // Mutable pointer to the field. - pub fn mut_dependency(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.dependency - } - - // Take field - pub fn take_dependency(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.dependency, crate::RepeatedField::new()) - } - - // repeated int32 public_dependency = 10; - - - pub fn get_public_dependency(&self) -> &[i32] { - &self.public_dependency - } - pub fn clear_public_dependency(&mut self) { - self.public_dependency.clear(); - } - - // Param is passed by value, moved - pub fn set_public_dependency(&mut self, v: ::std::vec::Vec<i32>) { - self.public_dependency = v; - } - - // Mutable pointer to the field. - pub fn mut_public_dependency(&mut self) -> &mut ::std::vec::Vec<i32> { - &mut self.public_dependency - } - - // Take field - pub fn take_public_dependency(&mut self) -> ::std::vec::Vec<i32> { - ::std::mem::replace(&mut self.public_dependency, ::std::vec::Vec::new()) - } - - // repeated int32 weak_dependency = 11; - - - pub fn get_weak_dependency(&self) -> &[i32] { - &self.weak_dependency - } - pub fn clear_weak_dependency(&mut self) { - self.weak_dependency.clear(); - } - - // Param is passed by value, moved - pub fn set_weak_dependency(&mut self, v: ::std::vec::Vec<i32>) { - self.weak_dependency = v; - } - - // Mutable pointer to the field. - pub fn mut_weak_dependency(&mut self) -> &mut ::std::vec::Vec<i32> { - &mut self.weak_dependency - } - - // Take field - pub fn take_weak_dependency(&mut self) -> ::std::vec::Vec<i32> { - ::std::mem::replace(&mut self.weak_dependency, ::std::vec::Vec::new()) - } - - // repeated .google.protobuf.DescriptorProto message_type = 4; - - - pub fn get_message_type(&self) -> &[DescriptorProto] { - &self.message_type - } - pub fn clear_message_type(&mut self) { - self.message_type.clear(); - } - - // Param is passed by value, moved - pub fn set_message_type(&mut self, v: crate::RepeatedField<DescriptorProto>) { - self.message_type = v; - } - - // Mutable pointer to the field. - pub fn mut_message_type(&mut self) -> &mut crate::RepeatedField<DescriptorProto> { - &mut self.message_type - } - - // Take field - pub fn take_message_type(&mut self) -> crate::RepeatedField<DescriptorProto> { - ::std::mem::replace(&mut self.message_type, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 5; - - - pub fn get_enum_type(&self) -> &[EnumDescriptorProto] { - &self.enum_type - } - pub fn clear_enum_type(&mut self) { - self.enum_type.clear(); - } - - // Param is passed by value, moved - pub fn set_enum_type(&mut self, v: crate::RepeatedField<EnumDescriptorProto>) { - self.enum_type = v; - } - - // Mutable pointer to the field. - pub fn mut_enum_type(&mut self) -> &mut crate::RepeatedField<EnumDescriptorProto> { - &mut self.enum_type - } - - // Take field - pub fn take_enum_type(&mut self) -> crate::RepeatedField<EnumDescriptorProto> { - ::std::mem::replace(&mut self.enum_type, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.ServiceDescriptorProto service = 6; - - - pub fn get_service(&self) -> &[ServiceDescriptorProto] { - &self.service - } - pub fn clear_service(&mut self) { - self.service.clear(); - } - - // Param is passed by value, moved - pub fn set_service(&mut self, v: crate::RepeatedField<ServiceDescriptorProto>) { - self.service = v; - } - - // Mutable pointer to the field. - pub fn mut_service(&mut self) -> &mut crate::RepeatedField<ServiceDescriptorProto> { - &mut self.service - } - - // Take field - pub fn take_service(&mut self) -> crate::RepeatedField<ServiceDescriptorProto> { - ::std::mem::replace(&mut self.service, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 7; - - - pub fn get_extension(&self) -> &[FieldDescriptorProto] { - &self.extension - } - pub fn clear_extension(&mut self) { - self.extension.clear(); - } - - // Param is passed by value, moved - pub fn set_extension(&mut self, v: crate::RepeatedField<FieldDescriptorProto>) { - self.extension = v; - } - - // Mutable pointer to the field. - pub fn mut_extension(&mut self) -> &mut crate::RepeatedField<FieldDescriptorProto> { - &mut self.extension - } - - // Take field - pub fn take_extension(&mut self) -> crate::RepeatedField<FieldDescriptorProto> { - ::std::mem::replace(&mut self.extension, crate::RepeatedField::new()) - } - - // optional .google.protobuf.FileOptions options = 8; - - - pub fn get_options(&self) -> &FileOptions { - self.options.as_ref().unwrap_or_else(|| <FileOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: FileOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut FileOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> FileOptions { - self.options.take().unwrap_or_else(|| FileOptions::new()) - } - - // optional .google.protobuf.SourceCodeInfo source_code_info = 9; - - - pub fn get_source_code_info(&self) -> &SourceCodeInfo { - self.source_code_info.as_ref().unwrap_or_else(|| <SourceCodeInfo as crate::Message>::default_instance()) - } - pub fn clear_source_code_info(&mut self) { - self.source_code_info.clear(); - } - - pub fn has_source_code_info(&self) -> bool { - self.source_code_info.is_some() - } - - // Param is passed by value, moved - pub fn set_source_code_info(&mut self, v: SourceCodeInfo) { - self.source_code_info = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_source_code_info(&mut self) -> &mut SourceCodeInfo { - if self.source_code_info.is_none() { - self.source_code_info.set_default(); - } - self.source_code_info.as_mut().unwrap() - } - - // Take field - pub fn take_source_code_info(&mut self) -> SourceCodeInfo { - self.source_code_info.take().unwrap_or_else(|| SourceCodeInfo::new()) - } - // optional string syntax = 12; - - pub fn get_syntax(&self) -> &str { + pub fn syntax(&self) -> &str { match self.syntax.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_syntax(&mut self) { - self.syntax.clear(); + self.syntax = ::std::option::Option::None; } pub fn has_syntax(&self) -> bool { @@ -554,14 +298,14 @@ impl FileDescriptorProto { // Param is passed by value, moved pub fn set_syntax(&mut self, v: ::std::string::String) { - self.syntax = crate::SingularField::some(v); + self.syntax = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_syntax(&mut self) -> &mut ::std::string::String { if self.syntax.is_none() { - self.syntax.set_default(); + self.syntax = ::std::option::Option::Some(::std::string::String::new()); } self.syntax.as_mut().unwrap() } @@ -570,9 +314,81 @@ impl FileDescriptorProto { pub fn take_syntax(&mut self) -> ::std::string::String { self.syntax.take().unwrap_or_else(|| ::std::string::String::new()) } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(12); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &FileDescriptorProto| { &m.name }, + |m: &mut FileDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "package", + |m: &FileDescriptorProto| { &m.package }, + |m: &mut FileDescriptorProto| { &mut m.package }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "dependency", + |m: &FileDescriptorProto| { &m.dependency }, + |m: &mut FileDescriptorProto| { &mut m.dependency }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "public_dependency", + |m: &FileDescriptorProto| { &m.public_dependency }, + |m: &mut FileDescriptorProto| { &mut m.public_dependency }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "weak_dependency", + |m: &FileDescriptorProto| { &m.weak_dependency }, + |m: &mut FileDescriptorProto| { &mut m.weak_dependency }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "message_type", + |m: &FileDescriptorProto| { &m.message_type }, + |m: &mut FileDescriptorProto| { &mut m.message_type }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "enum_type", + |m: &FileDescriptorProto| { &m.enum_type }, + |m: &mut FileDescriptorProto| { &mut m.enum_type }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "service", + |m: &FileDescriptorProto| { &m.service }, + |m: &mut FileDescriptorProto| { &mut m.service }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "extension", + |m: &FileDescriptorProto| { &m.extension }, + |m: &mut FileDescriptorProto| { &mut m.extension }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, FileOptions>( + "options", + |m: &FileDescriptorProto| { &m.options }, + |m: &mut FileDescriptorProto| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, SourceCodeInfo>( + "source_code_info", + |m: &FileDescriptorProto| { &m.source_code_info }, + |m: &mut FileDescriptorProto| { &mut m.source_code_info }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "syntax", + |m: &FileDescriptorProto| { &m.syntax }, + |m: &mut FileDescriptorProto| { &mut m.syntax }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FileDescriptorProto>( + "FileDescriptorProto", + fields, + oneofs, + ) + } } impl crate::Message for FileDescriptorProto { + const NAME: &'static str = "FileDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.message_type { if !v.is_initialized() { @@ -607,48 +423,53 @@ impl crate::Message for FileDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.package)?; + 18 => { + self.package = ::std::option::Option::Some(is.read_string()?); }, - 3 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.dependency)?; + 26 => { + self.dependency.push(is.read_string()?); }, - 10 => { - crate::rt::read_repeated_int32_into(wire_type, is, &mut self.public_dependency)?; + 82 => { + is.read_repeated_packed_int32_into(&mut self.public_dependency)?; }, - 11 => { - crate::rt::read_repeated_int32_into(wire_type, is, &mut self.weak_dependency)?; + 80 => { + self.public_dependency.push(is.read_int32()?); }, - 4 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.message_type)?; + 90 => { + is.read_repeated_packed_int32_into(&mut self.weak_dependency)?; }, - 5 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.enum_type)?; + 88 => { + self.weak_dependency.push(is.read_int32()?); }, - 6 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.service)?; + 34 => { + self.message_type.push(is.read_message()?); + }, + 42 => { + self.enum_type.push(is.read_message()?); }, - 7 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.extension)?; + 50 => { + self.service.push(is.read_message()?); }, - 8 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 58 => { + self.extension.push(is.read_message()?); }, - 9 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.source_code_info)?; + 66 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - 12 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.syntax)?; + 74 => { + crate::rt::read_singular_message_into_field(is, &mut self.source_code_info)?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + 98 => { + self.syntax = ::std::option::Option::Some(is.read_string()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -657,61 +478,61 @@ impl crate::Message for FileDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } - if let Some(ref v) = self.package.as_ref() { + if let Some(v) = self.package.as_ref() { my_size += crate::rt::string_size(2, &v); } for value in &self.dependency { my_size += crate::rt::string_size(3, &value); }; for value in &self.public_dependency { - my_size += crate::rt::value_size(10, *value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(10, *value); }; for value in &self.weak_dependency { - my_size += crate::rt::value_size(11, *value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(11, *value); }; for value in &self.message_type { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.enum_type { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.service { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.extension { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - if let Some(ref v) = self.source_code_info.as_ref() { + if let Some(v) = self.source_code_info.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - if let Some(ref v) = self.syntax.as_ref() { + if let Some(v) = self.syntax.as_ref() { my_size += crate::rt::string_size(12, &v); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } - if let Some(ref v) = self.package.as_ref() { - os.write_string(2, &v)?; + if let Some(v) = self.package.as_ref() { + os.write_string(2, v)?; } for v in &self.dependency { os.write_string(3, &v)?; @@ -723,154 +544,45 @@ impl crate::Message for FileDescriptorProto { os.write_int32(11, *v)?; }; for v in &self.message_type { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(4, v, os)?; }; for v in &self.enum_type { - os.write_tag(5, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(5, v, os)?; }; for v in &self.service { - os.write_tag(6, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(6, v, os)?; }; for v in &self.extension { - os.write_tag(7, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(7, v, os)?; }; - if let Some(ref v) = self.options.as_ref() { - os.write_tag(8, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(8, v, os)?; } - if let Some(ref v) = self.source_code_info.as_ref() { - os.write_tag(9, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.source_code_info.as_ref() { + crate::rt::write_message_field_with_cached_size(9, v, os)?; } - if let Some(ref v) = self.syntax.as_ref() { - os.write_string(12, &v)?; + if let Some(v) = self.syntax.as_ref() { + os.write_string(12, v)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FileDescriptorProto { FileDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &FileDescriptorProto| { &m.name }, - |m: &mut FileDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "package", - |m: &FileDescriptorProto| { &m.package }, - |m: &mut FileDescriptorProto| { &mut m.package }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "dependency", - |m: &FileDescriptorProto| { &m.dependency }, - |m: &mut FileDescriptorProto| { &mut m.dependency }, - )); - fields.push(crate::reflect::accessor::make_vec_accessor::<_, crate::types::ProtobufTypeInt32>( - "public_dependency", - |m: &FileDescriptorProto| { &m.public_dependency }, - |m: &mut FileDescriptorProto| { &mut m.public_dependency }, - )); - fields.push(crate::reflect::accessor::make_vec_accessor::<_, crate::types::ProtobufTypeInt32>( - "weak_dependency", - |m: &FileDescriptorProto| { &m.weak_dependency }, - |m: &mut FileDescriptorProto| { &mut m.weak_dependency }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<DescriptorProto>>( - "message_type", - |m: &FileDescriptorProto| { &m.message_type }, - |m: &mut FileDescriptorProto| { &mut m.message_type }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumDescriptorProto>>( - "enum_type", - |m: &FileDescriptorProto| { &m.enum_type }, - |m: &mut FileDescriptorProto| { &mut m.enum_type }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<ServiceDescriptorProto>>( - "service", - |m: &FileDescriptorProto| { &m.service }, - |m: &mut FileDescriptorProto| { &mut m.service }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<FieldDescriptorProto>>( - "extension", - |m: &FileDescriptorProto| { &m.extension }, - |m: &mut FileDescriptorProto| { &mut m.extension }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<FileOptions>>( - "options", - |m: &FileDescriptorProto| { &m.options }, - |m: &mut FileDescriptorProto| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<SourceCodeInfo>>( - "source_code_info", - |m: &FileDescriptorProto| { &m.source_code_info }, - |m: &mut FileDescriptorProto| { &mut m.source_code_info }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "syntax", - |m: &FileDescriptorProto| { &m.syntax }, - |m: &mut FileDescriptorProto| { &mut m.syntax }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FileDescriptorProto>( - "FileDescriptorProto", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static FileDescriptorProto { - static instance: crate::rt::LazyV2<FileDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(FileDescriptorProto::new) - } -} - -impl crate::Clear for FileDescriptorProto { fn clear(&mut self) { - self.name.clear(); - self.package.clear(); + self.name = ::std::option::Option::None; + self.package = ::std::option::Option::None; self.dependency.clear(); self.public_dependency.clear(); self.weak_dependency.clear(); @@ -880,42 +592,77 @@ impl crate::Clear for FileDescriptorProto { self.extension.clear(); self.options.clear(); self.source_code_info.clear(); - self.syntax.clear(); - self.unknown_fields.clear(); + self.syntax = ::std::option::Option::None; + self.special_fields.clear(); + } + + fn default_instance() -> &'static FileDescriptorProto { + static instance: FileDescriptorProto = FileDescriptorProto { + name: ::std::option::Option::None, + package: ::std::option::Option::None, + dependency: ::std::vec::Vec::new(), + public_dependency: ::std::vec::Vec::new(), + weak_dependency: ::std::vec::Vec::new(), + message_type: ::std::vec::Vec::new(), + enum_type: ::std::vec::Vec::new(), + service: ::std::vec::Vec::new(), + extension: ::std::vec::Vec::new(), + options: crate::MessageField::none(), + source_code_info: crate::MessageField::none(), + syntax: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl ::std::fmt::Debug for FileDescriptorProto { +impl crate::MessageFull for FileDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FileDescriptorProto").unwrap()).clone() + } +} + +impl ::std::fmt::Display for FileDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for FileDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a message type. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.DescriptorProto) pub struct DescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - pub field: crate::RepeatedField<FieldDescriptorProto>, - pub extension: crate::RepeatedField<FieldDescriptorProto>, - pub nested_type: crate::RepeatedField<DescriptorProto>, - pub enum_type: crate::RepeatedField<EnumDescriptorProto>, - pub extension_range: crate::RepeatedField<DescriptorProto_ExtensionRange>, - pub oneof_decl: crate::RepeatedField<OneofDescriptorProto>, - pub options: crate::SingularPtrField<MessageOptions>, - pub reserved_range: crate::RepeatedField<DescriptorProto_ReservedRange>, - pub reserved_name: crate::RepeatedField<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.field) + pub field: ::std::vec::Vec<FieldDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.extension) + pub extension: ::std::vec::Vec<FieldDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.nested_type) + pub nested_type: ::std::vec::Vec<DescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.enum_type) + pub enum_type: ::std::vec::Vec<EnumDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.extension_range) + pub extension_range: ::std::vec::Vec<descriptor_proto::ExtensionRange>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.oneof_decl) + pub oneof_decl: ::std::vec::Vec<OneofDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.options) + pub options: crate::MessageField<MessageOptions>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.reserved_range) + pub reserved_range: ::std::vec::Vec<descriptor_proto::ReservedRange>, + /// Reserved field names, which may not be used by fields in the same message. + /// A given name may only be reserved once. + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.reserved_name) + pub reserved_name: ::std::vec::Vec<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.DescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a DescriptorProto { @@ -931,15 +678,15 @@ impl DescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -948,14 +695,14 @@ impl DescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -965,241 +712,70 @@ impl DescriptorProto { self.name.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated .google.protobuf.FieldDescriptorProto field = 2; - - - pub fn get_field(&self) -> &[FieldDescriptorProto] { - &self.field - } - pub fn clear_field(&mut self) { - self.field.clear(); - } - - // Param is passed by value, moved - pub fn set_field(&mut self, v: crate::RepeatedField<FieldDescriptorProto>) { - self.field = v; - } - - // Mutable pointer to the field. - pub fn mut_field(&mut self) -> &mut crate::RepeatedField<FieldDescriptorProto> { - &mut self.field - } - - // Take field - pub fn take_field(&mut self) -> crate::RepeatedField<FieldDescriptorProto> { - ::std::mem::replace(&mut self.field, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.FieldDescriptorProto extension = 6; - - - pub fn get_extension(&self) -> &[FieldDescriptorProto] { - &self.extension - } - pub fn clear_extension(&mut self) { - self.extension.clear(); - } - - // Param is passed by value, moved - pub fn set_extension(&mut self, v: crate::RepeatedField<FieldDescriptorProto>) { - self.extension = v; - } - - // Mutable pointer to the field. - pub fn mut_extension(&mut self) -> &mut crate::RepeatedField<FieldDescriptorProto> { - &mut self.extension - } - - // Take field - pub fn take_extension(&mut self) -> crate::RepeatedField<FieldDescriptorProto> { - ::std::mem::replace(&mut self.extension, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.DescriptorProto nested_type = 3; - - - pub fn get_nested_type(&self) -> &[DescriptorProto] { - &self.nested_type - } - pub fn clear_nested_type(&mut self) { - self.nested_type.clear(); - } - - // Param is passed by value, moved - pub fn set_nested_type(&mut self, v: crate::RepeatedField<DescriptorProto>) { - self.nested_type = v; - } - - // Mutable pointer to the field. - pub fn mut_nested_type(&mut self) -> &mut crate::RepeatedField<DescriptorProto> { - &mut self.nested_type - } - - // Take field - pub fn take_nested_type(&mut self) -> crate::RepeatedField<DescriptorProto> { - ::std::mem::replace(&mut self.nested_type, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.EnumDescriptorProto enum_type = 4; - - - pub fn get_enum_type(&self) -> &[EnumDescriptorProto] { - &self.enum_type - } - pub fn clear_enum_type(&mut self) { - self.enum_type.clear(); - } - - // Param is passed by value, moved - pub fn set_enum_type(&mut self, v: crate::RepeatedField<EnumDescriptorProto>) { - self.enum_type = v; - } - - // Mutable pointer to the field. - pub fn mut_enum_type(&mut self) -> &mut crate::RepeatedField<EnumDescriptorProto> { - &mut self.enum_type - } - - // Take field - pub fn take_enum_type(&mut self) -> crate::RepeatedField<EnumDescriptorProto> { - ::std::mem::replace(&mut self.enum_type, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; - - - pub fn get_extension_range(&self) -> &[DescriptorProto_ExtensionRange] { - &self.extension_range - } - pub fn clear_extension_range(&mut self) { - self.extension_range.clear(); - } - - // Param is passed by value, moved - pub fn set_extension_range(&mut self, v: crate::RepeatedField<DescriptorProto_ExtensionRange>) { - self.extension_range = v; - } - - // Mutable pointer to the field. - pub fn mut_extension_range(&mut self) -> &mut crate::RepeatedField<DescriptorProto_ExtensionRange> { - &mut self.extension_range - } - - // Take field - pub fn take_extension_range(&mut self) -> crate::RepeatedField<DescriptorProto_ExtensionRange> { - ::std::mem::replace(&mut self.extension_range, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.OneofDescriptorProto oneof_decl = 8; - - - pub fn get_oneof_decl(&self) -> &[OneofDescriptorProto] { - &self.oneof_decl - } - pub fn clear_oneof_decl(&mut self) { - self.oneof_decl.clear(); - } - - // Param is passed by value, moved - pub fn set_oneof_decl(&mut self, v: crate::RepeatedField<OneofDescriptorProto>) { - self.oneof_decl = v; - } - - // Mutable pointer to the field. - pub fn mut_oneof_decl(&mut self) -> &mut crate::RepeatedField<OneofDescriptorProto> { - &mut self.oneof_decl - } - - // Take field - pub fn take_oneof_decl(&mut self) -> crate::RepeatedField<OneofDescriptorProto> { - ::std::mem::replace(&mut self.oneof_decl, crate::RepeatedField::new()) - } - - // optional .google.protobuf.MessageOptions options = 7; - - - pub fn get_options(&self) -> &MessageOptions { - self.options.as_ref().unwrap_or_else(|| <MessageOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: MessageOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut MessageOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> MessageOptions { - self.options.take().unwrap_or_else(|| MessageOptions::new()) - } - - // repeated .google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; - - - pub fn get_reserved_range(&self) -> &[DescriptorProto_ReservedRange] { - &self.reserved_range - } - pub fn clear_reserved_range(&mut self) { - self.reserved_range.clear(); - } - - // Param is passed by value, moved - pub fn set_reserved_range(&mut self, v: crate::RepeatedField<DescriptorProto_ReservedRange>) { - self.reserved_range = v; - } - - // Mutable pointer to the field. - pub fn mut_reserved_range(&mut self) -> &mut crate::RepeatedField<DescriptorProto_ReservedRange> { - &mut self.reserved_range - } - - // Take field - pub fn take_reserved_range(&mut self) -> crate::RepeatedField<DescriptorProto_ReservedRange> { - ::std::mem::replace(&mut self.reserved_range, crate::RepeatedField::new()) - } - - // repeated string reserved_name = 10; - - - pub fn get_reserved_name(&self) -> &[::std::string::String] { - &self.reserved_name - } - pub fn clear_reserved_name(&mut self) { - self.reserved_name.clear(); - } - - // Param is passed by value, moved - pub fn set_reserved_name(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.reserved_name = v; - } - - // Mutable pointer to the field. - pub fn mut_reserved_name(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.reserved_name - } - - // Take field - pub fn take_reserved_name(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.reserved_name, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(10); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &DescriptorProto| { &m.name }, + |m: &mut DescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "field", + |m: &DescriptorProto| { &m.field }, + |m: &mut DescriptorProto| { &mut m.field }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "extension", + |m: &DescriptorProto| { &m.extension }, + |m: &mut DescriptorProto| { &mut m.extension }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "nested_type", + |m: &DescriptorProto| { &m.nested_type }, + |m: &mut DescriptorProto| { &mut m.nested_type }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "enum_type", + |m: &DescriptorProto| { &m.enum_type }, + |m: &mut DescriptorProto| { &mut m.enum_type }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "extension_range", + |m: &DescriptorProto| { &m.extension_range }, + |m: &mut DescriptorProto| { &mut m.extension_range }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "oneof_decl", + |m: &DescriptorProto| { &m.oneof_decl }, + |m: &mut DescriptorProto| { &mut m.oneof_decl }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, MessageOptions>( + "options", + |m: &DescriptorProto| { &m.options }, + |m: &mut DescriptorProto| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "reserved_range", + |m: &DescriptorProto| { &m.reserved_range }, + |m: &mut DescriptorProto| { &mut m.reserved_range }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "reserved_name", + |m: &DescriptorProto| { &m.reserved_name }, + |m: &mut DescriptorProto| { &mut m.reserved_name }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<DescriptorProto>( + "DescriptorProto", + fields, + oneofs, + ) } } impl crate::Message for DescriptorProto { + const NAME: &'static str = "DescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.field { if !v.is_initialized() { @@ -1244,42 +820,41 @@ impl crate::Message for DescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.field)?; + 18 => { + self.field.push(is.read_message()?); }, - 6 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.extension)?; + 50 => { + self.extension.push(is.read_message()?); }, - 3 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.nested_type)?; + 26 => { + self.nested_type.push(is.read_message()?); }, - 4 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.enum_type)?; + 34 => { + self.enum_type.push(is.read_message()?); }, - 5 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.extension_range)?; + 42 => { + self.extension_range.push(is.read_message()?); }, - 8 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.oneof_decl)?; + 66 => { + self.oneof_decl.push(is.read_message()?); }, - 7 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 58 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - 9 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.reserved_range)?; + 74 => { + self.reserved_range.push(is.read_message()?); }, - 10 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.reserved_name)?; + 82 => { + self.reserved_name.push(is.read_string()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -1288,203 +863,100 @@ impl crate::Message for DescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } for value in &self.field { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.extension { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.nested_type { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.enum_type { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.extension_range { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.oneof_decl { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } for value in &self.reserved_range { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.reserved_name { my_size += crate::rt::string_size(10, &value); }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } for v in &self.field { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; }; for v in &self.extension { - os.write_tag(6, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(6, v, os)?; }; for v in &self.nested_type { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(3, v, os)?; }; for v in &self.enum_type { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(4, v, os)?; }; for v in &self.extension_range { - os.write_tag(5, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(5, v, os)?; }; for v in &self.oneof_decl { - os.write_tag(8, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(8, v, os)?; }; - if let Some(ref v) = self.options.as_ref() { - os.write_tag(7, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(7, v, os)?; } for v in &self.reserved_range { - os.write_tag(9, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(9, v, os)?; }; for v in &self.reserved_name { os.write_string(10, &v)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> DescriptorProto { DescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &DescriptorProto| { &m.name }, - |m: &mut DescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<FieldDescriptorProto>>( - "field", - |m: &DescriptorProto| { &m.field }, - |m: &mut DescriptorProto| { &mut m.field }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<FieldDescriptorProto>>( - "extension", - |m: &DescriptorProto| { &m.extension }, - |m: &mut DescriptorProto| { &mut m.extension }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<DescriptorProto>>( - "nested_type", - |m: &DescriptorProto| { &m.nested_type }, - |m: &mut DescriptorProto| { &mut m.nested_type }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumDescriptorProto>>( - "enum_type", - |m: &DescriptorProto| { &m.enum_type }, - |m: &mut DescriptorProto| { &mut m.enum_type }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<DescriptorProto_ExtensionRange>>( - "extension_range", - |m: &DescriptorProto| { &m.extension_range }, - |m: &mut DescriptorProto| { &mut m.extension_range }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<OneofDescriptorProto>>( - "oneof_decl", - |m: &DescriptorProto| { &m.oneof_decl }, - |m: &mut DescriptorProto| { &mut m.oneof_decl }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<MessageOptions>>( - "options", - |m: &DescriptorProto| { &m.options }, - |m: &mut DescriptorProto| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<DescriptorProto_ReservedRange>>( - "reserved_range", - |m: &DescriptorProto| { &m.reserved_range }, - |m: &mut DescriptorProto| { &mut m.reserved_range }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "reserved_name", - |m: &DescriptorProto| { &m.reserved_name }, - |m: &mut DescriptorProto| { &mut m.reserved_name }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<DescriptorProto>( - "DescriptorProto", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static DescriptorProto { - static instance: crate::rt::LazyV2<DescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(DescriptorProto::new) - } -} - -impl crate::Clear for DescriptorProto { fn clear(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; self.field.clear(); self.extension.clear(); self.nested_type.clear(); @@ -1494,485 +966,440 @@ impl crate::Clear for DescriptorProto { self.options.clear(); self.reserved_range.clear(); self.reserved_name.clear(); - self.unknown_fields.clear(); + self.special_fields.clear(); } -} -impl ::std::fmt::Debug for DescriptorProto { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + fn default_instance() -> &'static DescriptorProto { + static instance: DescriptorProto = DescriptorProto { + name: ::std::option::Option::None, + field: ::std::vec::Vec::new(), + extension: ::std::vec::Vec::new(), + nested_type: ::std::vec::Vec::new(), + enum_type: ::std::vec::Vec::new(), + extension_range: ::std::vec::Vec::new(), + oneof_decl: ::std::vec::Vec::new(), + options: crate::MessageField::none(), + reserved_range: ::std::vec::Vec::new(), + reserved_name: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::reflect::ProtobufValue for DescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) +impl crate::MessageFull for DescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("DescriptorProto").unwrap()).clone() } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct DescriptorProto_ExtensionRange { - // message fields - start: ::std::option::Option<i32>, - end: ::std::option::Option<i32>, - pub options: crate::SingularPtrField<ExtensionRangeOptions>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a DescriptorProto_ExtensionRange { - fn default() -> &'a DescriptorProto_ExtensionRange { - <DescriptorProto_ExtensionRange as crate::Message>::default_instance() +impl ::std::fmt::Display for DescriptorProto { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) } } -impl DescriptorProto_ExtensionRange { - pub fn new() -> DescriptorProto_ExtensionRange { - ::std::default::Default::default() - } - - // optional int32 start = 1; - - - pub fn get_start(&self) -> i32 { - self.start.unwrap_or(0) - } - pub fn clear_start(&mut self) { - self.start = ::std::option::Option::None; - } - - pub fn has_start(&self) -> bool { - self.start.is_some() - } - - // Param is passed by value, moved - pub fn set_start(&mut self, v: i32) { - self.start = ::std::option::Option::Some(v); - } - - // optional int32 end = 2; - - - pub fn get_end(&self) -> i32 { - self.end.unwrap_or(0) - } - pub fn clear_end(&mut self) { - self.end = ::std::option::Option::None; - } - - pub fn has_end(&self) -> bool { - self.end.is_some() - } - - // Param is passed by value, moved - pub fn set_end(&mut self, v: i32) { - self.end = ::std::option::Option::Some(v); - } - - // optional .google.protobuf.ExtensionRangeOptions options = 3; - - - pub fn get_options(&self) -> &ExtensionRangeOptions { - self.options.as_ref().unwrap_or_else(|| <ExtensionRangeOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } +impl crate::reflect::ProtobufValue for DescriptorProto { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} - // Param is passed by value, moved - pub fn set_options(&mut self, v: ExtensionRangeOptions) { - self.options = crate::SingularPtrField::some(v); +/// Nested message and enums of message `DescriptorProto` +pub mod descriptor_proto { + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.DescriptorProto.ExtensionRange) + pub struct ExtensionRange { + // message fields + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.ExtensionRange.start) + pub start: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.ExtensionRange.end) + pub end: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.ExtensionRange.options) + pub options: crate::MessageField<super::ExtensionRangeOptions>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.DescriptorProto.ExtensionRange.special_fields) + pub special_fields: crate::SpecialFields, } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut ExtensionRangeOptions { - if self.options.is_none() { - self.options.set_default(); + impl<'a> ::std::default::Default for &'a ExtensionRange { + fn default() -> &'a ExtensionRange { + <ExtensionRange as crate::Message>::default_instance() } - self.options.as_mut().unwrap() } - // Take field - pub fn take_options(&mut self) -> ExtensionRangeOptions { - self.options.take().unwrap_or_else(|| ExtensionRangeOptions::new()) - } -} + impl ExtensionRange { + pub fn new() -> ExtensionRange { + ::std::default::Default::default() + } -impl crate::Message for DescriptorProto_ExtensionRange { - fn is_initialized(&self) -> bool { - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - true - } + // optional int32 start = 1; - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.start = ::std::option::Option::Some(tmp); - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.end = ::std::option::Option::Some(tmp); - }, - 3 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + pub fn start(&self) -> i32 { + self.start.unwrap_or(0) } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let Some(v) = self.start { - my_size += crate::rt::value_size(1, v, crate::wire_format::WireTypeVarint); + pub fn clear_start(&mut self) { + self.start = ::std::option::Option::None; } - if let Some(v) = self.end { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); - } - if let Some(ref v) = self.options.as_ref() { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(v) = self.start { - os.write_int32(1, v)?; - } - if let Some(v) = self.end { - os.write_int32(2, v)?; + pub fn has_start(&self) -> bool { + self.start.is_some() } - if let Some(ref v) = self.options.as_ref() { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + + // Param is passed by value, moved + pub fn set_start(&mut self, v: i32) { + self.start = ::std::option::Option::Some(v); } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } + // optional int32 end = 2; - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } + pub fn end(&self) -> i32 { + self.end.unwrap_or(0) + } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + pub fn clear_end(&mut self) { + self.end = ::std::option::Option::None; + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + pub fn has_end(&self) -> bool { + self.end.is_some() + } - fn new() -> DescriptorProto_ExtensionRange { - DescriptorProto_ExtensionRange::new() - } + // Param is passed by value, moved + pub fn set_end(&mut self, v: i32) { + self.end = ::std::option::Option::Some(v); + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "start", - |m: &DescriptorProto_ExtensionRange| { &m.start }, - |m: &mut DescriptorProto_ExtensionRange| { &mut m.start }, + |m: &ExtensionRange| { &m.start }, + |m: &mut ExtensionRange| { &mut m.start }, )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "end", - |m: &DescriptorProto_ExtensionRange| { &m.end }, - |m: &mut DescriptorProto_ExtensionRange| { &mut m.end }, + |m: &ExtensionRange| { &m.end }, + |m: &mut ExtensionRange| { &mut m.end }, )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<ExtensionRangeOptions>>( + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, super::ExtensionRangeOptions>( "options", - |m: &DescriptorProto_ExtensionRange| { &m.options }, - |m: &mut DescriptorProto_ExtensionRange| { &mut m.options }, + |m: &ExtensionRange| { &m.options }, + |m: &mut ExtensionRange| { &mut m.options }, )); - crate::reflect::MessageDescriptor::new_pb_name::<DescriptorProto_ExtensionRange>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<ExtensionRange>( "DescriptorProto.ExtensionRange", fields, - file_descriptor_proto() + oneofs, ) - }) - } - - fn default_instance() -> &'static DescriptorProto_ExtensionRange { - static instance: crate::rt::LazyV2<DescriptorProto_ExtensionRange> = crate::rt::LazyV2::INIT; - instance.get(DescriptorProto_ExtensionRange::new) - } -} - -impl crate::Clear for DescriptorProto_ExtensionRange { - fn clear(&mut self) { - self.start = ::std::option::Option::None; - self.end = ::std::option::Option::None; - self.options.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for DescriptorProto_ExtensionRange { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for DescriptorProto_ExtensionRange { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} + impl crate::Message for ExtensionRange { + const NAME: &'static str = "ExtensionRange"; -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct DescriptorProto_ReservedRange { - // message fields - start: ::std::option::Option<i32>, - end: ::std::option::Option<i32>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} + fn is_initialized(&self) -> bool { + for v in &self.options { + if !v.is_initialized() { + return false; + } + }; + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.start = ::std::option::Option::Some(is.read_int32()?); + }, + 16 => { + self.end = ::std::option::Option::Some(is.read_int32()?); + }, + 26 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } -impl<'a> ::std::default::Default for &'a DescriptorProto_ReservedRange { - fn default() -> &'a DescriptorProto_ReservedRange { - <DescriptorProto_ReservedRange as crate::Message>::default_instance() - } -} + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let Some(v) = self.start { + my_size += crate::rt::int32_size(1, v); + } + if let Some(v) = self.end { + my_size += crate::rt::int32_size(2, v); + } + if let Some(v) = self.options.as_ref() { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } -impl DescriptorProto_ReservedRange { - pub fn new() -> DescriptorProto_ReservedRange { - ::std::default::Default::default() - } + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.start { + os.write_int32(1, v)?; + } + if let Some(v) = self.end { + os.write_int32(2, v)?; + } + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(3, v, os)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } - // optional int32 start = 1; + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } - pub fn get_start(&self) -> i32 { - self.start.unwrap_or(0) - } - pub fn clear_start(&mut self) { - self.start = ::std::option::Option::None; - } + fn new() -> ExtensionRange { + ExtensionRange::new() + } - pub fn has_start(&self) -> bool { - self.start.is_some() - } + fn clear(&mut self) { + self.start = ::std::option::Option::None; + self.end = ::std::option::Option::None; + self.options.clear(); + self.special_fields.clear(); + } - // Param is passed by value, moved - pub fn set_start(&mut self, v: i32) { - self.start = ::std::option::Option::Some(v); + fn default_instance() -> &'static ExtensionRange { + static instance: ExtensionRange = ExtensionRange { + start: ::std::option::Option::None, + end: ::std::option::Option::None, + options: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } } - // optional int32 end = 2; - - - pub fn get_end(&self) -> i32 { - self.end.unwrap_or(0) - } - pub fn clear_end(&mut self) { - self.end = ::std::option::Option::None; + impl crate::MessageFull for ExtensionRange { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("DescriptorProto.ExtensionRange").unwrap()).clone() + } } - pub fn has_end(&self) -> bool { - self.end.is_some() + impl ::std::fmt::Display for ExtensionRange { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } - // Param is passed by value, moved - pub fn set_end(&mut self, v: i32) { - self.end = ::std::option::Option::Some(v); + impl crate::reflect::ProtobufValue for ExtensionRange { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -} -impl crate::Message for DescriptorProto_ReservedRange { - fn is_initialized(&self) -> bool { - true + /// Range of reserved tag numbers. Reserved tag numbers may not be used by + /// fields or extension ranges in the same message. Reserved ranges may + /// not overlap. + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.DescriptorProto.ReservedRange) + pub struct ReservedRange { + // message fields + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.ReservedRange.start) + pub start: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.DescriptorProto.ReservedRange.end) + pub end: ::std::option::Option<i32>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.DescriptorProto.ReservedRange.special_fields) + pub special_fields: crate::SpecialFields, } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.start = ::std::option::Option::Some(tmp); - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.end = ::std::option::Option::Some(tmp); - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + impl<'a> ::std::default::Default for &'a ReservedRange { + fn default() -> &'a ReservedRange { + <ReservedRange as crate::Message>::default_instance() } - ::std::result::Result::Ok(()) } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let Some(v) = self.start { - my_size += crate::rt::value_size(1, v, crate::wire_format::WireTypeVarint); + impl ReservedRange { + pub fn new() -> ReservedRange { + ::std::default::Default::default() } - if let Some(v) = self.end { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); + + // optional int32 start = 1; + + pub fn start(&self) -> i32 { + self.start.unwrap_or(0) } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(v) = self.start { - os.write_int32(1, v)?; + pub fn clear_start(&mut self) { + self.start = ::std::option::Option::None; } - if let Some(v) = self.end { - os.write_int32(2, v)?; + + pub fn has_start(&self) -> bool { + self.start.is_some() } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } + // Param is passed by value, moved + pub fn set_start(&mut self, v: i32) { + self.start = ::std::option::Option::Some(v); + } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } + // optional int32 end = 2; - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } + pub fn end(&self) -> i32 { + self.end.unwrap_or(0) + } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + pub fn clear_end(&mut self) { + self.end = ::std::option::Option::None; + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + pub fn has_end(&self) -> bool { + self.end.is_some() + } - fn new() -> DescriptorProto_ReservedRange { - DescriptorProto_ReservedRange::new() - } + // Param is passed by value, moved + pub fn set_end(&mut self, v: i32) { + self.end = ::std::option::Option::Some(v); + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "start", - |m: &DescriptorProto_ReservedRange| { &m.start }, - |m: &mut DescriptorProto_ReservedRange| { &mut m.start }, + |m: &ReservedRange| { &m.start }, + |m: &mut ReservedRange| { &mut m.start }, )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "end", - |m: &DescriptorProto_ReservedRange| { &m.end }, - |m: &mut DescriptorProto_ReservedRange| { &mut m.end }, + |m: &ReservedRange| { &m.end }, + |m: &mut ReservedRange| { &mut m.end }, )); - crate::reflect::MessageDescriptor::new_pb_name::<DescriptorProto_ReservedRange>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<ReservedRange>( "DescriptorProto.ReservedRange", fields, - file_descriptor_proto() + oneofs, ) - }) + } } - fn default_instance() -> &'static DescriptorProto_ReservedRange { - static instance: crate::rt::LazyV2<DescriptorProto_ReservedRange> = crate::rt::LazyV2::INIT; - instance.get(DescriptorProto_ReservedRange::new) + impl crate::Message for ReservedRange { + const NAME: &'static str = "ReservedRange"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.start = ::std::option::Option::Some(is.read_int32()?); + }, + 16 => { + self.end = ::std::option::Option::Some(is.read_int32()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let Some(v) = self.start { + my_size += crate::rt::int32_size(1, v); + } + if let Some(v) = self.end { + my_size += crate::rt::int32_size(2, v); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.start { + os.write_int32(1, v)?; + } + if let Some(v) = self.end { + os.write_int32(2, v)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> ReservedRange { + ReservedRange::new() + } + + fn clear(&mut self) { + self.start = ::std::option::Option::None; + self.end = ::std::option::Option::None; + self.special_fields.clear(); + } + + fn default_instance() -> &'static ReservedRange { + static instance: ReservedRange = ReservedRange { + start: ::std::option::Option::None, + end: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl crate::Clear for DescriptorProto_ReservedRange { - fn clear(&mut self) { - self.start = ::std::option::Option::None; - self.end = ::std::option::Option::None; - self.unknown_fields.clear(); + impl crate::MessageFull for ReservedRange { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("DescriptorProto.ReservedRange").unwrap()).clone() + } } -} -impl ::std::fmt::Debug for DescriptorProto_ReservedRange { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl ::std::fmt::Display for ReservedRange { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for DescriptorProto_ReservedRange { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl crate::reflect::ProtobufValue for ReservedRange { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.ExtensionRangeOptions) pub struct ExtensionRangeOptions { // message fields - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.ExtensionRangeOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.ExtensionRangeOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a ExtensionRangeOptions { @@ -1986,33 +1413,25 @@ impl ExtensionRangeOptions { ::std::default::Default::default() } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &ExtensionRangeOptions| { &m.uninterpreted_option }, + |m: &mut ExtensionRangeOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<ExtensionRangeOptions>( + "ExtensionRangeOptions", + fields, + oneofs, + ) } } impl crate::Message for ExtensionRangeOptions { + const NAME: &'static str = "ExtensionRangeOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -2022,15 +1441,14 @@ impl crate::Message for ExtensionRangeOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -2039,119 +1457,139 @@ impl crate::Message for ExtensionRangeOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> ExtensionRangeOptions { ExtensionRangeOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &ExtensionRangeOptions| { &m.uninterpreted_option }, - |m: &mut ExtensionRangeOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<ExtensionRangeOptions>( - "ExtensionRangeOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static ExtensionRangeOptions { - static instance: crate::rt::LazyV2<ExtensionRangeOptions> = crate::rt::LazyV2::INIT; - instance.get(ExtensionRangeOptions::new) + static instance: ExtensionRangeOptions = ExtensionRangeOptions { + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for ExtensionRangeOptions { - fn clear(&mut self) { - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for ExtensionRangeOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("ExtensionRangeOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for ExtensionRangeOptions { +impl ::std::fmt::Display for ExtensionRangeOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for ExtensionRangeOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a field within a message. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FieldDescriptorProto) pub struct FieldDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - number: ::std::option::Option<i32>, - label: ::std::option::Option<FieldDescriptorProto_Label>, - field_type: ::std::option::Option<FieldDescriptorProto_Type>, - type_name: crate::SingularField<::std::string::String>, - extendee: crate::SingularField<::std::string::String>, - default_value: crate::SingularField<::std::string::String>, - oneof_index: ::std::option::Option<i32>, - json_name: crate::SingularField<::std::string::String>, - pub options: crate::SingularPtrField<FieldOptions>, - proto3_optional: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.number) + pub number: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.label) + pub label: ::std::option::Option<crate::EnumOrUnknown<field_descriptor_proto::Label>>, + /// If type_name is set, this need not be set. If both this and type_name + /// are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP. + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.type) + pub type_: ::std::option::Option<crate::EnumOrUnknown<field_descriptor_proto::Type>>, + /// For message and enum types, this is the name of the type. If the name + /// starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + /// rules are used to find the type (i.e. first the nested types within this + /// message are searched, then within the parent, on up to the root + /// namespace). + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.type_name) + pub type_name: ::std::option::Option<::std::string::String>, + /// For extensions, this is the name of the type being extended. It is + /// resolved in the same manner as type_name. + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.extendee) + pub extendee: ::std::option::Option<::std::string::String>, + /// For numeric types, contains the original text representation of the value. + /// For booleans, "true" or "false". + /// For strings, contains the default text contents (not escaped in any way). + /// For bytes, contains the C escaped value. All bytes >= 128 are escaped. + /// TODO(kenton): Base-64 encode? + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.default_value) + pub default_value: ::std::option::Option<::std::string::String>, + /// If set, gives the index of a oneof in the containing type's oneof_decl + /// list. This field is a member of that oneof. + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.oneof_index) + pub oneof_index: ::std::option::Option<i32>, + /// JSON name of this field. The value is set by protocol compiler. If the + /// user has set a "json_name" option on this field, that option's value + /// will be used. Otherwise, it's deduced from the field's name by converting + /// it to camelCase. + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.json_name) + pub json_name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.options) + pub options: crate::MessageField<FieldOptions>, + /// If true, this is a proto3 "optional". When a proto3 field is optional, it + /// tracks presence regardless of field type. + /// + /// When proto3_optional is true, this field must be belong to a oneof to + /// signal to old proto3 clients that presence is tracked for this field. This + /// oneof is known as a "synthetic" oneof, and this field must be its sole + /// member (each proto3 optional field gets its own synthetic oneof). Synthetic + /// oneofs exist in the descriptor only, and do not generate any API. Synthetic + /// oneofs must be ordered after all "real" oneofs. + /// + /// For message fields, proto3_optional doesn't create any semantic change, + /// since non-repeated message fields always track presence. However it still + /// indicates the semantic detail of whether the user wrote "optional" or not. + /// This can be useful for round-tripping the .proto file. For consistency we + /// give message fields a synthetic oneof also, even though it is not required + /// to track presence. This is especially important because the parser can't + /// tell if a field is a message or an enum, so it must always create a + /// synthetic oneof. + /// + /// Proto2 optional fields do not set this flag, because they already indicate + /// optional with `LABEL_OPTIONAL`. + // @@protoc_insertion_point(field:google.protobuf.FieldDescriptorProto.proto3_optional) + pub proto3_optional: ::std::option::Option<bool>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FieldDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FieldDescriptorProto { @@ -2167,15 +1605,15 @@ impl FieldDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -2184,14 +1622,14 @@ impl FieldDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -2203,10 +1641,10 @@ impl FieldDescriptorProto { // optional int32 number = 3; - - pub fn get_number(&self) -> i32 { + pub fn number(&self) -> i32 { self.number.unwrap_or(0) } + pub fn clear_number(&mut self) { self.number = ::std::option::Option::None; } @@ -2222,10 +1660,13 @@ impl FieldDescriptorProto { // optional .google.protobuf.FieldDescriptorProto.Label label = 4; - - pub fn get_label(&self) -> FieldDescriptorProto_Label { - self.label.unwrap_or(FieldDescriptorProto_Label::LABEL_OPTIONAL) + pub fn label(&self) -> field_descriptor_proto::Label { + match self.label { + Some(e) => e.enum_value_or(field_descriptor_proto::Label::LABEL_OPTIONAL), + None => field_descriptor_proto::Label::LABEL_OPTIONAL, + } } + pub fn clear_label(&mut self) { self.label = ::std::option::Option::None; } @@ -2235,40 +1676,43 @@ impl FieldDescriptorProto { } // Param is passed by value, moved - pub fn set_label(&mut self, v: FieldDescriptorProto_Label) { - self.label = ::std::option::Option::Some(v); + pub fn set_label(&mut self, v: field_descriptor_proto::Label) { + self.label = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); } // optional .google.protobuf.FieldDescriptorProto.Type type = 5; - - pub fn get_field_type(&self) -> FieldDescriptorProto_Type { - self.field_type.unwrap_or(FieldDescriptorProto_Type::TYPE_DOUBLE) + pub fn type_(&self) -> field_descriptor_proto::Type { + match self.type_ { + Some(e) => e.enum_value_or(field_descriptor_proto::Type::TYPE_DOUBLE), + None => field_descriptor_proto::Type::TYPE_DOUBLE, + } } - pub fn clear_field_type(&mut self) { - self.field_type = ::std::option::Option::None; + + pub fn clear_type_(&mut self) { + self.type_ = ::std::option::Option::None; } - pub fn has_field_type(&self) -> bool { - self.field_type.is_some() + pub fn has_type(&self) -> bool { + self.type_.is_some() } // Param is passed by value, moved - pub fn set_field_type(&mut self, v: FieldDescriptorProto_Type) { - self.field_type = ::std::option::Option::Some(v); + pub fn set_type(&mut self, v: field_descriptor_proto::Type) { + self.type_ = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); } // optional string type_name = 6; - - pub fn get_type_name(&self) -> &str { + pub fn type_name(&self) -> &str { match self.type_name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_type_name(&mut self) { - self.type_name.clear(); + self.type_name = ::std::option::Option::None; } pub fn has_type_name(&self) -> bool { @@ -2277,14 +1721,14 @@ impl FieldDescriptorProto { // Param is passed by value, moved pub fn set_type_name(&mut self, v: ::std::string::String) { - self.type_name = crate::SingularField::some(v); + self.type_name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_type_name(&mut self) -> &mut ::std::string::String { if self.type_name.is_none() { - self.type_name.set_default(); + self.type_name = ::std::option::Option::Some(::std::string::String::new()); } self.type_name.as_mut().unwrap() } @@ -2296,15 +1740,15 @@ impl FieldDescriptorProto { // optional string extendee = 2; - - pub fn get_extendee(&self) -> &str { + pub fn extendee(&self) -> &str { match self.extendee.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_extendee(&mut self) { - self.extendee.clear(); + self.extendee = ::std::option::Option::None; } pub fn has_extendee(&self) -> bool { @@ -2313,14 +1757,14 @@ impl FieldDescriptorProto { // Param is passed by value, moved pub fn set_extendee(&mut self, v: ::std::string::String) { - self.extendee = crate::SingularField::some(v); + self.extendee = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_extendee(&mut self) -> &mut ::std::string::String { if self.extendee.is_none() { - self.extendee.set_default(); + self.extendee = ::std::option::Option::Some(::std::string::String::new()); } self.extendee.as_mut().unwrap() } @@ -2332,15 +1776,15 @@ impl FieldDescriptorProto { // optional string default_value = 7; - - pub fn get_default_value(&self) -> &str { + pub fn default_value(&self) -> &str { match self.default_value.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_default_value(&mut self) { - self.default_value.clear(); + self.default_value = ::std::option::Option::None; } pub fn has_default_value(&self) -> bool { @@ -2349,14 +1793,14 @@ impl FieldDescriptorProto { // Param is passed by value, moved pub fn set_default_value(&mut self, v: ::std::string::String) { - self.default_value = crate::SingularField::some(v); + self.default_value = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_default_value(&mut self) -> &mut ::std::string::String { if self.default_value.is_none() { - self.default_value.set_default(); + self.default_value = ::std::option::Option::Some(::std::string::String::new()); } self.default_value.as_mut().unwrap() } @@ -2368,10 +1812,10 @@ impl FieldDescriptorProto { // optional int32 oneof_index = 9; - - pub fn get_oneof_index(&self) -> i32 { + pub fn oneof_index(&self) -> i32 { self.oneof_index.unwrap_or(0) } + pub fn clear_oneof_index(&mut self) { self.oneof_index = ::std::option::Option::None; } @@ -2387,15 +1831,15 @@ impl FieldDescriptorProto { // optional string json_name = 10; - - pub fn get_json_name(&self) -> &str { + pub fn json_name(&self) -> &str { match self.json_name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_json_name(&mut self) { - self.json_name.clear(); + self.json_name = ::std::option::Option::None; } pub fn has_json_name(&self) -> bool { @@ -2404,14 +1848,14 @@ impl FieldDescriptorProto { // Param is passed by value, moved pub fn set_json_name(&mut self, v: ::std::string::String) { - self.json_name = crate::SingularField::some(v); + self.json_name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_json_name(&mut self) -> &mut ::std::string::String { if self.json_name.is_none() { - self.json_name.set_default(); + self.json_name = ::std::option::Option::Some(::std::string::String::new()); } self.json_name.as_mut().unwrap() } @@ -2421,45 +1865,12 @@ impl FieldDescriptorProto { self.json_name.take().unwrap_or_else(|| ::std::string::String::new()) } - // optional .google.protobuf.FieldOptions options = 8; - - - pub fn get_options(&self) -> &FieldOptions { - self.options.as_ref().unwrap_or_else(|| <FieldOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: FieldOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut FieldOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> FieldOptions { - self.options.take().unwrap_or_else(|| FieldOptions::new()) - } - // optional bool proto3_optional = 17; - - pub fn get_proto3_optional(&self) -> bool { + pub fn proto3_optional(&self) -> bool { self.proto3_optional.unwrap_or(false) } + pub fn clear_proto3_optional(&mut self) { self.proto3_optional = ::std::option::Option::None; } @@ -2472,9 +1883,76 @@ impl FieldDescriptorProto { pub fn set_proto3_optional(&mut self, v: bool) { self.proto3_optional = ::std::option::Option::Some(v); } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(11); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &FieldDescriptorProto| { &m.name }, + |m: &mut FieldDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "number", + |m: &FieldDescriptorProto| { &m.number }, + |m: &mut FieldDescriptorProto| { &mut m.number }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "label", + |m: &FieldDescriptorProto| { &m.label }, + |m: &mut FieldDescriptorProto| { &mut m.label }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "type", + |m: &FieldDescriptorProto| { &m.type_ }, + |m: &mut FieldDescriptorProto| { &mut m.type_ }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "type_name", + |m: &FieldDescriptorProto| { &m.type_name }, + |m: &mut FieldDescriptorProto| { &mut m.type_name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "extendee", + |m: &FieldDescriptorProto| { &m.extendee }, + |m: &mut FieldDescriptorProto| { &mut m.extendee }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "default_value", + |m: &FieldDescriptorProto| { &m.default_value }, + |m: &mut FieldDescriptorProto| { &mut m.default_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "oneof_index", + |m: &FieldDescriptorProto| { &m.oneof_index }, + |m: &mut FieldDescriptorProto| { &mut m.oneof_index }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "json_name", + |m: &FieldDescriptorProto| { &m.json_name }, + |m: &mut FieldDescriptorProto| { &mut m.json_name }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, FieldOptions>( + "options", + |m: &FieldDescriptorProto| { &m.options }, + |m: &mut FieldDescriptorProto| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "proto3_optional", + |m: &FieldDescriptorProto| { &m.proto3_optional }, + |m: &mut FieldDescriptorProto| { &mut m.proto3_optional }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FieldDescriptorProto>( + "FieldDescriptorProto", + fields, + oneofs, + ) + } } impl crate::Message for FieldDescriptorProto { + const NAME: &'static str = "FieldDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.options { if !v.is_initialized() { @@ -2484,57 +1962,44 @@ impl crate::Message for FieldDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.number = ::std::option::Option::Some(tmp); + 24 => { + self.number = ::std::option::Option::Some(is.read_int32()?); }, - 4 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.label, 4, &mut self.unknown_fields)? + 32 => { + self.label = ::std::option::Option::Some(is.read_enum_or_unknown()?); }, - 5 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.field_type, 5, &mut self.unknown_fields)? + 40 => { + self.type_ = ::std::option::Option::Some(is.read_enum_or_unknown()?); }, - 6 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.type_name)?; + 50 => { + self.type_name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.extendee)?; + 18 => { + self.extendee = ::std::option::Option::Some(is.read_string()?); }, - 7 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.default_value)?; + 58 => { + self.default_value = ::std::option::Option::Some(is.read_string()?); }, - 9 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.oneof_index = ::std::option::Option::Some(tmp); + 72 => { + self.oneof_index = ::std::option::Option::Some(is.read_int32()?); }, - 10 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.json_name)?; + 82 => { + self.json_name = ::std::option::Option::Some(is.read_string()?); }, - 8 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 66 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - 17 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.proto3_optional = ::std::option::Option::Some(tmp); + 136 => { + self.proto3_optional = ::std::option::Option::Some(is.read_bool()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -2543,385 +2008,364 @@ impl crate::Message for FieldDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } if let Some(v) = self.number { - my_size += crate::rt::value_size(3, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(3, v); } if let Some(v) = self.label { - my_size += crate::rt::enum_size(4, v); + my_size += crate::rt::int32_size(4, v.value()); } - if let Some(v) = self.field_type { - my_size += crate::rt::enum_size(5, v); + if let Some(v) = self.type_ { + my_size += crate::rt::int32_size(5, v.value()); } - if let Some(ref v) = self.type_name.as_ref() { + if let Some(v) = self.type_name.as_ref() { my_size += crate::rt::string_size(6, &v); } - if let Some(ref v) = self.extendee.as_ref() { + if let Some(v) = self.extendee.as_ref() { my_size += crate::rt::string_size(2, &v); } - if let Some(ref v) = self.default_value.as_ref() { + if let Some(v) = self.default_value.as_ref() { my_size += crate::rt::string_size(7, &v); } if let Some(v) = self.oneof_index { - my_size += crate::rt::value_size(9, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(9, v); } - if let Some(ref v) = self.json_name.as_ref() { + if let Some(v) = self.json_name.as_ref() { my_size += crate::rt::string_size(10, &v); } - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } if let Some(v) = self.proto3_optional { - my_size += 3; + my_size += 2 + 1; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } if let Some(v) = self.number { os.write_int32(3, v)?; } if let Some(v) = self.label { - os.write_enum(4, crate::ProtobufEnum::value(&v))?; + os.write_enum(4, crate::EnumOrUnknown::value(&v))?; } - if let Some(v) = self.field_type { - os.write_enum(5, crate::ProtobufEnum::value(&v))?; + if let Some(v) = self.type_ { + os.write_enum(5, crate::EnumOrUnknown::value(&v))?; } - if let Some(ref v) = self.type_name.as_ref() { - os.write_string(6, &v)?; + if let Some(v) = self.type_name.as_ref() { + os.write_string(6, v)?; } - if let Some(ref v) = self.extendee.as_ref() { - os.write_string(2, &v)?; + if let Some(v) = self.extendee.as_ref() { + os.write_string(2, v)?; } - if let Some(ref v) = self.default_value.as_ref() { - os.write_string(7, &v)?; + if let Some(v) = self.default_value.as_ref() { + os.write_string(7, v)?; } if let Some(v) = self.oneof_index { os.write_int32(9, v)?; } - if let Some(ref v) = self.json_name.as_ref() { - os.write_string(10, &v)?; + if let Some(v) = self.json_name.as_ref() { + os.write_string(10, v)?; } - if let Some(ref v) = self.options.as_ref() { - os.write_tag(8, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(8, v, os)?; } if let Some(v) = self.proto3_optional { os.write_bool(17, v)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FieldDescriptorProto { FieldDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &FieldDescriptorProto| { &m.name }, - |m: &mut FieldDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "number", - |m: &FieldDescriptorProto| { &m.number }, - |m: &mut FieldDescriptorProto| { &mut m.number }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<FieldDescriptorProto_Label>>( - "label", - |m: &FieldDescriptorProto| { &m.label }, - |m: &mut FieldDescriptorProto| { &mut m.label }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<FieldDescriptorProto_Type>>( - "type", - |m: &FieldDescriptorProto| { &m.field_type }, - |m: &mut FieldDescriptorProto| { &mut m.field_type }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "type_name", - |m: &FieldDescriptorProto| { &m.type_name }, - |m: &mut FieldDescriptorProto| { &mut m.type_name }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "extendee", - |m: &FieldDescriptorProto| { &m.extendee }, - |m: &mut FieldDescriptorProto| { &mut m.extendee }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "default_value", - |m: &FieldDescriptorProto| { &m.default_value }, - |m: &mut FieldDescriptorProto| { &mut m.default_value }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "oneof_index", - |m: &FieldDescriptorProto| { &m.oneof_index }, - |m: &mut FieldDescriptorProto| { &mut m.oneof_index }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "json_name", - |m: &FieldDescriptorProto| { &m.json_name }, - |m: &mut FieldDescriptorProto| { &mut m.json_name }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<FieldOptions>>( - "options", - |m: &FieldDescriptorProto| { &m.options }, - |m: &mut FieldDescriptorProto| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "proto3_optional", - |m: &FieldDescriptorProto| { &m.proto3_optional }, - |m: &mut FieldDescriptorProto| { &mut m.proto3_optional }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FieldDescriptorProto>( - "FieldDescriptorProto", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static FieldDescriptorProto { - static instance: crate::rt::LazyV2<FieldDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(FieldDescriptorProto::new) - } -} - -impl crate::Clear for FieldDescriptorProto { fn clear(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; self.number = ::std::option::Option::None; self.label = ::std::option::Option::None; - self.field_type = ::std::option::Option::None; - self.type_name.clear(); - self.extendee.clear(); - self.default_value.clear(); + self.type_ = ::std::option::Option::None; + self.type_name = ::std::option::Option::None; + self.extendee = ::std::option::Option::None; + self.default_value = ::std::option::Option::None; self.oneof_index = ::std::option::Option::None; - self.json_name.clear(); + self.json_name = ::std::option::Option::None; self.options.clear(); self.proto3_optional = ::std::option::Option::None; - self.unknown_fields.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static FieldDescriptorProto { + static instance: FieldDescriptorProto = FieldDescriptorProto { + name: ::std::option::Option::None, + number: ::std::option::Option::None, + label: ::std::option::Option::None, + type_: ::std::option::Option::None, + type_name: ::std::option::Option::None, + extendee: ::std::option::Option::None, + default_value: ::std::option::Option::None, + oneof_index: ::std::option::Option::None, + json_name: ::std::option::Option::None, + options: crate::MessageField::none(), + proto3_optional: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for FieldDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FieldDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for FieldDescriptorProto { +impl ::std::fmt::Display for FieldDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for FieldDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum FieldDescriptorProto_Type { - TYPE_DOUBLE = 1, - TYPE_FLOAT = 2, - TYPE_INT64 = 3, - TYPE_UINT64 = 4, - TYPE_INT32 = 5, - TYPE_FIXED64 = 6, - TYPE_FIXED32 = 7, - TYPE_BOOL = 8, - TYPE_STRING = 9, - TYPE_GROUP = 10, - TYPE_MESSAGE = 11, - TYPE_BYTES = 12, - TYPE_UINT32 = 13, - TYPE_ENUM = 14, - TYPE_SFIXED32 = 15, - TYPE_SFIXED64 = 16, - TYPE_SINT32 = 17, - TYPE_SINT64 = 18, -} - -impl crate::ProtobufEnum for FieldDescriptorProto_Type { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<FieldDescriptorProto_Type> { - match value { - 1 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_DOUBLE), - 2 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_FLOAT), - 3 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_INT64), - 4 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_UINT64), - 5 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_INT32), - 6 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_FIXED64), - 7 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_FIXED32), - 8 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_BOOL), - 9 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_STRING), - 10 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_GROUP), - 11 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_MESSAGE), - 12 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_BYTES), - 13 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_UINT32), - 14 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_ENUM), - 15 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_SFIXED32), - 16 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_SFIXED64), - 17 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_SINT32), - 18 => ::std::option::Option::Some(FieldDescriptorProto_Type::TYPE_SINT64), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [FieldDescriptorProto_Type] = &[ - FieldDescriptorProto_Type::TYPE_DOUBLE, - FieldDescriptorProto_Type::TYPE_FLOAT, - FieldDescriptorProto_Type::TYPE_INT64, - FieldDescriptorProto_Type::TYPE_UINT64, - FieldDescriptorProto_Type::TYPE_INT32, - FieldDescriptorProto_Type::TYPE_FIXED64, - FieldDescriptorProto_Type::TYPE_FIXED32, - FieldDescriptorProto_Type::TYPE_BOOL, - FieldDescriptorProto_Type::TYPE_STRING, - FieldDescriptorProto_Type::TYPE_GROUP, - FieldDescriptorProto_Type::TYPE_MESSAGE, - FieldDescriptorProto_Type::TYPE_BYTES, - FieldDescriptorProto_Type::TYPE_UINT32, - FieldDescriptorProto_Type::TYPE_ENUM, - FieldDescriptorProto_Type::TYPE_SFIXED32, - FieldDescriptorProto_Type::TYPE_SFIXED64, - FieldDescriptorProto_Type::TYPE_SINT32, - FieldDescriptorProto_Type::TYPE_SINT64, + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `FieldDescriptorProto` +pub mod field_descriptor_proto { + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.FieldDescriptorProto.Type) + pub enum Type { + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_DOUBLE) + TYPE_DOUBLE = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_FLOAT) + TYPE_FLOAT = 2, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_INT64) + TYPE_INT64 = 3, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_UINT64) + TYPE_UINT64 = 4, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_INT32) + TYPE_INT32 = 5, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_FIXED64) + TYPE_FIXED64 = 6, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_FIXED32) + TYPE_FIXED32 = 7, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_BOOL) + TYPE_BOOL = 8, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_STRING) + TYPE_STRING = 9, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_GROUP) + TYPE_GROUP = 10, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE) + TYPE_MESSAGE = 11, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_BYTES) + TYPE_BYTES = 12, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_UINT32) + TYPE_UINT32 = 13, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_ENUM) + TYPE_ENUM = 14, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_SFIXED32) + TYPE_SFIXED32 = 15, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_SFIXED64) + TYPE_SFIXED64 = 16, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_SINT32) + TYPE_SINT32 = 17, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Type.TYPE_SINT64) + TYPE_SINT64 = 18, + } + + impl crate::Enum for Type { + const NAME: &'static str = "Type"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<Type> { + match value { + 1 => ::std::option::Option::Some(Type::TYPE_DOUBLE), + 2 => ::std::option::Option::Some(Type::TYPE_FLOAT), + 3 => ::std::option::Option::Some(Type::TYPE_INT64), + 4 => ::std::option::Option::Some(Type::TYPE_UINT64), + 5 => ::std::option::Option::Some(Type::TYPE_INT32), + 6 => ::std::option::Option::Some(Type::TYPE_FIXED64), + 7 => ::std::option::Option::Some(Type::TYPE_FIXED32), + 8 => ::std::option::Option::Some(Type::TYPE_BOOL), + 9 => ::std::option::Option::Some(Type::TYPE_STRING), + 10 => ::std::option::Option::Some(Type::TYPE_GROUP), + 11 => ::std::option::Option::Some(Type::TYPE_MESSAGE), + 12 => ::std::option::Option::Some(Type::TYPE_BYTES), + 13 => ::std::option::Option::Some(Type::TYPE_UINT32), + 14 => ::std::option::Option::Some(Type::TYPE_ENUM), + 15 => ::std::option::Option::Some(Type::TYPE_SFIXED32), + 16 => ::std::option::Option::Some(Type::TYPE_SFIXED64), + 17 => ::std::option::Option::Some(Type::TYPE_SINT32), + 18 => ::std::option::Option::Some(Type::TYPE_SINT64), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [Type] = &[ + Type::TYPE_DOUBLE, + Type::TYPE_FLOAT, + Type::TYPE_INT64, + Type::TYPE_UINT64, + Type::TYPE_INT32, + Type::TYPE_FIXED64, + Type::TYPE_FIXED32, + Type::TYPE_BOOL, + Type::TYPE_STRING, + Type::TYPE_GROUP, + Type::TYPE_MESSAGE, + Type::TYPE_BYTES, + Type::TYPE_UINT32, + Type::TYPE_ENUM, + Type::TYPE_SFIXED32, + Type::TYPE_SFIXED64, + Type::TYPE_SINT32, + Type::TYPE_SINT64, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<FieldDescriptorProto_Type>("FieldDescriptorProto.Type", file_descriptor_proto()) - }) + impl crate::EnumFull for Type { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("FieldDescriptorProto.Type").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = match self { + Type::TYPE_DOUBLE => 0, + Type::TYPE_FLOAT => 1, + Type::TYPE_INT64 => 2, + Type::TYPE_UINT64 => 3, + Type::TYPE_INT32 => 4, + Type::TYPE_FIXED64 => 5, + Type::TYPE_FIXED32 => 6, + Type::TYPE_BOOL => 7, + Type::TYPE_STRING => 8, + Type::TYPE_GROUP => 9, + Type::TYPE_MESSAGE => 10, + Type::TYPE_BYTES => 11, + Type::TYPE_UINT32 => 12, + Type::TYPE_ENUM => 13, + Type::TYPE_SFIXED32 => 14, + Type::TYPE_SFIXED64 => 15, + Type::TYPE_SINT32 => 16, + Type::TYPE_SINT64 => 17, + }; + Self::enum_descriptor().value_by_index(index) + } } -} -impl ::std::marker::Copy for FieldDescriptorProto_Type { -} + // Note, `Default` is implemented although default value is not 0 + impl ::std::default::Default for Type { + fn default() -> Self { + Type::TYPE_DOUBLE + } + } -// Note, `Default` is implemented although default value is not 0 -impl ::std::default::Default for FieldDescriptorProto_Type { - fn default() -> Self { - FieldDescriptorProto_Type::TYPE_DOUBLE + impl Type { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Type>("FieldDescriptorProto.Type") + } } -} -impl crate::reflect::ProtobufValue for FieldDescriptorProto_Type { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.FieldDescriptorProto.Label) + pub enum Label { + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Label.LABEL_OPTIONAL) + LABEL_OPTIONAL = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Label.LABEL_REQUIRED) + LABEL_REQUIRED = 2, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED) + LABEL_REPEATED = 3, } -} -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum FieldDescriptorProto_Label { - LABEL_OPTIONAL = 1, - LABEL_REQUIRED = 2, - LABEL_REPEATED = 3, -} + impl crate::Enum for Label { + const NAME: &'static str = "Label"; -impl crate::ProtobufEnum for FieldDescriptorProto_Label { - fn value(&self) -> i32 { - *self as i32 - } + fn value(&self) -> i32 { + *self as i32 + } - fn from_i32(value: i32) -> ::std::option::Option<FieldDescriptorProto_Label> { - match value { - 1 => ::std::option::Option::Some(FieldDescriptorProto_Label::LABEL_OPTIONAL), - 2 => ::std::option::Option::Some(FieldDescriptorProto_Label::LABEL_REQUIRED), - 3 => ::std::option::Option::Some(FieldDescriptorProto_Label::LABEL_REPEATED), - _ => ::std::option::Option::None + fn from_i32(value: i32) -> ::std::option::Option<Label> { + match value { + 1 => ::std::option::Option::Some(Label::LABEL_OPTIONAL), + 2 => ::std::option::Option::Some(Label::LABEL_REQUIRED), + 3 => ::std::option::Option::Some(Label::LABEL_REPEATED), + _ => ::std::option::Option::None + } } - } - fn values() -> &'static [Self] { - static values: &'static [FieldDescriptorProto_Label] = &[ - FieldDescriptorProto_Label::LABEL_OPTIONAL, - FieldDescriptorProto_Label::LABEL_REQUIRED, - FieldDescriptorProto_Label::LABEL_REPEATED, + const VALUES: &'static [Label] = &[ + Label::LABEL_OPTIONAL, + Label::LABEL_REQUIRED, + Label::LABEL_REPEATED, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<FieldDescriptorProto_Label>("FieldDescriptorProto.Label", file_descriptor_proto()) - }) - } -} + impl crate::EnumFull for Label { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("FieldDescriptorProto.Label").unwrap()).clone() + } -impl ::std::marker::Copy for FieldDescriptorProto_Label { -} + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = match self { + Label::LABEL_OPTIONAL => 0, + Label::LABEL_REQUIRED => 1, + Label::LABEL_REPEATED => 2, + }; + Self::enum_descriptor().value_by_index(index) + } + } -// Note, `Default` is implemented although default value is not 0 -impl ::std::default::Default for FieldDescriptorProto_Label { - fn default() -> Self { - FieldDescriptorProto_Label::LABEL_OPTIONAL + // Note, `Default` is implemented although default value is not 0 + impl ::std::default::Default for Label { + fn default() -> Self { + Label::LABEL_OPTIONAL + } } -} -impl crate::reflect::ProtobufValue for FieldDescriptorProto_Label { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + impl Label { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Label>("FieldDescriptorProto.Label") + } } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a oneof. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.OneofDescriptorProto) pub struct OneofDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - pub options: crate::SingularPtrField<OneofOptions>, + // @@protoc_insertion_point(field:google.protobuf.OneofDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.OneofDescriptorProto.options) + pub options: crate::MessageField<OneofOptions>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.OneofDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a OneofDescriptorProto { @@ -2937,15 +2381,15 @@ impl OneofDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -2954,14 +2398,14 @@ impl OneofDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -2971,41 +2415,30 @@ impl OneofDescriptorProto { self.name.take().unwrap_or_else(|| ::std::string::String::new()) } - // optional .google.protobuf.OneofOptions options = 2; - - - pub fn get_options(&self) -> &OneofOptions { - self.options.as_ref().unwrap_or_else(|| <OneofOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: OneofOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut OneofOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> OneofOptions { - self.options.take().unwrap_or_else(|| OneofOptions::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &OneofDescriptorProto| { &m.name }, + |m: &mut OneofDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, OneofOptions>( + "options", + |m: &OneofDescriptorProto| { &m.options }, + |m: &mut OneofDescriptorProto| { &mut m.options }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<OneofDescriptorProto>( + "OneofDescriptorProto", + fields, + oneofs, + ) } } impl crate::Message for OneofDescriptorProto { + const NAME: &'static str = "OneofDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.options { if !v.is_initialized() { @@ -3015,18 +2448,17 @@ impl crate::Message for OneofDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 18 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -3035,125 +2467,99 @@ impl crate::Message for OneofDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } - if let Some(ref v) = self.options.as_ref() { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(2, v, os)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> OneofDescriptorProto { OneofDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &OneofDescriptorProto| { &m.name }, - |m: &mut OneofDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<OneofOptions>>( - "options", - |m: &OneofDescriptorProto| { &m.options }, - |m: &mut OneofDescriptorProto| { &mut m.options }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<OneofDescriptorProto>( - "OneofDescriptorProto", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.options.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static OneofDescriptorProto { - static instance: crate::rt::LazyV2<OneofDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(OneofDescriptorProto::new) + static instance: OneofDescriptorProto = OneofDescriptorProto { + name: ::std::option::Option::None, + options: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for OneofDescriptorProto { - fn clear(&mut self) { - self.name.clear(); - self.options.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for OneofDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("OneofDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for OneofDescriptorProto { +impl ::std::fmt::Display for OneofDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for OneofDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes an enum type. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.EnumDescriptorProto) pub struct EnumDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - pub value: crate::RepeatedField<EnumValueDescriptorProto>, - pub options: crate::SingularPtrField<EnumOptions>, - pub reserved_range: crate::RepeatedField<EnumDescriptorProto_EnumReservedRange>, - pub reserved_name: crate::RepeatedField<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.value) + pub value: ::std::vec::Vec<EnumValueDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.options) + pub options: crate::MessageField<EnumOptions>, + /// Range of reserved numeric values. Reserved numeric values may not be used + /// by enum values in the same enum declaration. Reserved ranges may not + /// overlap. + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.reserved_range) + pub reserved_range: ::std::vec::Vec<enum_descriptor_proto::EnumReservedRange>, + /// Reserved enum value names, which may not be reused. A given name may only + /// be reserved once. + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.reserved_name) + pub reserved_name: ::std::vec::Vec<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.EnumDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a EnumDescriptorProto { @@ -3169,15 +2575,15 @@ impl EnumDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -3186,14 +2592,14 @@ impl EnumDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -3203,116 +2609,45 @@ impl EnumDescriptorProto { self.name.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated .google.protobuf.EnumValueDescriptorProto value = 2; - - - pub fn get_value(&self) -> &[EnumValueDescriptorProto] { - &self.value - } - pub fn clear_value(&mut self) { - self.value.clear(); - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: crate::RepeatedField<EnumValueDescriptorProto>) { - self.value = v; - } - - // Mutable pointer to the field. - pub fn mut_value(&mut self) -> &mut crate::RepeatedField<EnumValueDescriptorProto> { - &mut self.value - } - - // Take field - pub fn take_value(&mut self) -> crate::RepeatedField<EnumValueDescriptorProto> { - ::std::mem::replace(&mut self.value, crate::RepeatedField::new()) - } - - // optional .google.protobuf.EnumOptions options = 3; - - - pub fn get_options(&self) -> &EnumOptions { - self.options.as_ref().unwrap_or_else(|| <EnumOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: EnumOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut EnumOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> EnumOptions { - self.options.take().unwrap_or_else(|| EnumOptions::new()) - } - - // repeated .google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; - - - pub fn get_reserved_range(&self) -> &[EnumDescriptorProto_EnumReservedRange] { - &self.reserved_range - } - pub fn clear_reserved_range(&mut self) { - self.reserved_range.clear(); - } - - // Param is passed by value, moved - pub fn set_reserved_range(&mut self, v: crate::RepeatedField<EnumDescriptorProto_EnumReservedRange>) { - self.reserved_range = v; - } - - // Mutable pointer to the field. - pub fn mut_reserved_range(&mut self) -> &mut crate::RepeatedField<EnumDescriptorProto_EnumReservedRange> { - &mut self.reserved_range - } - - // Take field - pub fn take_reserved_range(&mut self) -> crate::RepeatedField<EnumDescriptorProto_EnumReservedRange> { - ::std::mem::replace(&mut self.reserved_range, crate::RepeatedField::new()) - } - - // repeated string reserved_name = 5; - - - pub fn get_reserved_name(&self) -> &[::std::string::String] { - &self.reserved_name - } - pub fn clear_reserved_name(&mut self) { - self.reserved_name.clear(); - } - - // Param is passed by value, moved - pub fn set_reserved_name(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.reserved_name = v; - } - - // Mutable pointer to the field. - pub fn mut_reserved_name(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.reserved_name - } - - // Take field - pub fn take_reserved_name(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.reserved_name, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(5); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &EnumDescriptorProto| { &m.name }, + |m: &mut EnumDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "value", + |m: &EnumDescriptorProto| { &m.value }, + |m: &mut EnumDescriptorProto| { &mut m.value }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, EnumOptions>( + "options", + |m: &EnumDescriptorProto| { &m.options }, + |m: &mut EnumDescriptorProto| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "reserved_range", + |m: &EnumDescriptorProto| { &m.reserved_range }, + |m: &mut EnumDescriptorProto| { &mut m.reserved_range }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "reserved_name", + |m: &EnumDescriptorProto| { &m.reserved_name }, + |m: &mut EnumDescriptorProto| { &mut m.reserved_name }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumDescriptorProto>( + "EnumDescriptorProto", + fields, + oneofs, + ) } } impl crate::Message for EnumDescriptorProto { + const NAME: &'static str = "EnumDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.value { if !v.is_initialized() { @@ -3332,27 +2667,26 @@ impl crate::Message for EnumDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.value)?; + 18 => { + self.value.push(is.read_message()?); }, - 3 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 26 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - 4 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.reserved_range)?; + 34 => { + self.reserved_range.push(is.read_message()?); }, - 5 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.reserved_name)?; + 42 => { + self.reserved_name.push(is.read_string()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -3361,363 +2695,303 @@ impl crate::Message for EnumDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } for value in &self.value { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } for value in &self.reserved_range { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.reserved_name { my_size += crate::rt::string_size(5, &value); }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } for v in &self.value { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; }; - if let Some(ref v) = self.options.as_ref() { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(3, v, os)?; } for v in &self.reserved_range { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(4, v, os)?; }; for v in &self.reserved_name { os.write_string(5, &v)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> EnumDescriptorProto { EnumDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &EnumDescriptorProto| { &m.name }, - |m: &mut EnumDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumValueDescriptorProto>>( - "value", - |m: &EnumDescriptorProto| { &m.value }, - |m: &mut EnumDescriptorProto| { &mut m.value }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumOptions>>( - "options", - |m: &EnumDescriptorProto| { &m.options }, - |m: &mut EnumDescriptorProto| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumDescriptorProto_EnumReservedRange>>( - "reserved_range", - |m: &EnumDescriptorProto| { &m.reserved_range }, - |m: &mut EnumDescriptorProto| { &mut m.reserved_range }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "reserved_name", - |m: &EnumDescriptorProto| { &m.reserved_name }, - |m: &mut EnumDescriptorProto| { &mut m.reserved_name }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumDescriptorProto>( - "EnumDescriptorProto", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.value.clear(); + self.options.clear(); + self.reserved_range.clear(); + self.reserved_name.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static EnumDescriptorProto { - static instance: crate::rt::LazyV2<EnumDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(EnumDescriptorProto::new) + static instance: EnumDescriptorProto = EnumDescriptorProto { + name: ::std::option::Option::None, + value: ::std::vec::Vec::new(), + options: crate::MessageField::none(), + reserved_range: ::std::vec::Vec::new(), + reserved_name: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for EnumDescriptorProto { - fn clear(&mut self) { - self.name.clear(); - self.value.clear(); - self.options.clear(); - self.reserved_range.clear(); - self.reserved_name.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for EnumDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("EnumDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for EnumDescriptorProto { +impl ::std::fmt::Display for EnumDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for EnumDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct EnumDescriptorProto_EnumReservedRange { - // message fields - start: ::std::option::Option<i32>, - end: ::std::option::Option<i32>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -impl<'a> ::std::default::Default for &'a EnumDescriptorProto_EnumReservedRange { - fn default() -> &'a EnumDescriptorProto_EnumReservedRange { - <EnumDescriptorProto_EnumReservedRange as crate::Message>::default_instance() +/// Nested message and enums of message `EnumDescriptorProto` +pub mod enum_descriptor_proto { + /// Range of reserved numeric values. Reserved values may not be used by + /// entries in the same enum. Reserved ranges may not overlap. + /// + /// Note that this is distinct from DescriptorProto.ReservedRange in that it + /// is inclusive such that it can appropriately represent the entire int32 + /// domain. + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.EnumDescriptorProto.EnumReservedRange) + pub struct EnumReservedRange { + // message fields + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.EnumReservedRange.start) + pub start: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.EnumDescriptorProto.EnumReservedRange.end) + pub end: ::std::option::Option<i32>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.EnumDescriptorProto.EnumReservedRange.special_fields) + pub special_fields: crate::SpecialFields, } -} -impl EnumDescriptorProto_EnumReservedRange { - pub fn new() -> EnumDescriptorProto_EnumReservedRange { - ::std::default::Default::default() + impl<'a> ::std::default::Default for &'a EnumReservedRange { + fn default() -> &'a EnumReservedRange { + <EnumReservedRange as crate::Message>::default_instance() + } } - // optional int32 start = 1; - - - pub fn get_start(&self) -> i32 { - self.start.unwrap_or(0) - } - pub fn clear_start(&mut self) { - self.start = ::std::option::Option::None; - } + impl EnumReservedRange { + pub fn new() -> EnumReservedRange { + ::std::default::Default::default() + } - pub fn has_start(&self) -> bool { - self.start.is_some() - } + // optional int32 start = 1; - // Param is passed by value, moved - pub fn set_start(&mut self, v: i32) { - self.start = ::std::option::Option::Some(v); - } + pub fn start(&self) -> i32 { + self.start.unwrap_or(0) + } - // optional int32 end = 2; + pub fn clear_start(&mut self) { + self.start = ::std::option::Option::None; + } + pub fn has_start(&self) -> bool { + self.start.is_some() + } - pub fn get_end(&self) -> i32 { - self.end.unwrap_or(0) - } - pub fn clear_end(&mut self) { - self.end = ::std::option::Option::None; - } + // Param is passed by value, moved + pub fn set_start(&mut self, v: i32) { + self.start = ::std::option::Option::Some(v); + } - pub fn has_end(&self) -> bool { - self.end.is_some() - } + // optional int32 end = 2; - // Param is passed by value, moved - pub fn set_end(&mut self, v: i32) { - self.end = ::std::option::Option::Some(v); - } -} + pub fn end(&self) -> i32 { + self.end.unwrap_or(0) + } -impl crate::Message for EnumDescriptorProto_EnumReservedRange { - fn is_initialized(&self) -> bool { - true - } + pub fn clear_end(&mut self) { + self.end = ::std::option::Option::None; + } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.start = ::std::option::Option::Some(tmp); - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.end = ::std::option::Option::Some(tmp); - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + pub fn has_end(&self) -> bool { + self.end.is_some() } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let Some(v) = self.start { - my_size += crate::rt::value_size(1, v, crate::wire_format::WireTypeVarint); + // Param is passed by value, moved + pub fn set_end(&mut self, v: i32) { + self.end = ::std::option::Option::Some(v); } - if let Some(v) = self.end { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); + + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "start", + |m: &EnumReservedRange| { &m.start }, + |m: &mut EnumReservedRange| { &mut m.start }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "end", + |m: &EnumReservedRange| { &m.end }, + |m: &mut EnumReservedRange| { &mut m.end }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumReservedRange>( + "EnumDescriptorProto.EnumReservedRange", + fields, + oneofs, + ) } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(v) = self.start { - os.write_int32(1, v)?; - } - if let Some(v) = self.end { - os.write_int32(2, v)?; + impl crate::Message for EnumReservedRange { + const NAME: &'static str = "EnumReservedRange"; + + fn is_initialized(&self) -> bool { + true } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.start = ::std::option::Option::Some(is.read_int32()?); + }, + 16 => { + self.end = ::std::option::Option::Some(is.read_int32()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let Some(v) = self.start { + my_size += crate::rt::int32_size(1, v); + } + if let Some(v) = self.end { + my_size += crate::rt::int32_size(2, v); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.start { + os.write_int32(1, v)?; + } + if let Some(v) = self.end { + os.write_int32(2, v)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } - fn new() -> EnumDescriptorProto_EnumReservedRange { - EnumDescriptorProto_EnumReservedRange::new() - } + fn new() -> EnumReservedRange { + EnumReservedRange::new() + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "start", - |m: &EnumDescriptorProto_EnumReservedRange| { &m.start }, - |m: &mut EnumDescriptorProto_EnumReservedRange| { &mut m.start }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "end", - |m: &EnumDescriptorProto_EnumReservedRange| { &m.end }, - |m: &mut EnumDescriptorProto_EnumReservedRange| { &mut m.end }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumDescriptorProto_EnumReservedRange>( - "EnumDescriptorProto.EnumReservedRange", - fields, - file_descriptor_proto() - ) - }) - } + fn clear(&mut self) { + self.start = ::std::option::Option::None; + self.end = ::std::option::Option::None; + self.special_fields.clear(); + } - fn default_instance() -> &'static EnumDescriptorProto_EnumReservedRange { - static instance: crate::rt::LazyV2<EnumDescriptorProto_EnumReservedRange> = crate::rt::LazyV2::INIT; - instance.get(EnumDescriptorProto_EnumReservedRange::new) + fn default_instance() -> &'static EnumReservedRange { + static instance: EnumReservedRange = EnumReservedRange { + start: ::std::option::Option::None, + end: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl crate::Clear for EnumDescriptorProto_EnumReservedRange { - fn clear(&mut self) { - self.start = ::std::option::Option::None; - self.end = ::std::option::Option::None; - self.unknown_fields.clear(); + impl crate::MessageFull for EnumReservedRange { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("EnumDescriptorProto.EnumReservedRange").unwrap()).clone() + } } -} -impl ::std::fmt::Debug for EnumDescriptorProto_EnumReservedRange { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl ::std::fmt::Display for EnumReservedRange { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for EnumDescriptorProto_EnumReservedRange { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl crate::reflect::ProtobufValue for EnumReservedRange { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a value within an enum. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.EnumValueDescriptorProto) pub struct EnumValueDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - number: ::std::option::Option<i32>, - pub options: crate::SingularPtrField<EnumValueOptions>, + // @@protoc_insertion_point(field:google.protobuf.EnumValueDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.EnumValueDescriptorProto.number) + pub number: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.EnumValueDescriptorProto.options) + pub options: crate::MessageField<EnumValueOptions>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.EnumValueDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a EnumValueDescriptorProto { @@ -3733,15 +3007,15 @@ impl EnumValueDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -3750,14 +3024,14 @@ impl EnumValueDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -3769,10 +3043,10 @@ impl EnumValueDescriptorProto { // optional int32 number = 2; - - pub fn get_number(&self) -> i32 { + pub fn number(&self) -> i32 { self.number.unwrap_or(0) } + pub fn clear_number(&mut self) { self.number = ::std::option::Option::None; } @@ -3786,41 +3060,35 @@ impl EnumValueDescriptorProto { self.number = ::std::option::Option::Some(v); } - // optional .google.protobuf.EnumValueOptions options = 3; - - - pub fn get_options(&self) -> &EnumValueOptions { - self.options.as_ref().unwrap_or_else(|| <EnumValueOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: EnumValueOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut EnumValueOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> EnumValueOptions { - self.options.take().unwrap_or_else(|| EnumValueOptions::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &EnumValueDescriptorProto| { &m.name }, + |m: &mut EnumValueDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "number", + |m: &EnumValueDescriptorProto| { &m.number }, + |m: &mut EnumValueDescriptorProto| { &mut m.number }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, EnumValueOptions>( + "options", + |m: &EnumValueDescriptorProto| { &m.options }, + |m: &mut EnumValueDescriptorProto| { &mut m.options }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumValueDescriptorProto>( + "EnumValueDescriptorProto", + fields, + oneofs, + ) } } impl crate::Message for EnumValueDescriptorProto { + const NAME: &'static str = "EnumValueDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.options { if !v.is_initialized() { @@ -3830,25 +3098,20 @@ impl crate::Message for EnumValueDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.number = ::std::option::Option::Some(tmp); + 16 => { + self.number = ::std::option::Option::Some(is.read_int32()?); }, - 3 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 26 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -3857,135 +3120,98 @@ impl crate::Message for EnumValueDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } if let Some(v) = self.number { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(2, v); } - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } if let Some(v) = self.number { os.write_int32(2, v)?; } - if let Some(ref v) = self.options.as_ref() { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(3, v, os)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> EnumValueDescriptorProto { EnumValueDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &EnumValueDescriptorProto| { &m.name }, - |m: &mut EnumValueDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "number", - |m: &EnumValueDescriptorProto| { &m.number }, - |m: &mut EnumValueDescriptorProto| { &mut m.number }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumValueOptions>>( - "options", - |m: &EnumValueDescriptorProto| { &m.options }, - |m: &mut EnumValueDescriptorProto| { &mut m.options }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumValueDescriptorProto>( - "EnumValueDescriptorProto", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.number = ::std::option::Option::None; + self.options.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static EnumValueDescriptorProto { - static instance: crate::rt::LazyV2<EnumValueDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(EnumValueDescriptorProto::new) + static instance: EnumValueDescriptorProto = EnumValueDescriptorProto { + name: ::std::option::Option::None, + number: ::std::option::Option::None, + options: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for EnumValueDescriptorProto { - fn clear(&mut self) { - self.name.clear(); - self.number = ::std::option::Option::None; - self.options.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for EnumValueDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("EnumValueDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for EnumValueDescriptorProto { +impl ::std::fmt::Display for EnumValueDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for EnumValueDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a service. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.ServiceDescriptorProto) pub struct ServiceDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - pub method: crate::RepeatedField<MethodDescriptorProto>, - pub options: crate::SingularPtrField<ServiceOptions>, + // @@protoc_insertion_point(field:google.protobuf.ServiceDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.ServiceDescriptorProto.method) + pub method: ::std::vec::Vec<MethodDescriptorProto>, + // @@protoc_insertion_point(field:google.protobuf.ServiceDescriptorProto.options) + pub options: crate::MessageField<ServiceOptions>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.ServiceDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a ServiceDescriptorProto { @@ -4001,15 +3227,15 @@ impl ServiceDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -4018,14 +3244,14 @@ impl ServiceDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -4035,66 +3261,35 @@ impl ServiceDescriptorProto { self.name.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated .google.protobuf.MethodDescriptorProto method = 2; - - - pub fn get_method(&self) -> &[MethodDescriptorProto] { - &self.method - } - pub fn clear_method(&mut self) { - self.method.clear(); - } - - // Param is passed by value, moved - pub fn set_method(&mut self, v: crate::RepeatedField<MethodDescriptorProto>) { - self.method = v; - } - - // Mutable pointer to the field. - pub fn mut_method(&mut self) -> &mut crate::RepeatedField<MethodDescriptorProto> { - &mut self.method - } - - // Take field - pub fn take_method(&mut self) -> crate::RepeatedField<MethodDescriptorProto> { - ::std::mem::replace(&mut self.method, crate::RepeatedField::new()) - } - - // optional .google.protobuf.ServiceOptions options = 3; - - - pub fn get_options(&self) -> &ServiceOptions { - self.options.as_ref().unwrap_or_else(|| <ServiceOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: ServiceOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut ServiceOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> ServiceOptions { - self.options.take().unwrap_or_else(|| ServiceOptions::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &ServiceDescriptorProto| { &m.name }, + |m: &mut ServiceDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "method", + |m: &ServiceDescriptorProto| { &m.method }, + |m: &mut ServiceDescriptorProto| { &mut m.method }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, ServiceOptions>( + "options", + |m: &ServiceDescriptorProto| { &m.options }, + |m: &mut ServiceDescriptorProto| { &mut m.options }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<ServiceDescriptorProto>( + "ServiceDescriptorProto", + fields, + oneofs, + ) } } impl crate::Message for ServiceDescriptorProto { + const NAME: &'static str = "ServiceDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.method { if !v.is_initialized() { @@ -4109,21 +3304,20 @@ impl crate::Message for ServiceDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.method)?; + 18 => { + self.method.push(is.read_message()?); }, - 3 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 26 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -4132,141 +3326,109 @@ impl crate::Message for ServiceDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } for value in &self.method { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } for v in &self.method { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; }; - if let Some(ref v) = self.options.as_ref() { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(3, v, os)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> ServiceDescriptorProto { ServiceDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &ServiceDescriptorProto| { &m.name }, - |m: &mut ServiceDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<MethodDescriptorProto>>( - "method", - |m: &ServiceDescriptorProto| { &m.method }, - |m: &mut ServiceDescriptorProto| { &mut m.method }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<ServiceOptions>>( - "options", - |m: &ServiceDescriptorProto| { &m.options }, - |m: &mut ServiceDescriptorProto| { &mut m.options }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<ServiceDescriptorProto>( - "ServiceDescriptorProto", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.method.clear(); + self.options.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static ServiceDescriptorProto { - static instance: crate::rt::LazyV2<ServiceDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(ServiceDescriptorProto::new) + static instance: ServiceDescriptorProto = ServiceDescriptorProto { + name: ::std::option::Option::None, + method: ::std::vec::Vec::new(), + options: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for ServiceDescriptorProto { - fn clear(&mut self) { - self.name.clear(); - self.method.clear(); - self.options.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for ServiceDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("ServiceDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for ServiceDescriptorProto { +impl ::std::fmt::Display for ServiceDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for ServiceDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes a method of a service. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.MethodDescriptorProto) pub struct MethodDescriptorProto { // message fields - name: crate::SingularField<::std::string::String>, - input_type: crate::SingularField<::std::string::String>, - output_type: crate::SingularField<::std::string::String>, - pub options: crate::SingularPtrField<MethodOptions>, - client_streaming: ::std::option::Option<bool>, - server_streaming: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.name) + pub name: ::std::option::Option<::std::string::String>, + /// Input and output type names. These are resolved in the same way as + /// FieldDescriptorProto.type_name, but must refer to a message type. + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.input_type) + pub input_type: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.output_type) + pub output_type: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.options) + pub options: crate::MessageField<MethodOptions>, + /// Identifies if client streams multiple client messages + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.client_streaming) + pub client_streaming: ::std::option::Option<bool>, + /// Identifies if server streams multiple server messages + // @@protoc_insertion_point(field:google.protobuf.MethodDescriptorProto.server_streaming) + pub server_streaming: ::std::option::Option<bool>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.MethodDescriptorProto.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a MethodDescriptorProto { @@ -4282,15 +3444,15 @@ impl MethodDescriptorProto { // optional string name = 1; - - pub fn get_name(&self) -> &str { + pub fn name(&self) -> &str { match self.name.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_name(&mut self) { - self.name.clear(); + self.name = ::std::option::Option::None; } pub fn has_name(&self) -> bool { @@ -4299,14 +3461,14 @@ impl MethodDescriptorProto { // Param is passed by value, moved pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); + self.name = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_name(&mut self) -> &mut ::std::string::String { if self.name.is_none() { - self.name.set_default(); + self.name = ::std::option::Option::Some(::std::string::String::new()); } self.name.as_mut().unwrap() } @@ -4318,15 +3480,15 @@ impl MethodDescriptorProto { // optional string input_type = 2; - - pub fn get_input_type(&self) -> &str { + pub fn input_type(&self) -> &str { match self.input_type.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_input_type(&mut self) { - self.input_type.clear(); + self.input_type = ::std::option::Option::None; } pub fn has_input_type(&self) -> bool { @@ -4335,14 +3497,14 @@ impl MethodDescriptorProto { // Param is passed by value, moved pub fn set_input_type(&mut self, v: ::std::string::String) { - self.input_type = crate::SingularField::some(v); + self.input_type = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_input_type(&mut self) -> &mut ::std::string::String { if self.input_type.is_none() { - self.input_type.set_default(); + self.input_type = ::std::option::Option::Some(::std::string::String::new()); } self.input_type.as_mut().unwrap() } @@ -4354,15 +3516,15 @@ impl MethodDescriptorProto { // optional string output_type = 3; - - pub fn get_output_type(&self) -> &str { + pub fn output_type(&self) -> &str { match self.output_type.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_output_type(&mut self) { - self.output_type.clear(); + self.output_type = ::std::option::Option::None; } pub fn has_output_type(&self) -> bool { @@ -4371,14 +3533,14 @@ impl MethodDescriptorProto { // Param is passed by value, moved pub fn set_output_type(&mut self, v: ::std::string::String) { - self.output_type = crate::SingularField::some(v); + self.output_type = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_output_type(&mut self) -> &mut ::std::string::String { if self.output_type.is_none() { - self.output_type.set_default(); + self.output_type = ::std::option::Option::Some(::std::string::String::new()); } self.output_type.as_mut().unwrap() } @@ -4388,45 +3550,12 @@ impl MethodDescriptorProto { self.output_type.take().unwrap_or_else(|| ::std::string::String::new()) } - // optional .google.protobuf.MethodOptions options = 4; - - - pub fn get_options(&self) -> &MethodOptions { - self.options.as_ref().unwrap_or_else(|| <MethodOptions as crate::Message>::default_instance()) - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - pub fn has_options(&self) -> bool { - self.options.is_some() - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: MethodOptions) { - self.options = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_options(&mut self) -> &mut MethodOptions { - if self.options.is_none() { - self.options.set_default(); - } - self.options.as_mut().unwrap() - } - - // Take field - pub fn take_options(&mut self) -> MethodOptions { - self.options.take().unwrap_or_else(|| MethodOptions::new()) - } - // optional bool client_streaming = 5; - - pub fn get_client_streaming(&self) -> bool { + pub fn client_streaming(&self) -> bool { self.client_streaming.unwrap_or(false) } + pub fn clear_client_streaming(&mut self) { self.client_streaming = ::std::option::Option::None; } @@ -4442,10 +3571,10 @@ impl MethodDescriptorProto { // optional bool server_streaming = 6; - - pub fn get_server_streaming(&self) -> bool { + pub fn server_streaming(&self) -> bool { self.server_streaming.unwrap_or(false) } + pub fn clear_server_streaming(&mut self) { self.server_streaming = ::std::option::Option::None; } @@ -4458,9 +3587,51 @@ impl MethodDescriptorProto { pub fn set_server_streaming(&mut self, v: bool) { self.server_streaming = ::std::option::Option::Some(v); } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(6); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "name", + |m: &MethodDescriptorProto| { &m.name }, + |m: &mut MethodDescriptorProto| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "input_type", + |m: &MethodDescriptorProto| { &m.input_type }, + |m: &mut MethodDescriptorProto| { &mut m.input_type }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "output_type", + |m: &MethodDescriptorProto| { &m.output_type }, + |m: &mut MethodDescriptorProto| { &mut m.output_type }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, MethodOptions>( + "options", + |m: &MethodDescriptorProto| { &m.options }, + |m: &mut MethodDescriptorProto| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "client_streaming", + |m: &MethodDescriptorProto| { &m.client_streaming }, + |m: &mut MethodDescriptorProto| { &mut m.client_streaming }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "server_streaming", + |m: &MethodDescriptorProto| { &m.server_streaming }, + |m: &mut MethodDescriptorProto| { &mut m.server_streaming }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<MethodDescriptorProto>( + "MethodDescriptorProto", + fields, + oneofs, + ) + } } impl crate::Message for MethodDescriptorProto { + const NAME: &'static str = "MethodDescriptorProto"; + fn is_initialized(&self) -> bool { for v in &self.options { if !v.is_initialized() { @@ -4470,38 +3641,29 @@ impl crate::Message for MethodDescriptorProto { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.input_type)?; + 18 => { + self.input_type = ::std::option::Option::Some(is.read_string()?); }, - 3 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.output_type)?; + 26 => { + self.output_type = ::std::option::Option::Some(is.read_string()?); }, - 4 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.options)?; + 34 => { + crate::rt::read_singular_message_into_field(is, &mut self.options)?; }, - 5 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.client_streaming = ::std::option::Option::Some(tmp); + 40 => { + self.client_streaming = ::std::option::Option::Some(is.read_bool()?); }, - 6 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.server_streaming = ::std::option::Option::Some(tmp); + 48 => { + self.server_streaming = ::std::option::Option::Some(is.read_bool()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -4510,46 +3672,44 @@ impl crate::Message for MethodDescriptorProto { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { + if let Some(v) = self.name.as_ref() { my_size += crate::rt::string_size(1, &v); } - if let Some(ref v) = self.input_type.as_ref() { + if let Some(v) = self.input_type.as_ref() { my_size += crate::rt::string_size(2, &v); } - if let Some(ref v) = self.output_type.as_ref() { + if let Some(v) = self.output_type.as_ref() { my_size += crate::rt::string_size(3, &v); } - if let Some(ref v) = self.options.as_ref() { + if let Some(v) = self.options.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } if let Some(v) = self.client_streaming { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.server_streaming { - my_size += 2; + my_size += 1 + 1; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; } - if let Some(ref v) = self.input_type.as_ref() { - os.write_string(2, &v)?; + if let Some(v) = self.input_type.as_ref() { + os.write_string(2, v)?; } - if let Some(ref v) = self.output_type.as_ref() { - os.write_string(3, &v)?; + if let Some(v) = self.output_type.as_ref() { + os.write_string(3, v)?; } - if let Some(ref v) = self.options.as_ref() { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.options.as_ref() { + crate::rt::write_message_field_with_cached_size(4, v, os)?; } if let Some(v) = self.client_streaming { os.write_bool(5, v)?; @@ -4557,142 +3717,175 @@ impl crate::Message for MethodDescriptorProto { if let Some(v) = self.server_streaming { os.write_bool(6, v)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> MethodDescriptorProto { MethodDescriptorProto::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &MethodDescriptorProto| { &m.name }, - |m: &mut MethodDescriptorProto| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "input_type", - |m: &MethodDescriptorProto| { &m.input_type }, - |m: &mut MethodDescriptorProto| { &mut m.input_type }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "output_type", - |m: &MethodDescriptorProto| { &m.output_type }, - |m: &mut MethodDescriptorProto| { &mut m.output_type }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<MethodOptions>>( - "options", - |m: &MethodDescriptorProto| { &m.options }, - |m: &mut MethodDescriptorProto| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "client_streaming", - |m: &MethodDescriptorProto| { &m.client_streaming }, - |m: &mut MethodDescriptorProto| { &mut m.client_streaming }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "server_streaming", - |m: &MethodDescriptorProto| { &m.server_streaming }, - |m: &mut MethodDescriptorProto| { &mut m.server_streaming }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<MethodDescriptorProto>( - "MethodDescriptorProto", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.input_type = ::std::option::Option::None; + self.output_type = ::std::option::Option::None; + self.options.clear(); + self.client_streaming = ::std::option::Option::None; + self.server_streaming = ::std::option::Option::None; + self.special_fields.clear(); } fn default_instance() -> &'static MethodDescriptorProto { - static instance: crate::rt::LazyV2<MethodDescriptorProto> = crate::rt::LazyV2::INIT; - instance.get(MethodDescriptorProto::new) + static instance: MethodDescriptorProto = MethodDescriptorProto { + name: ::std::option::Option::None, + input_type: ::std::option::Option::None, + output_type: ::std::option::Option::None, + options: crate::MessageField::none(), + client_streaming: ::std::option::Option::None, + server_streaming: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for MethodDescriptorProto { - fn clear(&mut self) { - self.name.clear(); - self.input_type.clear(); - self.output_type.clear(); - self.options.clear(); - self.client_streaming = ::std::option::Option::None; - self.server_streaming = ::std::option::Option::None; - self.unknown_fields.clear(); +impl crate::MessageFull for MethodDescriptorProto { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("MethodDescriptorProto").unwrap()).clone() } } -impl ::std::fmt::Debug for MethodDescriptorProto { +impl ::std::fmt::Display for MethodDescriptorProto { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for MethodDescriptorProto { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FileOptions) pub struct FileOptions { // message fields - java_package: crate::SingularField<::std::string::String>, - java_outer_classname: crate::SingularField<::std::string::String>, - java_multiple_files: ::std::option::Option<bool>, - java_generate_equals_and_hash: ::std::option::Option<bool>, - java_string_check_utf8: ::std::option::Option<bool>, - optimize_for: ::std::option::Option<FileOptions_OptimizeMode>, - go_package: crate::SingularField<::std::string::String>, - cc_generic_services: ::std::option::Option<bool>, - java_generic_services: ::std::option::Option<bool>, - py_generic_services: ::std::option::Option<bool>, - php_generic_services: ::std::option::Option<bool>, - deprecated: ::std::option::Option<bool>, - cc_enable_arenas: ::std::option::Option<bool>, - objc_class_prefix: crate::SingularField<::std::string::String>, - csharp_namespace: crate::SingularField<::std::string::String>, - swift_prefix: crate::SingularField<::std::string::String>, - php_class_prefix: crate::SingularField<::std::string::String>, - php_namespace: crate::SingularField<::std::string::String>, - php_metadata_namespace: crate::SingularField<::std::string::String>, - ruby_package: crate::SingularField<::std::string::String>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// Sets the Java package where classes generated from this .proto will be + /// placed. By default, the proto package is used, but this is often + /// inappropriate because proto packages do not normally start with backwards + /// domain names. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_package) + pub java_package: ::std::option::Option<::std::string::String>, + /// Controls the name of the wrapper Java class generated for the .proto file. + /// That class will always contain the .proto file's getDescriptor() method as + /// well as any top-level extensions defined in the .proto file. + /// If java_multiple_files is disabled, then all the other classes from the + /// .proto file will be nested inside the single wrapper outer class. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_outer_classname) + pub java_outer_classname: ::std::option::Option<::std::string::String>, + /// If enabled, then the Java code generator will generate a separate .java + /// file for each top-level message, enum, and service defined in the .proto + /// file. Thus, these types will *not* be nested inside the wrapper class + /// named by java_outer_classname. However, the wrapper class will still be + /// generated to contain the file's getDescriptor() method as well as any + /// top-level extensions defined in the file. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_multiple_files) + pub java_multiple_files: ::std::option::Option<bool>, + /// This option does nothing. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_generate_equals_and_hash) + pub java_generate_equals_and_hash: ::std::option::Option<bool>, + /// If set true, then the Java2 code generator will generate code that + /// throws an exception whenever an attempt is made to assign a non-UTF-8 + /// byte sequence to a string field. + /// Message reflection will do the same. + /// However, an extension field still accepts non-UTF-8 byte sequences. + /// This option has no effect on when used with the lite runtime. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_string_check_utf8) + pub java_string_check_utf8: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.FileOptions.optimize_for) + pub optimize_for: ::std::option::Option<crate::EnumOrUnknown<file_options::OptimizeMode>>, + /// Sets the Go package where structs generated from this .proto will be + /// placed. If omitted, the Go package will be derived from the following: + /// - The basename of the package import path, if provided. + /// - Otherwise, the package statement in the .proto file, if present. + /// - Otherwise, the basename of the .proto file, without extension. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.go_package) + pub go_package: ::std::option::Option<::std::string::String>, + /// Should generic services be generated in each language? "Generic" services + /// are not specific to any particular RPC system. They are generated by the + /// main code generators in each language (without additional plugins). + /// Generic services were the only kind of service generation supported by + /// early versions of google.protobuf. + /// + /// Generic services are now considered deprecated in favor of using plugins + /// that generate code specific to your particular RPC system. Therefore, + /// these default to false. Old code which depends on generic services should + /// explicitly set them to true. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.cc_generic_services) + pub cc_generic_services: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.FileOptions.java_generic_services) + pub java_generic_services: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.FileOptions.py_generic_services) + pub py_generic_services: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.FileOptions.php_generic_services) + pub php_generic_services: ::std::option::Option<bool>, + /// Is this file deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for everything in the file, or it will be completely ignored; in the very + /// least, this is a formalization for deprecating files. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + /// Enables the use of arenas for the proto messages in this file. This applies + /// only to generated classes for C++. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.cc_enable_arenas) + pub cc_enable_arenas: ::std::option::Option<bool>, + /// Sets the objective c class prefix which is prepended to all objective c + /// generated classes from this .proto. There is no default. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.objc_class_prefix) + pub objc_class_prefix: ::std::option::Option<::std::string::String>, + /// Namespace for generated classes; defaults to the package. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.csharp_namespace) + pub csharp_namespace: ::std::option::Option<::std::string::String>, + /// By default Swift generators will take the proto package and CamelCase it + /// replacing '.' with underscore and use that to prefix the types/symbols + /// defined. When this options is provided, they will use this value instead + /// to prefix the types/symbols defined. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.swift_prefix) + pub swift_prefix: ::std::option::Option<::std::string::String>, + /// Sets the php class prefix which is prepended to all php generated classes + /// from this .proto. Default is empty. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.php_class_prefix) + pub php_class_prefix: ::std::option::Option<::std::string::String>, + /// Use this option to change the namespace of php generated classes. Default + /// is empty. When this option is empty, the package name will be used for + /// determining the namespace. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.php_namespace) + pub php_namespace: ::std::option::Option<::std::string::String>, + /// Use this option to change the namespace of php generated metadata classes. + /// Default is empty. When this option is empty, the proto file name will be + /// used for determining the namespace. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.php_metadata_namespace) + pub php_metadata_namespace: ::std::option::Option<::std::string::String>, + /// Use this option to change the package of ruby generated classes. Default + /// is empty. When this option is not set, the package name will be used for + /// determining the ruby package. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.ruby_package) + pub ruby_package: ::std::option::Option<::std::string::String>, + /// The parser stores options it doesn't recognize here. + /// See the documentation for the "Options" section above. + // @@protoc_insertion_point(field:google.protobuf.FileOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FileOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FileOptions { @@ -4708,15 +3901,15 @@ impl FileOptions { // optional string java_package = 1; - - pub fn get_java_package(&self) -> &str { + pub fn java_package(&self) -> &str { match self.java_package.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_java_package(&mut self) { - self.java_package.clear(); + self.java_package = ::std::option::Option::None; } pub fn has_java_package(&self) -> bool { @@ -4725,14 +3918,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_java_package(&mut self, v: ::std::string::String) { - self.java_package = crate::SingularField::some(v); + self.java_package = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_java_package(&mut self) -> &mut ::std::string::String { if self.java_package.is_none() { - self.java_package.set_default(); + self.java_package = ::std::option::Option::Some(::std::string::String::new()); } self.java_package.as_mut().unwrap() } @@ -4744,15 +3937,15 @@ impl FileOptions { // optional string java_outer_classname = 8; - - pub fn get_java_outer_classname(&self) -> &str { + pub fn java_outer_classname(&self) -> &str { match self.java_outer_classname.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_java_outer_classname(&mut self) { - self.java_outer_classname.clear(); + self.java_outer_classname = ::std::option::Option::None; } pub fn has_java_outer_classname(&self) -> bool { @@ -4761,14 +3954,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_java_outer_classname(&mut self, v: ::std::string::String) { - self.java_outer_classname = crate::SingularField::some(v); + self.java_outer_classname = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_java_outer_classname(&mut self) -> &mut ::std::string::String { if self.java_outer_classname.is_none() { - self.java_outer_classname.set_default(); + self.java_outer_classname = ::std::option::Option::Some(::std::string::String::new()); } self.java_outer_classname.as_mut().unwrap() } @@ -4780,10 +3973,10 @@ impl FileOptions { // optional bool java_multiple_files = 10; - - pub fn get_java_multiple_files(&self) -> bool { + pub fn java_multiple_files(&self) -> bool { self.java_multiple_files.unwrap_or(false) } + pub fn clear_java_multiple_files(&mut self) { self.java_multiple_files = ::std::option::Option::None; } @@ -4799,10 +3992,10 @@ impl FileOptions { // optional bool java_generate_equals_and_hash = 20; - - pub fn get_java_generate_equals_and_hash(&self) -> bool { + pub fn java_generate_equals_and_hash(&self) -> bool { self.java_generate_equals_and_hash.unwrap_or(false) } + pub fn clear_java_generate_equals_and_hash(&mut self) { self.java_generate_equals_and_hash = ::std::option::Option::None; } @@ -4818,10 +4011,10 @@ impl FileOptions { // optional bool java_string_check_utf8 = 27; - - pub fn get_java_string_check_utf8(&self) -> bool { + pub fn java_string_check_utf8(&self) -> bool { self.java_string_check_utf8.unwrap_or(false) } + pub fn clear_java_string_check_utf8(&mut self) { self.java_string_check_utf8 = ::std::option::Option::None; } @@ -4837,10 +4030,13 @@ impl FileOptions { // optional .google.protobuf.FileOptions.OptimizeMode optimize_for = 9; - - pub fn get_optimize_for(&self) -> FileOptions_OptimizeMode { - self.optimize_for.unwrap_or(FileOptions_OptimizeMode::SPEED) + pub fn optimize_for(&self) -> file_options::OptimizeMode { + match self.optimize_for { + Some(e) => e.enum_value_or(file_options::OptimizeMode::SPEED), + None => file_options::OptimizeMode::SPEED, + } } + pub fn clear_optimize_for(&mut self) { self.optimize_for = ::std::option::Option::None; } @@ -4850,21 +4046,21 @@ impl FileOptions { } // Param is passed by value, moved - pub fn set_optimize_for(&mut self, v: FileOptions_OptimizeMode) { - self.optimize_for = ::std::option::Option::Some(v); + pub fn set_optimize_for(&mut self, v: file_options::OptimizeMode) { + self.optimize_for = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); } // optional string go_package = 11; - - pub fn get_go_package(&self) -> &str { + pub fn go_package(&self) -> &str { match self.go_package.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_go_package(&mut self) { - self.go_package.clear(); + self.go_package = ::std::option::Option::None; } pub fn has_go_package(&self) -> bool { @@ -4873,14 +4069,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_go_package(&mut self, v: ::std::string::String) { - self.go_package = crate::SingularField::some(v); + self.go_package = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_go_package(&mut self) -> &mut ::std::string::String { if self.go_package.is_none() { - self.go_package.set_default(); + self.go_package = ::std::option::Option::Some(::std::string::String::new()); } self.go_package.as_mut().unwrap() } @@ -4892,10 +4088,10 @@ impl FileOptions { // optional bool cc_generic_services = 16; - - pub fn get_cc_generic_services(&self) -> bool { + pub fn cc_generic_services(&self) -> bool { self.cc_generic_services.unwrap_or(false) } + pub fn clear_cc_generic_services(&mut self) { self.cc_generic_services = ::std::option::Option::None; } @@ -4911,10 +4107,10 @@ impl FileOptions { // optional bool java_generic_services = 17; - - pub fn get_java_generic_services(&self) -> bool { + pub fn java_generic_services(&self) -> bool { self.java_generic_services.unwrap_or(false) } + pub fn clear_java_generic_services(&mut self) { self.java_generic_services = ::std::option::Option::None; } @@ -4930,10 +4126,10 @@ impl FileOptions { // optional bool py_generic_services = 18; - - pub fn get_py_generic_services(&self) -> bool { + pub fn py_generic_services(&self) -> bool { self.py_generic_services.unwrap_or(false) } + pub fn clear_py_generic_services(&mut self) { self.py_generic_services = ::std::option::Option::None; } @@ -4949,10 +4145,10 @@ impl FileOptions { // optional bool php_generic_services = 42; - - pub fn get_php_generic_services(&self) -> bool { + pub fn php_generic_services(&self) -> bool { self.php_generic_services.unwrap_or(false) } + pub fn clear_php_generic_services(&mut self) { self.php_generic_services = ::std::option::Option::None; } @@ -4968,10 +4164,10 @@ impl FileOptions { // optional bool deprecated = 23; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -4987,10 +4183,10 @@ impl FileOptions { // optional bool cc_enable_arenas = 31; - - pub fn get_cc_enable_arenas(&self) -> bool { + pub fn cc_enable_arenas(&self) -> bool { self.cc_enable_arenas.unwrap_or(true) } + pub fn clear_cc_enable_arenas(&mut self) { self.cc_enable_arenas = ::std::option::Option::None; } @@ -5006,15 +4202,15 @@ impl FileOptions { // optional string objc_class_prefix = 36; - - pub fn get_objc_class_prefix(&self) -> &str { + pub fn objc_class_prefix(&self) -> &str { match self.objc_class_prefix.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_objc_class_prefix(&mut self) { - self.objc_class_prefix.clear(); + self.objc_class_prefix = ::std::option::Option::None; } pub fn has_objc_class_prefix(&self) -> bool { @@ -5023,14 +4219,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_objc_class_prefix(&mut self, v: ::std::string::String) { - self.objc_class_prefix = crate::SingularField::some(v); + self.objc_class_prefix = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_objc_class_prefix(&mut self) -> &mut ::std::string::String { if self.objc_class_prefix.is_none() { - self.objc_class_prefix.set_default(); + self.objc_class_prefix = ::std::option::Option::Some(::std::string::String::new()); } self.objc_class_prefix.as_mut().unwrap() } @@ -5042,15 +4238,15 @@ impl FileOptions { // optional string csharp_namespace = 37; - - pub fn get_csharp_namespace(&self) -> &str { + pub fn csharp_namespace(&self) -> &str { match self.csharp_namespace.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_csharp_namespace(&mut self) { - self.csharp_namespace.clear(); + self.csharp_namespace = ::std::option::Option::None; } pub fn has_csharp_namespace(&self) -> bool { @@ -5059,14 +4255,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_csharp_namespace(&mut self, v: ::std::string::String) { - self.csharp_namespace = crate::SingularField::some(v); + self.csharp_namespace = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_csharp_namespace(&mut self) -> &mut ::std::string::String { if self.csharp_namespace.is_none() { - self.csharp_namespace.set_default(); + self.csharp_namespace = ::std::option::Option::Some(::std::string::String::new()); } self.csharp_namespace.as_mut().unwrap() } @@ -5078,15 +4274,15 @@ impl FileOptions { // optional string swift_prefix = 39; - - pub fn get_swift_prefix(&self) -> &str { + pub fn swift_prefix(&self) -> &str { match self.swift_prefix.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_swift_prefix(&mut self) { - self.swift_prefix.clear(); + self.swift_prefix = ::std::option::Option::None; } pub fn has_swift_prefix(&self) -> bool { @@ -5095,14 +4291,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_swift_prefix(&mut self, v: ::std::string::String) { - self.swift_prefix = crate::SingularField::some(v); + self.swift_prefix = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_swift_prefix(&mut self) -> &mut ::std::string::String { if self.swift_prefix.is_none() { - self.swift_prefix.set_default(); + self.swift_prefix = ::std::option::Option::Some(::std::string::String::new()); } self.swift_prefix.as_mut().unwrap() } @@ -5114,15 +4310,15 @@ impl FileOptions { // optional string php_class_prefix = 40; - - pub fn get_php_class_prefix(&self) -> &str { + pub fn php_class_prefix(&self) -> &str { match self.php_class_prefix.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_php_class_prefix(&mut self) { - self.php_class_prefix.clear(); + self.php_class_prefix = ::std::option::Option::None; } pub fn has_php_class_prefix(&self) -> bool { @@ -5131,14 +4327,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_php_class_prefix(&mut self, v: ::std::string::String) { - self.php_class_prefix = crate::SingularField::some(v); + self.php_class_prefix = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_php_class_prefix(&mut self) -> &mut ::std::string::String { if self.php_class_prefix.is_none() { - self.php_class_prefix.set_default(); + self.php_class_prefix = ::std::option::Option::Some(::std::string::String::new()); } self.php_class_prefix.as_mut().unwrap() } @@ -5150,15 +4346,15 @@ impl FileOptions { // optional string php_namespace = 41; - - pub fn get_php_namespace(&self) -> &str { + pub fn php_namespace(&self) -> &str { match self.php_namespace.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_php_namespace(&mut self) { - self.php_namespace.clear(); + self.php_namespace = ::std::option::Option::None; } pub fn has_php_namespace(&self) -> bool { @@ -5167,14 +4363,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_php_namespace(&mut self, v: ::std::string::String) { - self.php_namespace = crate::SingularField::some(v); + self.php_namespace = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_php_namespace(&mut self) -> &mut ::std::string::String { if self.php_namespace.is_none() { - self.php_namespace.set_default(); + self.php_namespace = ::std::option::Option::Some(::std::string::String::new()); } self.php_namespace.as_mut().unwrap() } @@ -5186,15 +4382,15 @@ impl FileOptions { // optional string php_metadata_namespace = 44; - - pub fn get_php_metadata_namespace(&self) -> &str { + pub fn php_metadata_namespace(&self) -> &str { match self.php_metadata_namespace.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_php_metadata_namespace(&mut self) { - self.php_metadata_namespace.clear(); + self.php_metadata_namespace = ::std::option::Option::None; } pub fn has_php_metadata_namespace(&self) -> bool { @@ -5203,14 +4399,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_php_metadata_namespace(&mut self, v: ::std::string::String) { - self.php_metadata_namespace = crate::SingularField::some(v); + self.php_metadata_namespace = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_php_metadata_namespace(&mut self) -> &mut ::std::string::String { if self.php_metadata_namespace.is_none() { - self.php_metadata_namespace.set_default(); + self.php_metadata_namespace = ::std::option::Option::Some(::std::string::String::new()); } self.php_metadata_namespace.as_mut().unwrap() } @@ -5222,15 +4418,15 @@ impl FileOptions { // optional string ruby_package = 45; - - pub fn get_ruby_package(&self) -> &str { + pub fn ruby_package(&self) -> &str { match self.ruby_package.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_ruby_package(&mut self) { - self.ruby_package.clear(); + self.ruby_package = ::std::option::Option::None; } pub fn has_ruby_package(&self) -> bool { @@ -5239,14 +4435,14 @@ impl FileOptions { // Param is passed by value, moved pub fn set_ruby_package(&mut self, v: ::std::string::String) { - self.ruby_package = crate::SingularField::some(v); + self.ruby_package = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_ruby_package(&mut self) -> &mut ::std::string::String { if self.ruby_package.is_none() { - self.ruby_package.set_default(); + self.ruby_package = ::std::option::Option::Some(::std::string::String::new()); } self.ruby_package.as_mut().unwrap() } @@ -5256,33 +4452,125 @@ impl FileOptions { self.ruby_package.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(21); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_package", + |m: &FileOptions| { &m.java_package }, + |m: &mut FileOptions| { &mut m.java_package }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_outer_classname", + |m: &FileOptions| { &m.java_outer_classname }, + |m: &mut FileOptions| { &mut m.java_outer_classname }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_multiple_files", + |m: &FileOptions| { &m.java_multiple_files }, + |m: &mut FileOptions| { &mut m.java_multiple_files }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_generate_equals_and_hash", + |m: &FileOptions| { &m.java_generate_equals_and_hash }, + |m: &mut FileOptions| { &mut m.java_generate_equals_and_hash }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_string_check_utf8", + |m: &FileOptions| { &m.java_string_check_utf8 }, + |m: &mut FileOptions| { &mut m.java_string_check_utf8 }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "optimize_for", + |m: &FileOptions| { &m.optimize_for }, + |m: &mut FileOptions| { &mut m.optimize_for }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "go_package", + |m: &FileOptions| { &m.go_package }, + |m: &mut FileOptions| { &mut m.go_package }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "cc_generic_services", + |m: &FileOptions| { &m.cc_generic_services }, + |m: &mut FileOptions| { &mut m.cc_generic_services }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "java_generic_services", + |m: &FileOptions| { &m.java_generic_services }, + |m: &mut FileOptions| { &mut m.java_generic_services }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "py_generic_services", + |m: &FileOptions| { &m.py_generic_services }, + |m: &mut FileOptions| { &mut m.py_generic_services }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "php_generic_services", + |m: &FileOptions| { &m.php_generic_services }, + |m: &mut FileOptions| { &mut m.php_generic_services }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &FileOptions| { &m.deprecated }, + |m: &mut FileOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "cc_enable_arenas", + |m: &FileOptions| { &m.cc_enable_arenas }, + |m: &mut FileOptions| { &mut m.cc_enable_arenas }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "objc_class_prefix", + |m: &FileOptions| { &m.objc_class_prefix }, + |m: &mut FileOptions| { &mut m.objc_class_prefix }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "csharp_namespace", + |m: &FileOptions| { &m.csharp_namespace }, + |m: &mut FileOptions| { &mut m.csharp_namespace }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "swift_prefix", + |m: &FileOptions| { &m.swift_prefix }, + |m: &mut FileOptions| { &mut m.swift_prefix }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "php_class_prefix", + |m: &FileOptions| { &m.php_class_prefix }, + |m: &mut FileOptions| { &mut m.php_class_prefix }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "php_namespace", + |m: &FileOptions| { &m.php_namespace }, + |m: &mut FileOptions| { &mut m.php_namespace }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "php_metadata_namespace", + |m: &FileOptions| { &m.php_metadata_namespace }, + |m: &mut FileOptions| { &mut m.php_metadata_namespace }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "ruby_package", + |m: &FileOptions| { &m.ruby_package }, + |m: &mut FileOptions| { &mut m.ruby_package }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &FileOptions| { &m.uninterpreted_option }, + |m: &mut FileOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FileOptions>( + "FileOptions", + fields, + oneofs, + ) } } impl crate::Message for FileOptions { + const NAME: &'static str = "FileOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -5292,111 +4580,74 @@ impl crate::Message for FileOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.java_package)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.java_package = ::std::option::Option::Some(is.read_string()?); }, - 8 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.java_outer_classname)?; + 66 => { + self.java_outer_classname = ::std::option::Option::Some(is.read_string()?); }, - 10 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.java_multiple_files = ::std::option::Option::Some(tmp); - }, - 20 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.java_generate_equals_and_hash = ::std::option::Option::Some(tmp); - }, - 27 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.java_string_check_utf8 = ::std::option::Option::Some(tmp); - }, - 9 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.optimize_for, 9, &mut self.unknown_fields)? - }, - 11 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.go_package)?; + 80 => { + self.java_multiple_files = ::std::option::Option::Some(is.read_bool()?); }, - 16 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.cc_generic_services = ::std::option::Option::Some(tmp); - }, - 17 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.java_generic_services = ::std::option::Option::Some(tmp); + 160 => { + self.java_generate_equals_and_hash = ::std::option::Option::Some(is.read_bool()?); }, - 18 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.py_generic_services = ::std::option::Option::Some(tmp); + 216 => { + self.java_string_check_utf8 = ::std::option::Option::Some(is.read_bool()?); }, - 42 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.php_generic_services = ::std::option::Option::Some(tmp); - }, - 23 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); - }, - 31 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.cc_enable_arenas = ::std::option::Option::Some(tmp); - }, - 36 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.objc_class_prefix)?; - }, - 37 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.csharp_namespace)?; - }, - 39 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.swift_prefix)?; + 72 => { + self.optimize_for = ::std::option::Option::Some(is.read_enum_or_unknown()?); }, - 40 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.php_class_prefix)?; + 90 => { + self.go_package = ::std::option::Option::Some(is.read_string()?); + }, + 128 => { + self.cc_generic_services = ::std::option::Option::Some(is.read_bool()?); + }, + 136 => { + self.java_generic_services = ::std::option::Option::Some(is.read_bool()?); + }, + 144 => { + self.py_generic_services = ::std::option::Option::Some(is.read_bool()?); + }, + 336 => { + self.php_generic_services = ::std::option::Option::Some(is.read_bool()?); + }, + 184 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); + }, + 248 => { + self.cc_enable_arenas = ::std::option::Option::Some(is.read_bool()?); + }, + 290 => { + self.objc_class_prefix = ::std::option::Option::Some(is.read_string()?); }, - 41 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.php_namespace)?; + 298 => { + self.csharp_namespace = ::std::option::Option::Some(is.read_string()?); }, - 44 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.php_metadata_namespace)?; + 314 => { + self.swift_prefix = ::std::option::Option::Some(is.read_string()?); }, - 45 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.ruby_package)?; + 322 => { + self.php_class_prefix = ::std::option::Option::Some(is.read_string()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 330 => { + self.php_namespace = ::std::option::Option::Some(is.read_string()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + 354 => { + self.php_metadata_namespace = ::std::option::Option::Some(is.read_string()?); + }, + 362 => { + self.ruby_package = ::std::option::Option::Some(is.read_string()?); + }, + 7994 => { + self.uninterpreted_option.push(is.read_message()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -5405,83 +4656,83 @@ impl crate::Message for FileOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.java_package.as_ref() { + if let Some(v) = self.java_package.as_ref() { my_size += crate::rt::string_size(1, &v); } - if let Some(ref v) = self.java_outer_classname.as_ref() { + if let Some(v) = self.java_outer_classname.as_ref() { my_size += crate::rt::string_size(8, &v); } if let Some(v) = self.java_multiple_files { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.java_generate_equals_and_hash { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.java_string_check_utf8 { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.optimize_for { - my_size += crate::rt::enum_size(9, v); + my_size += crate::rt::int32_size(9, v.value()); } - if let Some(ref v) = self.go_package.as_ref() { + if let Some(v) = self.go_package.as_ref() { my_size += crate::rt::string_size(11, &v); } if let Some(v) = self.cc_generic_services { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.java_generic_services { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.py_generic_services { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.php_generic_services { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.deprecated { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.cc_enable_arenas { - my_size += 3; + my_size += 2 + 1; } - if let Some(ref v) = self.objc_class_prefix.as_ref() { + if let Some(v) = self.objc_class_prefix.as_ref() { my_size += crate::rt::string_size(36, &v); } - if let Some(ref v) = self.csharp_namespace.as_ref() { + if let Some(v) = self.csharp_namespace.as_ref() { my_size += crate::rt::string_size(37, &v); } - if let Some(ref v) = self.swift_prefix.as_ref() { + if let Some(v) = self.swift_prefix.as_ref() { my_size += crate::rt::string_size(39, &v); } - if let Some(ref v) = self.php_class_prefix.as_ref() { + if let Some(v) = self.php_class_prefix.as_ref() { my_size += crate::rt::string_size(40, &v); } - if let Some(ref v) = self.php_namespace.as_ref() { + if let Some(v) = self.php_namespace.as_ref() { my_size += crate::rt::string_size(41, &v); } - if let Some(ref v) = self.php_metadata_namespace.as_ref() { + if let Some(v) = self.php_metadata_namespace.as_ref() { my_size += crate::rt::string_size(44, &v); } - if let Some(ref v) = self.ruby_package.as_ref() { + if let Some(v) = self.ruby_package.as_ref() { my_size += crate::rt::string_size(45, &v); } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.java_package.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.java_package.as_ref() { + os.write_string(1, v)?; } - if let Some(ref v) = self.java_outer_classname.as_ref() { - os.write_string(8, &v)?; + if let Some(v) = self.java_outer_classname.as_ref() { + os.write_string(8, v)?; } if let Some(v) = self.java_multiple_files { os.write_bool(10, v)?; @@ -5493,10 +4744,10 @@ impl crate::Message for FileOptions { os.write_bool(27, v)?; } if let Some(v) = self.optimize_for { - os.write_enum(9, crate::ProtobufEnum::value(&v))?; + os.write_enum(9, crate::EnumOrUnknown::value(&v))?; } - if let Some(ref v) = self.go_package.as_ref() { - os.write_string(11, &v)?; + if let Some(v) = self.go_package.as_ref() { + os.write_string(11, v)?; } if let Some(v) = self.cc_generic_services { os.write_bool(16, v)?; @@ -5516,297 +4767,209 @@ impl crate::Message for FileOptions { if let Some(v) = self.cc_enable_arenas { os.write_bool(31, v)?; } - if let Some(ref v) = self.objc_class_prefix.as_ref() { - os.write_string(36, &v)?; + if let Some(v) = self.objc_class_prefix.as_ref() { + os.write_string(36, v)?; } - if let Some(ref v) = self.csharp_namespace.as_ref() { - os.write_string(37, &v)?; + if let Some(v) = self.csharp_namespace.as_ref() { + os.write_string(37, v)?; } - if let Some(ref v) = self.swift_prefix.as_ref() { - os.write_string(39, &v)?; + if let Some(v) = self.swift_prefix.as_ref() { + os.write_string(39, v)?; } - if let Some(ref v) = self.php_class_prefix.as_ref() { - os.write_string(40, &v)?; + if let Some(v) = self.php_class_prefix.as_ref() { + os.write_string(40, v)?; } - if let Some(ref v) = self.php_namespace.as_ref() { - os.write_string(41, &v)?; + if let Some(v) = self.php_namespace.as_ref() { + os.write_string(41, v)?; } - if let Some(ref v) = self.php_metadata_namespace.as_ref() { - os.write_string(44, &v)?; + if let Some(v) = self.php_metadata_namespace.as_ref() { + os.write_string(44, v)?; } - if let Some(ref v) = self.ruby_package.as_ref() { - os.write_string(45, &v)?; + if let Some(v) = self.ruby_package.as_ref() { + os.write_string(45, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FileOptions { FileOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "java_package", - |m: &FileOptions| { &m.java_package }, - |m: &mut FileOptions| { &mut m.java_package }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "java_outer_classname", - |m: &FileOptions| { &m.java_outer_classname }, - |m: &mut FileOptions| { &mut m.java_outer_classname }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "java_multiple_files", - |m: &FileOptions| { &m.java_multiple_files }, - |m: &mut FileOptions| { &mut m.java_multiple_files }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "java_generate_equals_and_hash", - |m: &FileOptions| { &m.java_generate_equals_and_hash }, - |m: &mut FileOptions| { &mut m.java_generate_equals_and_hash }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "java_string_check_utf8", - |m: &FileOptions| { &m.java_string_check_utf8 }, - |m: &mut FileOptions| { &mut m.java_string_check_utf8 }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<FileOptions_OptimizeMode>>( - "optimize_for", - |m: &FileOptions| { &m.optimize_for }, - |m: &mut FileOptions| { &mut m.optimize_for }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "go_package", - |m: &FileOptions| { &m.go_package }, - |m: &mut FileOptions| { &mut m.go_package }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "cc_generic_services", - |m: &FileOptions| { &m.cc_generic_services }, - |m: &mut FileOptions| { &mut m.cc_generic_services }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "java_generic_services", - |m: &FileOptions| { &m.java_generic_services }, - |m: &mut FileOptions| { &mut m.java_generic_services }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "py_generic_services", - |m: &FileOptions| { &m.py_generic_services }, - |m: &mut FileOptions| { &mut m.py_generic_services }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "php_generic_services", - |m: &FileOptions| { &m.php_generic_services }, - |m: &mut FileOptions| { &mut m.php_generic_services }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &FileOptions| { &m.deprecated }, - |m: &mut FileOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "cc_enable_arenas", - |m: &FileOptions| { &m.cc_enable_arenas }, - |m: &mut FileOptions| { &mut m.cc_enable_arenas }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "objc_class_prefix", - |m: &FileOptions| { &m.objc_class_prefix }, - |m: &mut FileOptions| { &mut m.objc_class_prefix }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "csharp_namespace", - |m: &FileOptions| { &m.csharp_namespace }, - |m: &mut FileOptions| { &mut m.csharp_namespace }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "swift_prefix", - |m: &FileOptions| { &m.swift_prefix }, - |m: &mut FileOptions| { &mut m.swift_prefix }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "php_class_prefix", - |m: &FileOptions| { &m.php_class_prefix }, - |m: &mut FileOptions| { &mut m.php_class_prefix }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "php_namespace", - |m: &FileOptions| { &m.php_namespace }, - |m: &mut FileOptions| { &mut m.php_namespace }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "php_metadata_namespace", - |m: &FileOptions| { &m.php_metadata_namespace }, - |m: &mut FileOptions| { &mut m.php_metadata_namespace }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "ruby_package", - |m: &FileOptions| { &m.ruby_package }, - |m: &mut FileOptions| { &mut m.ruby_package }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &FileOptions| { &m.uninterpreted_option }, - |m: &mut FileOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FileOptions>( - "FileOptions", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static FileOptions { - static instance: crate::rt::LazyV2<FileOptions> = crate::rt::LazyV2::INIT; - instance.get(FileOptions::new) - } -} - -impl crate::Clear for FileOptions { fn clear(&mut self) { - self.java_package.clear(); - self.java_outer_classname.clear(); + self.java_package = ::std::option::Option::None; + self.java_outer_classname = ::std::option::Option::None; self.java_multiple_files = ::std::option::Option::None; self.java_generate_equals_and_hash = ::std::option::Option::None; self.java_string_check_utf8 = ::std::option::Option::None; self.optimize_for = ::std::option::Option::None; - self.go_package.clear(); + self.go_package = ::std::option::Option::None; self.cc_generic_services = ::std::option::Option::None; self.java_generic_services = ::std::option::Option::None; self.py_generic_services = ::std::option::Option::None; self.php_generic_services = ::std::option::Option::None; self.deprecated = ::std::option::Option::None; self.cc_enable_arenas = ::std::option::Option::None; - self.objc_class_prefix.clear(); - self.csharp_namespace.clear(); - self.swift_prefix.clear(); - self.php_class_prefix.clear(); - self.php_namespace.clear(); - self.php_metadata_namespace.clear(); - self.ruby_package.clear(); + self.objc_class_prefix = ::std::option::Option::None; + self.csharp_namespace = ::std::option::Option::None; + self.swift_prefix = ::std::option::Option::None; + self.php_class_prefix = ::std::option::Option::None; + self.php_namespace = ::std::option::Option::None; + self.php_metadata_namespace = ::std::option::Option::None; + self.ruby_package = ::std::option::Option::None; self.uninterpreted_option.clear(); - self.unknown_fields.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static FileOptions { + static instance: FileOptions = FileOptions { + java_package: ::std::option::Option::None, + java_outer_classname: ::std::option::Option::None, + java_multiple_files: ::std::option::Option::None, + java_generate_equals_and_hash: ::std::option::Option::None, + java_string_check_utf8: ::std::option::Option::None, + optimize_for: ::std::option::Option::None, + go_package: ::std::option::Option::None, + cc_generic_services: ::std::option::Option::None, + java_generic_services: ::std::option::Option::None, + py_generic_services: ::std::option::Option::None, + php_generic_services: ::std::option::Option::None, + deprecated: ::std::option::Option::None, + cc_enable_arenas: ::std::option::Option::None, + objc_class_prefix: ::std::option::Option::None, + csharp_namespace: ::std::option::Option::None, + swift_prefix: ::std::option::Option::None, + php_class_prefix: ::std::option::Option::None, + php_namespace: ::std::option::Option::None, + php_metadata_namespace: ::std::option::Option::None, + ruby_package: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl ::std::fmt::Debug for FileOptions { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) +impl crate::MessageFull for FileOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FileOptions").unwrap()).clone() } } -impl crate::reflect::ProtobufValue for FileOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) +impl ::std::fmt::Display for FileOptions { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) } } -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum FileOptions_OptimizeMode { - SPEED = 1, - CODE_SIZE = 2, - LITE_RUNTIME = 3, +impl crate::reflect::ProtobufValue for FileOptions { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -impl crate::ProtobufEnum for FileOptions_OptimizeMode { - fn value(&self) -> i32 { - *self as i32 +/// Nested message and enums of message `FileOptions` +pub mod file_options { + /// Generated classes can be optimized for speed or code size. + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.FileOptions.OptimizeMode) + pub enum OptimizeMode { + // @@protoc_insertion_point(enum_value:google.protobuf.FileOptions.OptimizeMode.SPEED) + SPEED = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.FileOptions.OptimizeMode.CODE_SIZE) + CODE_SIZE = 2, + // @@protoc_insertion_point(enum_value:google.protobuf.FileOptions.OptimizeMode.LITE_RUNTIME) + LITE_RUNTIME = 3, } - fn from_i32(value: i32) -> ::std::option::Option<FileOptions_OptimizeMode> { - match value { - 1 => ::std::option::Option::Some(FileOptions_OptimizeMode::SPEED), - 2 => ::std::option::Option::Some(FileOptions_OptimizeMode::CODE_SIZE), - 3 => ::std::option::Option::Some(FileOptions_OptimizeMode::LITE_RUNTIME), - _ => ::std::option::Option::None + impl crate::Enum for OptimizeMode { + const NAME: &'static str = "OptimizeMode"; + + fn value(&self) -> i32 { + *self as i32 } - } - fn values() -> &'static [Self] { - static values: &'static [FileOptions_OptimizeMode] = &[ - FileOptions_OptimizeMode::SPEED, - FileOptions_OptimizeMode::CODE_SIZE, - FileOptions_OptimizeMode::LITE_RUNTIME, + fn from_i32(value: i32) -> ::std::option::Option<OptimizeMode> { + match value { + 1 => ::std::option::Option::Some(OptimizeMode::SPEED), + 2 => ::std::option::Option::Some(OptimizeMode::CODE_SIZE), + 3 => ::std::option::Option::Some(OptimizeMode::LITE_RUNTIME), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [OptimizeMode] = &[ + OptimizeMode::SPEED, + OptimizeMode::CODE_SIZE, + OptimizeMode::LITE_RUNTIME, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<FileOptions_OptimizeMode>("FileOptions.OptimizeMode", file_descriptor_proto()) - }) - } -} + impl crate::EnumFull for OptimizeMode { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("FileOptions.OptimizeMode").unwrap()).clone() + } -impl ::std::marker::Copy for FileOptions_OptimizeMode { -} + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = match self { + OptimizeMode::SPEED => 0, + OptimizeMode::CODE_SIZE => 1, + OptimizeMode::LITE_RUNTIME => 2, + }; + Self::enum_descriptor().value_by_index(index) + } + } -// Note, `Default` is implemented although default value is not 0 -impl ::std::default::Default for FileOptions_OptimizeMode { - fn default() -> Self { - FileOptions_OptimizeMode::SPEED + // Note, `Default` is implemented although default value is not 0 + impl ::std::default::Default for OptimizeMode { + fn default() -> Self { + OptimizeMode::SPEED + } } -} -impl crate::reflect::ProtobufValue for FileOptions_OptimizeMode { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + impl OptimizeMode { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<OptimizeMode>("FileOptions.OptimizeMode") + } } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.MessageOptions) pub struct MessageOptions { // message fields - message_set_wire_format: ::std::option::Option<bool>, - no_standard_descriptor_accessor: ::std::option::Option<bool>, - deprecated: ::std::option::Option<bool>, - map_entry: ::std::option::Option<bool>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + // @@protoc_insertion_point(field:google.protobuf.MessageOptions.message_set_wire_format) + pub message_set_wire_format: ::std::option::Option<bool>, + /// Disables the generation of the standard "descriptor()" accessor, which can + /// conflict with a field of the same name. This is meant to make migration + /// from proto1 easier; new code should avoid fields named "descriptor". + // @@protoc_insertion_point(field:google.protobuf.MessageOptions.no_standard_descriptor_accessor) + pub no_standard_descriptor_accessor: ::std::option::Option<bool>, + /// Is this message deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the message, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating messages. + // @@protoc_insertion_point(field:google.protobuf.MessageOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.MessageOptions.map_entry) + pub map_entry: ::std::option::Option<bool>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.MessageOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.MessageOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a MessageOptions { @@ -5822,10 +4985,10 @@ impl MessageOptions { // optional bool message_set_wire_format = 1; - - pub fn get_message_set_wire_format(&self) -> bool { + pub fn message_set_wire_format(&self) -> bool { self.message_set_wire_format.unwrap_or(false) } + pub fn clear_message_set_wire_format(&mut self) { self.message_set_wire_format = ::std::option::Option::None; } @@ -5841,10 +5004,10 @@ impl MessageOptions { // optional bool no_standard_descriptor_accessor = 2; - - pub fn get_no_standard_descriptor_accessor(&self) -> bool { + pub fn no_standard_descriptor_accessor(&self) -> bool { self.no_standard_descriptor_accessor.unwrap_or(false) } + pub fn clear_no_standard_descriptor_accessor(&mut self) { self.no_standard_descriptor_accessor = ::std::option::Option::None; } @@ -5860,10 +5023,10 @@ impl MessageOptions { // optional bool deprecated = 3; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -5879,10 +5042,10 @@ impl MessageOptions { // optional bool map_entry = 7; - - pub fn get_map_entry(&self) -> bool { + pub fn map_entry(&self) -> bool { self.map_entry.unwrap_or(false) } + pub fn clear_map_entry(&mut self) { self.map_entry = ::std::option::Option::None; } @@ -5896,33 +5059,45 @@ impl MessageOptions { self.map_entry = ::std::option::Option::Some(v); } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(5); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "message_set_wire_format", + |m: &MessageOptions| { &m.message_set_wire_format }, + |m: &mut MessageOptions| { &mut m.message_set_wire_format }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "no_standard_descriptor_accessor", + |m: &MessageOptions| { &m.no_standard_descriptor_accessor }, + |m: &mut MessageOptions| { &mut m.no_standard_descriptor_accessor }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &MessageOptions| { &m.deprecated }, + |m: &mut MessageOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "map_entry", + |m: &MessageOptions| { &m.map_entry }, + |m: &mut MessageOptions| { &mut m.map_entry }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &MessageOptions| { &m.uninterpreted_option }, + |m: &mut MessageOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<MessageOptions>( + "MessageOptions", + fields, + oneofs, + ) } } impl crate::Message for MessageOptions { + const NAME: &'static str = "MessageOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -5932,43 +5107,26 @@ impl crate::Message for MessageOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.message_set_wire_format = ::std::option::Option::Some(tmp); - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.no_standard_descriptor_accessor = ::std::option::Option::Some(tmp); - }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); - }, - 7 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.map_entry = ::std::option::Option::Some(tmp); - }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.message_set_wire_format = ::std::option::Option::Some(is.read_bool()?); + }, + 16 => { + self.no_standard_descriptor_accessor = ::std::option::Option::Some(is.read_bool()?); + }, + 24 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); + }, + 56 => { + self.map_entry = ::std::option::Option::Some(is.read_bool()?); + }, + 7994 => { + self.uninterpreted_option.push(is.read_message()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -5977,30 +5135,30 @@ impl crate::Message for MessageOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.message_set_wire_format { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.no_standard_descriptor_accessor { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.deprecated { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.map_entry { - my_size += 2; + my_size += 1 + 1; } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.message_set_wire_format { os.write_bool(1, v)?; } @@ -6014,126 +5172,138 @@ impl crate::Message for MessageOptions { os.write_bool(7, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> MessageOptions { MessageOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "message_set_wire_format", - |m: &MessageOptions| { &m.message_set_wire_format }, - |m: &mut MessageOptions| { &mut m.message_set_wire_format }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "no_standard_descriptor_accessor", - |m: &MessageOptions| { &m.no_standard_descriptor_accessor }, - |m: &mut MessageOptions| { &mut m.no_standard_descriptor_accessor }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &MessageOptions| { &m.deprecated }, - |m: &mut MessageOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "map_entry", - |m: &MessageOptions| { &m.map_entry }, - |m: &mut MessageOptions| { &mut m.map_entry }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &MessageOptions| { &m.uninterpreted_option }, - |m: &mut MessageOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<MessageOptions>( - "MessageOptions", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static MessageOptions { - static instance: crate::rt::LazyV2<MessageOptions> = crate::rt::LazyV2::INIT; - instance.get(MessageOptions::new) - } -} - -impl crate::Clear for MessageOptions { fn clear(&mut self) { self.message_set_wire_format = ::std::option::Option::None; self.no_standard_descriptor_accessor = ::std::option::Option::None; self.deprecated = ::std::option::Option::None; self.map_entry = ::std::option::Option::None; self.uninterpreted_option.clear(); - self.unknown_fields.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static MessageOptions { + static instance: MessageOptions = MessageOptions { + message_set_wire_format: ::std::option::Option::None, + no_standard_descriptor_accessor: ::std::option::Option::None, + deprecated: ::std::option::Option::None, + map_entry: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for MessageOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("MessageOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for MessageOptions { +impl ::std::fmt::Display for MessageOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for MessageOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FieldOptions) pub struct FieldOptions { // message fields - ctype: ::std::option::Option<FieldOptions_CType>, - packed: ::std::option::Option<bool>, - jstype: ::std::option::Option<FieldOptions_JSType>, - lazy: ::std::option::Option<bool>, - deprecated: ::std::option::Option<bool>, - weak: ::std::option::Option<bool>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// The ctype option instructs the C++ code generator to use a different + /// representation of the field than it normally would. See the specific + /// options below. This option is not yet implemented in the open source + /// release -- sorry, we'll try to include it in a future version! + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.ctype) + pub ctype: ::std::option::Option<crate::EnumOrUnknown<field_options::CType>>, + /// The packed option can be enabled for repeated primitive fields to enable + /// a more efficient representation on the wire. Rather than repeatedly + /// writing the tag and type for each element, the entire array is encoded as + /// a single length-delimited blob. In proto3, only explicit setting it to + /// false will avoid using packed encoding. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.packed) + pub packed: ::std::option::Option<bool>, + /// The jstype option determines the JavaScript type used for values of the + /// field. The option is permitted only for 64 bit integral and fixed types + /// (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING + /// is represented as JavaScript string, which avoids loss of precision that + /// can happen when a large value is converted to a floating point JavaScript. + /// Specifying JS_NUMBER for the jstype causes the generated JavaScript code to + /// use the JavaScript "number" type. The behavior of the default option + /// JS_NORMAL is implementation dependent. + /// + /// This option is an enum to permit additional types to be added, e.g. + /// goog.math.Integer. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.jstype) + pub jstype: ::std::option::Option<crate::EnumOrUnknown<field_options::JSType>>, + /// Should this field be parsed lazily? Lazy applies only to message-type + /// fields. It means that when the outer message is initially parsed, the + /// inner message's contents will not be parsed but instead stored in encoded + /// form. The inner message will actually be parsed when it is first accessed. + /// + /// This is only a hint. Implementations are free to choose whether to use + /// eager or lazy parsing regardless of the value of this option. However, + /// setting this option true suggests that the protocol author believes that + /// using lazy parsing on this field is worth the additional bookkeeping + /// overhead typically needed to implement it. + /// + /// This option does not affect the public interface of any generated code; + /// all method signatures remain the same. Furthermore, thread-safety of the + /// interface is not affected by this option; const methods remain safe to + /// call from multiple threads concurrently, while non-const methods continue + /// to require exclusive access. + /// + /// + /// Note that implementations may choose not to check required fields within + /// a lazy sub-message. That is, calling IsInitialized() on the outer message + /// may return true even if the inner message has missing required fields. + /// This is necessary because otherwise the inner message would have to be + /// parsed in order to perform the check, defeating the purpose of lazy + /// parsing. An implementation which chooses not to check required fields + /// must be consistent about it. That is, for any particular sub-message, the + /// implementation must either *always* check its required fields, or *never* + /// check its required fields, regardless of whether or not the message has + /// been parsed. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.lazy) + pub lazy: ::std::option::Option<bool>, + /// Is this field deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for accessors, or it will be completely ignored; in the very least, this + /// is a formalization for deprecating fields. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + /// For Google-internal migration only. Do not use. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.weak) + pub weak: ::std::option::Option<bool>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.FieldOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FieldOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FieldOptions { @@ -6149,10 +5319,13 @@ impl FieldOptions { // optional .google.protobuf.FieldOptions.CType ctype = 1; - - pub fn get_ctype(&self) -> FieldOptions_CType { - self.ctype.unwrap_or(FieldOptions_CType::STRING) + pub fn ctype(&self) -> field_options::CType { + match self.ctype { + Some(e) => e.enum_value_or(field_options::CType::STRING), + None => field_options::CType::STRING, + } } + pub fn clear_ctype(&mut self) { self.ctype = ::std::option::Option::None; } @@ -6162,16 +5335,16 @@ impl FieldOptions { } // Param is passed by value, moved - pub fn set_ctype(&mut self, v: FieldOptions_CType) { - self.ctype = ::std::option::Option::Some(v); + pub fn set_ctype(&mut self, v: field_options::CType) { + self.ctype = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); } // optional bool packed = 2; - - pub fn get_packed(&self) -> bool { + pub fn packed(&self) -> bool { self.packed.unwrap_or(false) } + pub fn clear_packed(&mut self) { self.packed = ::std::option::Option::None; } @@ -6187,10 +5360,13 @@ impl FieldOptions { // optional .google.protobuf.FieldOptions.JSType jstype = 6; - - pub fn get_jstype(&self) -> FieldOptions_JSType { - self.jstype.unwrap_or(FieldOptions_JSType::JS_NORMAL) + pub fn jstype(&self) -> field_options::JSType { + match self.jstype { + Some(e) => e.enum_value_or(field_options::JSType::JS_NORMAL), + None => field_options::JSType::JS_NORMAL, + } } + pub fn clear_jstype(&mut self) { self.jstype = ::std::option::Option::None; } @@ -6200,16 +5376,16 @@ impl FieldOptions { } // Param is passed by value, moved - pub fn set_jstype(&mut self, v: FieldOptions_JSType) { - self.jstype = ::std::option::Option::Some(v); + pub fn set_jstype(&mut self, v: field_options::JSType) { + self.jstype = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); } // optional bool lazy = 5; - - pub fn get_lazy(&self) -> bool { + pub fn lazy(&self) -> bool { self.lazy.unwrap_or(false) } + pub fn clear_lazy(&mut self) { self.lazy = ::std::option::Option::None; } @@ -6225,10 +5401,10 @@ impl FieldOptions { // optional bool deprecated = 3; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -6244,10 +5420,10 @@ impl FieldOptions { // optional bool weak = 10; - - pub fn get_weak(&self) -> bool { + pub fn weak(&self) -> bool { self.weak.unwrap_or(false) } + pub fn clear_weak(&mut self) { self.weak = ::std::option::Option::None; } @@ -6261,33 +5437,55 @@ impl FieldOptions { self.weak = ::std::option::Option::Some(v); } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(7); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "ctype", + |m: &FieldOptions| { &m.ctype }, + |m: &mut FieldOptions| { &mut m.ctype }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "packed", + |m: &FieldOptions| { &m.packed }, + |m: &mut FieldOptions| { &mut m.packed }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "jstype", + |m: &FieldOptions| { &m.jstype }, + |m: &mut FieldOptions| { &mut m.jstype }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "lazy", + |m: &FieldOptions| { &m.lazy }, + |m: &mut FieldOptions| { &mut m.lazy }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &FieldOptions| { &m.deprecated }, + |m: &mut FieldOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "weak", + |m: &FieldOptions| { &m.weak }, + |m: &mut FieldOptions| { &mut m.weak }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &FieldOptions| { &m.uninterpreted_option }, + |m: &mut FieldOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FieldOptions>( + "FieldOptions", + fields, + oneofs, + ) } } impl crate::Message for FieldOptions { + const NAME: &'static str = "FieldOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -6297,49 +5495,32 @@ impl crate::Message for FieldOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.ctype, 1, &mut self.unknown_fields)? - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.packed = ::std::option::Option::Some(tmp); - }, - 6 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.jstype, 6, &mut self.unknown_fields)? - }, - 5 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.lazy = ::std::option::Option::Some(tmp); - }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.ctype = ::std::option::Option::Some(is.read_enum_or_unknown()?); }, - 10 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.weak = ::std::option::Option::Some(tmp); + 16 => { + self.packed = ::std::option::Option::Some(is.read_bool()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 48 => { + self.jstype = ::std::option::Option::Some(is.read_enum_or_unknown()?); + }, + 40 => { + self.lazy = ::std::option::Option::Some(is.read_bool()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + 24 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); + }, + 80 => { + self.weak = ::std::option::Option::Some(is.read_bool()?); + }, + 7994 => { + self.uninterpreted_option.push(is.read_message()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -6348,44 +5529,44 @@ impl crate::Message for FieldOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.ctype { - my_size += crate::rt::enum_size(1, v); + my_size += crate::rt::int32_size(1, v.value()); } if let Some(v) = self.packed { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.jstype { - my_size += crate::rt::enum_size(6, v); + my_size += crate::rt::int32_size(6, v.value()); } if let Some(v) = self.lazy { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.deprecated { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.weak { - my_size += 2; + my_size += 1 + 1; } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.ctype { - os.write_enum(1, crate::ProtobufEnum::value(&v))?; + os.write_enum(1, crate::EnumOrUnknown::value(&v))?; } if let Some(v) = self.packed { os.write_bool(2, v)?; } if let Some(v) = self.jstype { - os.write_enum(6, crate::ProtobufEnum::value(&v))?; + os.write_enum(6, crate::EnumOrUnknown::value(&v))?; } if let Some(v) = self.lazy { os.write_bool(5, v)?; @@ -6397,98 +5578,24 @@ impl crate::Message for FieldOptions { os.write_bool(10, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FieldOptions { FieldOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<FieldOptions_CType>>( - "ctype", - |m: &FieldOptions| { &m.ctype }, - |m: &mut FieldOptions| { &mut m.ctype }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "packed", - |m: &FieldOptions| { &m.packed }, - |m: &mut FieldOptions| { &mut m.packed }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<FieldOptions_JSType>>( - "jstype", - |m: &FieldOptions| { &m.jstype }, - |m: &mut FieldOptions| { &mut m.jstype }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "lazy", - |m: &FieldOptions| { &m.lazy }, - |m: &mut FieldOptions| { &mut m.lazy }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &FieldOptions| { &m.deprecated }, - |m: &mut FieldOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "weak", - |m: &FieldOptions| { &m.weak }, - |m: &mut FieldOptions| { &mut m.weak }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &FieldOptions| { &m.uninterpreted_option }, - |m: &mut FieldOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FieldOptions>( - "FieldOptions", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static FieldOptions { - static instance: crate::rt::LazyV2<FieldOptions> = crate::rt::LazyV2::INIT; - instance.get(FieldOptions::new) - } -} - -impl crate::Clear for FieldOptions { fn clear(&mut self) { self.ctype = ::std::option::Option::None; self.packed = ::std::option::Option::None; @@ -6497,140 +5604,170 @@ impl crate::Clear for FieldOptions { self.deprecated = ::std::option::Option::None; self.weak = ::std::option::Option::None; self.uninterpreted_option.clear(); - self.unknown_fields.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static FieldOptions { + static instance: FieldOptions = FieldOptions { + ctype: ::std::option::Option::None, + packed: ::std::option::Option::None, + jstype: ::std::option::Option::None, + lazy: ::std::option::Option::None, + deprecated: ::std::option::Option::None, + weak: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl ::std::fmt::Debug for FieldOptions { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) +impl crate::MessageFull for FieldOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FieldOptions").unwrap()).clone() } } -impl crate::reflect::ProtobufValue for FieldOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) +impl ::std::fmt::Display for FieldOptions { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) } } -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum FieldOptions_CType { - STRING = 0, - CORD = 1, - STRING_PIECE = 2, +impl crate::reflect::ProtobufValue for FieldOptions { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -impl crate::ProtobufEnum for FieldOptions_CType { - fn value(&self) -> i32 { - *self as i32 +/// Nested message and enums of message `FieldOptions` +pub mod field_options { + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.FieldOptions.CType) + pub enum CType { + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.CType.STRING) + STRING = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.CType.CORD) + CORD = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.CType.STRING_PIECE) + STRING_PIECE = 2, } - fn from_i32(value: i32) -> ::std::option::Option<FieldOptions_CType> { - match value { - 0 => ::std::option::Option::Some(FieldOptions_CType::STRING), - 1 => ::std::option::Option::Some(FieldOptions_CType::CORD), - 2 => ::std::option::Option::Some(FieldOptions_CType::STRING_PIECE), - _ => ::std::option::Option::None + impl crate::Enum for CType { + const NAME: &'static str = "CType"; + + fn value(&self) -> i32 { + *self as i32 } - } - fn values() -> &'static [Self] { - static values: &'static [FieldOptions_CType] = &[ - FieldOptions_CType::STRING, - FieldOptions_CType::CORD, - FieldOptions_CType::STRING_PIECE, + fn from_i32(value: i32) -> ::std::option::Option<CType> { + match value { + 0 => ::std::option::Option::Some(CType::STRING), + 1 => ::std::option::Option::Some(CType::CORD), + 2 => ::std::option::Option::Some(CType::STRING_PIECE), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [CType] = &[ + CType::STRING, + CType::CORD, + CType::STRING_PIECE, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<FieldOptions_CType>("FieldOptions.CType", file_descriptor_proto()) - }) + impl crate::EnumFull for CType { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("FieldOptions.CType").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } } -} -impl ::std::marker::Copy for FieldOptions_CType { -} + impl ::std::default::Default for CType { + fn default() -> Self { + CType::STRING + } + } -impl ::std::default::Default for FieldOptions_CType { - fn default() -> Self { - FieldOptions_CType::STRING + impl CType { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<CType>("FieldOptions.CType") + } } -} -impl crate::reflect::ProtobufValue for FieldOptions_CType { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.FieldOptions.JSType) + pub enum JSType { + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.JSType.JS_NORMAL) + JS_NORMAL = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.JSType.JS_STRING) + JS_STRING = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.FieldOptions.JSType.JS_NUMBER) + JS_NUMBER = 2, } -} -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum FieldOptions_JSType { - JS_NORMAL = 0, - JS_STRING = 1, - JS_NUMBER = 2, -} + impl crate::Enum for JSType { + const NAME: &'static str = "JSType"; -impl crate::ProtobufEnum for FieldOptions_JSType { - fn value(&self) -> i32 { - *self as i32 - } + fn value(&self) -> i32 { + *self as i32 + } - fn from_i32(value: i32) -> ::std::option::Option<FieldOptions_JSType> { - match value { - 0 => ::std::option::Option::Some(FieldOptions_JSType::JS_NORMAL), - 1 => ::std::option::Option::Some(FieldOptions_JSType::JS_STRING), - 2 => ::std::option::Option::Some(FieldOptions_JSType::JS_NUMBER), - _ => ::std::option::Option::None + fn from_i32(value: i32) -> ::std::option::Option<JSType> { + match value { + 0 => ::std::option::Option::Some(JSType::JS_NORMAL), + 1 => ::std::option::Option::Some(JSType::JS_STRING), + 2 => ::std::option::Option::Some(JSType::JS_NUMBER), + _ => ::std::option::Option::None + } } - } - fn values() -> &'static [Self] { - static values: &'static [FieldOptions_JSType] = &[ - FieldOptions_JSType::JS_NORMAL, - FieldOptions_JSType::JS_STRING, - FieldOptions_JSType::JS_NUMBER, + const VALUES: &'static [JSType] = &[ + JSType::JS_NORMAL, + JSType::JS_STRING, + JSType::JS_NUMBER, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<FieldOptions_JSType>("FieldOptions.JSType", file_descriptor_proto()) - }) - } -} + impl crate::EnumFull for JSType { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("FieldOptions.JSType").unwrap()).clone() + } -impl ::std::marker::Copy for FieldOptions_JSType { -} + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } + } -impl ::std::default::Default for FieldOptions_JSType { - fn default() -> Self { - FieldOptions_JSType::JS_NORMAL + impl ::std::default::Default for JSType { + fn default() -> Self { + JSType::JS_NORMAL + } } -} -impl crate::reflect::ProtobufValue for FieldOptions_JSType { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + impl JSType { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<JSType>("FieldOptions.JSType") + } } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.OneofOptions) pub struct OneofOptions { // message fields - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.OneofOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.OneofOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a OneofOptions { @@ -6644,33 +5781,25 @@ impl OneofOptions { ::std::default::Default::default() } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &OneofOptions| { &m.uninterpreted_option }, + |m: &mut OneofOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<OneofOptions>( + "OneofOptions", + fields, + oneofs, + ) } } impl crate::Message for OneofOptions { + const NAME: &'static str = "OneofOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -6680,15 +5809,14 @@ impl crate::Message for OneofOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -6697,111 +5825,88 @@ impl crate::Message for OneofOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> OneofOptions { OneofOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &OneofOptions| { &m.uninterpreted_option }, - |m: &mut OneofOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<OneofOptions>( - "OneofOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static OneofOptions { - static instance: crate::rt::LazyV2<OneofOptions> = crate::rt::LazyV2::INIT; - instance.get(OneofOptions::new) + static instance: OneofOptions = OneofOptions { + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for OneofOptions { - fn clear(&mut self) { - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for OneofOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("OneofOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for OneofOptions { +impl ::std::fmt::Display for OneofOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for OneofOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.EnumOptions) pub struct EnumOptions { // message fields - allow_alias: ::std::option::Option<bool>, - deprecated: ::std::option::Option<bool>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// Set this option to true to allow mapping different tag names to the same + /// value. + // @@protoc_insertion_point(field:google.protobuf.EnumOptions.allow_alias) + pub allow_alias: ::std::option::Option<bool>, + /// Is this enum deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the enum, or it will be completely ignored; in the very least, this + /// is a formalization for deprecating enums. + // @@protoc_insertion_point(field:google.protobuf.EnumOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.EnumOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.EnumOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a EnumOptions { @@ -6817,10 +5922,10 @@ impl EnumOptions { // optional bool allow_alias = 2; - - pub fn get_allow_alias(&self) -> bool { + pub fn allow_alias(&self) -> bool { self.allow_alias.unwrap_or(false) } + pub fn clear_allow_alias(&mut self) { self.allow_alias = ::std::option::Option::None; } @@ -6836,10 +5941,10 @@ impl EnumOptions { // optional bool deprecated = 3; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -6853,33 +5958,35 @@ impl EnumOptions { self.deprecated = ::std::option::Option::Some(v); } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "allow_alias", + |m: &EnumOptions| { &m.allow_alias }, + |m: &mut EnumOptions| { &mut m.allow_alias }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &EnumOptions| { &m.deprecated }, + |m: &mut EnumOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &EnumOptions| { &m.uninterpreted_option }, + |m: &mut EnumOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumOptions>( + "EnumOptions", + fields, + oneofs, + ) } } impl crate::Message for EnumOptions { + const NAME: &'static str = "EnumOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -6889,29 +5996,20 @@ impl crate::Message for EnumOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.allow_alias = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 16 => { + self.allow_alias = ::std::option::Option::Some(is.read_bool()?); }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); + 24 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -6920,24 +6018,24 @@ impl crate::Message for EnumOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.allow_alias { - my_size += 2; + my_size += 1 + 1; } if let Some(v) = self.deprecated { - my_size += 2; + my_size += 1 + 1; } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.allow_alias { os.write_bool(2, v)?; } @@ -6945,109 +6043,75 @@ impl crate::Message for EnumOptions { os.write_bool(3, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> EnumOptions { EnumOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "allow_alias", - |m: &EnumOptions| { &m.allow_alias }, - |m: &mut EnumOptions| { &mut m.allow_alias }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &EnumOptions| { &m.deprecated }, - |m: &mut EnumOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &EnumOptions| { &m.uninterpreted_option }, - |m: &mut EnumOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumOptions>( - "EnumOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.allow_alias = ::std::option::Option::None; + self.deprecated = ::std::option::Option::None; + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static EnumOptions { - static instance: crate::rt::LazyV2<EnumOptions> = crate::rt::LazyV2::INIT; - instance.get(EnumOptions::new) + static instance: EnumOptions = EnumOptions { + allow_alias: ::std::option::Option::None, + deprecated: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for EnumOptions { - fn clear(&mut self) { - self.allow_alias = ::std::option::Option::None; - self.deprecated = ::std::option::Option::None; - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for EnumOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("EnumOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for EnumOptions { +impl ::std::fmt::Display for EnumOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for EnumOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.EnumValueOptions) pub struct EnumValueOptions { // message fields - deprecated: ::std::option::Option<bool>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// Is this enum value deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the enum value, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating enum values. + // @@protoc_insertion_point(field:google.protobuf.EnumValueOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.EnumValueOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.EnumValueOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a EnumValueOptions { @@ -7063,10 +6127,10 @@ impl EnumValueOptions { // optional bool deprecated = 1; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -7080,33 +6144,30 @@ impl EnumValueOptions { self.deprecated = ::std::option::Option::Some(v); } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &EnumValueOptions| { &m.deprecated }, + |m: &mut EnumValueOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &EnumValueOptions| { &m.uninterpreted_option }, + |m: &mut EnumValueOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumValueOptions>( + "EnumValueOptions", + fields, + oneofs, + ) } } impl crate::Message for EnumValueOptions { + const NAME: &'static str = "EnumValueOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -7116,22 +6177,17 @@ impl crate::Message for EnumValueOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -7140,122 +6196,92 @@ impl crate::Message for EnumValueOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.deprecated { - my_size += 2; + my_size += 1 + 1; } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.deprecated { os.write_bool(1, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> EnumValueOptions { EnumValueOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &EnumValueOptions| { &m.deprecated }, - |m: &mut EnumValueOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &EnumValueOptions| { &m.uninterpreted_option }, - |m: &mut EnumValueOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumValueOptions>( - "EnumValueOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.deprecated = ::std::option::Option::None; + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static EnumValueOptions { - static instance: crate::rt::LazyV2<EnumValueOptions> = crate::rt::LazyV2::INIT; - instance.get(EnumValueOptions::new) + static instance: EnumValueOptions = EnumValueOptions { + deprecated: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for EnumValueOptions { - fn clear(&mut self) { - self.deprecated = ::std::option::Option::None; - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for EnumValueOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("EnumValueOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for EnumValueOptions { +impl ::std::fmt::Display for EnumValueOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for EnumValueOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.ServiceOptions) pub struct ServiceOptions { // message fields - deprecated: ::std::option::Option<bool>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// Is this service deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the service, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating services. + // @@protoc_insertion_point(field:google.protobuf.ServiceOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.ServiceOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.ServiceOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a ServiceOptions { @@ -7271,10 +6297,10 @@ impl ServiceOptions { // optional bool deprecated = 33; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -7288,33 +6314,30 @@ impl ServiceOptions { self.deprecated = ::std::option::Option::Some(v); } - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &ServiceOptions| { &m.deprecated }, + |m: &mut ServiceOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &ServiceOptions| { &m.uninterpreted_option }, + |m: &mut ServiceOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<ServiceOptions>( + "ServiceOptions", + fields, + oneofs, + ) } } impl crate::Message for ServiceOptions { + const NAME: &'static str = "ServiceOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -7324,22 +6347,17 @@ impl crate::Message for ServiceOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 33 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 264 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -7348,123 +6366,94 @@ impl crate::Message for ServiceOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.deprecated { - my_size += 3; + my_size += 2 + 1; } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.deprecated { os.write_bool(33, v)?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> ServiceOptions { ServiceOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &ServiceOptions| { &m.deprecated }, - |m: &mut ServiceOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &ServiceOptions| { &m.uninterpreted_option }, - |m: &mut ServiceOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<ServiceOptions>( - "ServiceOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.deprecated = ::std::option::Option::None; + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static ServiceOptions { - static instance: crate::rt::LazyV2<ServiceOptions> = crate::rt::LazyV2::INIT; - instance.get(ServiceOptions::new) + static instance: ServiceOptions = ServiceOptions { + deprecated: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for ServiceOptions { - fn clear(&mut self) { - self.deprecated = ::std::option::Option::None; - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for ServiceOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("ServiceOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for ServiceOptions { +impl ::std::fmt::Display for ServiceOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for ServiceOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.MethodOptions) pub struct MethodOptions { // message fields - deprecated: ::std::option::Option<bool>, - idempotency_level: ::std::option::Option<MethodOptions_IdempotencyLevel>, - pub uninterpreted_option: crate::RepeatedField<UninterpretedOption>, + /// Is this method deprecated? + /// Depending on the target platform, this can emit Deprecated annotations + /// for the method, or it will be completely ignored; in the very least, + /// this is a formalization for deprecating methods. + // @@protoc_insertion_point(field:google.protobuf.MethodOptions.deprecated) + pub deprecated: ::std::option::Option<bool>, + // @@protoc_insertion_point(field:google.protobuf.MethodOptions.idempotency_level) + pub idempotency_level: ::std::option::Option<crate::EnumOrUnknown<method_options::IdempotencyLevel>>, + /// The parser stores options it doesn't recognize here. See above. + // @@protoc_insertion_point(field:google.protobuf.MethodOptions.uninterpreted_option) + pub uninterpreted_option: ::std::vec::Vec<UninterpretedOption>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.MethodOptions.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a MethodOptions { @@ -7480,10 +6469,10 @@ impl MethodOptions { // optional bool deprecated = 33; - - pub fn get_deprecated(&self) -> bool { + pub fn deprecated(&self) -> bool { self.deprecated.unwrap_or(false) } + pub fn clear_deprecated(&mut self) { self.deprecated = ::std::option::Option::None; } @@ -7499,10 +6488,13 @@ impl MethodOptions { // optional .google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34; - - pub fn get_idempotency_level(&self) -> MethodOptions_IdempotencyLevel { - self.idempotency_level.unwrap_or(MethodOptions_IdempotencyLevel::IDEMPOTENCY_UNKNOWN) + pub fn idempotency_level(&self) -> method_options::IdempotencyLevel { + match self.idempotency_level { + Some(e) => e.enum_value_or(method_options::IdempotencyLevel::IDEMPOTENCY_UNKNOWN), + None => method_options::IdempotencyLevel::IDEMPOTENCY_UNKNOWN, + } } + pub fn clear_idempotency_level(&mut self) { self.idempotency_level = ::std::option::Option::None; } @@ -7512,37 +6504,39 @@ impl MethodOptions { } // Param is passed by value, moved - pub fn set_idempotency_level(&mut self, v: MethodOptions_IdempotencyLevel) { - self.idempotency_level = ::std::option::Option::Some(v); - } - - // repeated .google.protobuf.UninterpretedOption uninterpreted_option = 999; - - - pub fn get_uninterpreted_option(&self) -> &[UninterpretedOption] { - &self.uninterpreted_option - } - pub fn clear_uninterpreted_option(&mut self) { - self.uninterpreted_option.clear(); - } - - // Param is passed by value, moved - pub fn set_uninterpreted_option(&mut self, v: crate::RepeatedField<UninterpretedOption>) { - self.uninterpreted_option = v; - } - - // Mutable pointer to the field. - pub fn mut_uninterpreted_option(&mut self) -> &mut crate::RepeatedField<UninterpretedOption> { - &mut self.uninterpreted_option - } - - // Take field - pub fn take_uninterpreted_option(&mut self) -> crate::RepeatedField<UninterpretedOption> { - ::std::mem::replace(&mut self.uninterpreted_option, crate::RepeatedField::new()) + pub fn set_idempotency_level(&mut self, v: method_options::IdempotencyLevel) { + self.idempotency_level = ::std::option::Option::Some(crate::EnumOrUnknown::new(v)); + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "deprecated", + |m: &MethodOptions| { &m.deprecated }, + |m: &mut MethodOptions| { &mut m.deprecated }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "idempotency_level", + |m: &MethodOptions| { &m.idempotency_level }, + |m: &mut MethodOptions| { &mut m.idempotency_level }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "uninterpreted_option", + |m: &MethodOptions| { &m.uninterpreted_option }, + |m: &mut MethodOptions| { &mut m.uninterpreted_option }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<MethodOptions>( + "MethodOptions", + fields, + oneofs, + ) } } impl crate::Message for MethodOptions { + const NAME: &'static str = "MethodOptions"; + fn is_initialized(&self) -> bool { for v in &self.uninterpreted_option { if !v.is_initialized() { @@ -7552,25 +6546,20 @@ impl crate::Message for MethodOptions { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 33 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.deprecated = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 264 => { + self.deprecated = ::std::option::Option::Some(is.read_bool()?); }, - 34 => { - crate::rt::read_proto2_enum_with_unknown_fields_into(wire_type, is, &mut self.idempotency_level, 34, &mut self.unknown_fields)? + 272 => { + self.idempotency_level = ::std::option::Option::Some(is.read_enum_or_unknown()?); }, - 999 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.uninterpreted_option)?; + 7994 => { + self.uninterpreted_option.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -7579,193 +6568,177 @@ impl crate::Message for MethodOptions { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.deprecated { - my_size += 3; + my_size += 2 + 1; } if let Some(v) = self.idempotency_level { - my_size += crate::rt::enum_size(34, v); + my_size += crate::rt::int32_size(34, v.value()); } for value in &self.uninterpreted_option { let len = value.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.deprecated { os.write_bool(33, v)?; } if let Some(v) = self.idempotency_level { - os.write_enum(34, crate::ProtobufEnum::value(&v))?; + os.write_enum(34, crate::EnumOrUnknown::value(&v))?; } for v in &self.uninterpreted_option { - os.write_tag(999, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(999, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> MethodOptions { MethodOptions::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( - "deprecated", - |m: &MethodOptions| { &m.deprecated }, - |m: &mut MethodOptions| { &mut m.deprecated }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeEnum<MethodOptions_IdempotencyLevel>>( - "idempotency_level", - |m: &MethodOptions| { &m.idempotency_level }, - |m: &mut MethodOptions| { &mut m.idempotency_level }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption>>( - "uninterpreted_option", - |m: &MethodOptions| { &m.uninterpreted_option }, - |m: &mut MethodOptions| { &mut m.uninterpreted_option }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<MethodOptions>( - "MethodOptions", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.deprecated = ::std::option::Option::None; + self.idempotency_level = ::std::option::Option::None; + self.uninterpreted_option.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static MethodOptions { - static instance: crate::rt::LazyV2<MethodOptions> = crate::rt::LazyV2::INIT; - instance.get(MethodOptions::new) + static instance: MethodOptions = MethodOptions { + deprecated: ::std::option::Option::None, + idempotency_level: ::std::option::Option::None, + uninterpreted_option: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for MethodOptions { - fn clear(&mut self) { - self.deprecated = ::std::option::Option::None; - self.idempotency_level = ::std::option::Option::None; - self.uninterpreted_option.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for MethodOptions { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("MethodOptions").unwrap()).clone() } } -impl ::std::fmt::Debug for MethodOptions { +impl ::std::fmt::Display for MethodOptions { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for MethodOptions { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum MethodOptions_IdempotencyLevel { - IDEMPOTENCY_UNKNOWN = 0, - NO_SIDE_EFFECTS = 1, - IDEMPOTENT = 2, -} - -impl crate::ProtobufEnum for MethodOptions_IdempotencyLevel { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<MethodOptions_IdempotencyLevel> { - match value { - 0 => ::std::option::Option::Some(MethodOptions_IdempotencyLevel::IDEMPOTENCY_UNKNOWN), - 1 => ::std::option::Option::Some(MethodOptions_IdempotencyLevel::NO_SIDE_EFFECTS), - 2 => ::std::option::Option::Some(MethodOptions_IdempotencyLevel::IDEMPOTENT), - _ => ::std::option::Option::None + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `MethodOptions` +pub mod method_options { + /// Is this method side-effect-free (or safe in HTTP parlance), or idempotent, + /// or neither? HTTP based RPC implementation may choose GET verb for safe + /// methods, and PUT verb for idempotent methods instead of the default POST. + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.MethodOptions.IdempotencyLevel) + pub enum IdempotencyLevel { + // @@protoc_insertion_point(enum_value:google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENCY_UNKNOWN) + IDEMPOTENCY_UNKNOWN = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.MethodOptions.IdempotencyLevel.NO_SIDE_EFFECTS) + NO_SIDE_EFFECTS = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.MethodOptions.IdempotencyLevel.IDEMPOTENT) + IDEMPOTENT = 2, + } + + impl crate::Enum for IdempotencyLevel { + const NAME: &'static str = "IdempotencyLevel"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<IdempotencyLevel> { + match value { + 0 => ::std::option::Option::Some(IdempotencyLevel::IDEMPOTENCY_UNKNOWN), + 1 => ::std::option::Option::Some(IdempotencyLevel::NO_SIDE_EFFECTS), + 2 => ::std::option::Option::Some(IdempotencyLevel::IDEMPOTENT), + _ => ::std::option::Option::None + } } - } - fn values() -> &'static [Self] { - static values: &'static [MethodOptions_IdempotencyLevel] = &[ - MethodOptions_IdempotencyLevel::IDEMPOTENCY_UNKNOWN, - MethodOptions_IdempotencyLevel::NO_SIDE_EFFECTS, - MethodOptions_IdempotencyLevel::IDEMPOTENT, + const VALUES: &'static [IdempotencyLevel] = &[ + IdempotencyLevel::IDEMPOTENCY_UNKNOWN, + IdempotencyLevel::NO_SIDE_EFFECTS, + IdempotencyLevel::IDEMPOTENT, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<MethodOptions_IdempotencyLevel>("MethodOptions.IdempotencyLevel", file_descriptor_proto()) - }) - } -} + impl crate::EnumFull for IdempotencyLevel { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("MethodOptions.IdempotencyLevel").unwrap()).clone() + } -impl ::std::marker::Copy for MethodOptions_IdempotencyLevel { -} + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } + } -impl ::std::default::Default for MethodOptions_IdempotencyLevel { - fn default() -> Self { - MethodOptions_IdempotencyLevel::IDEMPOTENCY_UNKNOWN + impl ::std::default::Default for IdempotencyLevel { + fn default() -> Self { + IdempotencyLevel::IDEMPOTENCY_UNKNOWN + } } -} -impl crate::reflect::ProtobufValue for MethodOptions_IdempotencyLevel { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + impl IdempotencyLevel { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<IdempotencyLevel>("MethodOptions.IdempotencyLevel") + } } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// A message representing a option the parser does not recognize. This only +/// appears in options protos created by the compiler::Parser class. +/// DescriptorPool resolves these when building Descriptor objects. Therefore, +/// options protos in descriptor objects (e.g. returned by Descriptor::options(), +/// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +/// in them. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.UninterpretedOption) pub struct UninterpretedOption { // message fields - pub name: crate::RepeatedField<UninterpretedOption_NamePart>, - identifier_value: crate::SingularField<::std::string::String>, - positive_int_value: ::std::option::Option<u64>, - negative_int_value: ::std::option::Option<i64>, - double_value: ::std::option::Option<f64>, - string_value: crate::SingularField<::std::vec::Vec<u8>>, - aggregate_value: crate::SingularField<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.name) + pub name: ::std::vec::Vec<uninterpreted_option::NamePart>, + /// The value of the uninterpreted option, in whatever type the tokenizer + /// identified it as during parsing. Exactly one of these should be set. + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.identifier_value) + pub identifier_value: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.positive_int_value) + pub positive_int_value: ::std::option::Option<u64>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.negative_int_value) + pub negative_int_value: ::std::option::Option<i64>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.double_value) + pub double_value: ::std::option::Option<f64>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.string_value) + pub string_value: ::std::option::Option<::std::vec::Vec<u8>>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.aggregate_value) + pub aggregate_value: ::std::option::Option<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.UninterpretedOption.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a UninterpretedOption { @@ -7779,42 +6752,17 @@ impl UninterpretedOption { ::std::default::Default::default() } - // repeated .google.protobuf.UninterpretedOption.NamePart name = 2; - - - pub fn get_name(&self) -> &[UninterpretedOption_NamePart] { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: crate::RepeatedField<UninterpretedOption_NamePart>) { - self.name = v; - } - - // Mutable pointer to the field. - pub fn mut_name(&mut self) -> &mut crate::RepeatedField<UninterpretedOption_NamePart> { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> crate::RepeatedField<UninterpretedOption_NamePart> { - ::std::mem::replace(&mut self.name, crate::RepeatedField::new()) - } - // optional string identifier_value = 3; - - pub fn get_identifier_value(&self) -> &str { + pub fn identifier_value(&self) -> &str { match self.identifier_value.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_identifier_value(&mut self) { - self.identifier_value.clear(); + self.identifier_value = ::std::option::Option::None; } pub fn has_identifier_value(&self) -> bool { @@ -7823,14 +6771,14 @@ impl UninterpretedOption { // Param is passed by value, moved pub fn set_identifier_value(&mut self, v: ::std::string::String) { - self.identifier_value = crate::SingularField::some(v); + self.identifier_value = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_identifier_value(&mut self) -> &mut ::std::string::String { if self.identifier_value.is_none() { - self.identifier_value.set_default(); + self.identifier_value = ::std::option::Option::Some(::std::string::String::new()); } self.identifier_value.as_mut().unwrap() } @@ -7842,10 +6790,10 @@ impl UninterpretedOption { // optional uint64 positive_int_value = 4; - - pub fn get_positive_int_value(&self) -> u64 { + pub fn positive_int_value(&self) -> u64 { self.positive_int_value.unwrap_or(0) } + pub fn clear_positive_int_value(&mut self) { self.positive_int_value = ::std::option::Option::None; } @@ -7861,10 +6809,10 @@ impl UninterpretedOption { // optional int64 negative_int_value = 5; - - pub fn get_negative_int_value(&self) -> i64 { + pub fn negative_int_value(&self) -> i64 { self.negative_int_value.unwrap_or(0) } + pub fn clear_negative_int_value(&mut self) { self.negative_int_value = ::std::option::Option::None; } @@ -7880,10 +6828,10 @@ impl UninterpretedOption { // optional double double_value = 6; - - pub fn get_double_value(&self) -> f64 { + pub fn double_value(&self) -> f64 { self.double_value.unwrap_or(0.) } + pub fn clear_double_value(&mut self) { self.double_value = ::std::option::Option::None; } @@ -7899,15 +6847,15 @@ impl UninterpretedOption { // optional bytes string_value = 7; - - pub fn get_string_value(&self) -> &[u8] { + pub fn string_value(&self) -> &[u8] { match self.string_value.as_ref() { - Some(v) => &v, + Some(v) => v, None => &[], } } + pub fn clear_string_value(&mut self) { - self.string_value.clear(); + self.string_value = ::std::option::Option::None; } pub fn has_string_value(&self) -> bool { @@ -7916,14 +6864,14 @@ impl UninterpretedOption { // Param is passed by value, moved pub fn set_string_value(&mut self, v: ::std::vec::Vec<u8>) { - self.string_value = crate::SingularField::some(v); + self.string_value = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_string_value(&mut self) -> &mut ::std::vec::Vec<u8> { if self.string_value.is_none() { - self.string_value.set_default(); + self.string_value = ::std::option::Option::Some(::std::vec::Vec::new()); } self.string_value.as_mut().unwrap() } @@ -7935,15 +6883,15 @@ impl UninterpretedOption { // optional string aggregate_value = 8; - - pub fn get_aggregate_value(&self) -> &str { + pub fn aggregate_value(&self) -> &str { match self.aggregate_value.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_aggregate_value(&mut self) { - self.aggregate_value.clear(); + self.aggregate_value = ::std::option::Option::None; } pub fn has_aggregate_value(&self) -> bool { @@ -7952,14 +6900,14 @@ impl UninterpretedOption { // Param is passed by value, moved pub fn set_aggregate_value(&mut self, v: ::std::string::String) { - self.aggregate_value = crate::SingularField::some(v); + self.aggregate_value = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_aggregate_value(&mut self) -> &mut ::std::string::String { if self.aggregate_value.is_none() { - self.aggregate_value.set_default(); + self.aggregate_value = ::std::option::Option::Some(::std::string::String::new()); } self.aggregate_value.as_mut().unwrap() } @@ -7968,9 +6916,56 @@ impl UninterpretedOption { pub fn take_aggregate_value(&mut self) -> ::std::string::String { self.aggregate_value.take().unwrap_or_else(|| ::std::string::String::new()) } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(7); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "name", + |m: &UninterpretedOption| { &m.name }, + |m: &mut UninterpretedOption| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "identifier_value", + |m: &UninterpretedOption| { &m.identifier_value }, + |m: &mut UninterpretedOption| { &mut m.identifier_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "positive_int_value", + |m: &UninterpretedOption| { &m.positive_int_value }, + |m: &mut UninterpretedOption| { &mut m.positive_int_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "negative_int_value", + |m: &UninterpretedOption| { &m.negative_int_value }, + |m: &mut UninterpretedOption| { &mut m.negative_int_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "double_value", + |m: &UninterpretedOption| { &m.double_value }, + |m: &mut UninterpretedOption| { &mut m.double_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "string_value", + |m: &UninterpretedOption| { &m.string_value }, + |m: &mut UninterpretedOption| { &mut m.string_value }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "aggregate_value", + |m: &UninterpretedOption| { &m.aggregate_value }, + |m: &mut UninterpretedOption| { &mut m.aggregate_value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<UninterpretedOption>( + "UninterpretedOption", + fields, + oneofs, + ) + } } impl crate::Message for UninterpretedOption { + const NAME: &'static str = "UninterpretedOption"; + fn is_initialized(&self) -> bool { for v in &self.name { if !v.is_initialized() { @@ -7980,45 +6975,32 @@ impl crate::Message for UninterpretedOption { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.name)?; - }, - 3 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.identifier_value)?; - }, - 4 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint64()?; - self.positive_int_value = ::std::option::Option::Some(tmp); - }, - 5 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int64()?; - self.negative_int_value = ::std::option::Option::Some(tmp); - }, - 6 => { - if wire_type != crate::wire_format::WireTypeFixed64 { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_double()?; - self.double_value = ::std::option::Option::Some(tmp); - }, - 7 => { - crate::rt::read_singular_bytes_into(wire_type, is, &mut self.string_value)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 18 => { + self.name.push(is.read_message()?); }, - 8 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.aggregate_value)?; + 26 => { + self.identifier_value = ::std::option::Option::Some(is.read_string()?); + }, + 32 => { + self.positive_int_value = ::std::option::Option::Some(is.read_uint64()?); + }, + 40 => { + self.negative_int_value = ::std::option::Option::Some(is.read_int64()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + 49 => { + self.double_value = ::std::option::Option::Some(is.read_double()?); + }, + 58 => { + self.string_value = ::std::option::Option::Some(is.read_bytes()?); + }, + 66 => { + self.aggregate_value = ::std::option::Option::Some(is.read_string()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -8027,43 +7009,41 @@ impl crate::Message for UninterpretedOption { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.name { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.identifier_value.as_ref() { + if let Some(v) = self.identifier_value.as_ref() { my_size += crate::rt::string_size(3, &v); } if let Some(v) = self.positive_int_value { - my_size += crate::rt::value_size(4, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::uint64_size(4, v); } if let Some(v) = self.negative_int_value { - my_size += crate::rt::value_size(5, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int64_size(5, v); } if let Some(v) = self.double_value { - my_size += 9; + my_size += 1 + 8; } - if let Some(ref v) = self.string_value.as_ref() { + if let Some(v) = self.string_value.as_ref() { my_size += crate::rt::bytes_size(7, &v); } - if let Some(ref v) = self.aggregate_value.as_ref() { + if let Some(v) = self.aggregate_value.as_ref() { my_size += crate::rt::string_size(8, &v); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.name { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; }; - if let Some(ref v) = self.identifier_value.as_ref() { - os.write_string(3, &v)?; + if let Some(v) = self.identifier_value.as_ref() { + os.write_string(3, v)?; } if let Some(v) = self.positive_int_value { os.write_uint64(4, v)?; @@ -8074,351 +7054,291 @@ impl crate::Message for UninterpretedOption { if let Some(v) = self.double_value { os.write_double(6, v)?; } - if let Some(ref v) = self.string_value.as_ref() { - os.write_bytes(7, &v)?; + if let Some(v) = self.string_value.as_ref() { + os.write_bytes(7, v)?; } - if let Some(ref v) = self.aggregate_value.as_ref() { - os.write_string(8, &v)?; + if let Some(v) = self.aggregate_value.as_ref() { + os.write_string(8, v)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> UninterpretedOption { UninterpretedOption::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<UninterpretedOption_NamePart>>( - "name", - |m: &UninterpretedOption| { &m.name }, - |m: &mut UninterpretedOption| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "identifier_value", - |m: &UninterpretedOption| { &m.identifier_value }, - |m: &mut UninterpretedOption| { &mut m.identifier_value }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeUint64>( - "positive_int_value", - |m: &UninterpretedOption| { &m.positive_int_value }, - |m: &mut UninterpretedOption| { &mut m.positive_int_value }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt64>( - "negative_int_value", - |m: &UninterpretedOption| { &m.negative_int_value }, - |m: &mut UninterpretedOption| { &mut m.negative_int_value }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeDouble>( - "double_value", - |m: &UninterpretedOption| { &m.double_value }, - |m: &mut UninterpretedOption| { &mut m.double_value }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeBytes>( - "string_value", - |m: &UninterpretedOption| { &m.string_value }, - |m: &mut UninterpretedOption| { &mut m.string_value }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "aggregate_value", - |m: &UninterpretedOption| { &m.aggregate_value }, - |m: &mut UninterpretedOption| { &mut m.aggregate_value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<UninterpretedOption>( - "UninterpretedOption", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static UninterpretedOption { - static instance: crate::rt::LazyV2<UninterpretedOption> = crate::rt::LazyV2::INIT; - instance.get(UninterpretedOption::new) - } -} - -impl crate::Clear for UninterpretedOption { fn clear(&mut self) { self.name.clear(); - self.identifier_value.clear(); + self.identifier_value = ::std::option::Option::None; self.positive_int_value = ::std::option::Option::None; self.negative_int_value = ::std::option::Option::None; self.double_value = ::std::option::Option::None; - self.string_value.clear(); - self.aggregate_value.clear(); - self.unknown_fields.clear(); + self.string_value = ::std::option::Option::None; + self.aggregate_value = ::std::option::Option::None; + self.special_fields.clear(); } -} -impl ::std::fmt::Debug for UninterpretedOption { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + fn default_instance() -> &'static UninterpretedOption { + static instance: UninterpretedOption = UninterpretedOption { + name: ::std::vec::Vec::new(), + identifier_value: ::std::option::Option::None, + positive_int_value: ::std::option::Option::None, + negative_int_value: ::std::option::Option::None, + double_value: ::std::option::Option::None, + string_value: ::std::option::Option::None, + aggregate_value: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::reflect::ProtobufValue for UninterpretedOption { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) +impl crate::MessageFull for UninterpretedOption { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("UninterpretedOption").unwrap()).clone() } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct UninterpretedOption_NamePart { - // message fields - name_part: crate::SingularField<::std::string::String>, - is_extension: ::std::option::Option<bool>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, +impl ::std::fmt::Display for UninterpretedOption { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -impl<'a> ::std::default::Default for &'a UninterpretedOption_NamePart { - fn default() -> &'a UninterpretedOption_NamePart { - <UninterpretedOption_NamePart as crate::Message>::default_instance() - } +impl crate::reflect::ProtobufValue for UninterpretedOption { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -impl UninterpretedOption_NamePart { - pub fn new() -> UninterpretedOption_NamePart { - ::std::default::Default::default() +/// Nested message and enums of message `UninterpretedOption` +pub mod uninterpreted_option { + /// The name of the uninterpreted option. Each string represents a segment in + /// a dot-separated name. is_extension is true iff a segment represents an + /// extension (denoted with parentheses in options specs in .proto files). + /// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + /// "foo.(bar.baz).qux". + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.UninterpretedOption.NamePart) + pub struct NamePart { + // message fields + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.NamePart.name_part) + pub name_part: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.UninterpretedOption.NamePart.is_extension) + pub is_extension: ::std::option::Option<bool>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.UninterpretedOption.NamePart.special_fields) + pub special_fields: crate::SpecialFields, } - // required string name_part = 1; - - - pub fn get_name_part(&self) -> &str { - match self.name_part.as_ref() { - Some(v) => &v, - None => "", + impl<'a> ::std::default::Default for &'a NamePart { + fn default() -> &'a NamePart { + <NamePart as crate::Message>::default_instance() } } - pub fn clear_name_part(&mut self) { - self.name_part.clear(); - } - - pub fn has_name_part(&self) -> bool { - self.name_part.is_some() - } - - // Param is passed by value, moved - pub fn set_name_part(&mut self, v: ::std::string::String) { - self.name_part = crate::SingularField::some(v); - } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name_part(&mut self) -> &mut ::std::string::String { - if self.name_part.is_none() { - self.name_part.set_default(); + impl NamePart { + pub fn new() -> NamePart { + ::std::default::Default::default() } - self.name_part.as_mut().unwrap() - } - - // Take field - pub fn take_name_part(&mut self) -> ::std::string::String { - self.name_part.take().unwrap_or_else(|| ::std::string::String::new()) - } - - // required bool is_extension = 2; + // required string name_part = 1; - pub fn get_is_extension(&self) -> bool { - self.is_extension.unwrap_or(false) - } - pub fn clear_is_extension(&mut self) { - self.is_extension = ::std::option::Option::None; - } - - pub fn has_is_extension(&self) -> bool { - self.is_extension.is_some() - } - - // Param is passed by value, moved - pub fn set_is_extension(&mut self, v: bool) { - self.is_extension = ::std::option::Option::Some(v); - } -} - -impl crate::Message for UninterpretedOption_NamePart { - fn is_initialized(&self) -> bool { - if self.name_part.is_none() { - return false; - } - if self.is_extension.is_none() { - return false; + pub fn name_part(&self) -> &str { + match self.name_part.as_ref() { + Some(v) => v, + None => "", + } } - true - } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name_part)?; - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.is_extension = ::std::option::Option::Some(tmp); - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + pub fn clear_name_part(&mut self) { + self.name_part = ::std::option::Option::None; } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let Some(ref v) = self.name_part.as_ref() { - my_size += crate::rt::string_size(1, &v); + pub fn has_name_part(&self) -> bool { + self.name_part.is_some() } - if let Some(v) = self.is_extension { - my_size += 2; - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name_part.as_ref() { - os.write_string(1, &v)?; + // Param is passed by value, moved + pub fn set_name_part(&mut self, v: ::std::string::String) { + self.name_part = ::std::option::Option::Some(v); } - if let Some(v) = self.is_extension { - os.write_bool(2, v)?; + + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_name_part(&mut self) -> &mut ::std::string::String { + if self.name_part.is_none() { + self.name_part = ::std::option::Option::Some(::std::string::String::new()); + } + self.name_part.as_mut().unwrap() } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } + // Take field + pub fn take_name_part(&mut self) -> ::std::string::String { + self.name_part.take().unwrap_or_else(|| ::std::string::String::new()) + } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } + // required bool is_extension = 2; - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } + pub fn is_extension(&self) -> bool { + self.is_extension.unwrap_or(false) + } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + pub fn clear_is_extension(&mut self) { + self.is_extension = ::std::option::Option::None; + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + pub fn has_is_extension(&self) -> bool { + self.is_extension.is_some() + } - fn new() -> UninterpretedOption_NamePart { - UninterpretedOption_NamePart::new() - } + // Param is passed by value, moved + pub fn set_is_extension(&mut self, v: bool) { + self.is_extension = ::std::option::Option::Some(v); + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "name_part", - |m: &UninterpretedOption_NamePart| { &m.name_part }, - |m: &mut UninterpretedOption_NamePart| { &mut m.name_part }, + |m: &NamePart| { &m.name_part }, + |m: &mut NamePart| { &mut m.name_part }, )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeBool>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "is_extension", - |m: &UninterpretedOption_NamePart| { &m.is_extension }, - |m: &mut UninterpretedOption_NamePart| { &mut m.is_extension }, + |m: &NamePart| { &m.is_extension }, + |m: &mut NamePart| { &mut m.is_extension }, )); - crate::reflect::MessageDescriptor::new_pb_name::<UninterpretedOption_NamePart>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<NamePart>( "UninterpretedOption.NamePart", fields, - file_descriptor_proto() + oneofs, ) - }) + } } - fn default_instance() -> &'static UninterpretedOption_NamePart { - static instance: crate::rt::LazyV2<UninterpretedOption_NamePart> = crate::rt::LazyV2::INIT; - instance.get(UninterpretedOption_NamePart::new) + impl crate::Message for NamePart { + const NAME: &'static str = "NamePart"; + + fn is_initialized(&self) -> bool { + if self.name_part.is_none() { + return false; + } + if self.is_extension.is_none() { + return false; + } + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name_part = ::std::option::Option::Some(is.read_string()?); + }, + 16 => { + self.is_extension = ::std::option::Option::Some(is.read_bool()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let Some(v) = self.name_part.as_ref() { + my_size += crate::rt::string_size(1, &v); + } + if let Some(v) = self.is_extension { + my_size += 1 + 1; + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name_part.as_ref() { + os.write_string(1, v)?; + } + if let Some(v) = self.is_extension { + os.write_bool(2, v)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> NamePart { + NamePart::new() + } + + fn clear(&mut self) { + self.name_part = ::std::option::Option::None; + self.is_extension = ::std::option::Option::None; + self.special_fields.clear(); + } + + fn default_instance() -> &'static NamePart { + static instance: NamePart = NamePart { + name_part: ::std::option::Option::None, + is_extension: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl crate::Clear for UninterpretedOption_NamePart { - fn clear(&mut self) { - self.name_part.clear(); - self.is_extension = ::std::option::Option::None; - self.unknown_fields.clear(); + impl crate::MessageFull for NamePart { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("UninterpretedOption.NamePart").unwrap()).clone() + } } -} -impl ::std::fmt::Debug for UninterpretedOption_NamePart { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl ::std::fmt::Display for NamePart { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for UninterpretedOption_NamePart { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl crate::reflect::ProtobufValue for NamePart { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Encapsulates information about the original source file from which a +/// FileDescriptorProto was generated. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.SourceCodeInfo) pub struct SourceCodeInfo { // message fields - pub location: crate::RepeatedField<SourceCodeInfo_Location>, + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.location) + pub location: ::std::vec::Vec<source_code_info::Location>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.SourceCodeInfo.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a SourceCodeInfo { @@ -8432,51 +7352,37 @@ impl SourceCodeInfo { ::std::default::Default::default() } - // repeated .google.protobuf.SourceCodeInfo.Location location = 1; - - - pub fn get_location(&self) -> &[SourceCodeInfo_Location] { - &self.location - } - pub fn clear_location(&mut self) { - self.location.clear(); - } - - // Param is passed by value, moved - pub fn set_location(&mut self, v: crate::RepeatedField<SourceCodeInfo_Location>) { - self.location = v; - } - - // Mutable pointer to the field. - pub fn mut_location(&mut self) -> &mut crate::RepeatedField<SourceCodeInfo_Location> { - &mut self.location - } - - // Take field - pub fn take_location(&mut self) -> crate::RepeatedField<SourceCodeInfo_Location> { - ::std::mem::replace(&mut self.location, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "location", + |m: &SourceCodeInfo| { &m.location }, + |m: &mut SourceCodeInfo| { &mut m.location }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<SourceCodeInfo>( + "SourceCodeInfo", + fields, + oneofs, + ) } } impl crate::Message for SourceCodeInfo { + const NAME: &'static str = "SourceCodeInfo"; + fn is_initialized(&self) -> bool { - for v in &self.location { - if !v.is_initialized() { - return false; - } - }; true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.location)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.location.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -8485,466 +7391,354 @@ impl crate::Message for SourceCodeInfo { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.location { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.location { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(1, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> SourceCodeInfo { SourceCodeInfo::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<SourceCodeInfo_Location>>( - "location", - |m: &SourceCodeInfo| { &m.location }, - |m: &mut SourceCodeInfo| { &mut m.location }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<SourceCodeInfo>( - "SourceCodeInfo", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.location.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static SourceCodeInfo { - static instance: crate::rt::LazyV2<SourceCodeInfo> = crate::rt::LazyV2::INIT; - instance.get(SourceCodeInfo::new) + static instance: SourceCodeInfo = SourceCodeInfo { + location: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for SourceCodeInfo { - fn clear(&mut self) { - self.location.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for SourceCodeInfo { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("SourceCodeInfo").unwrap()).clone() } } -impl ::std::fmt::Debug for SourceCodeInfo { +impl ::std::fmt::Display for SourceCodeInfo { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for SourceCodeInfo { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct SourceCodeInfo_Location { - // message fields - pub path: ::std::vec::Vec<i32>, - pub span: ::std::vec::Vec<i32>, - leading_comments: crate::SingularField<::std::string::String>, - trailing_comments: crate::SingularField<::std::string::String>, - pub leading_detached_comments: crate::RepeatedField<::std::string::String>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a SourceCodeInfo_Location { - fn default() -> &'a SourceCodeInfo_Location { - <SourceCodeInfo_Location as crate::Message>::default_instance() - } -} - -impl SourceCodeInfo_Location { - pub fn new() -> SourceCodeInfo_Location { - ::std::default::Default::default() - } - - // repeated int32 path = 1; - - - pub fn get_path(&self) -> &[i32] { - &self.path - } - pub fn clear_path(&mut self) { - self.path.clear(); - } - - // Param is passed by value, moved - pub fn set_path(&mut self, v: ::std::vec::Vec<i32>) { - self.path = v; - } - - // Mutable pointer to the field. - pub fn mut_path(&mut self) -> &mut ::std::vec::Vec<i32> { - &mut self.path - } - - // Take field - pub fn take_path(&mut self) -> ::std::vec::Vec<i32> { - ::std::mem::replace(&mut self.path, ::std::vec::Vec::new()) - } - - // repeated int32 span = 2; - - - pub fn get_span(&self) -> &[i32] { - &self.span - } - pub fn clear_span(&mut self) { - self.span.clear(); - } - - // Param is passed by value, moved - pub fn set_span(&mut self, v: ::std::vec::Vec<i32>) { - self.span = v; - } - - // Mutable pointer to the field. - pub fn mut_span(&mut self) -> &mut ::std::vec::Vec<i32> { - &mut self.span - } - - // Take field - pub fn take_span(&mut self) -> ::std::vec::Vec<i32> { - ::std::mem::replace(&mut self.span, ::std::vec::Vec::new()) - } - - // optional string leading_comments = 3; - - - pub fn get_leading_comments(&self) -> &str { - match self.leading_comments.as_ref() { - Some(v) => &v, - None => "", + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `SourceCodeInfo` +pub mod source_code_info { + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.SourceCodeInfo.Location) + pub struct Location { + // message fields + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.Location.path) + pub path: ::std::vec::Vec<i32>, + /// Always has exactly three or four elements: start line, start column, + /// end line (optional, otherwise assumed same as start line), end column. + /// These are packed into a single field for efficiency. Note that line + /// and column numbers are zero-based -- typically you will want to add + /// 1 to each before displaying to a user. + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.Location.span) + pub span: ::std::vec::Vec<i32>, + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.Location.leading_comments) + pub leading_comments: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.Location.trailing_comments) + pub trailing_comments: ::std::option::Option<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.SourceCodeInfo.Location.leading_detached_comments) + pub leading_detached_comments: ::std::vec::Vec<::std::string::String>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.SourceCodeInfo.Location.special_fields) + pub special_fields: crate::SpecialFields, + } + + impl<'a> ::std::default::Default for &'a Location { + fn default() -> &'a Location { + <Location as crate::Message>::default_instance() + } + } + + impl Location { + pub fn new() -> Location { + ::std::default::Default::default() + } + + // optional string leading_comments = 3; + + pub fn leading_comments(&self) -> &str { + match self.leading_comments.as_ref() { + Some(v) => v, + None => "", + } } - } - pub fn clear_leading_comments(&mut self) { - self.leading_comments.clear(); - } - - pub fn has_leading_comments(&self) -> bool { - self.leading_comments.is_some() - } - // Param is passed by value, moved - pub fn set_leading_comments(&mut self, v: ::std::string::String) { - self.leading_comments = crate::SingularField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_leading_comments(&mut self) -> &mut ::std::string::String { - if self.leading_comments.is_none() { - self.leading_comments.set_default(); + pub fn clear_leading_comments(&mut self) { + self.leading_comments = ::std::option::Option::None; } - self.leading_comments.as_mut().unwrap() - } - - // Take field - pub fn take_leading_comments(&mut self) -> ::std::string::String { - self.leading_comments.take().unwrap_or_else(|| ::std::string::String::new()) - } - - // optional string trailing_comments = 4; - - pub fn get_trailing_comments(&self) -> &str { - match self.trailing_comments.as_ref() { - Some(v) => &v, - None => "", + pub fn has_leading_comments(&self) -> bool { + self.leading_comments.is_some() } - } - pub fn clear_trailing_comments(&mut self) { - self.trailing_comments.clear(); - } - - pub fn has_trailing_comments(&self) -> bool { - self.trailing_comments.is_some() - } - // Param is passed by value, moved - pub fn set_trailing_comments(&mut self, v: ::std::string::String) { - self.trailing_comments = crate::SingularField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_trailing_comments(&mut self) -> &mut ::std::string::String { - if self.trailing_comments.is_none() { - self.trailing_comments.set_default(); + // Param is passed by value, moved + pub fn set_leading_comments(&mut self, v: ::std::string::String) { + self.leading_comments = ::std::option::Option::Some(v); } - self.trailing_comments.as_mut().unwrap() - } - - // Take field - pub fn take_trailing_comments(&mut self) -> ::std::string::String { - self.trailing_comments.take().unwrap_or_else(|| ::std::string::String::new()) - } - // repeated string leading_detached_comments = 6; - - - pub fn get_leading_detached_comments(&self) -> &[::std::string::String] { - &self.leading_detached_comments - } - pub fn clear_leading_detached_comments(&mut self) { - self.leading_detached_comments.clear(); - } - - // Param is passed by value, moved - pub fn set_leading_detached_comments(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.leading_detached_comments = v; - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_leading_comments(&mut self) -> &mut ::std::string::String { + if self.leading_comments.is_none() { + self.leading_comments = ::std::option::Option::Some(::std::string::String::new()); + } + self.leading_comments.as_mut().unwrap() + } - // Mutable pointer to the field. - pub fn mut_leading_detached_comments(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.leading_detached_comments - } + // Take field + pub fn take_leading_comments(&mut self) -> ::std::string::String { + self.leading_comments.take().unwrap_or_else(|| ::std::string::String::new()) + } - // Take field - pub fn take_leading_detached_comments(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.leading_detached_comments, crate::RepeatedField::new()) - } -} + // optional string trailing_comments = 4; -impl crate::Message for SourceCodeInfo_Location { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_int32_into(wire_type, is, &mut self.path)?; - }, - 2 => { - crate::rt::read_repeated_int32_into(wire_type, is, &mut self.span)?; - }, - 3 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.leading_comments)?; - }, - 4 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.trailing_comments)?; - }, - 6 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.leading_detached_comments)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + pub fn trailing_comments(&self) -> &str { + match self.trailing_comments.as_ref() { + Some(v) => v, + None => "", + } } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.path.is_empty() { - my_size += crate::rt::vec_packed_varint_size(1, &self.path); - } - if !self.span.is_empty() { - my_size += crate::rt::vec_packed_varint_size(2, &self.span); - } - if let Some(ref v) = self.leading_comments.as_ref() { - my_size += crate::rt::string_size(3, &v); + pub fn clear_trailing_comments(&mut self) { + self.trailing_comments = ::std::option::Option::None; } - if let Some(ref v) = self.trailing_comments.as_ref() { - my_size += crate::rt::string_size(4, &v); - } - for value in &self.leading_detached_comments { - my_size += crate::rt::string_size(6, &value); - }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.path.is_empty() { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - // TODO: Data size is computed again, it should be cached - os.write_raw_varint32(crate::rt::vec_packed_varint_data_size(&self.path))?; - for v in &self.path { - os.write_int32_no_tag(*v)?; - }; - } - if !self.span.is_empty() { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - // TODO: Data size is computed again, it should be cached - os.write_raw_varint32(crate::rt::vec_packed_varint_data_size(&self.span))?; - for v in &self.span { - os.write_int32_no_tag(*v)?; - }; - } - if let Some(ref v) = self.leading_comments.as_ref() { - os.write_string(3, &v)?; + pub fn has_trailing_comments(&self) -> bool { + self.trailing_comments.is_some() } - if let Some(ref v) = self.trailing_comments.as_ref() { - os.write_string(4, &v)?; - } - for v in &self.leading_detached_comments { - os.write_string(6, &v)?; - }; - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + // Param is passed by value, moved + pub fn set_trailing_comments(&mut self, v: ::std::string::String) { + self.trailing_comments = ::std::option::Option::Some(v); + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_trailing_comments(&mut self) -> &mut ::std::string::String { + if self.trailing_comments.is_none() { + self.trailing_comments = ::std::option::Option::Some(::std::string::String::new()); + } + self.trailing_comments.as_mut().unwrap() + } - fn new() -> SourceCodeInfo_Location { - SourceCodeInfo_Location::new() - } + // Take field + pub fn take_trailing_comments(&mut self) -> ::std::string::String { + self.trailing_comments.take().unwrap_or_else(|| ::std::string::String::new()) + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_vec_accessor::<_, crate::types::ProtobufTypeInt32>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(5); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( "path", - |m: &SourceCodeInfo_Location| { &m.path }, - |m: &mut SourceCodeInfo_Location| { &mut m.path }, + |m: &Location| { &m.path }, + |m: &mut Location| { &mut m.path }, )); - fields.push(crate::reflect::accessor::make_vec_accessor::<_, crate::types::ProtobufTypeInt32>( + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( "span", - |m: &SourceCodeInfo_Location| { &m.span }, - |m: &mut SourceCodeInfo_Location| { &mut m.span }, + |m: &Location| { &m.span }, + |m: &mut Location| { &mut m.span }, )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "leading_comments", - |m: &SourceCodeInfo_Location| { &m.leading_comments }, - |m: &mut SourceCodeInfo_Location| { &mut m.leading_comments }, + |m: &Location| { &m.leading_comments }, + |m: &mut Location| { &mut m.leading_comments }, )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "trailing_comments", - |m: &SourceCodeInfo_Location| { &m.trailing_comments }, - |m: &mut SourceCodeInfo_Location| { &mut m.trailing_comments }, + |m: &Location| { &m.trailing_comments }, + |m: &mut Location| { &mut m.trailing_comments }, )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( "leading_detached_comments", - |m: &SourceCodeInfo_Location| { &m.leading_detached_comments }, - |m: &mut SourceCodeInfo_Location| { &mut m.leading_detached_comments }, + |m: &Location| { &m.leading_detached_comments }, + |m: &mut Location| { &mut m.leading_detached_comments }, )); - crate::reflect::MessageDescriptor::new_pb_name::<SourceCodeInfo_Location>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<Location>( "SourceCodeInfo.Location", fields, - file_descriptor_proto() + oneofs, ) - }) + } } - fn default_instance() -> &'static SourceCodeInfo_Location { - static instance: crate::rt::LazyV2<SourceCodeInfo_Location> = crate::rt::LazyV2::INIT; - instance.get(SourceCodeInfo_Location::new) + impl crate::Message for Location { + const NAME: &'static str = "Location"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + is.read_repeated_packed_int32_into(&mut self.path)?; + }, + 8 => { + self.path.push(is.read_int32()?); + }, + 18 => { + is.read_repeated_packed_int32_into(&mut self.span)?; + }, + 16 => { + self.span.push(is.read_int32()?); + }, + 26 => { + self.leading_comments = ::std::option::Option::Some(is.read_string()?); + }, + 34 => { + self.trailing_comments = ::std::option::Option::Some(is.read_string()?); + }, + 50 => { + self.leading_detached_comments.push(is.read_string()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + my_size += crate::rt::vec_packed_int32_size(1, &self.path); + my_size += crate::rt::vec_packed_int32_size(2, &self.span); + if let Some(v) = self.leading_comments.as_ref() { + my_size += crate::rt::string_size(3, &v); + } + if let Some(v) = self.trailing_comments.as_ref() { + my_size += crate::rt::string_size(4, &v); + } + for value in &self.leading_detached_comments { + my_size += crate::rt::string_size(6, &value); + }; + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + os.write_repeated_packed_int32(1, &self.path)?; + os.write_repeated_packed_int32(2, &self.span)?; + if let Some(v) = self.leading_comments.as_ref() { + os.write_string(3, v)?; + } + if let Some(v) = self.trailing_comments.as_ref() { + os.write_string(4, v)?; + } + for v in &self.leading_detached_comments { + os.write_string(6, &v)?; + }; + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Location { + Location::new() + } + + fn clear(&mut self) { + self.path.clear(); + self.span.clear(); + self.leading_comments = ::std::option::Option::None; + self.trailing_comments = ::std::option::Option::None; + self.leading_detached_comments.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Location { + static instance: Location = Location { + path: ::std::vec::Vec::new(), + span: ::std::vec::Vec::new(), + leading_comments: ::std::option::Option::None, + trailing_comments: ::std::option::Option::None, + leading_detached_comments: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl crate::Clear for SourceCodeInfo_Location { - fn clear(&mut self) { - self.path.clear(); - self.span.clear(); - self.leading_comments.clear(); - self.trailing_comments.clear(); - self.leading_detached_comments.clear(); - self.unknown_fields.clear(); + impl crate::MessageFull for Location { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("SourceCodeInfo.Location").unwrap()).clone() + } } -} -impl ::std::fmt::Debug for SourceCodeInfo_Location { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl ::std::fmt::Display for Location { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for SourceCodeInfo_Location { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl crate::reflect::ProtobufValue for Location { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Describes the relationship between generated code and its original source +/// file. A GeneratedCodeInfo message is associated with only one generated +/// source file, but may contain references to different source .proto files. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.GeneratedCodeInfo) pub struct GeneratedCodeInfo { // message fields - pub annotation: crate::RepeatedField<GeneratedCodeInfo_Annotation>, + /// An Annotation connects some span of text in generated code to an element + /// of its generating .proto file. + // @@protoc_insertion_point(field:google.protobuf.GeneratedCodeInfo.annotation) + pub annotation: ::std::vec::Vec<generated_code_info::Annotation>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.GeneratedCodeInfo.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a GeneratedCodeInfo { @@ -8958,51 +7752,37 @@ impl GeneratedCodeInfo { ::std::default::Default::default() } - // repeated .google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; - - - pub fn get_annotation(&self) -> &[GeneratedCodeInfo_Annotation] { - &self.annotation - } - pub fn clear_annotation(&mut self) { - self.annotation.clear(); - } - - // Param is passed by value, moved - pub fn set_annotation(&mut self, v: crate::RepeatedField<GeneratedCodeInfo_Annotation>) { - self.annotation = v; - } - - // Mutable pointer to the field. - pub fn mut_annotation(&mut self) -> &mut crate::RepeatedField<GeneratedCodeInfo_Annotation> { - &mut self.annotation - } - - // Take field - pub fn take_annotation(&mut self) -> crate::RepeatedField<GeneratedCodeInfo_Annotation> { - ::std::mem::replace(&mut self.annotation, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "annotation", + |m: &GeneratedCodeInfo| { &m.annotation }, + |m: &mut GeneratedCodeInfo| { &mut m.annotation }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<GeneratedCodeInfo>( + "GeneratedCodeInfo", + fields, + oneofs, + ) } } impl crate::Message for GeneratedCodeInfo { + const NAME: &'static str = "GeneratedCodeInfo"; + fn is_initialized(&self) -> bool { - for v in &self.annotation { - if !v.is_initialized() { - return false; - } - }; true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.annotation)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.annotation.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -9011,392 +7791,325 @@ impl crate::Message for GeneratedCodeInfo { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.annotation { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.annotation { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(1, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> GeneratedCodeInfo { GeneratedCodeInfo::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<GeneratedCodeInfo_Annotation>>( - "annotation", - |m: &GeneratedCodeInfo| { &m.annotation }, - |m: &mut GeneratedCodeInfo| { &mut m.annotation }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<GeneratedCodeInfo>( - "GeneratedCodeInfo", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.annotation.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static GeneratedCodeInfo { - static instance: crate::rt::LazyV2<GeneratedCodeInfo> = crate::rt::LazyV2::INIT; - instance.get(GeneratedCodeInfo::new) + static instance: GeneratedCodeInfo = GeneratedCodeInfo { + annotation: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for GeneratedCodeInfo { - fn clear(&mut self) { - self.annotation.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for GeneratedCodeInfo { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("GeneratedCodeInfo").unwrap()).clone() } } -impl ::std::fmt::Debug for GeneratedCodeInfo { +impl ::std::fmt::Display for GeneratedCodeInfo { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for GeneratedCodeInfo { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct GeneratedCodeInfo_Annotation { - // message fields - pub path: ::std::vec::Vec<i32>, - source_file: crate::SingularField<::std::string::String>, - begin: ::std::option::Option<i32>, - end: ::std::option::Option<i32>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a GeneratedCodeInfo_Annotation { - fn default() -> &'a GeneratedCodeInfo_Annotation { - <GeneratedCodeInfo_Annotation as crate::Message>::default_instance() - } -} - -impl GeneratedCodeInfo_Annotation { - pub fn new() -> GeneratedCodeInfo_Annotation { - ::std::default::Default::default() - } - - // repeated int32 path = 1; - - - pub fn get_path(&self) -> &[i32] { - &self.path - } - pub fn clear_path(&mut self) { - self.path.clear(); - } - - // Param is passed by value, moved - pub fn set_path(&mut self, v: ::std::vec::Vec<i32>) { - self.path = v; - } - - // Mutable pointer to the field. - pub fn mut_path(&mut self) -> &mut ::std::vec::Vec<i32> { - &mut self.path - } - - // Take field - pub fn take_path(&mut self) -> ::std::vec::Vec<i32> { - ::std::mem::replace(&mut self.path, ::std::vec::Vec::new()) - } - - // optional string source_file = 2; - - - pub fn get_source_file(&self) -> &str { - match self.source_file.as_ref() { - Some(v) => &v, - None => "", + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `GeneratedCodeInfo` +pub mod generated_code_info { + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.GeneratedCodeInfo.Annotation) + pub struct Annotation { + // message fields + /// Identifies the element in the original source .proto file. This field + /// is formatted the same as SourceCodeInfo.Location.path. + // @@protoc_insertion_point(field:google.protobuf.GeneratedCodeInfo.Annotation.path) + pub path: ::std::vec::Vec<i32>, + /// Identifies the filesystem path to the original source .proto. + // @@protoc_insertion_point(field:google.protobuf.GeneratedCodeInfo.Annotation.source_file) + pub source_file: ::std::option::Option<::std::string::String>, + /// Identifies the starting offset in bytes in the generated code + /// that relates to the identified object. + // @@protoc_insertion_point(field:google.protobuf.GeneratedCodeInfo.Annotation.begin) + pub begin: ::std::option::Option<i32>, + /// Identifies the ending offset in bytes in the generated code that + /// relates to the identified offset. The end offset should be one past + /// the last relevant byte (so the length of the text = end - begin). + // @@protoc_insertion_point(field:google.protobuf.GeneratedCodeInfo.Annotation.end) + pub end: ::std::option::Option<i32>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.GeneratedCodeInfo.Annotation.special_fields) + pub special_fields: crate::SpecialFields, + } + + impl<'a> ::std::default::Default for &'a Annotation { + fn default() -> &'a Annotation { + <Annotation as crate::Message>::default_instance() + } + } + + impl Annotation { + pub fn new() -> Annotation { + ::std::default::Default::default() + } + + // optional string source_file = 2; + + pub fn source_file(&self) -> &str { + match self.source_file.as_ref() { + Some(v) => v, + None => "", + } } - } - pub fn clear_source_file(&mut self) { - self.source_file.clear(); - } - - pub fn has_source_file(&self) -> bool { - self.source_file.is_some() - } - // Param is passed by value, moved - pub fn set_source_file(&mut self, v: ::std::string::String) { - self.source_file = crate::SingularField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_source_file(&mut self) -> &mut ::std::string::String { - if self.source_file.is_none() { - self.source_file.set_default(); + pub fn clear_source_file(&mut self) { + self.source_file = ::std::option::Option::None; } - self.source_file.as_mut().unwrap() - } - - // Take field - pub fn take_source_file(&mut self) -> ::std::string::String { - self.source_file.take().unwrap_or_else(|| ::std::string::String::new()) - } - - // optional int32 begin = 3; - - - pub fn get_begin(&self) -> i32 { - self.begin.unwrap_or(0) - } - pub fn clear_begin(&mut self) { - self.begin = ::std::option::Option::None; - } - - pub fn has_begin(&self) -> bool { - self.begin.is_some() - } - - // Param is passed by value, moved - pub fn set_begin(&mut self, v: i32) { - self.begin = ::std::option::Option::Some(v); - } - - // optional int32 end = 4; + pub fn has_source_file(&self) -> bool { + self.source_file.is_some() + } - pub fn get_end(&self) -> i32 { - self.end.unwrap_or(0) - } - pub fn clear_end(&mut self) { - self.end = ::std::option::Option::None; - } + // Param is passed by value, moved + pub fn set_source_file(&mut self, v: ::std::string::String) { + self.source_file = ::std::option::Option::Some(v); + } - pub fn has_end(&self) -> bool { - self.end.is_some() - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_source_file(&mut self) -> &mut ::std::string::String { + if self.source_file.is_none() { + self.source_file = ::std::option::Option::Some(::std::string::String::new()); + } + self.source_file.as_mut().unwrap() + } - // Param is passed by value, moved - pub fn set_end(&mut self, v: i32) { - self.end = ::std::option::Option::Some(v); - } -} + // Take field + pub fn take_source_file(&mut self) -> ::std::string::String { + self.source_file.take().unwrap_or_else(|| ::std::string::String::new()) + } -impl crate::Message for GeneratedCodeInfo_Annotation { - fn is_initialized(&self) -> bool { - true - } + // optional int32 begin = 3; - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_int32_into(wire_type, is, &mut self.path)?; - }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.source_file)?; - }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.begin = ::std::option::Option::Some(tmp); - }, - 4 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.end = ::std::option::Option::Some(tmp); - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; + pub fn begin(&self) -> i32 { + self.begin.unwrap_or(0) } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.path.is_empty() { - my_size += crate::rt::vec_packed_varint_size(1, &self.path); - } - if let Some(ref v) = self.source_file.as_ref() { - my_size += crate::rt::string_size(2, &v); - } - if let Some(v) = self.begin { - my_size += crate::rt::value_size(3, v, crate::wire_format::WireTypeVarint); + pub fn clear_begin(&mut self) { + self.begin = ::std::option::Option::None; } - if let Some(v) = self.end { - my_size += crate::rt::value_size(4, v, crate::wire_format::WireTypeVarint); - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.path.is_empty() { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - // TODO: Data size is computed again, it should be cached - os.write_raw_varint32(crate::rt::vec_packed_varint_data_size(&self.path))?; - for v in &self.path { - os.write_int32_no_tag(*v)?; - }; + pub fn has_begin(&self) -> bool { + self.begin.is_some() } - if let Some(ref v) = self.source_file.as_ref() { - os.write_string(2, &v)?; - } - if let Some(v) = self.begin { - os.write_int32(3, v)?; - } - if let Some(v) = self.end { - os.write_int32(4, v)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } + // Param is passed by value, moved + pub fn set_begin(&mut self, v: i32) { + self.begin = ::std::option::Option::Some(v); + } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } + // optional int32 end = 4; - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } + pub fn end(&self) -> i32 { + self.end.unwrap_or(0) + } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + pub fn clear_end(&mut self) { + self.end = ::std::option::Option::None; + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + pub fn has_end(&self) -> bool { + self.end.is_some() + } - fn new() -> GeneratedCodeInfo_Annotation { - GeneratedCodeInfo_Annotation::new() - } + // Param is passed by value, moved + pub fn set_end(&mut self, v: i32) { + self.end = ::std::option::Option::Some(v); + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_vec_accessor::<_, crate::types::ProtobufTypeInt32>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(4); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( "path", - |m: &GeneratedCodeInfo_Annotation| { &m.path }, - |m: &mut GeneratedCodeInfo_Annotation| { &mut m.path }, + |m: &Annotation| { &m.path }, + |m: &mut Annotation| { &mut m.path }, )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "source_file", - |m: &GeneratedCodeInfo_Annotation| { &m.source_file }, - |m: &mut GeneratedCodeInfo_Annotation| { &mut m.source_file }, + |m: &Annotation| { &m.source_file }, + |m: &mut Annotation| { &mut m.source_file }, )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "begin", - |m: &GeneratedCodeInfo_Annotation| { &m.begin }, - |m: &mut GeneratedCodeInfo_Annotation| { &mut m.begin }, + |m: &Annotation| { &m.begin }, + |m: &mut Annotation| { &mut m.begin }, )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "end", - |m: &GeneratedCodeInfo_Annotation| { &m.end }, - |m: &mut GeneratedCodeInfo_Annotation| { &mut m.end }, + |m: &Annotation| { &m.end }, + |m: &mut Annotation| { &mut m.end }, )); - crate::reflect::MessageDescriptor::new_pb_name::<GeneratedCodeInfo_Annotation>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<Annotation>( "GeneratedCodeInfo.Annotation", fields, - file_descriptor_proto() + oneofs, ) - }) + } } - fn default_instance() -> &'static GeneratedCodeInfo_Annotation { - static instance: crate::rt::LazyV2<GeneratedCodeInfo_Annotation> = crate::rt::LazyV2::INIT; - instance.get(GeneratedCodeInfo_Annotation::new) + impl crate::Message for Annotation { + const NAME: &'static str = "Annotation"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + is.read_repeated_packed_int32_into(&mut self.path)?; + }, + 8 => { + self.path.push(is.read_int32()?); + }, + 18 => { + self.source_file = ::std::option::Option::Some(is.read_string()?); + }, + 24 => { + self.begin = ::std::option::Option::Some(is.read_int32()?); + }, + 32 => { + self.end = ::std::option::Option::Some(is.read_int32()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + my_size += crate::rt::vec_packed_int32_size(1, &self.path); + if let Some(v) = self.source_file.as_ref() { + my_size += crate::rt::string_size(2, &v); + } + if let Some(v) = self.begin { + my_size += crate::rt::int32_size(3, v); + } + if let Some(v) = self.end { + my_size += crate::rt::int32_size(4, v); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + os.write_repeated_packed_int32(1, &self.path)?; + if let Some(v) = self.source_file.as_ref() { + os.write_string(2, v)?; + } + if let Some(v) = self.begin { + os.write_int32(3, v)?; + } + if let Some(v) = self.end { + os.write_int32(4, v)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Annotation { + Annotation::new() + } + + fn clear(&mut self) { + self.path.clear(); + self.source_file = ::std::option::Option::None; + self.begin = ::std::option::Option::None; + self.end = ::std::option::Option::None; + self.special_fields.clear(); + } + + fn default_instance() -> &'static Annotation { + static instance: Annotation = Annotation { + path: ::std::vec::Vec::new(), + source_file: ::std::option::Option::None, + begin: ::std::option::Option::None, + end: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl crate::Clear for GeneratedCodeInfo_Annotation { - fn clear(&mut self) { - self.path.clear(); - self.source_file.clear(); - self.begin = ::std::option::Option::None; - self.end = ::std::option::Option::None; - self.unknown_fields.clear(); + impl crate::MessageFull for Annotation { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("GeneratedCodeInfo.Annotation").unwrap()).clone() + } } -} -impl ::std::fmt::Debug for GeneratedCodeInfo_Annotation { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl ::std::fmt::Display for Annotation { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -impl crate::reflect::ProtobufValue for GeneratedCodeInfo_Annotation { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl crate::reflect::ProtobufValue for Annotation { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } } @@ -9504,75 +8217,76 @@ static file_descriptor_proto_data: &'static [u8] = b"\ $.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\":\n\x0cOp\ timizeMode\x12\t\n\x05SPEED\x10\x01\x12\r\n\tCODE_SIZE\x10\x02\x12\x10\n\ \x0cLITE_RUNTIME\x10\x03*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\ - &\x10'\"\xd1\x02\n\x0eMessageOptions\x12<\n\x17message_set_wire_format\ + &\x10'\"\xe3\x02\n\x0eMessageOptions\x12<\n\x17message_set_wire_format\ \x18\x01\x20\x01(\x08:\x05falseR\x14messageSetWireFormat\x12L\n\x1fno_st\ andard_descriptor_accessor\x18\x02\x20\x01(\x08:\x05falseR\x1cnoStandard\ DescriptorAccessor\x12%\n\ndeprecated\x18\x03\x20\x01(\x08:\x05falseR\nd\ eprecated\x12\x1b\n\tmap_entry\x18\x07\x20\x01(\x08R\x08mapEntry\x12X\n\ \x14uninterpreted_option\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.Unin\ terpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\ - \x80\x02J\x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xe2\x03\n\x0cFieldOptions\ - \x12A\n\x05ctype\x18\x01\x20\x01(\x0e2#.google.protobuf.FieldOptions.CTy\ - pe:\x06STRINGR\x05ctype\x12\x16\n\x06packed\x18\x02\x20\x01(\x08R\x06pac\ - ked\x12G\n\x06jstype\x18\x06\x20\x01(\x0e2$.google.protobuf.FieldOptions\ - .JSType:\tJS_NORMALR\x06jstype\x12\x19\n\x04lazy\x18\x05\x20\x01(\x08:\ - \x05falseR\x04lazy\x12%\n\ndeprecated\x18\x03\x20\x01(\x08:\x05falseR\nd\ - eprecated\x12\x19\n\x04weak\x18\n\x20\x01(\x08:\x05falseR\x04weak\x12X\n\ + \x80\x02J\x04\x08\x04\x10\x05J\x04\x08\x05\x10\x06J\x04\x08\x06\x10\x07J\ + \x04\x08\x08\x10\tJ\x04\x08\t\x10\n\"\xe2\x03\n\x0cFieldOptions\x12A\n\ + \x05ctype\x18\x01\x20\x01(\x0e2#.google.protobuf.FieldOptions.CType:\x06\ + STRINGR\x05ctype\x12\x16\n\x06packed\x18\x02\x20\x01(\x08R\x06packed\x12\ + G\n\x06jstype\x18\x06\x20\x01(\x0e2$.google.protobuf.FieldOptions.JSType\ + :\tJS_NORMALR\x06jstype\x12\x19\n\x04lazy\x18\x05\x20\x01(\x08:\x05false\ + R\x04lazy\x12%\n\ndeprecated\x18\x03\x20\x01(\x08:\x05falseR\ndeprecated\ + \x12\x19\n\x04weak\x18\n\x20\x01(\x08:\x05falseR\x04weak\x12X\n\x14unint\ + erpreted_option\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.Uninterpreted\ + OptionR\x13uninterpretedOption\"/\n\x05CType\x12\n\n\x06STRING\x10\0\x12\ + \x08\n\x04CORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\x06JSType\ + \x12\r\n\tJS_NORMAL\x10\0\x12\r\n\tJS_STRING\x10\x01\x12\r\n\tJS_NUMBER\ + \x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\x10\x05\"s\ + \n\x0cOneofOptions\x12X\n\x14uninterpreted_option\x18\xe7\x07\x20\x03(\ + \x0b2$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption*\t\ + \x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xc0\x01\n\x0bEnumOptions\x12\x1f\ + \n\x0ballow_alias\x18\x02\x20\x01(\x08R\nallowAlias\x12%\n\ndeprecated\ + \x18\x03\x20\x01(\x08:\x05falseR\ndeprecated\x12X\n\x14uninterpreted_opt\ + ion\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.UninterpretedOptionR\x13u\ + ninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x05\ + \x10\x06\"\x9e\x01\n\x10EnumValueOptions\x12%\n\ndeprecated\x18\x01\x20\ + \x01(\x08:\x05falseR\ndeprecated\x12X\n\x14uninterpreted_option\x18\xe7\ + \x07\x20\x03(\x0b2$.google.protobuf.UninterpretedOptionR\x13uninterprete\ + dOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9c\x01\n\x0eServiceOpt\ + ions\x12%\n\ndeprecated\x18!\x20\x01(\x08:\x05falseR\ndeprecated\x12X\n\ \x14uninterpreted_option\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.Unin\ - terpretedOptionR\x13uninterpretedOption\"/\n\x05CType\x12\n\n\x06STRING\ - \x10\0\x12\x08\n\x04CORD\x10\x01\x12\x10\n\x0cSTRING_PIECE\x10\x02\"5\n\ - \x06JSType\x12\r\n\tJS_NORMAL\x10\0\x12\r\n\tJS_STRING\x10\x01\x12\r\n\t\ - JS_NUMBER\x10\x02*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\x04\ - \x10\x05\"s\n\x0cOneofOptions\x12X\n\x14uninterpreted_option\x18\xe7\x07\ - \x20\x03(\x0b2$.google.protobuf.UninterpretedOptionR\x13uninterpretedOpt\ - ion*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\xc0\x01\n\x0bEnumOptions\ - \x12\x1f\n\x0ballow_alias\x18\x02\x20\x01(\x08R\nallowAlias\x12%\n\ndepr\ - ecated\x18\x03\x20\x01(\x08:\x05falseR\ndeprecated\x12X\n\x14uninterpret\ - ed_option\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.UninterpretedOption\ - R\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02J\x04\x08\ - \x05\x10\x06\"\x9e\x01\n\x10EnumValueOptions\x12%\n\ndeprecated\x18\x01\ - \x20\x01(\x08:\x05falseR\ndeprecated\x12X\n\x14uninterpreted_option\x18\ - \xe7\x07\x20\x03(\x0b2$.google.protobuf.UninterpretedOptionR\x13uninterp\ - retedOption*\t\x08\xe8\x07\x10\x80\x80\x80\x80\x02\"\x9c\x01\n\x0eServic\ - eOptions\x12%\n\ndeprecated\x18!\x20\x01(\x08:\x05falseR\ndeprecated\x12\ - X\n\x14uninterpreted_option\x18\xe7\x07\x20\x03(\x0b2$.google.protobuf.U\ - ninterpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\ - \x80\x80\x02\"\xe0\x02\n\rMethodOptions\x12%\n\ndeprecated\x18!\x20\x01(\ - \x08:\x05falseR\ndeprecated\x12q\n\x11idempotency_level\x18\"\x20\x01(\ - \x0e2/.google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UN\ - KNOWNR\x10idempotencyLevel\x12X\n\x14uninterpreted_option\x18\xe7\x07\ - \x20\x03(\x0b2$.google.protobuf.UninterpretedOptionR\x13uninterpretedOpt\ - ion\"P\n\x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\0\x12\ - \x13\n\x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\ - \xe8\x07\x10\x80\x80\x80\x80\x02\"\x9a\x03\n\x13UninterpretedOption\x12A\ - \n\x04name\x18\x02\x20\x03(\x0b2-.google.protobuf.UninterpretedOption.Na\ - mePartR\x04name\x12)\n\x10identifier_value\x18\x03\x20\x01(\tR\x0fidenti\ - fierValue\x12,\n\x12positive_int_value\x18\x04\x20\x01(\x04R\x10positive\ - IntValue\x12,\n\x12negative_int_value\x18\x05\x20\x01(\x03R\x10negativeI\ - ntValue\x12!\n\x0cdouble_value\x18\x06\x20\x01(\x01R\x0bdoubleValue\x12!\ - \n\x0cstring_value\x18\x07\x20\x01(\x0cR\x0bstringValue\x12'\n\x0faggreg\ - ate_value\x18\x08\x20\x01(\tR\x0eaggregateValue\x1aJ\n\x08NamePart\x12\ - \x1b\n\tname_part\x18\x01\x20\x02(\tR\x08namePart\x12!\n\x0cis_extension\ - \x18\x02\x20\x02(\x08R\x0bisExtension\"\xa7\x02\n\x0eSourceCodeInfo\x12D\ - \n\x08location\x18\x01\x20\x03(\x0b2(.google.protobuf.SourceCodeInfo.Loc\ - ationR\x08location\x1a\xce\x01\n\x08Location\x12\x16\n\x04path\x18\x01\ - \x20\x03(\x05R\x04pathB\x02\x10\x01\x12\x16\n\x04span\x18\x02\x20\x03(\ - \x05R\x04spanB\x02\x10\x01\x12)\n\x10leading_comments\x18\x03\x20\x01(\t\ - R\x0fleadingComments\x12+\n\x11trailing_comments\x18\x04\x20\x01(\tR\x10\ - trailingComments\x12:\n\x19leading_detached_comments\x18\x06\x20\x03(\tR\ - \x17leadingDetachedComments\"\xd1\x01\n\x11GeneratedCodeInfo\x12M\n\nann\ - otation\x18\x01\x20\x03(\x0b2-.google.protobuf.GeneratedCodeInfo.Annotat\ - ionR\nannotation\x1am\n\nAnnotation\x12\x16\n\x04path\x18\x01\x20\x03(\ - \x05R\x04pathB\x02\x10\x01\x12\x1f\n\x0bsource_file\x18\x02\x20\x01(\tR\ - \nsourceFile\x12\x14\n\x05begin\x18\x03\x20\x01(\x05R\x05begin\x12\x10\n\ - \x03end\x18\x04\x20\x01(\x05R\x03endB~\n\x13com.google.protobufB\x10Desc\ - riptorProtosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\ - \x01\xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.ReflectionJ\xbc\xc8\x02\n\ - \x07\x12\x05'\0\x8c\x07\x01\n\xaa\x0f\n\x01\x0c\x12\x03'\0\x122\xc1\x0c\ - \x20Protocol\x20Buffers\x20-\x20Google's\x20data\x20interchange\x20forma\ - t\n\x20Copyright\x202008\x20Google\x20Inc.\x20\x20All\x20rights\x20reser\ - ved.\n\x20https://developers.google.com/protocol-buffers/\n\n\x20Redistr\ - ibution\x20and\x20use\x20in\x20source\x20and\x20binary\x20forms,\x20with\ + terpretedOptionR\x13uninterpretedOption*\t\x08\xe8\x07\x10\x80\x80\x80\ + \x80\x02\"\xe0\x02\n\rMethodOptions\x12%\n\ndeprecated\x18!\x20\x01(\x08\ + :\x05falseR\ndeprecated\x12q\n\x11idempotency_level\x18\"\x20\x01(\x0e2/\ + .google.protobuf.MethodOptions.IdempotencyLevel:\x13IDEMPOTENCY_UNKNOWNR\ + \x10idempotencyLevel\x12X\n\x14uninterpreted_option\x18\xe7\x07\x20\x03(\ + \x0b2$.google.protobuf.UninterpretedOptionR\x13uninterpretedOption\"P\n\ + \x10IdempotencyLevel\x12\x17\n\x13IDEMPOTENCY_UNKNOWN\x10\0\x12\x13\n\ + \x0fNO_SIDE_EFFECTS\x10\x01\x12\x0e\n\nIDEMPOTENT\x10\x02*\t\x08\xe8\x07\ + \x10\x80\x80\x80\x80\x02\"\x9a\x03\n\x13UninterpretedOption\x12A\n\x04na\ + me\x18\x02\x20\x03(\x0b2-.google.protobuf.UninterpretedOption.NamePartR\ + \x04name\x12)\n\x10identifier_value\x18\x03\x20\x01(\tR\x0fidentifierVal\ + ue\x12,\n\x12positive_int_value\x18\x04\x20\x01(\x04R\x10positiveIntValu\ + e\x12,\n\x12negative_int_value\x18\x05\x20\x01(\x03R\x10negativeIntValue\ + \x12!\n\x0cdouble_value\x18\x06\x20\x01(\x01R\x0bdoubleValue\x12!\n\x0cs\ + tring_value\x18\x07\x20\x01(\x0cR\x0bstringValue\x12'\n\x0faggregate_val\ + ue\x18\x08\x20\x01(\tR\x0eaggregateValue\x1aJ\n\x08NamePart\x12\x1b\n\tn\ + ame_part\x18\x01\x20\x02(\tR\x08namePart\x12!\n\x0cis_extension\x18\x02\ + \x20\x02(\x08R\x0bisExtension\"\xa7\x02\n\x0eSourceCodeInfo\x12D\n\x08lo\ + cation\x18\x01\x20\x03(\x0b2(.google.protobuf.SourceCodeInfo.LocationR\ + \x08location\x1a\xce\x01\n\x08Location\x12\x16\n\x04path\x18\x01\x20\x03\ + (\x05R\x04pathB\x02\x10\x01\x12\x16\n\x04span\x18\x02\x20\x03(\x05R\x04s\ + panB\x02\x10\x01\x12)\n\x10leading_comments\x18\x03\x20\x01(\tR\x0fleadi\ + ngComments\x12+\n\x11trailing_comments\x18\x04\x20\x01(\tR\x10trailingCo\ + mments\x12:\n\x19leading_detached_comments\x18\x06\x20\x03(\tR\x17leadin\ + gDetachedComments\"\xd1\x01\n\x11GeneratedCodeInfo\x12M\n\nannotation\ + \x18\x01\x20\x03(\x0b2-.google.protobuf.GeneratedCodeInfo.AnnotationR\na\ + nnotation\x1am\n\nAnnotation\x12\x16\n\x04path\x18\x01\x20\x03(\x05R\x04\ + pathB\x02\x10\x01\x12\x1f\n\x0bsource_file\x18\x02\x20\x01(\tR\nsourceFi\ + le\x12\x14\n\x05begin\x18\x03\x20\x01(\x05R\x05begin\x12\x10\n\x03end\ + \x18\x04\x20\x01(\x05R\x03endB~\n\x13com.google.protobufB\x10DescriptorP\ + rotosH\x01Z-google.golang.org/protobuf/types/descriptorpb\xf8\x01\x01\ + \xa2\x02\x03GPB\xaa\x02\x1aGoogle.Protobuf.ReflectionJ\x82\xca\x02\n\x07\ + \x12\x05'\0\x8e\x07\x01\n\xaa\x0f\n\x01\x0c\x12\x03'\0\x122\xc1\x0c\x20P\ + rotocol\x20Buffers\x20-\x20Google's\x20data\x20interchange\x20format\n\ + \x20Copyright\x202008\x20Google\x20Inc.\x20\x20All\x20rights\x20reserved\ + .\n\x20https://developers.google.com/protocol-buffers/\n\n\x20Redistribu\ + tion\x20and\x20use\x20in\x20source\x20and\x20binary\x20forms,\x20with\ \x20or\x20without\n\x20modification,\x20are\x20permitted\x20provided\x20\ that\x20the\x20following\x20conditions\x20are\n\x20met:\n\n\x20\x20\x20\ \x20\x20*\x20Redistributions\x20of\x20source\x20code\x20must\x20retain\ @@ -10073,53 +8787,54 @@ static file_descriptor_proto_data: &'static [u8] = b"\ t\x20normally\x20start\x20with\x20backwards\n\x20domain\x20names.\n\n\r\ \n\x05\x04\n\x02\0\x04\x12\x04\xdb\x02\x02\n\n\r\n\x05\x04\n\x02\0\x05\ \x12\x04\xdb\x02\x0b\x11\n\r\n\x05\x04\n\x02\0\x01\x12\x04\xdb\x02\x12\ - \x1e\n\r\n\x05\x04\n\x02\0\x03\x12\x04\xdb\x02!\"\n\xbf\x02\n\x04\x04\n\ - \x02\x01\x12\x04\xe3\x02\x02+\x1a\xb0\x02\x20If\x20set,\x20all\x20the\ - \x20classes\x20from\x20the\x20.proto\x20file\x20are\x20wrapped\x20in\x20\ - a\x20single\n\x20outer\x20class\x20with\x20the\x20given\x20name.\x20\x20\ - This\x20applies\x20to\x20both\x20Proto1\n\x20(equivalent\x20to\x20the\ - \x20old\x20\"--one_java_file\"\x20option)\x20and\x20Proto2\x20(where\n\ - \x20a\x20.proto\x20always\x20translates\x20to\x20a\x20single\x20class,\ - \x20but\x20you\x20may\x20want\x20to\n\x20explicitly\x20choose\x20the\x20\ - class\x20name).\n\n\r\n\x05\x04\n\x02\x01\x04\x12\x04\xe3\x02\x02\n\n\r\ - \n\x05\x04\n\x02\x01\x05\x12\x04\xe3\x02\x0b\x11\n\r\n\x05\x04\n\x02\x01\ - \x01\x12\x04\xe3\x02\x12&\n\r\n\x05\x04\n\x02\x01\x03\x12\x04\xe3\x02)*\ - \n\xa3\x03\n\x04\x04\n\x02\x02\x12\x04\xeb\x02\x02;\x1a\x94\x03\x20If\ - \x20set\x20true,\x20then\x20the\x20Java\x20code\x20generator\x20will\x20\ - generate\x20a\x20separate\x20.java\n\x20file\x20for\x20each\x20top-level\ - \x20message,\x20enum,\x20and\x20service\x20defined\x20in\x20the\x20.prot\ - o\n\x20file.\x20\x20Thus,\x20these\x20types\x20will\x20*not*\x20be\x20ne\ - sted\x20inside\x20the\x20outer\x20class\n\x20named\x20by\x20java_outer_c\ - lassname.\x20\x20However,\x20the\x20outer\x20class\x20will\x20still\x20b\ - e\n\x20generated\x20to\x20contain\x20the\x20file's\x20getDescriptor()\ - \x20method\x20as\x20well\x20as\x20any\n\x20top-level\x20extensions\x20de\ - fined\x20in\x20the\x20file.\n\n\r\n\x05\x04\n\x02\x02\x04\x12\x04\xeb\ - \x02\x02\n\n\r\n\x05\x04\n\x02\x02\x05\x12\x04\xeb\x02\x0b\x0f\n\r\n\x05\ - \x04\n\x02\x02\x01\x12\x04\xeb\x02\x10#\n\r\n\x05\x04\n\x02\x02\x03\x12\ - \x04\xeb\x02&(\n\r\n\x05\x04\n\x02\x02\x08\x12\x04\xeb\x02):\n\r\n\x05\ - \x04\n\x02\x02\x07\x12\x04\xeb\x0249\n)\n\x04\x04\n\x02\x03\x12\x04\xee\ - \x02\x02E\x1a\x1b\x20This\x20option\x20does\x20nothing.\n\n\r\n\x05\x04\ - \n\x02\x03\x04\x12\x04\xee\x02\x02\n\n\r\n\x05\x04\n\x02\x03\x05\x12\x04\ - \xee\x02\x0b\x0f\n\r\n\x05\x04\n\x02\x03\x01\x12\x04\xee\x02\x10-\n\r\n\ - \x05\x04\n\x02\x03\x03\x12\x04\xee\x0202\n\r\n\x05\x04\n\x02\x03\x08\x12\ - \x04\xee\x023D\n\x0e\n\x06\x04\n\x02\x03\x08\x03\x12\x04\xee\x024C\n\xe6\ - \x02\n\x04\x04\n\x02\x04\x12\x04\xf6\x02\x02>\x1a\xd7\x02\x20If\x20set\ - \x20true,\x20then\x20the\x20Java2\x20code\x20generator\x20will\x20genera\ - te\x20code\x20that\n\x20throws\x20an\x20exception\x20whenever\x20an\x20a\ - ttempt\x20is\x20made\x20to\x20assign\x20a\x20non-UTF-8\n\x20byte\x20sequ\ - ence\x20to\x20a\x20string\x20field.\n\x20Message\x20reflection\x20will\ - \x20do\x20the\x20same.\n\x20However,\x20an\x20extension\x20field\x20stil\ - l\x20accepts\x20non-UTF-8\x20byte\x20sequences.\n\x20This\x20option\x20h\ - as\x20no\x20effect\x20on\x20when\x20used\x20with\x20the\x20lite\x20runti\ - me.\n\n\r\n\x05\x04\n\x02\x04\x04\x12\x04\xf6\x02\x02\n\n\r\n\x05\x04\n\ - \x02\x04\x05\x12\x04\xf6\x02\x0b\x0f\n\r\n\x05\x04\n\x02\x04\x01\x12\x04\ - \xf6\x02\x10&\n\r\n\x05\x04\n\x02\x04\x03\x12\x04\xf6\x02)+\n\r\n\x05\ - \x04\n\x02\x04\x08\x12\x04\xf6\x02,=\n\r\n\x05\x04\n\x02\x04\x07\x12\x04\ - \xf6\x027<\nL\n\x04\x04\n\x04\0\x12\x06\xfa\x02\x02\xff\x02\x03\x1a<\x20\ - Generated\x20classes\x20can\x20be\x20optimized\x20for\x20speed\x20or\x20\ - code\x20size.\n\n\r\n\x05\x04\n\x04\0\x01\x12\x04\xfa\x02\x07\x13\nD\n\ - \x06\x04\n\x04\0\x02\0\x12\x04\xfb\x02\x04\x0e\"4\x20Generate\x20complet\ - e\x20code\x20for\x20parsing,\x20serialization,\n\n\x0f\n\x07\x04\n\x04\0\ + \x1e\n\r\n\x05\x04\n\x02\0\x03\x12\x04\xdb\x02!\"\n\xf1\x02\n\x04\x04\n\ + \x02\x01\x12\x04\xe3\x02\x02+\x1a\xe2\x02\x20Controls\x20the\x20name\x20\ + of\x20the\x20wrapper\x20Java\x20class\x20generated\x20for\x20the\x20.pro\ + to\x20file.\n\x20That\x20class\x20will\x20always\x20contain\x20the\x20.p\ + roto\x20file's\x20getDescriptor()\x20method\x20as\n\x20well\x20as\x20any\ + \x20top-level\x20extensions\x20defined\x20in\x20the\x20.proto\x20file.\n\ + \x20If\x20java_multiple_files\x20is\x20disabled,\x20then\x20all\x20the\ + \x20other\x20classes\x20from\x20the\n\x20.proto\x20file\x20will\x20be\ + \x20nested\x20inside\x20the\x20single\x20wrapper\x20outer\x20class.\n\n\ + \r\n\x05\x04\n\x02\x01\x04\x12\x04\xe3\x02\x02\n\n\r\n\x05\x04\n\x02\x01\ + \x05\x12\x04\xe3\x02\x0b\x11\n\r\n\x05\x04\n\x02\x01\x01\x12\x04\xe3\x02\ + \x12&\n\r\n\x05\x04\n\x02\x01\x03\x12\x04\xe3\x02)*\n\xa6\x03\n\x04\x04\ + \n\x02\x02\x12\x04\xeb\x02\x02;\x1a\x97\x03\x20If\x20enabled,\x20then\ + \x20the\x20Java\x20code\x20generator\x20will\x20generate\x20a\x20separat\ + e\x20.java\n\x20file\x20for\x20each\x20top-level\x20message,\x20enum,\ + \x20and\x20service\x20defined\x20in\x20the\x20.proto\n\x20file.\x20\x20T\ + hus,\x20these\x20types\x20will\x20*not*\x20be\x20nested\x20inside\x20the\ + \x20wrapper\x20class\n\x20named\x20by\x20java_outer_classname.\x20\x20Ho\ + wever,\x20the\x20wrapper\x20class\x20will\x20still\x20be\n\x20generated\ + \x20to\x20contain\x20the\x20file's\x20getDescriptor()\x20method\x20as\ + \x20well\x20as\x20any\n\x20top-level\x20extensions\x20defined\x20in\x20t\ + he\x20file.\n\n\r\n\x05\x04\n\x02\x02\x04\x12\x04\xeb\x02\x02\n\n\r\n\ + \x05\x04\n\x02\x02\x05\x12\x04\xeb\x02\x0b\x0f\n\r\n\x05\x04\n\x02\x02\ + \x01\x12\x04\xeb\x02\x10#\n\r\n\x05\x04\n\x02\x02\x03\x12\x04\xeb\x02&(\ + \n\r\n\x05\x04\n\x02\x02\x08\x12\x04\xeb\x02):\n\r\n\x05\x04\n\x02\x02\ + \x07\x12\x04\xeb\x0249\n)\n\x04\x04\n\x02\x03\x12\x04\xee\x02\x02E\x1a\ + \x1b\x20This\x20option\x20does\x20nothing.\n\n\r\n\x05\x04\n\x02\x03\x04\ + \x12\x04\xee\x02\x02\n\n\r\n\x05\x04\n\x02\x03\x05\x12\x04\xee\x02\x0b\ + \x0f\n\r\n\x05\x04\n\x02\x03\x01\x12\x04\xee\x02\x10-\n\r\n\x05\x04\n\ + \x02\x03\x03\x12\x04\xee\x0202\n\r\n\x05\x04\n\x02\x03\x08\x12\x04\xee\ + \x023D\n\x0e\n\x06\x04\n\x02\x03\x08\x03\x12\x04\xee\x024C\n\xe6\x02\n\ + \x04\x04\n\x02\x04\x12\x04\xf6\x02\x02>\x1a\xd7\x02\x20If\x20set\x20true\ + ,\x20then\x20the\x20Java2\x20code\x20generator\x20will\x20generate\x20co\ + de\x20that\n\x20throws\x20an\x20exception\x20whenever\x20an\x20attempt\ + \x20is\x20made\x20to\x20assign\x20a\x20non-UTF-8\n\x20byte\x20sequence\ + \x20to\x20a\x20string\x20field.\n\x20Message\x20reflection\x20will\x20do\ + \x20the\x20same.\n\x20However,\x20an\x20extension\x20field\x20still\x20a\ + ccepts\x20non-UTF-8\x20byte\x20sequences.\n\x20This\x20option\x20has\x20\ + no\x20effect\x20on\x20when\x20used\x20with\x20the\x20lite\x20runtime.\n\ + \n\r\n\x05\x04\n\x02\x04\x04\x12\x04\xf6\x02\x02\n\n\r\n\x05\x04\n\x02\ + \x04\x05\x12\x04\xf6\x02\x0b\x0f\n\r\n\x05\x04\n\x02\x04\x01\x12\x04\xf6\ + \x02\x10&\n\r\n\x05\x04\n\x02\x04\x03\x12\x04\xf6\x02)+\n\r\n\x05\x04\n\ + \x02\x04\x08\x12\x04\xf6\x02,=\n\r\n\x05\x04\n\x02\x04\x07\x12\x04\xf6\ + \x027<\nL\n\x04\x04\n\x04\0\x12\x06\xfa\x02\x02\xff\x02\x03\x1a<\x20Gene\ + rated\x20classes\x20can\x20be\x20optimized\x20for\x20speed\x20or\x20code\ + \x20size.\n\n\r\n\x05\x04\n\x04\0\x01\x12\x04\xfa\x02\x07\x13\nD\n\x06\ + \x04\n\x04\0\x02\0\x12\x04\xfb\x02\x04\x0e\"4\x20Generate\x20complete\ + \x20code\x20for\x20parsing,\x20serialization,\n\n\x0f\n\x07\x04\n\x04\0\ \x02\0\x01\x12\x04\xfb\x02\x04\t\n\x0f\n\x07\x04\n\x04\0\x02\0\x02\x12\ \x04\xfb\x02\x0c\r\nG\n\x06\x04\n\x04\0\x02\x01\x12\x04\xfd\x02\x04\x12\ \x1a\x06\x20etc.\n\"/\x20Use\x20ReflectionOps\x20to\x20implement\x20thes\ @@ -10254,7 +8969,7 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \xcd\x03\r\x11\n\r\n\x05\x04\n\x05\0\x02\x12\x04\xcd\x03\x15\x18\n\x0b\n\ \x03\x04\n\t\x12\x04\xcf\x03\x02\x0e\n\x0c\n\x04\x04\n\t\0\x12\x04\xcf\ \x03\x0b\r\n\r\n\x05\x04\n\t\0\x01\x12\x04\xcf\x03\x0b\r\n\r\n\x05\x04\n\ - \t\0\x02\x12\x04\xcf\x03\x0b\r\n\x0c\n\x02\x04\x0b\x12\x06\xd2\x03\0\x92\ + \t\0\x02\x12\x04\xcf\x03\x0b\r\n\x0c\n\x02\x04\x0b\x12\x06\xd2\x03\0\x94\ \x04\x01\n\x0b\n\x03\x04\x0b\x01\x12\x04\xd2\x03\x08\x16\n\xd8\x05\n\x04\ \x04\x0b\x02\0\x12\x04\xe5\x03\x02>\x1a\xc9\x05\x20Set\x20true\x20to\x20\ use\x20the\x20old\x20proto1\x20MessageSet\x20wire\x20format\x20for\x20ex\ @@ -10295,68 +9010,75 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x03\x02\n\n\r\n\x05\x04\x0b\x02\x02\x05\x12\x04\xf0\x03\x0b\x0f\n\r\n\ \x05\x04\x0b\x02\x02\x01\x12\x04\xf0\x03\x10\x1a\n\r\n\x05\x04\x0b\x02\ \x02\x03\x12\x04\xf0\x03\x1d\x1e\n\r\n\x05\x04\x0b\x02\x02\x08\x12\x04\ - \xf0\x03\x1f0\n\r\n\x05\x04\x0b\x02\x02\x07\x12\x04\xf0\x03*/\n\xa0\x06\ - \n\x04\x04\x0b\x02\x03\x12\x04\x87\x04\x02\x1e\x1a\x91\x06\x20Whether\ - \x20the\x20message\x20is\x20an\x20automatically\x20generated\x20map\x20e\ - ntry\x20type\x20for\x20the\n\x20maps\x20field.\n\n\x20For\x20maps\x20fie\ - lds:\n\x20\x20\x20\x20\x20map<KeyType,\x20ValueType>\x20map_field\x20=\ - \x201;\n\x20The\x20parsed\x20descriptor\x20looks\x20like:\n\x20\x20\x20\ - \x20\x20message\x20MapFieldEntry\x20{\n\x20\x20\x20\x20\x20\x20\x20\x20\ - \x20option\x20map_entry\x20=\x20true;\n\x20\x20\x20\x20\x20\x20\x20\x20\ - \x20optional\x20KeyType\x20key\x20=\x201;\n\x20\x20\x20\x20\x20\x20\x20\ - \x20\x20optional\x20ValueType\x20value\x20=\x202;\n\x20\x20\x20\x20\x20}\ - \n\x20\x20\x20\x20\x20repeated\x20MapFieldEntry\x20map_field\x20=\x201;\ - \n\n\x20Implementations\x20may\x20choose\x20not\x20to\x20generate\x20the\ - \x20map_entry=true\x20message,\x20but\n\x20use\x20a\x20native\x20map\x20\ - in\x20the\x20target\x20language\x20to\x20hold\x20the\x20keys\x20and\x20v\ - alues.\n\x20The\x20reflection\x20APIs\x20in\x20such\x20implementations\ - \x20still\x20need\x20to\x20work\x20as\n\x20if\x20the\x20field\x20is\x20a\ - \x20repeated\x20message\x20field.\n\n\x20NOTE:\x20Do\x20not\x20set\x20th\ - e\x20option\x20in\x20.proto\x20files.\x20Always\x20use\x20the\x20maps\ - \x20syntax\n\x20instead.\x20The\x20option\x20should\x20only\x20be\x20imp\ - licitly\x20set\x20by\x20the\x20proto\x20compiler\n\x20parser.\n\n\r\n\ - \x05\x04\x0b\x02\x03\x04\x12\x04\x87\x04\x02\n\n\r\n\x05\x04\x0b\x02\x03\ - \x05\x12\x04\x87\x04\x0b\x0f\n\r\n\x05\x04\x0b\x02\x03\x01\x12\x04\x87\ - \x04\x10\x19\n\r\n\x05\x04\x0b\x02\x03\x03\x12\x04\x87\x04\x1c\x1d\n$\n\ - \x03\x04\x0b\t\x12\x04\x89\x04\x02\r\"\x17\x20javalite_serializable\n\n\ - \x0c\n\x04\x04\x0b\t\0\x12\x04\x89\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\0\x01\ - \x12\x04\x89\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\0\x02\x12\x04\x89\x04\x0b\ - \x0c\n\x1f\n\x03\x04\x0b\t\x12\x04\x8a\x04\x02\r\"\x12\x20javanano_as_li\ - te\n\n\x0c\n\x04\x04\x0b\t\x01\x12\x04\x8a\x04\x0b\x0c\n\r\n\x05\x04\x0b\ - \t\x01\x01\x12\x04\x8a\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\x01\x02\x12\x04\ - \x8a\x04\x0b\x0c\nO\n\x04\x04\x0b\x02\x04\x12\x04\x8e\x04\x02:\x1aA\x20T\ - he\x20parser\x20stores\x20options\x20it\x20doesn't\x20recognize\x20here.\ - \x20See\x20above.\n\n\r\n\x05\x04\x0b\x02\x04\x04\x12\x04\x8e\x04\x02\n\ - \n\r\n\x05\x04\x0b\x02\x04\x06\x12\x04\x8e\x04\x0b\x1e\n\r\n\x05\x04\x0b\ - \x02\x04\x01\x12\x04\x8e\x04\x1f3\n\r\n\x05\x04\x0b\x02\x04\x03\x12\x04\ - \x8e\x0469\nZ\n\x03\x04\x0b\x05\x12\x04\x91\x04\x02\x19\x1aM\x20Clients\ - \x20can\x20define\x20custom\x20options\x20in\x20extensions\x20of\x20this\ - \x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x0b\x05\0\x12\x04\x91\ - \x04\r\x18\n\r\n\x05\x04\x0b\x05\0\x01\x12\x04\x91\x04\r\x11\n\r\n\x05\ - \x04\x0b\x05\0\x02\x12\x04\x91\x04\x15\x18\n\x0c\n\x02\x04\x0c\x12\x06\ - \x94\x04\0\xef\x04\x01\n\x0b\n\x03\x04\x0c\x01\x12\x04\x94\x04\x08\x14\n\ - \xa3\x02\n\x04\x04\x0c\x02\0\x12\x04\x99\x04\x02.\x1a\x94\x02\x20The\x20\ - ctype\x20option\x20instructs\x20the\x20C++\x20code\x20generator\x20to\ - \x20use\x20a\x20different\n\x20representation\x20of\x20the\x20field\x20t\ - han\x20it\x20normally\x20would.\x20\x20See\x20the\x20specific\n\x20optio\ - ns\x20below.\x20\x20This\x20option\x20is\x20not\x20yet\x20implemented\ - \x20in\x20the\x20open\x20source\n\x20release\x20--\x20sorry,\x20we'll\ - \x20try\x20to\x20include\x20it\x20in\x20a\x20future\x20version!\n\n\r\n\ - \x05\x04\x0c\x02\0\x04\x12\x04\x99\x04\x02\n\n\r\n\x05\x04\x0c\x02\0\x06\ - \x12\x04\x99\x04\x0b\x10\n\r\n\x05\x04\x0c\x02\0\x01\x12\x04\x99\x04\x11\ - \x16\n\r\n\x05\x04\x0c\x02\0\x03\x12\x04\x99\x04\x19\x1a\n\r\n\x05\x04\ - \x0c\x02\0\x08\x12\x04\x99\x04\x1b-\n\r\n\x05\x04\x0c\x02\0\x07\x12\x04\ - \x99\x04&,\n\x0e\n\x04\x04\x0c\x04\0\x12\x06\x9a\x04\x02\xa1\x04\x03\n\r\ - \n\x05\x04\x0c\x04\0\x01\x12\x04\x9a\x04\x07\x0c\n\x1f\n\x06\x04\x0c\x04\ - \0\x02\0\x12\x04\x9c\x04\x04\x0f\x1a\x0f\x20Default\x20mode.\n\n\x0f\n\ - \x07\x04\x0c\x04\0\x02\0\x01\x12\x04\x9c\x04\x04\n\n\x0f\n\x07\x04\x0c\ - \x04\0\x02\0\x02\x12\x04\x9c\x04\r\x0e\n\x0e\n\x06\x04\x0c\x04\0\x02\x01\ - \x12\x04\x9e\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\0\x02\x01\x01\x12\x04\x9e\ - \x04\x04\x08\n\x0f\n\x07\x04\x0c\x04\0\x02\x01\x02\x12\x04\x9e\x04\x0b\ - \x0c\n\x0e\n\x06\x04\x0c\x04\0\x02\x02\x12\x04\xa0\x04\x04\x15\n\x0f\n\ - \x07\x04\x0c\x04\0\x02\x02\x01\x12\x04\xa0\x04\x04\x10\n\x0f\n\x07\x04\ - \x0c\x04\0\x02\x02\x02\x12\x04\xa0\x04\x13\x14\n\xda\x02\n\x04\x04\x0c\ - \x02\x01\x12\x04\xa7\x04\x02\x1b\x1a\xcb\x02\x20The\x20packed\x20option\ + \xf0\x03\x1f0\n\r\n\x05\x04\x0b\x02\x02\x07\x12\x04\xf0\x03*/\n\x0b\n\ + \x03\x04\x0b\t\x12\x04\xf2\x03\x02\x13\n\x0c\n\x04\x04\x0b\t\0\x12\x04\ + \xf2\x03\x0b\x0c\n\r\n\x05\x04\x0b\t\0\x01\x12\x04\xf2\x03\x0b\x0c\n\r\n\ + \x05\x04\x0b\t\0\x02\x12\x04\xf2\x03\x0b\x0c\n\x0c\n\x04\x04\x0b\t\x01\ + \x12\x04\xf2\x03\x0e\x0f\n\r\n\x05\x04\x0b\t\x01\x01\x12\x04\xf2\x03\x0e\ + \x0f\n\r\n\x05\x04\x0b\t\x01\x02\x12\x04\xf2\x03\x0e\x0f\n\x0c\n\x04\x04\ + \x0b\t\x02\x12\x04\xf2\x03\x11\x12\n\r\n\x05\x04\x0b\t\x02\x01\x12\x04\ + \xf2\x03\x11\x12\n\r\n\x05\x04\x0b\t\x02\x02\x12\x04\xf2\x03\x11\x12\n\ + \xa0\x06\n\x04\x04\x0b\x02\x03\x12\x04\x89\x04\x02\x1e\x1a\x91\x06\x20Wh\ + ether\x20the\x20message\x20is\x20an\x20automatically\x20generated\x20map\ + \x20entry\x20type\x20for\x20the\n\x20maps\x20field.\n\n\x20For\x20maps\ + \x20fields:\n\x20\x20\x20\x20\x20map<KeyType,\x20ValueType>\x20map_field\ + \x20=\x201;\n\x20The\x20parsed\x20descriptor\x20looks\x20like:\n\x20\x20\ + \x20\x20\x20message\x20MapFieldEntry\x20{\n\x20\x20\x20\x20\x20\x20\x20\ + \x20\x20option\x20map_entry\x20=\x20true;\n\x20\x20\x20\x20\x20\x20\x20\ + \x20\x20optional\x20KeyType\x20key\x20=\x201;\n\x20\x20\x20\x20\x20\x20\ + \x20\x20\x20optional\x20ValueType\x20value\x20=\x202;\n\x20\x20\x20\x20\ + \x20}\n\x20\x20\x20\x20\x20repeated\x20MapFieldEntry\x20map_field\x20=\ + \x201;\n\n\x20Implementations\x20may\x20choose\x20not\x20to\x20generate\ + \x20the\x20map_entry=true\x20message,\x20but\n\x20use\x20a\x20native\x20\ + map\x20in\x20the\x20target\x20language\x20to\x20hold\x20the\x20keys\x20a\ + nd\x20values.\n\x20The\x20reflection\x20APIs\x20in\x20such\x20implementa\ + tions\x20still\x20need\x20to\x20work\x20as\n\x20if\x20the\x20field\x20is\ + \x20a\x20repeated\x20message\x20field.\n\n\x20NOTE:\x20Do\x20not\x20set\ + \x20the\x20option\x20in\x20.proto\x20files.\x20Always\x20use\x20the\x20m\ + aps\x20syntax\n\x20instead.\x20The\x20option\x20should\x20only\x20be\x20\ + implicitly\x20set\x20by\x20the\x20proto\x20compiler\n\x20parser.\n\n\r\n\ + \x05\x04\x0b\x02\x03\x04\x12\x04\x89\x04\x02\n\n\r\n\x05\x04\x0b\x02\x03\ + \x05\x12\x04\x89\x04\x0b\x0f\n\r\n\x05\x04\x0b\x02\x03\x01\x12\x04\x89\ + \x04\x10\x19\n\r\n\x05\x04\x0b\x02\x03\x03\x12\x04\x89\x04\x1c\x1d\n$\n\ + \x03\x04\x0b\t\x12\x04\x8b\x04\x02\r\"\x17\x20javalite_serializable\n\n\ + \x0c\n\x04\x04\x0b\t\x03\x12\x04\x8b\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\x03\ + \x01\x12\x04\x8b\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\x03\x02\x12\x04\x8b\x04\ + \x0b\x0c\n\x1f\n\x03\x04\x0b\t\x12\x04\x8c\x04\x02\r\"\x12\x20javanano_a\ + s_lite\n\n\x0c\n\x04\x04\x0b\t\x04\x12\x04\x8c\x04\x0b\x0c\n\r\n\x05\x04\ + \x0b\t\x04\x01\x12\x04\x8c\x04\x0b\x0c\n\r\n\x05\x04\x0b\t\x04\x02\x12\ + \x04\x8c\x04\x0b\x0c\nO\n\x04\x04\x0b\x02\x04\x12\x04\x90\x04\x02:\x1aA\ + \x20The\x20parser\x20stores\x20options\x20it\x20doesn't\x20recognize\x20\ + here.\x20See\x20above.\n\n\r\n\x05\x04\x0b\x02\x04\x04\x12\x04\x90\x04\ + \x02\n\n\r\n\x05\x04\x0b\x02\x04\x06\x12\x04\x90\x04\x0b\x1e\n\r\n\x05\ + \x04\x0b\x02\x04\x01\x12\x04\x90\x04\x1f3\n\r\n\x05\x04\x0b\x02\x04\x03\ + \x12\x04\x90\x0469\nZ\n\x03\x04\x0b\x05\x12\x04\x93\x04\x02\x19\x1aM\x20\ + Clients\x20can\x20define\x20custom\x20options\x20in\x20extensions\x20of\ + \x20this\x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x0b\x05\0\x12\ + \x04\x93\x04\r\x18\n\r\n\x05\x04\x0b\x05\0\x01\x12\x04\x93\x04\r\x11\n\r\ + \n\x05\x04\x0b\x05\0\x02\x12\x04\x93\x04\x15\x18\n\x0c\n\x02\x04\x0c\x12\ + \x06\x96\x04\0\xf1\x04\x01\n\x0b\n\x03\x04\x0c\x01\x12\x04\x96\x04\x08\ + \x14\n\xa3\x02\n\x04\x04\x0c\x02\0\x12\x04\x9b\x04\x02.\x1a\x94\x02\x20T\ + he\x20ctype\x20option\x20instructs\x20the\x20C++\x20code\x20generator\ + \x20to\x20use\x20a\x20different\n\x20representation\x20of\x20the\x20fiel\ + d\x20than\x20it\x20normally\x20would.\x20\x20See\x20the\x20specific\n\ + \x20options\x20below.\x20\x20This\x20option\x20is\x20not\x20yet\x20imple\ + mented\x20in\x20the\x20open\x20source\n\x20release\x20--\x20sorry,\x20we\ + 'll\x20try\x20to\x20include\x20it\x20in\x20a\x20future\x20version!\n\n\r\ + \n\x05\x04\x0c\x02\0\x04\x12\x04\x9b\x04\x02\n\n\r\n\x05\x04\x0c\x02\0\ + \x06\x12\x04\x9b\x04\x0b\x10\n\r\n\x05\x04\x0c\x02\0\x01\x12\x04\x9b\x04\ + \x11\x16\n\r\n\x05\x04\x0c\x02\0\x03\x12\x04\x9b\x04\x19\x1a\n\r\n\x05\ + \x04\x0c\x02\0\x08\x12\x04\x9b\x04\x1b-\n\r\n\x05\x04\x0c\x02\0\x07\x12\ + \x04\x9b\x04&,\n\x0e\n\x04\x04\x0c\x04\0\x12\x06\x9c\x04\x02\xa3\x04\x03\ + \n\r\n\x05\x04\x0c\x04\0\x01\x12\x04\x9c\x04\x07\x0c\n\x1f\n\x06\x04\x0c\ + \x04\0\x02\0\x12\x04\x9e\x04\x04\x0f\x1a\x0f\x20Default\x20mode.\n\n\x0f\ + \n\x07\x04\x0c\x04\0\x02\0\x01\x12\x04\x9e\x04\x04\n\n\x0f\n\x07\x04\x0c\ + \x04\0\x02\0\x02\x12\x04\x9e\x04\r\x0e\n\x0e\n\x06\x04\x0c\x04\0\x02\x01\ + \x12\x04\xa0\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\0\x02\x01\x01\x12\x04\xa0\ + \x04\x04\x08\n\x0f\n\x07\x04\x0c\x04\0\x02\x01\x02\x12\x04\xa0\x04\x0b\ + \x0c\n\x0e\n\x06\x04\x0c\x04\0\x02\x02\x12\x04\xa2\x04\x04\x15\n\x0f\n\ + \x07\x04\x0c\x04\0\x02\x02\x01\x12\x04\xa2\x04\x04\x10\n\x0f\n\x07\x04\ + \x0c\x04\0\x02\x02\x02\x12\x04\xa2\x04\x13\x14\n\xda\x02\n\x04\x04\x0c\ + \x02\x01\x12\x04\xa9\x04\x02\x1b\x1a\xcb\x02\x20The\x20packed\x20option\ \x20can\x20be\x20enabled\x20for\x20repeated\x20primitive\x20fields\x20to\ \x20enable\n\x20a\x20more\x20efficient\x20representation\x20on\x20the\ \x20wire.\x20Rather\x20than\x20repeatedly\n\x20writing\x20the\x20tag\x20\ @@ -10364,10 +9086,10 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x20encoded\x20as\n\x20a\x20single\x20length-delimited\x20blob.\x20In\ \x20proto3,\x20only\x20explicit\x20setting\x20it\x20to\n\x20false\x20wil\ l\x20avoid\x20using\x20packed\x20encoding.\n\n\r\n\x05\x04\x0c\x02\x01\ - \x04\x12\x04\xa7\x04\x02\n\n\r\n\x05\x04\x0c\x02\x01\x05\x12\x04\xa7\x04\ - \x0b\x0f\n\r\n\x05\x04\x0c\x02\x01\x01\x12\x04\xa7\x04\x10\x16\n\r\n\x05\ - \x04\x0c\x02\x01\x03\x12\x04\xa7\x04\x19\x1a\n\x9a\x05\n\x04\x04\x0c\x02\ - \x02\x12\x04\xb4\x04\x023\x1a\x8b\x05\x20The\x20jstype\x20option\x20dete\ + \x04\x12\x04\xa9\x04\x02\n\n\r\n\x05\x04\x0c\x02\x01\x05\x12\x04\xa9\x04\ + \x0b\x0f\n\r\n\x05\x04\x0c\x02\x01\x01\x12\x04\xa9\x04\x10\x16\n\r\n\x05\ + \x04\x0c\x02\x01\x03\x12\x04\xa9\x04\x19\x1a\n\x9a\x05\n\x04\x04\x0c\x02\ + \x02\x12\x04\xb6\x04\x023\x1a\x8b\x05\x20The\x20jstype\x20option\x20dete\ rmines\x20the\x20JavaScript\x20type\x20used\x20for\x20values\x20of\x20th\ e\n\x20field.\x20\x20The\x20option\x20is\x20permitted\x20only\x20for\x20\ 64\x20bit\x20integral\x20and\x20fixed\x20types\n\x20(int64,\x20uint64,\ @@ -10381,23 +9103,23 @@ static file_descriptor_proto_data: &'static [u8] = b"\ of\x20the\x20default\x20option\n\x20JS_NORMAL\x20is\x20implementation\ \x20dependent.\n\n\x20This\x20option\x20is\x20an\x20enum\x20to\x20permit\ \x20additional\x20types\x20to\x20be\x20added,\x20e.g.\n\x20goog.math.Int\ - eger.\n\n\r\n\x05\x04\x0c\x02\x02\x04\x12\x04\xb4\x04\x02\n\n\r\n\x05\ - \x04\x0c\x02\x02\x06\x12\x04\xb4\x04\x0b\x11\n\r\n\x05\x04\x0c\x02\x02\ - \x01\x12\x04\xb4\x04\x12\x18\n\r\n\x05\x04\x0c\x02\x02\x03\x12\x04\xb4\ - \x04\x1b\x1c\n\r\n\x05\x04\x0c\x02\x02\x08\x12\x04\xb4\x04\x1d2\n\r\n\ - \x05\x04\x0c\x02\x02\x07\x12\x04\xb4\x04(1\n\x0e\n\x04\x04\x0c\x04\x01\ - \x12\x06\xb5\x04\x02\xbe\x04\x03\n\r\n\x05\x04\x0c\x04\x01\x01\x12\x04\ - \xb5\x04\x07\r\n'\n\x06\x04\x0c\x04\x01\x02\0\x12\x04\xb7\x04\x04\x12\ + eger.\n\n\r\n\x05\x04\x0c\x02\x02\x04\x12\x04\xb6\x04\x02\n\n\r\n\x05\ + \x04\x0c\x02\x02\x06\x12\x04\xb6\x04\x0b\x11\n\r\n\x05\x04\x0c\x02\x02\ + \x01\x12\x04\xb6\x04\x12\x18\n\r\n\x05\x04\x0c\x02\x02\x03\x12\x04\xb6\ + \x04\x1b\x1c\n\r\n\x05\x04\x0c\x02\x02\x08\x12\x04\xb6\x04\x1d2\n\r\n\ + \x05\x04\x0c\x02\x02\x07\x12\x04\xb6\x04(1\n\x0e\n\x04\x04\x0c\x04\x01\ + \x12\x06\xb7\x04\x02\xc0\x04\x03\n\r\n\x05\x04\x0c\x04\x01\x01\x12\x04\ + \xb7\x04\x07\r\n'\n\x06\x04\x0c\x04\x01\x02\0\x12\x04\xb9\x04\x04\x12\ \x1a\x17\x20Use\x20the\x20default\x20type.\n\n\x0f\n\x07\x04\x0c\x04\x01\ - \x02\0\x01\x12\x04\xb7\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\x01\x02\0\x02\ - \x12\x04\xb7\x04\x10\x11\n)\n\x06\x04\x0c\x04\x01\x02\x01\x12\x04\xba\ + \x02\0\x01\x12\x04\xb9\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\x01\x02\0\x02\ + \x12\x04\xb9\x04\x10\x11\n)\n\x06\x04\x0c\x04\x01\x02\x01\x12\x04\xbc\ \x04\x04\x12\x1a\x19\x20Use\x20JavaScript\x20strings.\n\n\x0f\n\x07\x04\ - \x0c\x04\x01\x02\x01\x01\x12\x04\xba\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\ - \x01\x02\x01\x02\x12\x04\xba\x04\x10\x11\n)\n\x06\x04\x0c\x04\x01\x02\ - \x02\x12\x04\xbd\x04\x04\x12\x1a\x19\x20Use\x20JavaScript\x20numbers.\n\ - \n\x0f\n\x07\x04\x0c\x04\x01\x02\x02\x01\x12\x04\xbd\x04\x04\r\n\x0f\n\ - \x07\x04\x0c\x04\x01\x02\x02\x02\x12\x04\xbd\x04\x10\x11\n\xef\x0c\n\x04\ - \x04\x0c\x02\x03\x12\x04\xdc\x04\x02+\x1a\xe0\x0c\x20Should\x20this\x20f\ + \x0c\x04\x01\x02\x01\x01\x12\x04\xbc\x04\x04\r\n\x0f\n\x07\x04\x0c\x04\ + \x01\x02\x01\x02\x12\x04\xbc\x04\x10\x11\n)\n\x06\x04\x0c\x04\x01\x02\ + \x02\x12\x04\xbf\x04\x04\x12\x1a\x19\x20Use\x20JavaScript\x20numbers.\n\ + \n\x0f\n\x07\x04\x0c\x04\x01\x02\x02\x01\x12\x04\xbf\x04\x04\r\n\x0f\n\ + \x07\x04\x0c\x04\x01\x02\x02\x02\x12\x04\xbf\x04\x10\x11\n\xef\x0c\n\x04\ + \x04\x0c\x02\x03\x12\x04\xde\x04\x02+\x1a\xe0\x0c\x20Should\x20this\x20f\ ield\x20be\x20parsed\x20lazily?\x20\x20Lazy\x20applies\x20only\x20to\x20\ message-type\n\x20fields.\x20\x20It\x20means\x20that\x20when\x20the\x20o\ uter\x20message\x20is\x20initially\x20parsed,\x20the\n\x20inner\x20messa\ @@ -10432,101 +9154,101 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x20either\x20*always*\x20check\x20its\x20required\x20fields,\x20or\x20*\ never*\n\x20check\x20its\x20required\x20fields,\x20regardless\x20of\x20w\ hether\x20or\x20not\x20the\x20message\x20has\n\x20been\x20parsed.\n\n\r\ - \n\x05\x04\x0c\x02\x03\x04\x12\x04\xdc\x04\x02\n\n\r\n\x05\x04\x0c\x02\ - \x03\x05\x12\x04\xdc\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x03\x01\x12\x04\ - \xdc\x04\x10\x14\n\r\n\x05\x04\x0c\x02\x03\x03\x12\x04\xdc\x04\x17\x18\n\ - \r\n\x05\x04\x0c\x02\x03\x08\x12\x04\xdc\x04\x19*\n\r\n\x05\x04\x0c\x02\ - \x03\x07\x12\x04\xdc\x04$)\n\xe8\x01\n\x04\x04\x0c\x02\x04\x12\x04\xe2\ + \n\x05\x04\x0c\x02\x03\x04\x12\x04\xde\x04\x02\n\n\r\n\x05\x04\x0c\x02\ + \x03\x05\x12\x04\xde\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x03\x01\x12\x04\ + \xde\x04\x10\x14\n\r\n\x05\x04\x0c\x02\x03\x03\x12\x04\xde\x04\x17\x18\n\ + \r\n\x05\x04\x0c\x02\x03\x08\x12\x04\xde\x04\x19*\n\r\n\x05\x04\x0c\x02\ + \x03\x07\x12\x04\xde\x04$)\n\xe8\x01\n\x04\x04\x0c\x02\x04\x12\x04\xe4\ \x04\x021\x1a\xd9\x01\x20Is\x20this\x20field\x20deprecated?\n\x20Dependi\ ng\x20on\x20the\x20target\x20platform,\x20this\x20can\x20emit\x20Depreca\ ted\x20annotations\n\x20for\x20accessors,\x20or\x20it\x20will\x20be\x20c\ ompletely\x20ignored;\x20in\x20the\x20very\x20least,\x20this\n\x20is\x20\ a\x20formalization\x20for\x20deprecating\x20fields.\n\n\r\n\x05\x04\x0c\ - \x02\x04\x04\x12\x04\xe2\x04\x02\n\n\r\n\x05\x04\x0c\x02\x04\x05\x12\x04\ - \xe2\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x04\x01\x12\x04\xe2\x04\x10\x1a\n\ - \r\n\x05\x04\x0c\x02\x04\x03\x12\x04\xe2\x04\x1d\x1e\n\r\n\x05\x04\x0c\ - \x02\x04\x08\x12\x04\xe2\x04\x1f0\n\r\n\x05\x04\x0c\x02\x04\x07\x12\x04\ - \xe2\x04*/\n?\n\x04\x04\x0c\x02\x05\x12\x04\xe5\x04\x02,\x1a1\x20For\x20\ + \x02\x04\x04\x12\x04\xe4\x04\x02\n\n\r\n\x05\x04\x0c\x02\x04\x05\x12\x04\ + \xe4\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x04\x01\x12\x04\xe4\x04\x10\x1a\n\ + \r\n\x05\x04\x0c\x02\x04\x03\x12\x04\xe4\x04\x1d\x1e\n\r\n\x05\x04\x0c\ + \x02\x04\x08\x12\x04\xe4\x04\x1f0\n\r\n\x05\x04\x0c\x02\x04\x07\x12\x04\ + \xe4\x04*/\n?\n\x04\x04\x0c\x02\x05\x12\x04\xe7\x04\x02,\x1a1\x20For\x20\ Google-internal\x20migration\x20only.\x20Do\x20not\x20use.\n\n\r\n\x05\ - \x04\x0c\x02\x05\x04\x12\x04\xe5\x04\x02\n\n\r\n\x05\x04\x0c\x02\x05\x05\ - \x12\x04\xe5\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x05\x01\x12\x04\xe5\x04\ - \x10\x14\n\r\n\x05\x04\x0c\x02\x05\x03\x12\x04\xe5\x04\x17\x19\n\r\n\x05\ - \x04\x0c\x02\x05\x08\x12\x04\xe5\x04\x1a+\n\r\n\x05\x04\x0c\x02\x05\x07\ - \x12\x04\xe5\x04%*\nO\n\x04\x04\x0c\x02\x06\x12\x04\xe9\x04\x02:\x1aA\ + \x04\x0c\x02\x05\x04\x12\x04\xe7\x04\x02\n\n\r\n\x05\x04\x0c\x02\x05\x05\ + \x12\x04\xe7\x04\x0b\x0f\n\r\n\x05\x04\x0c\x02\x05\x01\x12\x04\xe7\x04\ + \x10\x14\n\r\n\x05\x04\x0c\x02\x05\x03\x12\x04\xe7\x04\x17\x19\n\r\n\x05\ + \x04\x0c\x02\x05\x08\x12\x04\xe7\x04\x1a+\n\r\n\x05\x04\x0c\x02\x05\x07\ + \x12\x04\xe7\x04%*\nO\n\x04\x04\x0c\x02\x06\x12\x04\xeb\x04\x02:\x1aA\ \x20The\x20parser\x20stores\x20options\x20it\x20doesn't\x20recognize\x20\ - here.\x20See\x20above.\n\n\r\n\x05\x04\x0c\x02\x06\x04\x12\x04\xe9\x04\ - \x02\n\n\r\n\x05\x04\x0c\x02\x06\x06\x12\x04\xe9\x04\x0b\x1e\n\r\n\x05\ - \x04\x0c\x02\x06\x01\x12\x04\xe9\x04\x1f3\n\r\n\x05\x04\x0c\x02\x06\x03\ - \x12\x04\xe9\x0469\nZ\n\x03\x04\x0c\x05\x12\x04\xec\x04\x02\x19\x1aM\x20\ + here.\x20See\x20above.\n\n\r\n\x05\x04\x0c\x02\x06\x04\x12\x04\xeb\x04\ + \x02\n\n\r\n\x05\x04\x0c\x02\x06\x06\x12\x04\xeb\x04\x0b\x1e\n\r\n\x05\ + \x04\x0c\x02\x06\x01\x12\x04\xeb\x04\x1f3\n\r\n\x05\x04\x0c\x02\x06\x03\ + \x12\x04\xeb\x0469\nZ\n\x03\x04\x0c\x05\x12\x04\xee\x04\x02\x19\x1aM\x20\ Clients\x20can\x20define\x20custom\x20options\x20in\x20extensions\x20of\ \x20this\x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x0c\x05\0\x12\ - \x04\xec\x04\r\x18\n\r\n\x05\x04\x0c\x05\0\x01\x12\x04\xec\x04\r\x11\n\r\ - \n\x05\x04\x0c\x05\0\x02\x12\x04\xec\x04\x15\x18\n\x1c\n\x03\x04\x0c\t\ - \x12\x04\xee\x04\x02\r\"\x0f\x20removed\x20jtype\n\n\x0c\n\x04\x04\x0c\t\ - \0\x12\x04\xee\x04\x0b\x0c\n\r\n\x05\x04\x0c\t\0\x01\x12\x04\xee\x04\x0b\ - \x0c\n\r\n\x05\x04\x0c\t\0\x02\x12\x04\xee\x04\x0b\x0c\n\x0c\n\x02\x04\r\ - \x12\x06\xf1\x04\0\xf7\x04\x01\n\x0b\n\x03\x04\r\x01\x12\x04\xf1\x04\x08\ - \x14\nO\n\x04\x04\r\x02\0\x12\x04\xf3\x04\x02:\x1aA\x20The\x20parser\x20\ + \x04\xee\x04\r\x18\n\r\n\x05\x04\x0c\x05\0\x01\x12\x04\xee\x04\r\x11\n\r\ + \n\x05\x04\x0c\x05\0\x02\x12\x04\xee\x04\x15\x18\n\x1c\n\x03\x04\x0c\t\ + \x12\x04\xf0\x04\x02\r\"\x0f\x20removed\x20jtype\n\n\x0c\n\x04\x04\x0c\t\ + \0\x12\x04\xf0\x04\x0b\x0c\n\r\n\x05\x04\x0c\t\0\x01\x12\x04\xf0\x04\x0b\ + \x0c\n\r\n\x05\x04\x0c\t\0\x02\x12\x04\xf0\x04\x0b\x0c\n\x0c\n\x02\x04\r\ + \x12\x06\xf3\x04\0\xf9\x04\x01\n\x0b\n\x03\x04\r\x01\x12\x04\xf3\x04\x08\ + \x14\nO\n\x04\x04\r\x02\0\x12\x04\xf5\x04\x02:\x1aA\x20The\x20parser\x20\ stores\x20options\x20it\x20doesn't\x20recognize\x20here.\x20See\x20above\ - .\n\n\r\n\x05\x04\r\x02\0\x04\x12\x04\xf3\x04\x02\n\n\r\n\x05\x04\r\x02\ - \0\x06\x12\x04\xf3\x04\x0b\x1e\n\r\n\x05\x04\r\x02\0\x01\x12\x04\xf3\x04\ - \x1f3\n\r\n\x05\x04\r\x02\0\x03\x12\x04\xf3\x0469\nZ\n\x03\x04\r\x05\x12\ - \x04\xf6\x04\x02\x19\x1aM\x20Clients\x20can\x20define\x20custom\x20optio\ + .\n\n\r\n\x05\x04\r\x02\0\x04\x12\x04\xf5\x04\x02\n\n\r\n\x05\x04\r\x02\ + \0\x06\x12\x04\xf5\x04\x0b\x1e\n\r\n\x05\x04\r\x02\0\x01\x12\x04\xf5\x04\ + \x1f3\n\r\n\x05\x04\r\x02\0\x03\x12\x04\xf5\x0469\nZ\n\x03\x04\r\x05\x12\ + \x04\xf8\x04\x02\x19\x1aM\x20Clients\x20can\x20define\x20custom\x20optio\ ns\x20in\x20extensions\x20of\x20this\x20message.\x20See\x20above.\n\n\ - \x0c\n\x04\x04\r\x05\0\x12\x04\xf6\x04\r\x18\n\r\n\x05\x04\r\x05\0\x01\ - \x12\x04\xf6\x04\r\x11\n\r\n\x05\x04\r\x05\0\x02\x12\x04\xf6\x04\x15\x18\ - \n\x0c\n\x02\x04\x0e\x12\x06\xf9\x04\0\x8c\x05\x01\n\x0b\n\x03\x04\x0e\ - \x01\x12\x04\xf9\x04\x08\x13\n`\n\x04\x04\x0e\x02\0\x12\x04\xfd\x04\x02\ + \x0c\n\x04\x04\r\x05\0\x12\x04\xf8\x04\r\x18\n\r\n\x05\x04\r\x05\0\x01\ + \x12\x04\xf8\x04\r\x11\n\r\n\x05\x04\r\x05\0\x02\x12\x04\xf8\x04\x15\x18\ + \n\x0c\n\x02\x04\x0e\x12\x06\xfb\x04\0\x8e\x05\x01\n\x0b\n\x03\x04\x0e\ + \x01\x12\x04\xfb\x04\x08\x13\n`\n\x04\x04\x0e\x02\0\x12\x04\xff\x04\x02\ \x20\x1aR\x20Set\x20this\x20option\x20to\x20true\x20to\x20allow\x20mappi\ ng\x20different\x20tag\x20names\x20to\x20the\x20same\n\x20value.\n\n\r\n\ - \x05\x04\x0e\x02\0\x04\x12\x04\xfd\x04\x02\n\n\r\n\x05\x04\x0e\x02\0\x05\ - \x12\x04\xfd\x04\x0b\x0f\n\r\n\x05\x04\x0e\x02\0\x01\x12\x04\xfd\x04\x10\ - \x1b\n\r\n\x05\x04\x0e\x02\0\x03\x12\x04\xfd\x04\x1e\x1f\n\xe5\x01\n\x04\ - \x04\x0e\x02\x01\x12\x04\x83\x05\x021\x1a\xd6\x01\x20Is\x20this\x20enum\ + \x05\x04\x0e\x02\0\x04\x12\x04\xff\x04\x02\n\n\r\n\x05\x04\x0e\x02\0\x05\ + \x12\x04\xff\x04\x0b\x0f\n\r\n\x05\x04\x0e\x02\0\x01\x12\x04\xff\x04\x10\ + \x1b\n\r\n\x05\x04\x0e\x02\0\x03\x12\x04\xff\x04\x1e\x1f\n\xe5\x01\n\x04\ + \x04\x0e\x02\x01\x12\x04\x85\x05\x021\x1a\xd6\x01\x20Is\x20this\x20enum\ \x20deprecated?\n\x20Depending\x20on\x20the\x20target\x20platform,\x20th\ is\x20can\x20emit\x20Deprecated\x20annotations\n\x20for\x20the\x20enum,\ \x20or\x20it\x20will\x20be\x20completely\x20ignored;\x20in\x20the\x20ver\ y\x20least,\x20this\n\x20is\x20a\x20formalization\x20for\x20deprecating\ - \x20enums.\n\n\r\n\x05\x04\x0e\x02\x01\x04\x12\x04\x83\x05\x02\n\n\r\n\ - \x05\x04\x0e\x02\x01\x05\x12\x04\x83\x05\x0b\x0f\n\r\n\x05\x04\x0e\x02\ - \x01\x01\x12\x04\x83\x05\x10\x1a\n\r\n\x05\x04\x0e\x02\x01\x03\x12\x04\ - \x83\x05\x1d\x1e\n\r\n\x05\x04\x0e\x02\x01\x08\x12\x04\x83\x05\x1f0\n\r\ - \n\x05\x04\x0e\x02\x01\x07\x12\x04\x83\x05*/\n\x1f\n\x03\x04\x0e\t\x12\ - \x04\x85\x05\x02\r\"\x12\x20javanano_as_lite\n\n\x0c\n\x04\x04\x0e\t\0\ - \x12\x04\x85\x05\x0b\x0c\n\r\n\x05\x04\x0e\t\0\x01\x12\x04\x85\x05\x0b\ - \x0c\n\r\n\x05\x04\x0e\t\0\x02\x12\x04\x85\x05\x0b\x0c\nO\n\x04\x04\x0e\ - \x02\x02\x12\x04\x88\x05\x02:\x1aA\x20The\x20parser\x20stores\x20options\ + \x20enums.\n\n\r\n\x05\x04\x0e\x02\x01\x04\x12\x04\x85\x05\x02\n\n\r\n\ + \x05\x04\x0e\x02\x01\x05\x12\x04\x85\x05\x0b\x0f\n\r\n\x05\x04\x0e\x02\ + \x01\x01\x12\x04\x85\x05\x10\x1a\n\r\n\x05\x04\x0e\x02\x01\x03\x12\x04\ + \x85\x05\x1d\x1e\n\r\n\x05\x04\x0e\x02\x01\x08\x12\x04\x85\x05\x1f0\n\r\ + \n\x05\x04\x0e\x02\x01\x07\x12\x04\x85\x05*/\n\x1f\n\x03\x04\x0e\t\x12\ + \x04\x87\x05\x02\r\"\x12\x20javanano_as_lite\n\n\x0c\n\x04\x04\x0e\t\0\ + \x12\x04\x87\x05\x0b\x0c\n\r\n\x05\x04\x0e\t\0\x01\x12\x04\x87\x05\x0b\ + \x0c\n\r\n\x05\x04\x0e\t\0\x02\x12\x04\x87\x05\x0b\x0c\nO\n\x04\x04\x0e\ + \x02\x02\x12\x04\x8a\x05\x02:\x1aA\x20The\x20parser\x20stores\x20options\ \x20it\x20doesn't\x20recognize\x20here.\x20See\x20above.\n\n\r\n\x05\x04\ - \x0e\x02\x02\x04\x12\x04\x88\x05\x02\n\n\r\n\x05\x04\x0e\x02\x02\x06\x12\ - \x04\x88\x05\x0b\x1e\n\r\n\x05\x04\x0e\x02\x02\x01\x12\x04\x88\x05\x1f3\ - \n\r\n\x05\x04\x0e\x02\x02\x03\x12\x04\x88\x0569\nZ\n\x03\x04\x0e\x05\ - \x12\x04\x8b\x05\x02\x19\x1aM\x20Clients\x20can\x20define\x20custom\x20o\ + \x0e\x02\x02\x04\x12\x04\x8a\x05\x02\n\n\r\n\x05\x04\x0e\x02\x02\x06\x12\ + \x04\x8a\x05\x0b\x1e\n\r\n\x05\x04\x0e\x02\x02\x01\x12\x04\x8a\x05\x1f3\ + \n\r\n\x05\x04\x0e\x02\x02\x03\x12\x04\x8a\x0569\nZ\n\x03\x04\x0e\x05\ + \x12\x04\x8d\x05\x02\x19\x1aM\x20Clients\x20can\x20define\x20custom\x20o\ ptions\x20in\x20extensions\x20of\x20this\x20message.\x20See\x20above.\n\ - \n\x0c\n\x04\x04\x0e\x05\0\x12\x04\x8b\x05\r\x18\n\r\n\x05\x04\x0e\x05\0\ - \x01\x12\x04\x8b\x05\r\x11\n\r\n\x05\x04\x0e\x05\0\x02\x12\x04\x8b\x05\ - \x15\x18\n\x0c\n\x02\x04\x0f\x12\x06\x8e\x05\0\x9a\x05\x01\n\x0b\n\x03\ - \x04\x0f\x01\x12\x04\x8e\x05\x08\x18\n\xf7\x01\n\x04\x04\x0f\x02\0\x12\ - \x04\x93\x05\x021\x1a\xe8\x01\x20Is\x20this\x20enum\x20value\x20deprecat\ + \n\x0c\n\x04\x04\x0e\x05\0\x12\x04\x8d\x05\r\x18\n\r\n\x05\x04\x0e\x05\0\ + \x01\x12\x04\x8d\x05\r\x11\n\r\n\x05\x04\x0e\x05\0\x02\x12\x04\x8d\x05\ + \x15\x18\n\x0c\n\x02\x04\x0f\x12\x06\x90\x05\0\x9c\x05\x01\n\x0b\n\x03\ + \x04\x0f\x01\x12\x04\x90\x05\x08\x18\n\xf7\x01\n\x04\x04\x0f\x02\0\x12\ + \x04\x95\x05\x021\x1a\xe8\x01\x20Is\x20this\x20enum\x20value\x20deprecat\ ed?\n\x20Depending\x20on\x20the\x20target\x20platform,\x20this\x20can\ \x20emit\x20Deprecated\x20annotations\n\x20for\x20the\x20enum\x20value,\ \x20or\x20it\x20will\x20be\x20completely\x20ignored;\x20in\x20the\x20ver\ y\x20least,\n\x20this\x20is\x20a\x20formalization\x20for\x20deprecating\ - \x20enum\x20values.\n\n\r\n\x05\x04\x0f\x02\0\x04\x12\x04\x93\x05\x02\n\ - \n\r\n\x05\x04\x0f\x02\0\x05\x12\x04\x93\x05\x0b\x0f\n\r\n\x05\x04\x0f\ - \x02\0\x01\x12\x04\x93\x05\x10\x1a\n\r\n\x05\x04\x0f\x02\0\x03\x12\x04\ - \x93\x05\x1d\x1e\n\r\n\x05\x04\x0f\x02\0\x08\x12\x04\x93\x05\x1f0\n\r\n\ - \x05\x04\x0f\x02\0\x07\x12\x04\x93\x05*/\nO\n\x04\x04\x0f\x02\x01\x12\ - \x04\x96\x05\x02:\x1aA\x20The\x20parser\x20stores\x20options\x20it\x20do\ + \x20enum\x20values.\n\n\r\n\x05\x04\x0f\x02\0\x04\x12\x04\x95\x05\x02\n\ + \n\r\n\x05\x04\x0f\x02\0\x05\x12\x04\x95\x05\x0b\x0f\n\r\n\x05\x04\x0f\ + \x02\0\x01\x12\x04\x95\x05\x10\x1a\n\r\n\x05\x04\x0f\x02\0\x03\x12\x04\ + \x95\x05\x1d\x1e\n\r\n\x05\x04\x0f\x02\0\x08\x12\x04\x95\x05\x1f0\n\r\n\ + \x05\x04\x0f\x02\0\x07\x12\x04\x95\x05*/\nO\n\x04\x04\x0f\x02\x01\x12\ + \x04\x98\x05\x02:\x1aA\x20The\x20parser\x20stores\x20options\x20it\x20do\ esn't\x20recognize\x20here.\x20See\x20above.\n\n\r\n\x05\x04\x0f\x02\x01\ - \x04\x12\x04\x96\x05\x02\n\n\r\n\x05\x04\x0f\x02\x01\x06\x12\x04\x96\x05\ - \x0b\x1e\n\r\n\x05\x04\x0f\x02\x01\x01\x12\x04\x96\x05\x1f3\n\r\n\x05\ - \x04\x0f\x02\x01\x03\x12\x04\x96\x0569\nZ\n\x03\x04\x0f\x05\x12\x04\x99\ + \x04\x12\x04\x98\x05\x02\n\n\r\n\x05\x04\x0f\x02\x01\x06\x12\x04\x98\x05\ + \x0b\x1e\n\r\n\x05\x04\x0f\x02\x01\x01\x12\x04\x98\x05\x1f3\n\r\n\x05\ + \x04\x0f\x02\x01\x03\x12\x04\x98\x0569\nZ\n\x03\x04\x0f\x05\x12\x04\x9b\ \x05\x02\x19\x1aM\x20Clients\x20can\x20define\x20custom\x20options\x20in\ \x20extensions\x20of\x20this\x20message.\x20See\x20above.\n\n\x0c\n\x04\ - \x04\x0f\x05\0\x12\x04\x99\x05\r\x18\n\r\n\x05\x04\x0f\x05\0\x01\x12\x04\ - \x99\x05\r\x11\n\r\n\x05\x04\x0f\x05\0\x02\x12\x04\x99\x05\x15\x18\n\x0c\ - \n\x02\x04\x10\x12\x06\x9c\x05\0\xae\x05\x01\n\x0b\n\x03\x04\x10\x01\x12\ - \x04\x9c\x05\x08\x16\n\xd9\x03\n\x04\x04\x10\x02\0\x12\x04\xa7\x05\x022\ + \x04\x0f\x05\0\x12\x04\x9b\x05\r\x18\n\r\n\x05\x04\x0f\x05\0\x01\x12\x04\ + \x9b\x05\r\x11\n\r\n\x05\x04\x0f\x05\0\x02\x12\x04\x9b\x05\x15\x18\n\x0c\ + \n\x02\x04\x10\x12\x06\x9e\x05\0\xb0\x05\x01\n\x0b\n\x03\x04\x10\x01\x12\ + \x04\x9e\x05\x08\x16\n\xd9\x03\n\x04\x04\x10\x02\0\x12\x04\xa9\x05\x022\ \x1a\xdf\x01\x20Is\x20this\x20service\x20deprecated?\n\x20Depending\x20o\ n\x20the\x20target\x20platform,\x20this\x20can\x20emit\x20Deprecated\x20\ annotations\n\x20for\x20the\x20service,\x20or\x20it\x20will\x20be\x20com\ @@ -10537,22 +9259,22 @@ static file_descriptor_proto_data: &'static [u8] = b"\ logize\x20for\x20hoarding\x20these\x20numbers\x20to\x20ourselves,\x20but\ \n\x20\x20\x20we\x20were\x20already\x20using\x20them\x20long\x20before\ \x20we\x20decided\x20to\x20release\x20Protocol\n\x20\x20\x20Buffers.\n\n\ - \r\n\x05\x04\x10\x02\0\x04\x12\x04\xa7\x05\x02\n\n\r\n\x05\x04\x10\x02\0\ - \x05\x12\x04\xa7\x05\x0b\x0f\n\r\n\x05\x04\x10\x02\0\x01\x12\x04\xa7\x05\ - \x10\x1a\n\r\n\x05\x04\x10\x02\0\x03\x12\x04\xa7\x05\x1d\x1f\n\r\n\x05\ - \x04\x10\x02\0\x08\x12\x04\xa7\x05\x201\n\r\n\x05\x04\x10\x02\0\x07\x12\ - \x04\xa7\x05+0\nO\n\x04\x04\x10\x02\x01\x12\x04\xaa\x05\x02:\x1aA\x20The\ + \r\n\x05\x04\x10\x02\0\x04\x12\x04\xa9\x05\x02\n\n\r\n\x05\x04\x10\x02\0\ + \x05\x12\x04\xa9\x05\x0b\x0f\n\r\n\x05\x04\x10\x02\0\x01\x12\x04\xa9\x05\ + \x10\x1a\n\r\n\x05\x04\x10\x02\0\x03\x12\x04\xa9\x05\x1d\x1f\n\r\n\x05\ + \x04\x10\x02\0\x08\x12\x04\xa9\x05\x201\n\r\n\x05\x04\x10\x02\0\x07\x12\ + \x04\xa9\x05+0\nO\n\x04\x04\x10\x02\x01\x12\x04\xac\x05\x02:\x1aA\x20The\ \x20parser\x20stores\x20options\x20it\x20doesn't\x20recognize\x20here.\ - \x20See\x20above.\n\n\r\n\x05\x04\x10\x02\x01\x04\x12\x04\xaa\x05\x02\n\ - \n\r\n\x05\x04\x10\x02\x01\x06\x12\x04\xaa\x05\x0b\x1e\n\r\n\x05\x04\x10\ - \x02\x01\x01\x12\x04\xaa\x05\x1f3\n\r\n\x05\x04\x10\x02\x01\x03\x12\x04\ - \xaa\x0569\nZ\n\x03\x04\x10\x05\x12\x04\xad\x05\x02\x19\x1aM\x20Clients\ + \x20See\x20above.\n\n\r\n\x05\x04\x10\x02\x01\x04\x12\x04\xac\x05\x02\n\ + \n\r\n\x05\x04\x10\x02\x01\x06\x12\x04\xac\x05\x0b\x1e\n\r\n\x05\x04\x10\ + \x02\x01\x01\x12\x04\xac\x05\x1f3\n\r\n\x05\x04\x10\x02\x01\x03\x12\x04\ + \xac\x0569\nZ\n\x03\x04\x10\x05\x12\x04\xaf\x05\x02\x19\x1aM\x20Clients\ \x20can\x20define\x20custom\x20options\x20in\x20extensions\x20of\x20this\ - \x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x10\x05\0\x12\x04\xad\ - \x05\r\x18\n\r\n\x05\x04\x10\x05\0\x01\x12\x04\xad\x05\r\x11\n\r\n\x05\ - \x04\x10\x05\0\x02\x12\x04\xad\x05\x15\x18\n\x0c\n\x02\x04\x11\x12\x06\ - \xb0\x05\0\xcd\x05\x01\n\x0b\n\x03\x04\x11\x01\x12\x04\xb0\x05\x08\x15\n\ - \xd6\x03\n\x04\x04\x11\x02\0\x12\x04\xbb\x05\x022\x1a\xdc\x01\x20Is\x20t\ + \x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x10\x05\0\x12\x04\xaf\ + \x05\r\x18\n\r\n\x05\x04\x10\x05\0\x01\x12\x04\xaf\x05\r\x11\n\r\n\x05\ + \x04\x10\x05\0\x02\x12\x04\xaf\x05\x15\x18\n\x0c\n\x02\x04\x11\x12\x06\ + \xb2\x05\0\xcf\x05\x01\n\x0b\n\x03\x04\x11\x01\x12\x04\xb2\x05\x08\x15\n\ + \xd6\x03\n\x04\x04\x11\x02\0\x12\x04\xbd\x05\x022\x1a\xdc\x01\x20Is\x20t\ his\x20method\x20deprecated?\n\x20Depending\x20on\x20the\x20target\x20pl\ atform,\x20this\x20can\x20emit\x20Deprecated\x20annotations\n\x20for\x20\ the\x20method,\x20or\x20it\x20will\x20be\x20completely\x20ignored;\x20in\ @@ -10563,41 +9285,41 @@ static file_descriptor_proto_data: &'static [u8] = b"\ g\x20these\x20numbers\x20to\x20ourselves,\x20but\n\x20\x20\x20we\x20were\ \x20already\x20using\x20them\x20long\x20before\x20we\x20decided\x20to\ \x20release\x20Protocol\n\x20\x20\x20Buffers.\n\n\r\n\x05\x04\x11\x02\0\ - \x04\x12\x04\xbb\x05\x02\n\n\r\n\x05\x04\x11\x02\0\x05\x12\x04\xbb\x05\ - \x0b\x0f\n\r\n\x05\x04\x11\x02\0\x01\x12\x04\xbb\x05\x10\x1a\n\r\n\x05\ - \x04\x11\x02\0\x03\x12\x04\xbb\x05\x1d\x1f\n\r\n\x05\x04\x11\x02\0\x08\ - \x12\x04\xbb\x05\x201\n\r\n\x05\x04\x11\x02\0\x07\x12\x04\xbb\x05+0\n\ - \xf0\x01\n\x04\x04\x11\x04\0\x12\x06\xc0\x05\x02\xc4\x05\x03\x1a\xdf\x01\ + \x04\x12\x04\xbd\x05\x02\n\n\r\n\x05\x04\x11\x02\0\x05\x12\x04\xbd\x05\ + \x0b\x0f\n\r\n\x05\x04\x11\x02\0\x01\x12\x04\xbd\x05\x10\x1a\n\r\n\x05\ + \x04\x11\x02\0\x03\x12\x04\xbd\x05\x1d\x1f\n\r\n\x05\x04\x11\x02\0\x08\ + \x12\x04\xbd\x05\x201\n\r\n\x05\x04\x11\x02\0\x07\x12\x04\xbd\x05+0\n\ + \xf0\x01\n\x04\x04\x11\x04\0\x12\x06\xc2\x05\x02\xc6\x05\x03\x1a\xdf\x01\ \x20Is\x20this\x20method\x20side-effect-free\x20(or\x20safe\x20in\x20HTT\ P\x20parlance),\x20or\x20idempotent,\n\x20or\x20neither?\x20HTTP\x20base\ d\x20RPC\x20implementation\x20may\x20choose\x20GET\x20verb\x20for\x20saf\ e\n\x20methods,\x20and\x20PUT\x20verb\x20for\x20idempotent\x20methods\ \x20instead\x20of\x20the\x20default\x20POST.\n\n\r\n\x05\x04\x11\x04\0\ - \x01\x12\x04\xc0\x05\x07\x17\n\x0e\n\x06\x04\x11\x04\0\x02\0\x12\x04\xc1\ - \x05\x04\x1c\n\x0f\n\x07\x04\x11\x04\0\x02\0\x01\x12\x04\xc1\x05\x04\x17\ - \n\x0f\n\x07\x04\x11\x04\0\x02\0\x02\x12\x04\xc1\x05\x1a\x1b\n$\n\x06\ - \x04\x11\x04\0\x02\x01\x12\x04\xc2\x05\x04\x18\"\x14\x20implies\x20idemp\ - otent\n\n\x0f\n\x07\x04\x11\x04\0\x02\x01\x01\x12\x04\xc2\x05\x04\x13\n\ - \x0f\n\x07\x04\x11\x04\0\x02\x01\x02\x12\x04\xc2\x05\x16\x17\n7\n\x06\ - \x04\x11\x04\0\x02\x02\x12\x04\xc3\x05\x04\x13\"'\x20idempotent,\x20but\ + \x01\x12\x04\xc2\x05\x07\x17\n\x0e\n\x06\x04\x11\x04\0\x02\0\x12\x04\xc3\ + \x05\x04\x1c\n\x0f\n\x07\x04\x11\x04\0\x02\0\x01\x12\x04\xc3\x05\x04\x17\ + \n\x0f\n\x07\x04\x11\x04\0\x02\0\x02\x12\x04\xc3\x05\x1a\x1b\n$\n\x06\ + \x04\x11\x04\0\x02\x01\x12\x04\xc4\x05\x04\x18\"\x14\x20implies\x20idemp\ + otent\n\n\x0f\n\x07\x04\x11\x04\0\x02\x01\x01\x12\x04\xc4\x05\x04\x13\n\ + \x0f\n\x07\x04\x11\x04\0\x02\x01\x02\x12\x04\xc4\x05\x16\x17\n7\n\x06\ + \x04\x11\x04\0\x02\x02\x12\x04\xc5\x05\x04\x13\"'\x20idempotent,\x20but\ \x20may\x20have\x20side\x20effects\n\n\x0f\n\x07\x04\x11\x04\0\x02\x02\ - \x01\x12\x04\xc3\x05\x04\x0e\n\x0f\n\x07\x04\x11\x04\0\x02\x02\x02\x12\ - \x04\xc3\x05\x11\x12\n\x0e\n\x04\x04\x11\x02\x01\x12\x06\xc5\x05\x02\xc6\ - \x05&\n\r\n\x05\x04\x11\x02\x01\x04\x12\x04\xc5\x05\x02\n\n\r\n\x05\x04\ - \x11\x02\x01\x06\x12\x04\xc5\x05\x0b\x1b\n\r\n\x05\x04\x11\x02\x01\x01\ - \x12\x04\xc5\x05\x1c-\n\r\n\x05\x04\x11\x02\x01\x03\x12\x04\xc5\x0502\n\ - \r\n\x05\x04\x11\x02\x01\x08\x12\x04\xc6\x05\x06%\n\r\n\x05\x04\x11\x02\ - \x01\x07\x12\x04\xc6\x05\x11$\nO\n\x04\x04\x11\x02\x02\x12\x04\xc9\x05\ + \x01\x12\x04\xc5\x05\x04\x0e\n\x0f\n\x07\x04\x11\x04\0\x02\x02\x02\x12\ + \x04\xc5\x05\x11\x12\n\x0e\n\x04\x04\x11\x02\x01\x12\x06\xc7\x05\x02\xc8\ + \x05&\n\r\n\x05\x04\x11\x02\x01\x04\x12\x04\xc7\x05\x02\n\n\r\n\x05\x04\ + \x11\x02\x01\x06\x12\x04\xc7\x05\x0b\x1b\n\r\n\x05\x04\x11\x02\x01\x01\ + \x12\x04\xc7\x05\x1c-\n\r\n\x05\x04\x11\x02\x01\x03\x12\x04\xc7\x0502\n\ + \r\n\x05\x04\x11\x02\x01\x08\x12\x04\xc8\x05\x06%\n\r\n\x05\x04\x11\x02\ + \x01\x07\x12\x04\xc8\x05\x11$\nO\n\x04\x04\x11\x02\x02\x12\x04\xcb\x05\ \x02:\x1aA\x20The\x20parser\x20stores\x20options\x20it\x20doesn't\x20rec\ ognize\x20here.\x20See\x20above.\n\n\r\n\x05\x04\x11\x02\x02\x04\x12\x04\ - \xc9\x05\x02\n\n\r\n\x05\x04\x11\x02\x02\x06\x12\x04\xc9\x05\x0b\x1e\n\r\ - \n\x05\x04\x11\x02\x02\x01\x12\x04\xc9\x05\x1f3\n\r\n\x05\x04\x11\x02\ - \x02\x03\x12\x04\xc9\x0569\nZ\n\x03\x04\x11\x05\x12\x04\xcc\x05\x02\x19\ + \xcb\x05\x02\n\n\r\n\x05\x04\x11\x02\x02\x06\x12\x04\xcb\x05\x0b\x1e\n\r\ + \n\x05\x04\x11\x02\x02\x01\x12\x04\xcb\x05\x1f3\n\r\n\x05\x04\x11\x02\ + \x02\x03\x12\x04\xcb\x0569\nZ\n\x03\x04\x11\x05\x12\x04\xce\x05\x02\x19\ \x1aM\x20Clients\x20can\x20define\x20custom\x20options\x20in\x20extensio\ ns\x20of\x20this\x20message.\x20See\x20above.\n\n\x0c\n\x04\x04\x11\x05\ - \0\x12\x04\xcc\x05\r\x18\n\r\n\x05\x04\x11\x05\0\x01\x12\x04\xcc\x05\r\ - \x11\n\r\n\x05\x04\x11\x05\0\x02\x12\x04\xcc\x05\x15\x18\n\x8b\x03\n\x02\ - \x04\x12\x12\x06\xd6\x05\0\xea\x05\x01\x1a\xfc\x02\x20A\x20message\x20re\ + \0\x12\x04\xce\x05\r\x18\n\r\n\x05\x04\x11\x05\0\x01\x12\x04\xce\x05\r\ + \x11\n\r\n\x05\x04\x11\x05\0\x02\x12\x04\xce\x05\x15\x18\n\x8b\x03\n\x02\ + \x04\x12\x12\x06\xd8\x05\0\xec\x05\x01\x1a\xfc\x02\x20A\x20message\x20re\ presenting\x20a\x20option\x20the\x20parser\x20does\x20not\x20recognize.\ \x20This\x20only\n\x20appears\x20in\x20options\x20protos\x20created\x20b\ y\x20the\x20compiler::Parser\x20class.\n\x20DescriptorPool\x20resolves\ @@ -10605,58 +9327,58 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x20options\x20protos\x20in\x20descriptor\x20objects\x20(e.g.\x20returne\ d\x20by\x20Descriptor::options(),\n\x20or\x20produced\x20by\x20Descripto\ r::CopyTo())\x20will\x20never\x20have\x20UninterpretedOptions\n\x20in\ - \x20them.\n\n\x0b\n\x03\x04\x12\x01\x12\x04\xd6\x05\x08\x1b\n\xcb\x02\n\ - \x04\x04\x12\x03\0\x12\x06\xdc\x05\x02\xdf\x05\x03\x1a\xba\x02\x20The\ + \x20them.\n\n\x0b\n\x03\x04\x12\x01\x12\x04\xd8\x05\x08\x1b\n\xcb\x02\n\ + \x04\x04\x12\x03\0\x12\x06\xde\x05\x02\xe1\x05\x03\x1a\xba\x02\x20The\ \x20name\x20of\x20the\x20uninterpreted\x20option.\x20\x20Each\x20string\ \x20represents\x20a\x20segment\x20in\n\x20a\x20dot-separated\x20name.\ \x20\x20is_extension\x20is\x20true\x20iff\x20a\x20segment\x20represents\ \x20an\n\x20extension\x20(denoted\x20with\x20parentheses\x20in\x20option\ s\x20specs\x20in\x20.proto\x20files).\n\x20E.g.,{\x20[\"foo\",\x20false]\ ,\x20[\"bar.baz\",\x20true],\x20[\"qux\",\x20false]\x20}\x20represents\n\ - \x20\"foo.(bar.baz).qux\".\n\n\r\n\x05\x04\x12\x03\0\x01\x12\x04\xdc\x05\ - \n\x12\n\x0e\n\x06\x04\x12\x03\0\x02\0\x12\x04\xdd\x05\x04\"\n\x0f\n\x07\ - \x04\x12\x03\0\x02\0\x04\x12\x04\xdd\x05\x04\x0c\n\x0f\n\x07\x04\x12\x03\ - \0\x02\0\x05\x12\x04\xdd\x05\r\x13\n\x0f\n\x07\x04\x12\x03\0\x02\0\x01\ - \x12\x04\xdd\x05\x14\x1d\n\x0f\n\x07\x04\x12\x03\0\x02\0\x03\x12\x04\xdd\ - \x05\x20!\n\x0e\n\x06\x04\x12\x03\0\x02\x01\x12\x04\xde\x05\x04#\n\x0f\n\ - \x07\x04\x12\x03\0\x02\x01\x04\x12\x04\xde\x05\x04\x0c\n\x0f\n\x07\x04\ - \x12\x03\0\x02\x01\x05\x12\x04\xde\x05\r\x11\n\x0f\n\x07\x04\x12\x03\0\ - \x02\x01\x01\x12\x04\xde\x05\x12\x1e\n\x0f\n\x07\x04\x12\x03\0\x02\x01\ - \x03\x12\x04\xde\x05!\"\n\x0c\n\x04\x04\x12\x02\0\x12\x04\xe0\x05\x02\ - \x1d\n\r\n\x05\x04\x12\x02\0\x04\x12\x04\xe0\x05\x02\n\n\r\n\x05\x04\x12\ - \x02\0\x06\x12\x04\xe0\x05\x0b\x13\n\r\n\x05\x04\x12\x02\0\x01\x12\x04\ - \xe0\x05\x14\x18\n\r\n\x05\x04\x12\x02\0\x03\x12\x04\xe0\x05\x1b\x1c\n\ - \x9c\x01\n\x04\x04\x12\x02\x01\x12\x04\xe4\x05\x02'\x1a\x8d\x01\x20The\ + \x20\"foo.(bar.baz).qux\".\n\n\r\n\x05\x04\x12\x03\0\x01\x12\x04\xde\x05\ + \n\x12\n\x0e\n\x06\x04\x12\x03\0\x02\0\x12\x04\xdf\x05\x04\"\n\x0f\n\x07\ + \x04\x12\x03\0\x02\0\x04\x12\x04\xdf\x05\x04\x0c\n\x0f\n\x07\x04\x12\x03\ + \0\x02\0\x05\x12\x04\xdf\x05\r\x13\n\x0f\n\x07\x04\x12\x03\0\x02\0\x01\ + \x12\x04\xdf\x05\x14\x1d\n\x0f\n\x07\x04\x12\x03\0\x02\0\x03\x12\x04\xdf\ + \x05\x20!\n\x0e\n\x06\x04\x12\x03\0\x02\x01\x12\x04\xe0\x05\x04#\n\x0f\n\ + \x07\x04\x12\x03\0\x02\x01\x04\x12\x04\xe0\x05\x04\x0c\n\x0f\n\x07\x04\ + \x12\x03\0\x02\x01\x05\x12\x04\xe0\x05\r\x11\n\x0f\n\x07\x04\x12\x03\0\ + \x02\x01\x01\x12\x04\xe0\x05\x12\x1e\n\x0f\n\x07\x04\x12\x03\0\x02\x01\ + \x03\x12\x04\xe0\x05!\"\n\x0c\n\x04\x04\x12\x02\0\x12\x04\xe2\x05\x02\ + \x1d\n\r\n\x05\x04\x12\x02\0\x04\x12\x04\xe2\x05\x02\n\n\r\n\x05\x04\x12\ + \x02\0\x06\x12\x04\xe2\x05\x0b\x13\n\r\n\x05\x04\x12\x02\0\x01\x12\x04\ + \xe2\x05\x14\x18\n\r\n\x05\x04\x12\x02\0\x03\x12\x04\xe2\x05\x1b\x1c\n\ + \x9c\x01\n\x04\x04\x12\x02\x01\x12\x04\xe6\x05\x02'\x1a\x8d\x01\x20The\ \x20value\x20of\x20the\x20uninterpreted\x20option,\x20in\x20whatever\x20\ type\x20the\x20tokenizer\n\x20identified\x20it\x20as\x20during\x20parsin\ g.\x20Exactly\x20one\x20of\x20these\x20should\x20be\x20set.\n\n\r\n\x05\ - \x04\x12\x02\x01\x04\x12\x04\xe4\x05\x02\n\n\r\n\x05\x04\x12\x02\x01\x05\ - \x12\x04\xe4\x05\x0b\x11\n\r\n\x05\x04\x12\x02\x01\x01\x12\x04\xe4\x05\ - \x12\"\n\r\n\x05\x04\x12\x02\x01\x03\x12\x04\xe4\x05%&\n\x0c\n\x04\x04\ - \x12\x02\x02\x12\x04\xe5\x05\x02)\n\r\n\x05\x04\x12\x02\x02\x04\x12\x04\ - \xe5\x05\x02\n\n\r\n\x05\x04\x12\x02\x02\x05\x12\x04\xe5\x05\x0b\x11\n\r\ - \n\x05\x04\x12\x02\x02\x01\x12\x04\xe5\x05\x12$\n\r\n\x05\x04\x12\x02\ - \x02\x03\x12\x04\xe5\x05'(\n\x0c\n\x04\x04\x12\x02\x03\x12\x04\xe6\x05\ - \x02(\n\r\n\x05\x04\x12\x02\x03\x04\x12\x04\xe6\x05\x02\n\n\r\n\x05\x04\ - \x12\x02\x03\x05\x12\x04\xe6\x05\x0b\x10\n\r\n\x05\x04\x12\x02\x03\x01\ - \x12\x04\xe6\x05\x11#\n\r\n\x05\x04\x12\x02\x03\x03\x12\x04\xe6\x05&'\n\ - \x0c\n\x04\x04\x12\x02\x04\x12\x04\xe7\x05\x02#\n\r\n\x05\x04\x12\x02\ - \x04\x04\x12\x04\xe7\x05\x02\n\n\r\n\x05\x04\x12\x02\x04\x05\x12\x04\xe7\ - \x05\x0b\x11\n\r\n\x05\x04\x12\x02\x04\x01\x12\x04\xe7\x05\x12\x1e\n\r\n\ - \x05\x04\x12\x02\x04\x03\x12\x04\xe7\x05!\"\n\x0c\n\x04\x04\x12\x02\x05\ - \x12\x04\xe8\x05\x02\"\n\r\n\x05\x04\x12\x02\x05\x04\x12\x04\xe8\x05\x02\ - \n\n\r\n\x05\x04\x12\x02\x05\x05\x12\x04\xe8\x05\x0b\x10\n\r\n\x05\x04\ - \x12\x02\x05\x01\x12\x04\xe8\x05\x11\x1d\n\r\n\x05\x04\x12\x02\x05\x03\ - \x12\x04\xe8\x05\x20!\n\x0c\n\x04\x04\x12\x02\x06\x12\x04\xe9\x05\x02&\n\ - \r\n\x05\x04\x12\x02\x06\x04\x12\x04\xe9\x05\x02\n\n\r\n\x05\x04\x12\x02\ - \x06\x05\x12\x04\xe9\x05\x0b\x11\n\r\n\x05\x04\x12\x02\x06\x01\x12\x04\ - \xe9\x05\x12!\n\r\n\x05\x04\x12\x02\x06\x03\x12\x04\xe9\x05$%\n\xda\x01\ - \n\x02\x04\x13\x12\x06\xf1\x05\0\xf2\x06\x01\x1aj\x20Encapsulates\x20inf\ + \x04\x12\x02\x01\x04\x12\x04\xe6\x05\x02\n\n\r\n\x05\x04\x12\x02\x01\x05\ + \x12\x04\xe6\x05\x0b\x11\n\r\n\x05\x04\x12\x02\x01\x01\x12\x04\xe6\x05\ + \x12\"\n\r\n\x05\x04\x12\x02\x01\x03\x12\x04\xe6\x05%&\n\x0c\n\x04\x04\ + \x12\x02\x02\x12\x04\xe7\x05\x02)\n\r\n\x05\x04\x12\x02\x02\x04\x12\x04\ + \xe7\x05\x02\n\n\r\n\x05\x04\x12\x02\x02\x05\x12\x04\xe7\x05\x0b\x11\n\r\ + \n\x05\x04\x12\x02\x02\x01\x12\x04\xe7\x05\x12$\n\r\n\x05\x04\x12\x02\ + \x02\x03\x12\x04\xe7\x05'(\n\x0c\n\x04\x04\x12\x02\x03\x12\x04\xe8\x05\ + \x02(\n\r\n\x05\x04\x12\x02\x03\x04\x12\x04\xe8\x05\x02\n\n\r\n\x05\x04\ + \x12\x02\x03\x05\x12\x04\xe8\x05\x0b\x10\n\r\n\x05\x04\x12\x02\x03\x01\ + \x12\x04\xe8\x05\x11#\n\r\n\x05\x04\x12\x02\x03\x03\x12\x04\xe8\x05&'\n\ + \x0c\n\x04\x04\x12\x02\x04\x12\x04\xe9\x05\x02#\n\r\n\x05\x04\x12\x02\ + \x04\x04\x12\x04\xe9\x05\x02\n\n\r\n\x05\x04\x12\x02\x04\x05\x12\x04\xe9\ + \x05\x0b\x11\n\r\n\x05\x04\x12\x02\x04\x01\x12\x04\xe9\x05\x12\x1e\n\r\n\ + \x05\x04\x12\x02\x04\x03\x12\x04\xe9\x05!\"\n\x0c\n\x04\x04\x12\x02\x05\ + \x12\x04\xea\x05\x02\"\n\r\n\x05\x04\x12\x02\x05\x04\x12\x04\xea\x05\x02\ + \n\n\r\n\x05\x04\x12\x02\x05\x05\x12\x04\xea\x05\x0b\x10\n\r\n\x05\x04\ + \x12\x02\x05\x01\x12\x04\xea\x05\x11\x1d\n\r\n\x05\x04\x12\x02\x05\x03\ + \x12\x04\xea\x05\x20!\n\x0c\n\x04\x04\x12\x02\x06\x12\x04\xeb\x05\x02&\n\ + \r\n\x05\x04\x12\x02\x06\x04\x12\x04\xeb\x05\x02\n\n\r\n\x05\x04\x12\x02\ + \x06\x05\x12\x04\xeb\x05\x0b\x11\n\r\n\x05\x04\x12\x02\x06\x01\x12\x04\ + \xeb\x05\x12!\n\r\n\x05\x04\x12\x02\x06\x03\x12\x04\xeb\x05$%\n\xda\x01\ + \n\x02\x04\x13\x12\x06\xf3\x05\0\xf4\x06\x01\x1aj\x20Encapsulates\x20inf\ ormation\x20about\x20the\x20original\x20source\x20file\x20from\x20which\ \x20a\n\x20FileDescriptorProto\x20was\x20generated.\n2`\x20=============\ ======================================================\n\x20Optional\x20\ - source\x20code\x20info\n\n\x0b\n\x03\x04\x13\x01\x12\x04\xf1\x05\x08\x16\ - \n\x82\x11\n\x04\x04\x13\x02\0\x12\x04\x9d\x06\x02!\x1a\xf3\x10\x20A\x20\ + source\x20code\x20info\n\n\x0b\n\x03\x04\x13\x01\x12\x04\xf3\x05\x08\x16\ + \n\x82\x11\n\x04\x04\x13\x02\0\x12\x04\x9f\x06\x02!\x1a\xf3\x10\x20A\x20\ Location\x20identifies\x20a\x20piece\x20of\x20source\x20code\x20in\x20a\ \x20.proto\x20file\x20which\n\x20corresponds\x20to\x20a\x20particular\ \x20definition.\x20\x20This\x20information\x20is\x20intended\n\x20to\x20\ @@ -10709,11 +9431,11 @@ static file_descriptor_proto_data: &'static [u8] = b"\ o\n\x20\x20\x20ignore\x20those\x20that\x20it\x20doesn't\x20understand,\ \x20as\x20more\x20types\x20of\x20locations\x20could\n\x20\x20\x20be\x20r\ ecorded\x20in\x20the\x20future.\n\n\r\n\x05\x04\x13\x02\0\x04\x12\x04\ - \x9d\x06\x02\n\n\r\n\x05\x04\x13\x02\0\x06\x12\x04\x9d\x06\x0b\x13\n\r\n\ - \x05\x04\x13\x02\0\x01\x12\x04\x9d\x06\x14\x1c\n\r\n\x05\x04\x13\x02\0\ - \x03\x12\x04\x9d\x06\x1f\x20\n\x0e\n\x04\x04\x13\x03\0\x12\x06\x9e\x06\ - \x02\xf1\x06\x03\n\r\n\x05\x04\x13\x03\0\x01\x12\x04\x9e\x06\n\x12\n\x83\ - \x07\n\x06\x04\x13\x03\0\x02\0\x12\x04\xb6\x06\x04,\x1a\xf2\x06\x20Ident\ + \x9f\x06\x02\n\n\r\n\x05\x04\x13\x02\0\x06\x12\x04\x9f\x06\x0b\x13\n\r\n\ + \x05\x04\x13\x02\0\x01\x12\x04\x9f\x06\x14\x1c\n\r\n\x05\x04\x13\x02\0\ + \x03\x12\x04\x9f\x06\x1f\x20\n\x0e\n\x04\x04\x13\x03\0\x12\x06\xa0\x06\ + \x02\xf3\x06\x03\n\r\n\x05\x04\x13\x03\0\x01\x12\x04\xa0\x06\n\x12\n\x83\ + \x07\n\x06\x04\x13\x03\0\x02\0\x12\x04\xb8\x06\x04,\x1a\xf2\x06\x20Ident\ ifies\x20which\x20part\x20of\x20the\x20FileDescriptorProto\x20was\x20def\ ined\x20at\x20this\n\x20location.\n\n\x20Each\x20element\x20is\x20a\x20f\ ield\x20number\x20or\x20an\x20index.\x20\x20They\x20form\x20a\x20path\ @@ -10734,12 +9456,12 @@ static file_descriptor_proto_data: &'static [u8] = b"\ lement:\n\x20\x20\x20[\x204,\x203,\x202,\x207\x20]\n\x20this\x20path\x20\ refers\x20to\x20the\x20whole\x20field\x20declaration\x20(from\x20the\x20\ beginning\n\x20of\x20the\x20label\x20to\x20the\x20terminating\x20semicol\ - on).\n\n\x0f\n\x07\x04\x13\x03\0\x02\0\x04\x12\x04\xb6\x06\x04\x0c\n\x0f\ - \n\x07\x04\x13\x03\0\x02\0\x05\x12\x04\xb6\x06\r\x12\n\x0f\n\x07\x04\x13\ - \x03\0\x02\0\x01\x12\x04\xb6\x06\x13\x17\n\x0f\n\x07\x04\x13\x03\0\x02\0\ - \x03\x12\x04\xb6\x06\x1a\x1b\n\x0f\n\x07\x04\x13\x03\0\x02\0\x08\x12\x04\ - \xb6\x06\x1c+\n\x10\n\x08\x04\x13\x03\0\x02\0\x08\x02\x12\x04\xb6\x06\ - \x1d*\n\xd2\x02\n\x06\x04\x13\x03\0\x02\x01\x12\x04\xbd\x06\x04,\x1a\xc1\ + on).\n\n\x0f\n\x07\x04\x13\x03\0\x02\0\x04\x12\x04\xb8\x06\x04\x0c\n\x0f\ + \n\x07\x04\x13\x03\0\x02\0\x05\x12\x04\xb8\x06\r\x12\n\x0f\n\x07\x04\x13\ + \x03\0\x02\0\x01\x12\x04\xb8\x06\x13\x17\n\x0f\n\x07\x04\x13\x03\0\x02\0\ + \x03\x12\x04\xb8\x06\x1a\x1b\n\x0f\n\x07\x04\x13\x03\0\x02\0\x08\x12\x04\ + \xb8\x06\x1c+\n\x10\n\x08\x04\x13\x03\0\x02\0\x08\x02\x12\x04\xb8\x06\ + \x1d*\n\xd2\x02\n\x06\x04\x13\x03\0\x02\x01\x12\x04\xbf\x06\x04,\x1a\xc1\ \x02\x20Always\x20has\x20exactly\x20three\x20or\x20four\x20elements:\x20\ start\x20line,\x20start\x20column,\n\x20end\x20line\x20(optional,\x20oth\ erwise\x20assumed\x20same\x20as\x20start\x20line),\x20end\x20column.\n\ @@ -10747,12 +9469,12 @@ static file_descriptor_proto_data: &'static [u8] = b"\ iciency.\x20\x20Note\x20that\x20line\n\x20and\x20column\x20numbers\x20ar\ e\x20zero-based\x20--\x20typically\x20you\x20will\x20want\x20to\x20add\n\ \x201\x20to\x20each\x20before\x20displaying\x20to\x20a\x20user.\n\n\x0f\ - \n\x07\x04\x13\x03\0\x02\x01\x04\x12\x04\xbd\x06\x04\x0c\n\x0f\n\x07\x04\ - \x13\x03\0\x02\x01\x05\x12\x04\xbd\x06\r\x12\n\x0f\n\x07\x04\x13\x03\0\ - \x02\x01\x01\x12\x04\xbd\x06\x13\x17\n\x0f\n\x07\x04\x13\x03\0\x02\x01\ - \x03\x12\x04\xbd\x06\x1a\x1b\n\x0f\n\x07\x04\x13\x03\0\x02\x01\x08\x12\ - \x04\xbd\x06\x1c+\n\x10\n\x08\x04\x13\x03\0\x02\x01\x08\x02\x12\x04\xbd\ - \x06\x1d*\n\xa5\x0c\n\x06\x04\x13\x03\0\x02\x02\x12\x04\xee\x06\x04)\x1a\ + \n\x07\x04\x13\x03\0\x02\x01\x04\x12\x04\xbf\x06\x04\x0c\n\x0f\n\x07\x04\ + \x13\x03\0\x02\x01\x05\x12\x04\xbf\x06\r\x12\n\x0f\n\x07\x04\x13\x03\0\ + \x02\x01\x01\x12\x04\xbf\x06\x13\x17\n\x0f\n\x07\x04\x13\x03\0\x02\x01\ + \x03\x12\x04\xbf\x06\x1a\x1b\n\x0f\n\x07\x04\x13\x03\0\x02\x01\x08\x12\ + \x04\xbf\x06\x1c+\n\x10\n\x08\x04\x13\x03\0\x02\x01\x08\x02\x12\x04\xbf\ + \x06\x1d*\n\xa5\x0c\n\x06\x04\x13\x03\0\x02\x02\x12\x04\xf0\x06\x04)\x1a\ \x94\x0c\x20If\x20this\x20SourceCodeInfo\x20represents\x20a\x20complete\ \x20declaration,\x20these\x20are\x20any\n\x20comments\x20appearing\x20be\ fore\x20and\x20after\x20the\x20declaration\x20which\x20appear\x20to\x20b\ @@ -10788,71 +9510,120 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x20removed.\x20*/\n\x20\x20\x20/*\x20Block\x20comment\x20attached\x20to\ \n\x20\x20\x20\x20*\x20grault.\x20*/\n\x20\x20\x20optional\x20int32\x20g\ rault\x20=\x206;\n\n\x20\x20\x20//\x20ignored\x20detached\x20comments.\n\ - \n\x0f\n\x07\x04\x13\x03\0\x02\x02\x04\x12\x04\xee\x06\x04\x0c\n\x0f\n\ - \x07\x04\x13\x03\0\x02\x02\x05\x12\x04\xee\x06\r\x13\n\x0f\n\x07\x04\x13\ - \x03\0\x02\x02\x01\x12\x04\xee\x06\x14$\n\x0f\n\x07\x04\x13\x03\0\x02\ - \x02\x03\x12\x04\xee\x06'(\n\x0e\n\x06\x04\x13\x03\0\x02\x03\x12\x04\xef\ - \x06\x04*\n\x0f\n\x07\x04\x13\x03\0\x02\x03\x04\x12\x04\xef\x06\x04\x0c\ - \n\x0f\n\x07\x04\x13\x03\0\x02\x03\x05\x12\x04\xef\x06\r\x13\n\x0f\n\x07\ - \x04\x13\x03\0\x02\x03\x01\x12\x04\xef\x06\x14%\n\x0f\n\x07\x04\x13\x03\ - \0\x02\x03\x03\x12\x04\xef\x06()\n\x0e\n\x06\x04\x13\x03\0\x02\x04\x12\ - \x04\xf0\x06\x042\n\x0f\n\x07\x04\x13\x03\0\x02\x04\x04\x12\x04\xf0\x06\ - \x04\x0c\n\x0f\n\x07\x04\x13\x03\0\x02\x04\x05\x12\x04\xf0\x06\r\x13\n\ - \x0f\n\x07\x04\x13\x03\0\x02\x04\x01\x12\x04\xf0\x06\x14-\n\x0f\n\x07\ - \x04\x13\x03\0\x02\x04\x03\x12\x04\xf0\x0601\n\xee\x01\n\x02\x04\x14\x12\ - \x06\xf7\x06\0\x8c\x07\x01\x1a\xdf\x01\x20Describes\x20the\x20relationsh\ + \n\x0f\n\x07\x04\x13\x03\0\x02\x02\x04\x12\x04\xf0\x06\x04\x0c\n\x0f\n\ + \x07\x04\x13\x03\0\x02\x02\x05\x12\x04\xf0\x06\r\x13\n\x0f\n\x07\x04\x13\ + \x03\0\x02\x02\x01\x12\x04\xf0\x06\x14$\n\x0f\n\x07\x04\x13\x03\0\x02\ + \x02\x03\x12\x04\xf0\x06'(\n\x0e\n\x06\x04\x13\x03\0\x02\x03\x12\x04\xf1\ + \x06\x04*\n\x0f\n\x07\x04\x13\x03\0\x02\x03\x04\x12\x04\xf1\x06\x04\x0c\ + \n\x0f\n\x07\x04\x13\x03\0\x02\x03\x05\x12\x04\xf1\x06\r\x13\n\x0f\n\x07\ + \x04\x13\x03\0\x02\x03\x01\x12\x04\xf1\x06\x14%\n\x0f\n\x07\x04\x13\x03\ + \0\x02\x03\x03\x12\x04\xf1\x06()\n\x0e\n\x06\x04\x13\x03\0\x02\x04\x12\ + \x04\xf2\x06\x042\n\x0f\n\x07\x04\x13\x03\0\x02\x04\x04\x12\x04\xf2\x06\ + \x04\x0c\n\x0f\n\x07\x04\x13\x03\0\x02\x04\x05\x12\x04\xf2\x06\r\x13\n\ + \x0f\n\x07\x04\x13\x03\0\x02\x04\x01\x12\x04\xf2\x06\x14-\n\x0f\n\x07\ + \x04\x13\x03\0\x02\x04\x03\x12\x04\xf2\x0601\n\xee\x01\n\x02\x04\x14\x12\ + \x06\xf9\x06\0\x8e\x07\x01\x1a\xdf\x01\x20Describes\x20the\x20relationsh\ ip\x20between\x20generated\x20code\x20and\x20its\x20original\x20source\n\ \x20file.\x20A\x20GeneratedCodeInfo\x20message\x20is\x20associated\x20wi\ th\x20only\x20one\x20generated\n\x20source\x20file,\x20but\x20may\x20con\ tain\x20references\x20to\x20different\x20source\x20.proto\x20files.\n\n\ - \x0b\n\x03\x04\x14\x01\x12\x04\xf7\x06\x08\x19\nx\n\x04\x04\x14\x02\0\ - \x12\x04\xfa\x06\x02%\x1aj\x20An\x20Annotation\x20connects\x20some\x20sp\ + \x0b\n\x03\x04\x14\x01\x12\x04\xf9\x06\x08\x19\nx\n\x04\x04\x14\x02\0\ + \x12\x04\xfc\x06\x02%\x1aj\x20An\x20Annotation\x20connects\x20some\x20sp\ an\x20of\x20text\x20in\x20generated\x20code\x20to\x20an\x20element\n\x20\ of\x20its\x20generating\x20.proto\x20file.\n\n\r\n\x05\x04\x14\x02\0\x04\ - \x12\x04\xfa\x06\x02\n\n\r\n\x05\x04\x14\x02\0\x06\x12\x04\xfa\x06\x0b\ - \x15\n\r\n\x05\x04\x14\x02\0\x01\x12\x04\xfa\x06\x16\x20\n\r\n\x05\x04\ - \x14\x02\0\x03\x12\x04\xfa\x06#$\n\x0e\n\x04\x04\x14\x03\0\x12\x06\xfb\ - \x06\x02\x8b\x07\x03\n\r\n\x05\x04\x14\x03\0\x01\x12\x04\xfb\x06\n\x14\n\ - \x8f\x01\n\x06\x04\x14\x03\0\x02\0\x12\x04\xfe\x06\x04,\x1a\x7f\x20Ident\ + \x12\x04\xfc\x06\x02\n\n\r\n\x05\x04\x14\x02\0\x06\x12\x04\xfc\x06\x0b\ + \x15\n\r\n\x05\x04\x14\x02\0\x01\x12\x04\xfc\x06\x16\x20\n\r\n\x05\x04\ + \x14\x02\0\x03\x12\x04\xfc\x06#$\n\x0e\n\x04\x04\x14\x03\0\x12\x06\xfd\ + \x06\x02\x8d\x07\x03\n\r\n\x05\x04\x14\x03\0\x01\x12\x04\xfd\x06\n\x14\n\ + \x8f\x01\n\x06\x04\x14\x03\0\x02\0\x12\x04\x80\x07\x04,\x1a\x7f\x20Ident\ ifies\x20the\x20element\x20in\x20the\x20original\x20source\x20.proto\x20\ file.\x20This\x20field\n\x20is\x20formatted\x20the\x20same\x20as\x20Sour\ ceCodeInfo.Location.path.\n\n\x0f\n\x07\x04\x14\x03\0\x02\0\x04\x12\x04\ - \xfe\x06\x04\x0c\n\x0f\n\x07\x04\x14\x03\0\x02\0\x05\x12\x04\xfe\x06\r\ - \x12\n\x0f\n\x07\x04\x14\x03\0\x02\0\x01\x12\x04\xfe\x06\x13\x17\n\x0f\n\ - \x07\x04\x14\x03\0\x02\0\x03\x12\x04\xfe\x06\x1a\x1b\n\x0f\n\x07\x04\x14\ - \x03\0\x02\0\x08\x12\x04\xfe\x06\x1c+\n\x10\n\x08\x04\x14\x03\0\x02\0\ - \x08\x02\x12\x04\xfe\x06\x1d*\nO\n\x06\x04\x14\x03\0\x02\x01\x12\x04\x81\ + \x80\x07\x04\x0c\n\x0f\n\x07\x04\x14\x03\0\x02\0\x05\x12\x04\x80\x07\r\ + \x12\n\x0f\n\x07\x04\x14\x03\0\x02\0\x01\x12\x04\x80\x07\x13\x17\n\x0f\n\ + \x07\x04\x14\x03\0\x02\0\x03\x12\x04\x80\x07\x1a\x1b\n\x0f\n\x07\x04\x14\ + \x03\0\x02\0\x08\x12\x04\x80\x07\x1c+\n\x10\n\x08\x04\x14\x03\0\x02\0\ + \x08\x02\x12\x04\x80\x07\x1d*\nO\n\x06\x04\x14\x03\0\x02\x01\x12\x04\x83\ \x07\x04$\x1a?\x20Identifies\x20the\x20filesystem\x20path\x20to\x20the\ \x20original\x20source\x20.proto.\n\n\x0f\n\x07\x04\x14\x03\0\x02\x01\ - \x04\x12\x04\x81\x07\x04\x0c\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x05\x12\ - \x04\x81\x07\r\x13\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x01\x12\x04\x81\x07\ - \x14\x1f\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x03\x12\x04\x81\x07\"#\nw\n\ - \x06\x04\x14\x03\0\x02\x02\x12\x04\x85\x07\x04\x1d\x1ag\x20Identifies\ + \x04\x12\x04\x83\x07\x04\x0c\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x05\x12\ + \x04\x83\x07\r\x13\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x01\x12\x04\x83\x07\ + \x14\x1f\n\x0f\n\x07\x04\x14\x03\0\x02\x01\x03\x12\x04\x83\x07\"#\nw\n\ + \x06\x04\x14\x03\0\x02\x02\x12\x04\x87\x07\x04\x1d\x1ag\x20Identifies\ \x20the\x20starting\x20offset\x20in\x20bytes\x20in\x20the\x20generated\ \x20code\n\x20that\x20relates\x20to\x20the\x20identified\x20object.\n\n\ - \x0f\n\x07\x04\x14\x03\0\x02\x02\x04\x12\x04\x85\x07\x04\x0c\n\x0f\n\x07\ - \x04\x14\x03\0\x02\x02\x05\x12\x04\x85\x07\r\x12\n\x0f\n\x07\x04\x14\x03\ - \0\x02\x02\x01\x12\x04\x85\x07\x13\x18\n\x0f\n\x07\x04\x14\x03\0\x02\x02\ - \x03\x12\x04\x85\x07\x1b\x1c\n\xdb\x01\n\x06\x04\x14\x03\0\x02\x03\x12\ - \x04\x8a\x07\x04\x1b\x1a\xca\x01\x20Identifies\x20the\x20ending\x20offse\ + \x0f\n\x07\x04\x14\x03\0\x02\x02\x04\x12\x04\x87\x07\x04\x0c\n\x0f\n\x07\ + \x04\x14\x03\0\x02\x02\x05\x12\x04\x87\x07\r\x12\n\x0f\n\x07\x04\x14\x03\ + \0\x02\x02\x01\x12\x04\x87\x07\x13\x18\n\x0f\n\x07\x04\x14\x03\0\x02\x02\ + \x03\x12\x04\x87\x07\x1b\x1c\n\xdb\x01\n\x06\x04\x14\x03\0\x02\x03\x12\ + \x04\x8c\x07\x04\x1b\x1a\xca\x01\x20Identifies\x20the\x20ending\x20offse\ t\x20in\x20bytes\x20in\x20the\x20generated\x20code\x20that\n\x20relates\ \x20to\x20the\x20identified\x20offset.\x20The\x20end\x20offset\x20should\ \x20be\x20one\x20past\n\x20the\x20last\x20relevant\x20byte\x20(so\x20the\ \x20length\x20of\x20the\x20text\x20=\x20end\x20-\x20begin).\n\n\x0f\n\ - \x07\x04\x14\x03\0\x02\x03\x04\x12\x04\x8a\x07\x04\x0c\n\x0f\n\x07\x04\ - \x14\x03\0\x02\x03\x05\x12\x04\x8a\x07\r\x12\n\x0f\n\x07\x04\x14\x03\0\ - \x02\x03\x01\x12\x04\x8a\x07\x13\x16\n\x0f\n\x07\x04\x14\x03\0\x02\x03\ - \x03\x12\x04\x8a\x07\x19\x1a\ + \x07\x04\x14\x03\0\x02\x03\x04\x12\x04\x8c\x07\x04\x0c\n\x0f\n\x07\x04\ + \x14\x03\0\x02\x03\x05\x12\x04\x8c\x07\r\x12\n\x0f\n\x07\x04\x14\x03\0\ + \x02\x03\x01\x12\x04\x8c\x07\x13\x16\n\x0f\n\x07\x04\x14\x03\0\x02\x03\ + \x03\x12\x04\x8c\x07\x19\x1a\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(27); + messages.push(FileDescriptorSet::generated_message_descriptor_data()); + messages.push(FileDescriptorProto::generated_message_descriptor_data()); + messages.push(DescriptorProto::generated_message_descriptor_data()); + messages.push(ExtensionRangeOptions::generated_message_descriptor_data()); + messages.push(FieldDescriptorProto::generated_message_descriptor_data()); + messages.push(OneofDescriptorProto::generated_message_descriptor_data()); + messages.push(EnumDescriptorProto::generated_message_descriptor_data()); + messages.push(EnumValueDescriptorProto::generated_message_descriptor_data()); + messages.push(ServiceDescriptorProto::generated_message_descriptor_data()); + messages.push(MethodDescriptorProto::generated_message_descriptor_data()); + messages.push(FileOptions::generated_message_descriptor_data()); + messages.push(MessageOptions::generated_message_descriptor_data()); + messages.push(FieldOptions::generated_message_descriptor_data()); + messages.push(OneofOptions::generated_message_descriptor_data()); + messages.push(EnumOptions::generated_message_descriptor_data()); + messages.push(EnumValueOptions::generated_message_descriptor_data()); + messages.push(ServiceOptions::generated_message_descriptor_data()); + messages.push(MethodOptions::generated_message_descriptor_data()); + messages.push(UninterpretedOption::generated_message_descriptor_data()); + messages.push(SourceCodeInfo::generated_message_descriptor_data()); + messages.push(GeneratedCodeInfo::generated_message_descriptor_data()); + messages.push(descriptor_proto::ExtensionRange::generated_message_descriptor_data()); + messages.push(descriptor_proto::ReservedRange::generated_message_descriptor_data()); + messages.push(enum_descriptor_proto::EnumReservedRange::generated_message_descriptor_data()); + messages.push(uninterpreted_option::NamePart::generated_message_descriptor_data()); + messages.push(source_code_info::Location::generated_message_descriptor_data()); + messages.push(generated_code_info::Annotation::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(6); + enums.push(field_descriptor_proto::Type::generated_enum_descriptor_data()); + enums.push(field_descriptor_proto::Label::generated_enum_descriptor_data()); + enums.push(file_options::OptimizeMode::generated_enum_descriptor_data()); + enums.push(field_options::CType::generated_enum_descriptor_data()); + enums.push(field_options::JSType::generated_enum_descriptor_data()); + enums.push(method_options::IdempotencyLevel::generated_enum_descriptor_data()); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/descriptorx.rs b/src/descriptorx.rs deleted file mode 100644 index 7b046ec..0000000 --- a/src/descriptorx.rs +++ /dev/null @@ -1,656 +0,0 @@ -// Should not be a part of public API -#![doc(hidden)] - -use crate::descriptor::DescriptorProto; -use crate::descriptor::EnumDescriptorProto; -use crate::descriptor::EnumValueDescriptorProto; -use crate::descriptor::FieldDescriptorProto; -/// utilities to work with descriptor -use crate::descriptor::FileDescriptorProto; -use crate::descriptor::OneofDescriptorProto; -use crate::rust; -use crate::strx; - -// Copy-pasted from libsyntax. -fn ident_start(c: char) -> bool { - (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' -} - -// Copy-pasted from libsyntax. -fn ident_continue(c: char) -> bool { - (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' -} - -pub fn proto_path_to_rust_mod(path: &str) -> String { - let without_dir = strx::remove_to(path, '/'); - let without_suffix = strx::remove_suffix(without_dir, ".proto"); - - let name = without_suffix - .chars() - .enumerate() - .map(|(i, c)| { - let valid = if i == 0 { - ident_start(c) - } else { - ident_continue(c) - }; - if valid { - c - } else { - '_' - } - }) - .collect::<String>(); - - let name = if rust::is_rust_keyword(&name) { - format!("{}_pb", name) - } else { - name - }; - name -} - -pub struct RootScope<'a> { - pub file_descriptors: &'a [FileDescriptorProto], -} - -impl<'a> RootScope<'a> { - fn packages(&'a self) -> Vec<FileScope<'a>> { - self.file_descriptors - .iter() - .map(|fd| FileScope { - file_descriptor: fd, - }) - .collect() - } - - // find enum by fully qualified name - pub fn find_enum(&'a self, fqn: &str) -> EnumWithScope<'a> { - match self.find_message_or_enum(fqn) { - MessageOrEnumWithScope::Enum(e) => e, - _ => panic!("not an enum: {}", fqn), - } - } - - // find message by fully qualified name - pub fn find_message(&'a self, fqn: &str) -> MessageWithScope<'a> { - match self.find_message_or_enum(fqn) { - MessageOrEnumWithScope::Message(m) => m, - _ => panic!("not a message: {}", fqn), - } - } - - // find message or enum by fully qualified name - pub fn find_message_or_enum(&'a self, fqn: &str) -> MessageOrEnumWithScope<'a> { - assert!(fqn.starts_with("."), "name must start with dot: {}", fqn); - let fqn1 = &fqn[1..]; - self.packages() - .into_iter() - .flat_map(|p| { - (if p.get_package().is_empty() { - p.find_message_or_enum(fqn1) - } else if fqn1.starts_with(&(p.get_package().to_string() + ".")) { - let remaining = &fqn1[(p.get_package().len() + 1)..]; - p.find_message_or_enum(remaining) - } else { - None - }) - .into_iter() - }) - .next() - .expect(&format!("enum not found by name: {}", fqn)) - } -} - -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum Syntax { - PROTO2, - PROTO3, -} - -impl Syntax { - pub fn parse(s: &str) -> Self { - match s { - "" | "proto2" => Syntax::PROTO2, - "proto3" => Syntax::PROTO3, - _ => panic!("unsupported syntax value: {:?}", s), - } - } -} - -#[derive(Clone)] -pub struct FileScope<'a> { - pub file_descriptor: &'a FileDescriptorProto, -} - -impl<'a> FileScope<'a> { - fn get_package(&self) -> &'a str { - self.file_descriptor.get_package() - } - - pub fn syntax(&self) -> Syntax { - Syntax::parse(self.file_descriptor.get_syntax()) - } - - pub fn to_scope(&self) -> Scope<'a> { - Scope { - file_scope: self.clone(), - path: Vec::new(), - } - } - - fn find_message_or_enum(&self, name: &str) -> Option<MessageOrEnumWithScope<'a>> { - assert!(!name.starts_with(".")); - self.find_messages_and_enums() - .into_iter() - .filter(|e| e.name_to_package() == name) - .next() - } - - // find all enums in given file descriptor - pub fn find_enums(&self) -> Vec<EnumWithScope<'a>> { - let mut r = Vec::new(); - - self.to_scope().walk_scopes(|scope| { - r.extend(scope.get_enums()); - }); - - r - } - - // find all messages in given file descriptor - pub fn find_messages(&self) -> Vec<MessageWithScope<'a>> { - let mut r = Vec::new(); - - self.to_scope().walk_scopes(|scope| { - r.extend(scope.get_messages()); - }); - - r - } - - // find all messages and enums in given file descriptor - pub fn find_messages_and_enums(&self) -> Vec<MessageOrEnumWithScope<'a>> { - let mut r = Vec::new(); - - self.to_scope().walk_scopes(|scope| { - r.extend(scope.get_messages_and_enums()); - }); - - r - } -} - -#[derive(Clone)] -pub struct Scope<'a> { - pub file_scope: FileScope<'a>, - pub path: Vec<&'a DescriptorProto>, -} - -impl<'a> Scope<'a> { - pub fn get_file_descriptor(&self) -> &'a FileDescriptorProto { - self.file_scope.file_descriptor - } - - // get message descriptors in this scope - fn get_message_descriptors(&self) -> &'a [DescriptorProto] { - if self.path.is_empty() { - self.file_scope.file_descriptor.get_message_type() - } else { - self.path.last().unwrap().get_nested_type() - } - } - - // get enum descriptors in this scope - fn get_enum_descriptors(&self) -> &'a [EnumDescriptorProto] { - if self.path.is_empty() { - self.file_scope.file_descriptor.get_enum_type() - } else { - self.path.last().unwrap().get_enum_type() - } - } - - // get messages with attached scopes in this scope - pub fn get_messages(&self) -> Vec<MessageWithScope<'a>> { - self.get_message_descriptors() - .iter() - .map(|m| MessageWithScope { - scope: self.clone(), - message: m, - }) - .collect() - } - - // get enums with attached scopes in this scope - pub fn get_enums(&self) -> Vec<EnumWithScope<'a>> { - self.get_enum_descriptors() - .iter() - .map(|e| EnumWithScope { - scope: self.clone(), - en: e, - }) - .collect() - } - - // get messages and enums with attached scopes in this scope - pub fn get_messages_and_enums(&self) -> Vec<MessageOrEnumWithScope<'a>> { - self.get_messages() - .into_iter() - .map(|m| MessageOrEnumWithScope::Message(m)) - .chain( - self.get_enums() - .into_iter() - .map(|m| MessageOrEnumWithScope::Enum(m)), - ) - .collect() - } - - // nested scopes, i. e. scopes of nested messages - fn nested_scopes(&self) -> Vec<Scope<'a>> { - self.get_message_descriptors() - .iter() - .map(|m| { - let mut nested = self.clone(); - nested.path.push(m); - nested - }) - .collect() - } - - fn walk_scopes_impl<F: FnMut(&Scope<'a>)>(&self, callback: &mut F) { - (*callback)(self); - - for nested in self.nested_scopes() { - nested.walk_scopes_impl(callback); - } - } - - // apply callback for this scope and all nested scopes - fn walk_scopes<F>(&self, mut callback: F) - where - F: FnMut(&Scope<'a>), - { - self.walk_scopes_impl(&mut callback); - } - - pub fn prefix(&self) -> String { - if self.path.is_empty() { - "".to_string() - } else { - let v: Vec<&'a str> = self.path.iter().map(|m| m.get_name()).collect(); - let mut r = v.join("."); - r.push_str("."); - r - } - } - - // rust type name prefix for this scope - pub fn rust_prefix(&self) -> String { - self.prefix().replace(".", "_") - } -} - -pub trait WithScope<'a> { - fn get_scope(&self) -> &Scope<'a>; - - fn get_file_descriptor(&self) -> &'a FileDescriptorProto { - self.get_scope().get_file_descriptor() - } - - // message or enum name - fn get_name(&self) -> &'a str; - - fn escape_prefix(&self) -> &'static str; - - fn name_to_package(&self) -> String { - let mut r = self.get_scope().prefix(); - r.push_str(self.get_name()); - r - } - - /// Return absolute name starting with dot - fn name_absolute(&self) -> String { - let mut r = String::new(); - r.push_str("."); - let package = self.get_file_descriptor().get_package(); - if !package.is_empty() { - r.push_str(package); - r.push_str("."); - } - r.push_str(&self.name_to_package()); - r - } - - // rust type name of this descriptor - fn rust_name(&self) -> String { - let mut r = self.get_scope().rust_prefix(); - // Only escape if prefix is not empty - if r.is_empty() && rust::is_rust_keyword(self.get_name()) { - r.push_str(self.escape_prefix()); - } - r.push_str(self.get_name()); - r - } - - // fully-qualified name of this type - fn rust_fq_name(&self) -> String { - format!( - "{}::{}", - proto_path_to_rust_mod(self.get_scope().get_file_descriptor().get_name()), - self.rust_name() - ) - } -} - -#[derive(Clone)] -pub struct MessageWithScope<'a> { - pub scope: Scope<'a>, - pub message: &'a DescriptorProto, -} - -impl<'a> WithScope<'a> for MessageWithScope<'a> { - fn get_scope(&self) -> &Scope<'a> { - &self.scope - } - - fn escape_prefix(&self) -> &'static str { - "message_" - } - - fn get_name(&self) -> &'a str { - self.message.get_name() - } -} - -impl<'a> MessageWithScope<'a> { - pub fn into_scope(mut self) -> Scope<'a> { - self.scope.path.push(self.message); - self.scope - } - - pub fn to_scope(&self) -> Scope<'a> { - self.clone().into_scope() - } - - pub fn fields(&self) -> Vec<FieldWithContext<'a>> { - self.message - .get_field() - .iter() - .map(|f| FieldWithContext { - field: f, - message: self.clone(), - }) - .collect() - } - - pub fn oneofs(&self) -> Vec<OneofWithContext<'a>> { - self.message - .get_oneof_decl() - .iter() - .enumerate() - .map(|(index, oneof)| OneofWithContext { - message: self.clone(), - oneof: &oneof, - index: index as u32, - }) - .collect() - } - - pub fn oneof_by_index(&self, index: u32) -> OneofWithContext<'a> { - self.oneofs().swap_remove(index as usize) - } - - /// Pair of (key, value) if this message is map entry - pub fn map_entry(&'a self) -> Option<(FieldWithContext<'a>, FieldWithContext<'a>)> { - if self.message.get_options().get_map_entry() { - let key = self - .fields() - .into_iter() - .find(|f| f.field.get_number() == 1) - .unwrap(); - let value = self - .fields() - .into_iter() - .find(|f| f.field.get_number() == 2) - .unwrap(); - Some((key, value)) - } else { - None - } - } -} - -#[derive(Clone)] -pub struct EnumWithScope<'a> { - pub scope: Scope<'a>, - pub en: &'a EnumDescriptorProto, -} - -impl<'a> EnumWithScope<'a> { - // enum values - pub fn values(&'a self) -> &'a [EnumValueDescriptorProto] { - self.en.get_value() - } - - // find enum value by name - pub fn value_by_name(&'a self, name: &str) -> &'a EnumValueDescriptorProto { - self.en - .get_value() - .into_iter() - .find(|v| v.get_name() == name) - .unwrap() - } -} - -pub trait EnumValueDescriptorEx { - fn rust_name(&self) -> String; -} - -impl EnumValueDescriptorEx for EnumValueDescriptorProto { - fn rust_name(&self) -> String { - let mut r = String::new(); - if rust::is_rust_keyword(self.get_name()) { - r.push_str("value_"); - } - r.push_str(self.get_name()); - r - } -} - -impl<'a> WithScope<'a> for EnumWithScope<'a> { - fn get_scope(&self) -> &Scope<'a> { - &self.scope - } - - fn escape_prefix(&self) -> &'static str { - "enum_" - } - - fn get_name(&self) -> &'a str { - self.en.get_name() - } -} - -pub enum MessageOrEnumWithScope<'a> { - Message(MessageWithScope<'a>), - Enum(EnumWithScope<'a>), -} - -impl<'a> WithScope<'a> for MessageOrEnumWithScope<'a> { - fn get_scope(&self) -> &Scope<'a> { - match self { - &MessageOrEnumWithScope::Message(ref m) => m.get_scope(), - &MessageOrEnumWithScope::Enum(ref e) => e.get_scope(), - } - } - - fn escape_prefix(&self) -> &'static str { - match self { - &MessageOrEnumWithScope::Message(ref m) => m.escape_prefix(), - &MessageOrEnumWithScope::Enum(ref e) => e.escape_prefix(), - } - } - - fn get_name(&self) -> &'a str { - match self { - &MessageOrEnumWithScope::Message(ref m) => m.get_name(), - &MessageOrEnumWithScope::Enum(ref e) => e.get_name(), - } - } -} - -pub trait FieldDescriptorProtoExt { - fn rust_name(&self) -> String; -} - -impl FieldDescriptorProtoExt for FieldDescriptorProto { - fn rust_name(&self) -> String { - if rust::is_rust_keyword(self.get_name()) { - format!("field_{}", self.get_name()) - } else { - self.get_name().to_string() - } - } -} - -#[derive(Clone)] -pub struct FieldWithContext<'a> { - pub field: &'a FieldDescriptorProto, - pub message: MessageWithScope<'a>, -} - -impl<'a> FieldWithContext<'a> { - #[doc(hidden)] - pub fn is_oneof(&self) -> bool { - self.field.has_oneof_index() - } - - pub fn oneof(&self) -> Option<OneofWithContext<'a>> { - if self.is_oneof() { - Some( - self.message - .oneof_by_index(self.field.get_oneof_index() as u32), - ) - } else { - None - } - } - - pub fn number(&self) -> u32 { - self.field.get_number() as u32 - } - - /// Shortcut - pub fn name(&self) -> &str { - self.field.get_name() - } - - // field name in generated code - #[deprecated] - pub fn rust_name(&self) -> String { - self.field.rust_name() - } - - // From field to file root - pub fn containing_messages(&self) -> Vec<&'a DescriptorProto> { - let mut r = Vec::new(); - r.push(self.message.message); - r.extend(self.message.scope.path.iter().rev()); - r - } -} - -#[derive(Clone)] -pub struct OneofVariantWithContext<'a> { - pub oneof: &'a OneofWithContext<'a>, - pub field: &'a FieldDescriptorProto, -} - -#[derive(Clone)] -pub struct OneofWithContext<'a> { - pub oneof: &'a OneofDescriptorProto, - pub index: u32, - pub message: MessageWithScope<'a>, -} - -impl<'a> OneofWithContext<'a> { - /// Oneof rust name - pub fn name(&'a self) -> &'a str { - match self.oneof.get_name() { - "type" => "field_type", - "box" => "field_box", - x => x, - } - } - - /// rust type name of enum - pub fn rust_name(&self) -> String { - format!( - "{}_oneof_{}", - self.message.rust_name(), - self.oneof.get_name() - ) - } - - /// Oneof variants - pub fn variants(&'a self) -> Vec<OneofVariantWithContext<'a>> { - self.message - .fields() - .iter() - .filter(|f| f.field.has_oneof_index() && f.field.get_oneof_index() == self.index as i32) - .map(|f| OneofVariantWithContext { - oneof: self, - field: &f.field, - }) - .collect() - } -} - -/// Find message by rust type name -pub fn find_message_by_rust_name<'a>( - fd: &'a FileDescriptorProto, - rust_name: &str, -) -> MessageWithScope<'a> { - FileScope { - file_descriptor: fd, - } - .find_messages() - .into_iter() - .find(|m| m.rust_name() == rust_name) - .unwrap() -} - -/// Find enum by rust type name -pub fn find_enum_by_rust_name<'a>( - fd: &'a FileDescriptorProto, - rust_name: &str, -) -> EnumWithScope<'a> { - FileScope { - file_descriptor: fd, - } - .find_enums() - .into_iter() - .find(|e| e.rust_name() == rust_name) - .unwrap() -} - -#[cfg(test)] -mod test { - - use super::proto_path_to_rust_mod; - - #[test] - fn test_mod_path_proto_ext() { - assert_eq!("proto", proto_path_to_rust_mod("proto.proto")); - } - - #[test] - fn test_mod_path_unknown_ext() { - assert_eq!("proto_proto3", proto_path_to_rust_mod("proto.proto3")); - } - - #[test] - fn test_mod_path_empty_ext() { - assert_eq!("proto", proto_path_to_rust_mod("proto")); - } -} diff --git a/src/doctest_pb.rs b/src/doctest_pb.rs new file mode 100644 index 0000000..327ffe4 --- /dev/null +++ b/src/doctest_pb.rs @@ -0,0 +1,161 @@ +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_results)] +#![allow(unused_mut)] + +//! Generated file from `doctest_pb.proto` + +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:MyMessage) +pub struct MyMessage { + // special fields + // @@protoc_insertion_point(special_field:MyMessage.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a MyMessage { + fn default() -> &'a MyMessage { + <MyMessage as crate::Message>::default_instance() + } +} + +impl MyMessage { + pub fn new() -> MyMessage { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(0); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedMessageDescriptorData::new_2::<MyMessage>( + "MyMessage", + fields, + oneofs, + ) + } +} + +impl crate::Message for MyMessage { + const NAME: &'static str = "MyMessage"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> MyMessage { + MyMessage::new() + } + + fn clear(&mut self) { + self.special_fields.clear(); + } + + fn default_instance() -> &'static MyMessage { + static instance: MyMessage = MyMessage { + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for MyMessage { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("MyMessage").unwrap()).clone() + } +} + +impl ::std::fmt::Display for MyMessage { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for MyMessage { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x10doctest_pb.proto\"\x0b\n\tMyMessageJG\n\x06\x12\x04\x02\0\x05\x01\ + \n%\n\x01\x0c\x12\x03\x02\0\x122\x1b\x20Messages\x20used\x20in\x20doctes\ + ts\n\n\n\n\x02\x04\0\x12\x04\x04\0\x05\x01\n\n\n\x03\x04\0\x01\x12\x03\ + \x04\x08\x11b\x06proto3\ +"; + +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) +} + +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(MyMessage::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) + }) +} diff --git a/src/enum_full.rs b/src/enum_full.rs new file mode 100644 index 0000000..36184f3 --- /dev/null +++ b/src/enum_full.rs @@ -0,0 +1,14 @@ +use crate::reflect::EnumDescriptor; +use crate::reflect::EnumValueDescriptor; +use crate::Enum; + +/// Trait is implemented for all enum types if lite runtime is not requested. +/// +/// This trait provides access to runtime reflection. +pub trait EnumFull: Enum { + /// Get enum value descriptor. + fn descriptor(&self) -> EnumValueDescriptor; + + /// Get enum descriptor by type. + fn enum_descriptor() -> EnumDescriptor; +} diff --git a/src/enum_or_unknown.rs b/src/enum_or_unknown.rs new file mode 100644 index 0000000..d042fba --- /dev/null +++ b/src/enum_or_unknown.rs @@ -0,0 +1,104 @@ +use std::fmt; +use std::marker::PhantomData; +use std::mem; + +use crate::reflect::runtime_types::RuntimeTypeEnumOrUnknown; +use crate::reflect::EnumDescriptor; +use crate::reflect::ProtobufValue; +use crate::Enum; +use crate::EnumFull; + +/// Protobuf enums with possibly unknown values are preserved in this struct. +#[derive(Eq, PartialEq, Ord, PartialOrd, Copy, Clone)] +#[repr(transparent)] +// This should be <E: ProtobufEnum> when it no longer prevents using const fns. +pub struct EnumOrUnknown<E> { + value: i32, + _marker: PhantomData<E>, +} + +// Move into <E: ProtobufEnum> when no longer: +// > trait bounds other than `Sized` on const fn parameters are unstable. +impl<E> EnumOrUnknown<E> { + /// Construct from any `i32` value. + /// + /// Note passed value is not required to be a valid enum value. + pub const fn from_i32(value: i32) -> EnumOrUnknown<E> { + EnumOrUnknown { + value, + _marker: PhantomData, + } + } +} + +impl<E: Enum> EnumOrUnknown<E> { + /// Construct from typed enum + pub fn new(e: E) -> EnumOrUnknown<E> { + EnumOrUnknown::from_i32(e.value()) + } + + /// Get contained `i32` value of enum + pub fn value(&self) -> i32 { + self.value + } + + /// Get `i32` value as typed enum. Return `None` is value is unknown. + pub fn enum_value(&self) -> Result<E, i32> { + E::from_i32(self.value).ok_or(self.value) + } + + /// Get contained enum, panic if value is unknown. + pub fn unwrap(&self) -> E { + self.enum_value().unwrap() + } + + /// Get `i32` value as typed enum. + /// Return default enum value (first value) if value is unknown. + pub fn enum_value_or_default(&self) -> E { + self.enum_value().unwrap_or_default() + } + + /// Get `i32` value as typed enum. + /// Return given enum value if value is unknown. + pub fn enum_value_or(&self, map_unknown: E) -> E { + self.enum_value().unwrap_or(map_unknown) + } + + pub(crate) fn cast_to_values(enums: &[EnumOrUnknown<E>]) -> &[i32] { + assert_eq!(mem::size_of::<EnumOrUnknown<E>>(), mem::size_of::<i32>()); + // SAFETY: `EnumOrUnknown` is `repr(C)`. + unsafe { std::slice::from_raw_parts(enums.as_ptr() as *const i32, enums.len()) } + } +} + +impl<E: EnumFull> EnumOrUnknown<E> { + /// Get enum descriptor by type. + pub fn enum_descriptor() -> EnumDescriptor { + E::enum_descriptor() + } +} + +impl<E: Enum> From<E> for EnumOrUnknown<E> { + fn from(e: E) -> Self { + EnumOrUnknown::new(e) + } +} + +impl<E: Enum> Default for EnumOrUnknown<E> { + fn default() -> EnumOrUnknown<E> { + EnumOrUnknown::new(E::default()) + } +} + +impl<E: Enum + fmt::Debug> fmt::Debug for EnumOrUnknown<E> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.enum_value() { + Ok(e) => fmt::Debug::fmt(&e, f), + Err(e) => fmt::Debug::fmt(&e, f), + } + } +} + +impl<E: EnumFull> ProtobufValue for EnumOrUnknown<E> { + type RuntimeType = RuntimeTypeEnumOrUnknown<E>; +} diff --git a/src/enums.rs b/src/enums.rs index 558d6ff..125559b 100644 --- a/src/enums.rs +++ b/src/enums.rs @@ -1,8 +1,17 @@ -use crate::reflect::EnumDescriptor; -use crate::reflect::EnumValueDescriptor; +use std::fmt; /// Trait implemented by all protobuf enum types. -pub trait ProtobufEnum: Eq + Sized + Copy + 'static { +/// +/// Additionally, generated enums also implement [`EnumFull`](crate::EnumFull) trait, +/// which provides access to reflection. +pub trait Enum: Eq + Sized + Copy + fmt::Debug + Default + Send + Sync + 'static { + /// Enum name as specified in `.proto` file. + /// + /// There's full reflection when non-lite runtime code generation is used, + /// and enums implement [`EnumFull`](crate::EnumFull) trait. + /// This operation is for lite runtime. + const NAME: &'static str; + /// Get enum `i32` value. fn value(&self) -> i32; @@ -10,23 +19,6 @@ pub trait ProtobufEnum: Eq + Sized + Copy + 'static { /// Return `None` if value is unknown. fn from_i32(v: i32) -> Option<Self>; - /// Get all enum values for enum type. - fn values() -> &'static [Self] { - panic!(); - } - - /// Get enum value descriptor. - fn descriptor(&self) -> &'static EnumValueDescriptor { - self.enum_descriptor().value_by_number(self.value()) - } - - /// Get enum descriptor. - fn enum_descriptor(&self) -> &'static EnumDescriptor { - Self::enum_descriptor_static() - } - - /// Get enum descriptor by type. - fn enum_descriptor_static() -> &'static EnumDescriptor { - panic!(); - } + /// All enum values for enum type. + const VALUES: &'static [Self] = &[]; } diff --git a/src/error.rs b/src/error.rs index 3f06909..38b68fb 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,151 +1,133 @@ -//! Protobuf error type - -use std::error::Error; -use std::fmt; use std::io; use std::str; +use crate::reflect::error::ReflectError; use crate::wire_format::WireType; -/// `Result` alias for `ProtobufError` -pub type ProtobufResult<T> = Result<T, ProtobufError>; +/// [`Result`] alias for [`Error`]. +pub type Result<T> = std::result::Result<T, crate::Error>; /// Enum values added here for diagnostic purposes. /// Users should not depend on specific values. -#[derive(Debug)] -pub enum WireError { - /// Could not read complete message because stream is EOF +#[derive(Debug, thiserror::Error)] +pub(crate) enum WireError { + #[error("Unexpected EOF")] UnexpectedEof, - /// Wrong wire type for given field + #[error("Unexpected wire type")] UnexpectedWireType(WireType), - /// Incorrect tag value + #[error("Incorrect tag")] IncorrectTag(u32), - /// Malformed map field - IncompleteMap, - /// Malformed varint + #[error("Incorrect varint")] IncorrectVarint, - /// String is not valid UTD-8 + #[error("Invalid UTF-8 sequence")] Utf8Error, - /// Enum value is unknown - InvalidEnumValue(i32), - /// Message is too nested + #[error("Invalid enum `{}` value: {}", .0, .1)] + InvalidEnumValue(&'static str, i32), + #[error("Over recursion limit")] OverRecursionLimit, - /// Could not read complete message because stream is EOF + #[error("Truncated message")] TruncatedMessage, - /// Other error - Other, -} - -impl fmt::Display for WireError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - WireError::Utf8Error => write!(f, "invalid UTF-8 sequence"), - WireError::UnexpectedWireType(..) => write!(f, "unexpected wire type"), - WireError::InvalidEnumValue(..) => write!(f, "invalid enum value"), - WireError::IncorrectTag(..) => write!(f, "incorrect tag"), - WireError::IncorrectVarint => write!(f, "incorrect varint"), - WireError::IncompleteMap => write!(f, "incomplete map"), - WireError::UnexpectedEof => write!(f, "unexpected EOF"), - WireError::OverRecursionLimit => write!(f, "over recursion limit"), - WireError::TruncatedMessage => write!(f, "truncated message"), - WireError::Other => write!(f, "other error"), - } - } + // not really possible + #[error("Limit overflow")] + LimitOverflow, + #[error("New limit must not be greater than current limit")] + LimitIncrease, + #[error("Encoded message size {0} is too large")] + MessageTooLarge(u64), + #[error("Value too large for u32: {}", .0)] + U32Overflow(u64), + #[error("Value too large for i32: {}", .0)] + I32Overflow(i64), } /// Generic protobuf error -#[derive(Debug)] -pub enum ProtobufError { +#[derive(Debug, thiserror::Error)] +pub(crate) enum ProtobufError { /// I/O error when reading or writing - IoError(io::Error), + #[error(transparent)] + IoError(#[from] io::Error), /// Malformed input - WireError(WireError), + #[error(transparent)] + WireError(#[from] WireError), + #[error(transparent)] + Reflect(#[from] ReflectError), /// Protocol contains a string which is not valid UTF-8 string - Utf8(str::Utf8Error), - /// Not all required fields set - MessageNotInitialized { - /// Message name - message: &'static str, - }, -} - -impl ProtobufError { - /// Create message not initialized error. - #[doc(hidden)] - pub fn message_not_initialized(message: &'static str) -> ProtobufError { - ProtobufError::MessageNotInitialized { message: message } - } -} - -impl fmt::Display for ProtobufError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - // not sure that cause should be included in message - &ProtobufError::IoError(ref e) => write!(f, "IO error: {}", e), - &ProtobufError::WireError(ref e) => fmt::Display::fmt(e, f), - &ProtobufError::Utf8(ref e) => write!(f, "{}", e), - &ProtobufError::MessageNotInitialized { .. } => write!(f, "not all message fields set"), - } - } + #[error("UTF-8 decode error")] + Utf8( + #[source] + #[from] + str::Utf8Error, + ), + /// Not all required fields of message set. + #[error("Message `{}` is missing required fields", .0)] + MessageNotInitialized(String), + /// Message is too large. + #[error("Provided buffer has not enough capacity to write message `{0}`")] + BufferHasNotEnoughCapacity(String), + /// Protobuf type and runtime types mismatch. + #[error("Protobuf type and runtime types are not compatible")] + IncompatibleProtobufTypeAndRuntimeType, + /// Group field type not implemented. + #[error("Group field is not supported")] + GroupIsNotImplemented, } -impl Error for ProtobufError { - #[allow(deprecated)] // call to `description` - fn description(&self) -> &str { - match self { - // not sure that cause should be included in message - &ProtobufError::IoError(ref e) => e.description(), - &ProtobufError::WireError(ref e) => match *e { - WireError::Utf8Error => "invalid UTF-8 sequence", - WireError::UnexpectedWireType(..) => "unexpected wire type", - WireError::InvalidEnumValue(..) => "invalid enum value", - WireError::IncorrectTag(..) => "incorrect tag", - WireError::IncorrectVarint => "incorrect varint", - WireError::IncompleteMap => "incomplete map", - WireError::UnexpectedEof => "unexpected EOF", - WireError::OverRecursionLimit => "over recursion limit", - WireError::TruncatedMessage => "truncated message", - WireError::Other => "other error", - }, - &ProtobufError::Utf8(ref e) => &e.description(), - &ProtobufError::MessageNotInitialized { .. } => "not all message fields set", - } - } +/// Error type for protobuf operations. +#[derive(Debug, thiserror::Error)] +#[error(transparent)] +pub struct Error(pub(crate) Box<ProtobufError>); - fn cause(&self) -> Option<&dyn Error> { - match self { - &ProtobufError::IoError(ref e) => Some(e), - &ProtobufError::Utf8(ref e) => Some(e), - &ProtobufError::WireError(..) => None, - &ProtobufError::MessageNotInitialized { .. } => None, - } +impl From<ProtobufError> for Error { + #[cold] + fn from(e: ProtobufError) -> Self { + Self(Box::new(e)) } } -impl From<io::Error> for ProtobufError { - fn from(err: io::Error) -> Self { - ProtobufError::IoError(err) +impl From<WireError> for Error { + #[cold] + fn from(e: WireError) -> Self { + Self(Box::new(ProtobufError::WireError(e))) } } -impl From<str::Utf8Error> for ProtobufError { - fn from(err: str::Utf8Error) -> Self { - ProtobufError::Utf8(err) +impl From<ReflectError> for Error { + #[cold] + fn from(e: ReflectError) -> Self { + Self(Box::new(ProtobufError::Reflect(e))) } } -impl From<ProtobufError> for io::Error { - fn from(err: ProtobufError) -> Self { - match err { +impl From<Error> for io::Error { + #[cold] + fn from(err: Error) -> Self { + match *err.0 { ProtobufError::IoError(e) => e, ProtobufError::WireError(e) => { io::Error::new(io::ErrorKind::InvalidData, ProtobufError::WireError(e)) } - ProtobufError::MessageNotInitialized { message: msg } => io::Error::new( + ProtobufError::MessageNotInitialized(message) => io::Error::new( io::ErrorKind::InvalidInput, - ProtobufError::MessageNotInitialized { message: msg }, + ProtobufError::MessageNotInitialized(message), ), e => io::Error::new(io::ErrorKind::Other, Box::new(e)), } } } + +impl From<io::Error> for Error { + #[cold] + fn from(err: io::Error) -> Self { + Error(Box::new(ProtobufError::IoError(err))) + } +} + +#[cfg(test)] +mod test { + use std::mem; + + #[test] + fn error_size() { + assert_eq!(mem::size_of::<usize>(), mem::size_of::<crate::Error>()); + } +} @@ -1,47 +1,81 @@ //! Utilities to support "extension" fields. //! +//! This is a stopgap implementation, it only allows to fetch basic singular values, +//! and that's it. Anything similar to extension registry is not implemented yet. +//! //! Extensions are [described in the official protobuf documentation][exts]. //! //! [exts]: https://developers.google.com/protocol-buffers/docs/proto#extensions use std::marker::PhantomData; -use crate::message::Message; -use crate::types::ProtobufType; +use crate::descriptor::field_descriptor_proto::Type; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::Message; /// Optional ext field -pub struct ExtFieldOptional<M: Message, T: ProtobufType> { - /// Extension field number - pub field_number: u32, +/// +/// This is initialized from generated code, do not instantiate directly. +pub struct ExtFieldOptional<M, T> { + /// Extension field number. + field_number: u32, + /// Extension field type. + field_type: Type, /// Marker - // TODO: hide - pub phantom: PhantomData<(M, T)>, + phantom: PhantomData<(M, T)>, } /// Repeated ext field -pub struct ExtFieldRepeated<M: Message, T: ProtobufType> { +/// +/// This is initialized from generated code, do not instantiate directly. +pub struct ExtFieldRepeated<M, V> { /// Extension field number - pub field_number: u32, + #[allow(dead_code)] + field_number: u32, + /// Field type. + #[allow(dead_code)] + field_type: Type, /// Extension field number - // TODO: hide - pub phantom: PhantomData<(M, T)>, + phantom: PhantomData<(M, V)>, +} + +impl<M, V> ExtFieldOptional<M, V> { + /// Constructor. Called from generated code. + pub const fn new(field_number: u32, field_type: Type) -> Self { + ExtFieldOptional { + field_number, + field_type, + phantom: PhantomData, + } + } } -impl<M: Message, T: ProtobufType> ExtFieldOptional<M, T> { +impl<M: Message, V: ProtobufValue> ExtFieldOptional<M, V> { /// Get a copy of value from a message. /// /// Extension data is stored in [`UnknownFields`](crate::UnknownFields). - pub fn get(&self, m: &M) -> Option<T::Value> { - m.get_unknown_fields() + pub fn get(&self, m: &M) -> Option<V> { + m.unknown_fields() .get(self.field_number) - .and_then(T::get_from_unknown) + .and_then(|u| V::RuntimeType::get_from_unknown(u, self.field_type)) + } +} + +impl<M, V> ExtFieldRepeated<M, V> { + /// Constructor. Called from generated code. + pub const fn new(field_number: u32, field_type: Type) -> Self { + ExtFieldRepeated { + field_number, + field_type, + phantom: PhantomData, + } } } -impl<M: Message, T: ProtobufType> ExtFieldRepeated<M, T> { +impl<M: Message, V: ProtobufValue> ExtFieldRepeated<M, V> { /// Get a copy of value from a message (**not implemented**). - pub fn get(&self, _m: &M) -> Vec<T::Value> { - // TODO - unimplemented!() + pub fn get(&self, _m: &M) -> Vec<V> { + unimplemented!("extension fields implementation in rust-protobuf is stopgap") } } diff --git a/src/fixed.rs b/src/fixed.rs new file mode 100644 index 0000000..fe12770 --- /dev/null +++ b/src/fixed.rs @@ -0,0 +1,35 @@ +/// Fixed size integers. +pub(crate) trait ProtobufFixed { + /// Size of this fixed type in bytes. + const LEN: u32; +} + +impl ProtobufFixed for u32 { + const LEN: u32 = 4; +} + +impl ProtobufFixed for i32 { + const LEN: u32 = 4; +} + +impl ProtobufFixed for u64 { + const LEN: u32 = 8; +} + +impl ProtobufFixed for i64 { + const LEN: u32 = 8; +} + +impl ProtobufFixed for f32 { + const LEN: u32 = 4; +} + +impl ProtobufFixed for f64 { + const LEN: u32 = 8; +} + +/// Technically `bool` is not fixed, but it can be considered as fixed +/// for the purpose of encoding. +impl ProtobufFixed for bool { + const LEN: u32 = 1; +} diff --git a/src/json/json_name.rs b/src/json/json_name.rs deleted file mode 100644 index f5c9364..0000000 --- a/src/json/json_name.rs +++ /dev/null @@ -1,19 +0,0 @@ -/// Implementation must match exactly -/// `ToJsonName()` function in C++ `descriptor.cc`. -pub fn json_name(input: &str) -> String { - let mut capitalize_next = false; - let mut result = String::with_capacity(input.len()); - - for c in input.chars() { - if c == '_' { - capitalize_next = true; - } else if capitalize_next { - result.extend(c.to_uppercase()); - capitalize_next = false; - } else { - result.push(c); - } - } - - result -} diff --git a/src/json/mod.rs b/src/json/mod.rs deleted file mode 100644 index 2755aad..0000000 --- a/src/json/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! JSON serialization and deserialization. -//! -//! (Implemented in master, but not ported to stable branch yet). - -mod json_name; - -#[doc(hidden)] -pub use self::json_name::json_name; diff --git a/src/lazy.rs b/src/lazy.rs index 3575dd0..217f759 100644 --- a/src/lazy.rs +++ b/src/lazy.rs @@ -1,113 +1,24 @@ -//! Lazily initialized data. -//! Used in generated code. +use once_cell::sync::OnceCell; -// Avoid deprecation warnings when compiling rust-protobuf -#![allow(deprecated)] - -use std::mem; -use std::sync; - -/// Lasily initialized data. -#[deprecated( - since = "2.16", - note = "Please regenerate .rs files from .proto files to use newer APIs" -)] +/// Lazily initialized static variable. +/// +/// Used in generated code. +/// +/// Currently a wrapper around `once_cell`s `OnceCell`. pub struct Lazy<T> { - #[doc(hidden)] - pub lock: sync::Once, - #[doc(hidden)] - pub ptr: *const T, + once_cell: OnceCell<T>, } impl<T> Lazy<T> { - /// Uninitialized `Lazy` object. - /// - /// The initializer is added in rust-protobuf 2.11, for compatibility with - /// previously generated code, existing fields are kept public. - pub const INIT: Lazy<T> = Lazy { - lock: sync::Once::new(), - ptr: 0 as *const T, - }; - - /// Get lazy field value, initialize it with given function if not yet. - pub fn get<F>(&'static mut self, init: F) -> &'static T - where - F: FnOnce() -> T, - { - // ~ decouple the lifetimes of 'self' and 'self.lock' such we - // can initialize self.ptr in the call_once closure (note: we - // do have to initialize self.ptr in the closure to guarantee - // the ptr is valid for all calling threads at any point in - // time) - let lock: &sync::Once = unsafe { mem::transmute(&self.lock) }; - lock.call_once(|| unsafe { - self.ptr = mem::transmute(Box::new(init())); - }); - unsafe { &*self.ptr } + /// Uninitialized state. + pub const fn new() -> Lazy<T> { + Lazy { + once_cell: OnceCell::new(), + } } -} - -/// Used to initialize `lock` field in `Lazy` struct. -#[deprecated( - since = "2.11", - note = "Regenerate .proto files to use safer initializer" -)] -pub const ONCE_INIT: sync::Once = sync::Once::new(); - -#[cfg(test)] -mod test { - use std::sync::atomic::AtomicIsize; - use std::sync::atomic::Ordering; - use std::sync::Arc; - use std::sync::Barrier; - use std::thread; - - use super::Lazy; - #[test] - fn many_threads_calling_get() { - const N_THREADS: usize = 32; - const N_ITERS_IN_THREAD: usize = 32; - const N_ITERS: usize = 16; - - static mut LAZY: Lazy<String> = Lazy::INIT; - static CALL_COUNT: AtomicIsize = AtomicIsize::new(0); - - let value = "Hello, world!".to_owned(); - - for _ in 0..N_ITERS { - // Reset mutable state. - unsafe { - LAZY = Lazy::INIT; - } - CALL_COUNT.store(0, Ordering::SeqCst); - - // Create a bunch of threads, all calling .get() at the same time. - let mut threads = vec![]; - let barrier = Arc::new(Barrier::new(N_THREADS)); - - for _ in 0..N_THREADS { - let cloned_value_thread = value.clone(); - let cloned_barrier = barrier.clone(); - threads.push(thread::spawn(move || { - // Ensure all threads start at once to maximise contention. - cloned_barrier.wait(); - for _ in 0..N_ITERS_IN_THREAD { - assert_eq!(&cloned_value_thread, unsafe { - LAZY.get(|| { - CALL_COUNT.fetch_add(1, Ordering::SeqCst); - cloned_value_thread.clone() - }) - }); - } - })); - } - - for thread in threads { - thread.join().unwrap(); - } - - assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1); - } + /// Lazily initialize the value. + pub fn get(&self, f: impl FnOnce() -> T) -> &T { + self.once_cell.get_or_init(f) } } diff --git a/src/lazy_v2.rs b/src/lazy_v2.rs deleted file mode 100644 index 6f9ac1e..0000000 --- a/src/lazy_v2.rs +++ /dev/null @@ -1,90 +0,0 @@ -//! Lazily initialized data. -//! Used in generated code. - -use std::cell::UnsafeCell; -use std::sync; - -/// Lazily initialized data. -pub struct LazyV2<T: Sync> { - lock: sync::Once, - ptr: UnsafeCell<*const T>, -} - -unsafe impl<T: Sync> Sync for LazyV2<T> {} - -impl<T: Sync> LazyV2<T> { - /// Uninitialized `Lazy` object. - pub const INIT: LazyV2<T> = LazyV2 { - lock: sync::Once::new(), - ptr: UnsafeCell::new(0 as *const T), - }; - - /// Get lazy field value, initialize it with given function if not yet. - pub fn get<F>(&'static self, init: F) -> &'static T - where - F: FnOnce() -> T, - { - self.lock.call_once(|| unsafe { - *self.ptr.get() = Box::into_raw(Box::new(init())); - }); - unsafe { &**self.ptr.get() } - } -} - -#[cfg(test)] -mod test { - use std::sync::atomic::AtomicIsize; - use std::sync::atomic::Ordering; - use std::sync::Arc; - use std::sync::Barrier; - use std::thread; - - use super::LazyV2; - - #[test] - fn many_threads_calling_get() { - const N_THREADS: usize = 32; - const N_ITERS_IN_THREAD: usize = 32; - const N_ITERS: usize = 16; - - static mut LAZY: LazyV2<String> = LazyV2::INIT; - static CALL_COUNT: AtomicIsize = AtomicIsize::new(0); - - let value = "Hello, world!".to_owned(); - - for _ in 0..N_ITERS { - // Reset mutable state. - unsafe { - LAZY = LazyV2::INIT; - } - CALL_COUNT.store(0, Ordering::SeqCst); - - // Create a bunch of threads, all calling .get() at the same time. - let mut threads = vec![]; - let barrier = Arc::new(Barrier::new(N_THREADS)); - - for _ in 0..N_THREADS { - let cloned_value_thread = value.clone(); - let cloned_barrier = barrier.clone(); - threads.push(thread::spawn(move || { - // Ensure all threads start at once to maximise contention. - cloned_barrier.wait(); - for _ in 0..N_ITERS_IN_THREAD { - assert_eq!(&cloned_value_thread, unsafe { - LAZY.get(|| { - CALL_COUNT.fetch_add(1, Ordering::SeqCst); - cloned_value_thread.clone() - }) - }); - } - })); - } - - for thread in threads { - thread.join().unwrap(); - } - - assert_eq!(CALL_COUNT.load(Ordering::SeqCst), 1); - } - } -} @@ -1,186 +1,102 @@ //! # Library to read and write protocol buffers data //! -//! # Version 2 is stable +//! ## Features //! -//! Currently developed branch of rust-protobuf [is 3](https://docs.rs/protobuf/%3E=3.0.0-alpha). -//! It has the same spirit as version 2, but contains numerous improvements like: -//! * runtime reflection for mutability, not just for access -//! * protobuf text format and JSON parsing (which rely on reflection) -//! * dynamic message support: work with protobuf data without generating code from schema +//! This crate has one feature, which is `with-bytes`. //! -//! Stable version of rust-protobuf will be supported until version 3 released. +//! `with-bytes` enables `protobuf` crate support for +//! [`bytes` crate](https://github.com/tokio-rs/bytes): +//! when parsing bytes or strings from `bytes::Bytes`, +//! `protobuf` will be able to reference the input instead of allocating subarrays. //! -//! [Tracking issue for version 3](https://github.com/stepancheg/rust-protobuf/issues/518). +//! Note, codegen also need to be instructed to generate `Bytes` or `Chars` for +//! `bytes` or `string` protobuf types instead of default `Vec<u8>` or `String`, +//! just enabling option on this crate is not enough. //! -//! # How to generate rust code +//! See `Customize` struct in [`protobuf-codegen` crate](https://docs.rs/protobuf-codegen). //! -//! There are several ways to generate rust code from `.proto` files +//! ## Accompanying crates //! -//! ## Invoke `protoc` programmatically with protoc-rust crate (recommended) -//! -//! Have a look at readme in [protoc-rust crate](https://docs.rs/protoc-rust/=2). -//! -//! ## Use pure rust protobuf parser and code generator -//! -//! Readme should be in -//! [protobuf-codegen-pure crate](https://docs.rs/protobuf-codegen-pure/=2). -//! -//! ## Use protoc-gen-rust plugin -//! -//! Readme is [here](https://docs.rs/protobuf-codegen/=2). -//! -//! ## Generated code -//! -//! Have a look at generated files (for current development version), -//! used internally in rust-protobuf: -//! -//! * [descriptor.rs](https://github.com/stepancheg/rust-protobuf/blob/master/protobuf/src/descriptor.rs) -//! for [descriptor.proto](https://github.com/stepancheg/rust-protobuf/blob/master/protoc-bin-vendored/include/google/protobuf/descriptor.proto) -//! (that is part of Google protobuf) -//! -//! # Copy on write -//! -//! Rust-protobuf can be used with [bytes crate](https://github.com/tokio-rs/bytes). -//! -//! To enable `Bytes` you need to: -//! -//! 1. Enable `with-bytes` feature in rust-protobuf: -//! -//! ``` -//! [dependencies] -//! protobuf = { version = "~2.0", features = ["with-bytes"] } -//! ``` -//! -//! 2. Enable bytes option -//! -//! with `Customize` when codegen is invoked programmatically: -//! -//! ```ignore -//! protoc_rust::run(protoc_rust::Args { -//! ... -//! customize: Customize { -//! carllerche_bytes_for_bytes: Some(true), -//! carllerche_bytes_for_string: Some(true), -//! ..Default::default() -//! }, -//! }); -//! ``` -//! -//! or in `.proto` file: -//! -//! ```ignore -//! import "rustproto.proto"; -//! -//! option (rustproto.carllerche_bytes_for_bytes_all) = true; -//! option (rustproto.carllerche_bytes_for_string_all) = true; -//! ``` -//! -//! With these options enabled, fields of type `bytes` or `string` are -//! generated as `Bytes` or `Chars` respectively. When `CodedInputStream` is constructed -//! from `Bytes` object, fields of these types get subslices of original `Bytes` object, -//! instead of being allocated on heap. -//! -//! # Accompanying crates -//! -//! * [`protoc-rust`](https://docs.rs/protoc-rust/=2) -//! and [`protobuf-codegen-pure`](https://docs.rs/protobuf-codegen-pure/=2) +//! * [`protobuf-json-mapping`](https://docs.rs/protobuf-json-mapping) +//! implements JSON parsing and serialization for protobuf messages. +//! * [`protobuf-codegen`](https://docs.rs/protobuf-codegen) //! can be used to rust code from `.proto` crates. -//! * [`protobuf-codegen`](https://docs.rs/protobuf-codegen/=2) for `protoc-gen-rust` protoc plugin. -//! * [`protoc`](https://docs.rs/protoc/=2) crate can be used to invoke `protoc` programmatically. -//! * [`protoc-bin-vendored`](https://docs.rs/protoc-bin-vendored/=2) contains `protoc` command -//! packed into the crate. +//! * [`protoc-bin-vendored`](https://docs.rs/protoc-bin-vendored) +//! contains `protoc` command packed into the crate. +//! * [`protobuf-parse`](https://docs.rs/protobuf-parse) contains +//! `.proto` file parser. Rarely need to be used directly, +//! but can be used for mechanical processing of `.proto` files. #![deny(missing_docs)] #![deny(rustdoc::broken_intra_doc_links)] -#[cfg(feature = "bytes")] -extern crate bytes; -#[cfg(feature = "with-serde")] -extern crate serde; -#[macro_use] -#[cfg(feature = "with-serde")] -extern crate serde_derive; -pub use crate::cached_size::CachedSize; -#[cfg(feature = "bytes")] -pub use crate::chars::Chars; -pub use crate::clear::Clear; pub use crate::coded_input_stream::CodedInputStream; pub use crate::coded_output_stream::CodedOutputStream; -pub use crate::enums::ProtobufEnum; -pub use crate::error::ProtobufError; -pub use crate::error::ProtobufResult; -#[allow(deprecated)] -pub use crate::message::parse_from_bytes; -#[cfg(feature = "bytes")] -#[allow(deprecated)] -pub use crate::message::parse_from_carllerche_bytes; -#[allow(deprecated)] -pub use crate::message::parse_from_reader; -#[allow(deprecated)] -pub use crate::message::parse_length_delimited_from; -#[allow(deprecated)] -pub use crate::message::parse_length_delimited_from_bytes; -#[allow(deprecated)] -pub use crate::message::parse_length_delimited_from_reader; +pub use crate::enum_full::EnumFull; +pub use crate::enum_or_unknown::EnumOrUnknown; +pub use crate::enums::Enum; pub use crate::message::Message; -pub use crate::repeated::RepeatedField; -pub use crate::singular::SingularField; -pub use crate::singular::SingularPtrField; +pub use crate::message_dyn::MessageDyn; +pub use crate::message_field::MessageField; +pub use crate::message_full::MessageFull; +pub use crate::oneof::Oneof; +pub use crate::oneof_full::OneofFull; +pub use crate::special::SpecialFields; pub use crate::unknown::UnknownFields; pub use crate::unknown::UnknownFieldsIter; pub use crate::unknown::UnknownValue; pub use crate::unknown::UnknownValueRef; -pub use crate::unknown::UnknownValues; -pub use crate::unknown::UnknownValuesIter; +pub(crate) mod wire_format; +#[cfg(feature = "bytes")] +pub use crate::chars::Chars; +pub use crate::error::Error; +pub use crate::error::Result; // generated pub mod descriptor; pub mod plugin; pub mod rustproto; -pub mod wire_format; - -mod clear; +mod byteorder; mod coded_input_stream; mod coded_output_stream; -pub mod compiler_plugin; +mod enum_full; +mod enum_or_unknown; mod enums; -pub mod error; +mod error; pub mod ext; -pub mod json; -pub mod lazy; -mod lazy_v2; +mod lazy; mod message; +mod message_dyn; +mod message_field; +mod message_full; +mod oneof; +mod oneof_full; +mod owning_ref; pub mod reflect; -mod repeated; pub mod rt; -mod singular; pub mod text_format; -pub mod types; pub mod well_known_types; mod well_known_types_util; // used by test #[cfg(test)] -#[path = "../../protobuf-test-common/src/hex.rs"] +#[path = "../../test-crates/protobuf-test-common/src/hex.rs"] mod hex; -// used by rust-grpc -pub mod descriptorx; - mod cached_size; mod chars; -#[doc(hidden)] // used by codegen -pub mod rust; -mod strx; +mod fixed; +mod special; mod unknown; mod varint; mod zigzag; mod misc; -mod buf_read_iter; -mod buf_read_or_reader; +// This does not work: https://github.com/rust-lang/rust/issues/67295 +#[cfg(doctest)] +mod doctest_pb; /// This symbol is in generated `version.rs`, include here for IDE #[cfg(never)] diff --git a/src/message.rs b/src/message.rs index e9d6b30..9d7d429 100644 --- a/src/message.rs +++ b/src/message.rs @@ -1,42 +1,36 @@ -use std::any::Any; -use std::any::TypeId; -use std::fmt; use std::io::Read; use std::io::Write; -#[cfg(feature = "bytes")] -use bytes::Bytes; - -use crate::clear::Clear; -use crate::coded_input_stream::CodedInputStream; -use crate::coded_input_stream::WithCodedInputStream; -use crate::coded_output_stream::with_coded_output_stream_to_bytes; -use crate::coded_output_stream::CodedOutputStream; -use crate::coded_output_stream::WithCodedOutputStream; +use crate::coded_output_stream::with::WithCodedOutputStream; use crate::error::ProtobufError; -use crate::error::ProtobufResult; -use crate::reflect::MessageDescriptor; -use crate::unknown::UnknownFields; +use crate::wire_format::check_message_size; +use crate::CodedInputStream; +use crate::CodedOutputStream; +use crate::SpecialFields; +use crate::UnknownFields; -/// Trait implemented for all generated structs for protobuf messages. +/// Trait which is implemented by all generated message. /// -/// Also, generated messages implement `Clone + Default + PartialEq` -pub trait Message: fmt::Debug + Clear + Any + Send + Sync { - /// Message descriptor for this message, used for reflection. - fn descriptor(&self) -> &'static MessageDescriptor; +/// Note, by default all generated messages also implement [`MessageFull`](crate::MessageFull) +/// trait which provides access to reflection and features which depend on reflection +/// (text format and JSON serialization). +pub trait Message: Default + Clone + Send + Sync + Sized + PartialEq + 'static { + /// Message name as specified in `.proto` file. + /// + /// Message name can be accessed using + /// [`MessageFull::descriptor`](crate::MessageFull::descriptor), + /// but when lite runtime is requested, this field can be used. + const NAME: &'static str; /// True iff all required fields are initialized. /// Always returns `true` for protobuf 3. fn is_initialized(&self) -> bool; /// Update this message object with fields read from given stream. - fn merge_from(&mut self, is: &mut CodedInputStream) -> ProtobufResult<()>; + fn merge_from(&mut self, is: &mut CodedInputStream) -> crate::Result<()>; /// Parse message from stream. - fn parse_from(is: &mut CodedInputStream) -> ProtobufResult<Self> - where - Self: Sized, - { + fn parse_from(is: &mut CodedInputStream) -> crate::Result<Self> { let mut r: Self = Message::new(); r.merge_from(is)?; r.check_initialized()?; @@ -47,23 +41,30 @@ pub trait Message: fmt::Debug + Clear + Any + Send + Sync { /// /// Sizes of this messages and nested messages must be cached /// by calling `compute_size` prior to this call. - fn write_to_with_cached_sizes(&self, os: &mut CodedOutputStream) -> ProtobufResult<()>; + fn write_to_with_cached_sizes(&self, os: &mut CodedOutputStream) -> crate::Result<()>; - /// Compute and cache size of this message and all nested messages - fn compute_size(&self) -> u32; + /// Compute and cache size of this message and all nested messages. + /// + /// Note if the computation overflows u32, the cached size is stored truncated. + fn compute_size(&self) -> u64; /// Get size previously computed by `compute_size`. - fn get_cached_size(&self) -> u32; + /// + /// Note if message size exceeds u32, the cached size is stored truncated. + fn cached_size(&self) -> u32 { + self.special_fields().cached_size().get() + } /// Write the message to the stream. /// /// Results in error if message is not fully initialized. - fn write_to(&self, os: &mut CodedOutputStream) -> ProtobufResult<()> { + fn write_to(&self, os: &mut CodedOutputStream) -> crate::Result<()> { self.check_initialized()?; // cache sizes - self.compute_size(); - // TODO: reserve additional + let size = self.compute_size(); + let size = check_message_size(size)?; + os.reserve_additional(size as u32, Self::NAME)?; self.write_to_with_cached_sizes(os)?; Ok(()) @@ -71,19 +72,33 @@ pub trait Message: fmt::Debug + Clear + Any + Send + Sync { /// Write the message to the stream prepending the message with message length /// encoded as varint. - fn write_length_delimited_to(&self, os: &mut CodedOutputStream) -> ProtobufResult<()> { + fn write_length_delimited_to(&self, os: &mut CodedOutputStream) -> crate::Result<()> { let size = self.compute_size(); + let size = check_message_size(size)?; + + os.reserve_additional_for_length_delimited(size, Self::NAME)?; + os.write_raw_varint32(size)?; + + let written = os.total_bytes_written(); + self.write_to_with_cached_sizes(os)?; - // TODO: assert we've written same number of bytes as computed + // Self-check. + assert_eq!( + written + size as u64, + os.total_bytes_written(), + "Expected to write {}, actually wrote {}", + size, + os.total_bytes_written() - written + ); Ok(()) } /// Write the message to the vec, prepend the message with message length /// encoded as varint. - fn write_length_delimited_to_vec(&self, vec: &mut Vec<u8>) -> ProtobufResult<()> { + fn write_length_delimited_to_vec(&self, vec: &mut Vec<u8>) -> crate::Result<()> { let mut os = CodedOutputStream::vec(vec); self.write_length_delimited_to(&mut os)?; os.flush()?; @@ -91,17 +106,14 @@ pub trait Message: fmt::Debug + Clear + Any + Send + Sync { } /// Update this message object with fields read from given stream. - fn merge_from_bytes(&mut self, bytes: &[u8]) -> ProtobufResult<()> { + fn merge_from_bytes(&mut self, bytes: &[u8]) -> crate::Result<()> { let mut is = CodedInputStream::from_bytes(bytes); self.merge_from(&mut is) } /// Parse message from reader. /// Parse stops on EOF or when error encountered. - fn parse_from_reader(reader: &mut dyn Read) -> ProtobufResult<Self> - where - Self: Sized, - { + fn parse_from_reader(reader: &mut dyn Read) -> crate::Result<Self> { let mut is = CodedInputStream::new(reader); let r = Message::parse_from(&mut is)?; is.check_eof()?; @@ -109,10 +121,7 @@ pub trait Message: fmt::Debug + Clear + Any + Send + Sync { } /// Parse message from byte array. - fn parse_from_bytes(bytes: &[u8]) -> ProtobufResult<Self> - where - Self: Sized, - { + fn parse_from_bytes(bytes: &[u8]) -> crate::Result<Self> { let mut is = CodedInputStream::from_bytes(bytes); let r = Message::parse_from(&mut is)?; is.check_eof()?; @@ -122,191 +131,98 @@ pub trait Message: fmt::Debug + Clear + Any + Send + Sync { /// Parse message from `Bytes` object. /// Resulting message may share references to the passed bytes object. #[cfg(feature = "bytes")] - fn parse_from_carllerche_bytes(bytes: &Bytes) -> ProtobufResult<Self> - where - Self: Sized, - { - let mut is = CodedInputStream::from_carllerche_bytes(bytes); + fn parse_from_tokio_bytes(bytes: &bytes::Bytes) -> crate::Result<Self> { + let mut is = CodedInputStream::from_tokio_bytes(bytes); let r = Self::parse_from(&mut is)?; is.check_eof()?; Ok(r) } /// Check if all required fields of this object are initialized. - fn check_initialized(&self) -> ProtobufResult<()> { + fn check_initialized(&self) -> crate::Result<()> { if !self.is_initialized() { - Err(ProtobufError::message_not_initialized( - self.descriptor().name(), - )) + Err(ProtobufError::MessageNotInitialized(Self::NAME.to_owned()).into()) } else { Ok(()) } } /// Write the message to the writer. - fn write_to_writer(&self, w: &mut dyn Write) -> ProtobufResult<()> { + fn write_to_writer(&self, w: &mut dyn Write) -> crate::Result<()> { w.with_coded_output_stream(|os| self.write_to(os)) } /// Write the message to bytes vec. - fn write_to_vec(&self, v: &mut Vec<u8>) -> ProtobufResult<()> { + fn write_to_vec(&self, v: &mut Vec<u8>) -> crate::Result<()> { v.with_coded_output_stream(|os| self.write_to(os)) } /// Write the message to bytes vec. - fn write_to_bytes(&self) -> ProtobufResult<Vec<u8>> { + /// + /// > **Note**: You can use [`Message::parse_from_bytes`] + /// to do the reverse. + fn write_to_bytes(&self) -> crate::Result<Vec<u8>> { self.check_initialized()?; let size = self.compute_size() as usize; let mut v = Vec::with_capacity(size); - // skip zerofill - unsafe { - v.set_len(size); - } - { - let mut os = CodedOutputStream::bytes(&mut v); - self.write_to_with_cached_sizes(&mut os)?; - os.check_eof(); - } + let mut os = CodedOutputStream::vec(&mut v); + self.write_to_with_cached_sizes(&mut os)?; + os.flush()?; + drop(os); Ok(v) } /// Write the message to the writer, prepend the message with message length /// encoded as varint. - fn write_length_delimited_to_writer(&self, w: &mut dyn Write) -> ProtobufResult<()> { + fn write_length_delimited_to_writer(&self, w: &mut dyn Write) -> crate::Result<()> { w.with_coded_output_stream(|os| self.write_length_delimited_to(os)) } /// Write the message to the bytes vec, prepend the message with message length /// encoded as varint. - fn write_length_delimited_to_bytes(&self) -> ProtobufResult<Vec<u8>> { - with_coded_output_stream_to_bytes(|os| self.write_length_delimited_to(os)) - } - - /// Get a reference to unknown fields. - fn get_unknown_fields<'s>(&'s self) -> &'s UnknownFields; - /// Get a mutable reference to unknown fields. - fn mut_unknown_fields<'s>(&'s mut self) -> &'s mut UnknownFields; - - /// Get type id for downcasting. - fn type_id(&self) -> TypeId { - TypeId::of::<Self>() + fn write_length_delimited_to_bytes(&self) -> crate::Result<Vec<u8>> { + let mut v = Vec::new(); + v.with_coded_output_stream(|os| self.write_length_delimited_to(os))?; + Ok(v) } - /// View self as `Any`. - fn as_any(&self) -> &dyn Any; + /// Special fields (unknown fields and cached size). + fn special_fields(&self) -> &SpecialFields; + /// Special fields (unknown fields and cached size). + fn mut_special_fields(&mut self) -> &mut SpecialFields; - /// View self as mutable `Any`. - fn as_any_mut(&mut self) -> &mut dyn Any { - panic!() + /// Get a reference to unknown fields. + fn unknown_fields(&self) -> &UnknownFields { + &self.special_fields().unknown_fields() } - - /// Convert boxed self to boxed `Any`. - fn into_any(self: Box<Self>) -> Box<dyn Any> { - panic!() + /// Get a mutable reference to unknown fields. + fn mut_unknown_fields(&mut self) -> &mut UnknownFields { + self.mut_special_fields().mut_unknown_fields() } - // Rust does not allow implementation of trait for trait: - // impl<M : Message> fmt::Debug for M { - // ... - // } - /// Create an empty message object. /// - /// /// ``` - /// # use protobuf::Message; - /// # fn foo<MyMessage: Message>() { + /// # use protobuf::MessageFull; + /// # fn foo<MyMessage: MessageFull>() { /// let m = MyMessage::new(); /// # } /// ``` - fn new() -> Self - where - Self: Sized; + fn new() -> Self; - /// Get message descriptor for message type. - /// - /// ``` - /// # use protobuf::Message; - /// # fn foo<MyMessage: Message>() { - /// let descriptor = MyMessage::descriptor_static(); - /// assert_eq!("MyMessage", descriptor.name()); - /// # } - /// ``` - fn descriptor_static() -> &'static MessageDescriptor - where - Self: Sized, - { - panic!( - "descriptor_static is not implemented for message, \ - LITE_RUNTIME must be used" - ); + /// Reset all fields. + fn clear(&mut self) { + *self = Self::new(); } /// Return a pointer to default immutable message with static lifetime. /// /// ``` - /// # use protobuf::Message; - /// # fn foo<MyMessage: Message>() { + /// # use protobuf::MessageFull; + /// # fn foo<MyMessage: MessageFull>() { /// let m: &MyMessage = MyMessage::default_instance(); /// # } /// ``` - fn default_instance() -> &'static Self - where - Self: Sized; -} - -pub fn message_down_cast<'a, M: Message + 'a>(m: &'a dyn Message) -> &'a M { - m.as_any().downcast_ref::<M>().unwrap() -} - -/// Parse message from reader. -/// Parse stops on EOF or when error encountered. -#[deprecated(since = "2.19", note = "Use Message::parse_from_reader instead")] -pub fn parse_from_reader<M: Message>(reader: &mut dyn Read) -> ProtobufResult<M> { - M::parse_from_reader(reader) -} - -/// Parse message from byte array. -#[deprecated(since = "2.19", note = "Use Message::parse_from_bytes instead")] -pub fn parse_from_bytes<M: Message>(bytes: &[u8]) -> ProtobufResult<M> { - M::parse_from_bytes(bytes) -} - -/// Parse message from `Bytes` object. -/// Resulting message may share references to the passed bytes object. -#[cfg(feature = "bytes")] -#[deprecated( - since = "2.19", - note = "Use Message::parse_from_carllerche_bytes instead" -)] -pub fn parse_from_carllerche_bytes<M: Message>(bytes: &Bytes) -> ProtobufResult<M> { - M::parse_from_carllerche_bytes(bytes) -} - -/// Parse length-delimited message from stream. -/// -/// Read varint length first, and read messages of that length then. -/// -/// This function is deprecated and will be removed in the next major release. -#[deprecated] -pub fn parse_length_delimited_from<M: Message>(is: &mut CodedInputStream) -> ProtobufResult<M> { - is.read_message::<M>() -} - -/// Parse length-delimited message from `Read`. -/// -/// This function is deprecated and will be removed in the next major release. -#[deprecated] -pub fn parse_length_delimited_from_reader<M: Message>(r: &mut dyn Read) -> ProtobufResult<M> { - // TODO: wrong: we may read length first, and then read exact number of bytes needed - r.with_coded_input_stream(|is| is.read_message::<M>()) -} - -/// Parse length-delimited message from bytes. -/// -/// This function is deprecated and will be removed in the next major release. -#[deprecated] -pub fn parse_length_delimited_from_bytes<M: Message>(bytes: &[u8]) -> ProtobufResult<M> { - bytes.with_coded_input_stream(|is| is.read_message::<M>()) + fn default_instance() -> &'static Self; } diff --git a/src/message_dyn.rs b/src/message_dyn.rs new file mode 100644 index 0000000..1b8c36b --- /dev/null +++ b/src/message_dyn.rs @@ -0,0 +1,299 @@ +use std::any::Any; +use std::any::TypeId; +use std::fmt; +use std::io::Write; + +use crate::coded_output_stream::with::WithCodedOutputStream; +use crate::error::ProtobufError; +use crate::reflect::MessageDescriptor; +use crate::reflect::ReflectEqMode; +use crate::wire_format::check_message_size; +use crate::CodedInputStream; +use crate::CodedOutputStream; +use crate::MessageFull; +use crate::SpecialFields; +use crate::UnknownFields; + +/// Dynamic-dispatch version of either generated message or dynamic message. +/// +/// Generated messages implement [`MessageFull`](crate::MessageFull) unless lite runtime requested. +/// Dynamic messages can be created with +/// [`FileDescriptor::new_dynamic`](crate::reflect::FileDescriptor::new_dynamic). +pub trait MessageDyn: Any + fmt::Debug + fmt::Display + Send + Sync + 'static { + /// Message descriptor for this message, used for reflection. + fn descriptor_dyn(&self) -> MessageDescriptor; + + /// Update this message fields with contents of given stream. + fn merge_from_dyn(&mut self, is: &mut CodedInputStream) -> crate::Result<()>; + + /// Write the message. + fn write_to_with_cached_sizes_dyn(&self, os: &mut CodedOutputStream) -> crate::Result<()>; + + /// Compute (and cache) the message size. + fn compute_size_dyn(&self) -> u64; + + /// True iff all required fields are initialized. + /// Always returns `true` for protobuf 3. + fn is_initialized_dyn(&self) -> bool; + + /// Get a reference to special fields. + fn special_fields_dyn(&self) -> &SpecialFields; + /// Get a mutable reference to special fields. + fn mut_special_fields_dyn(&mut self) -> &mut SpecialFields; +} + +impl<M: MessageFull> MessageDyn for M { + fn descriptor_dyn(&self) -> MessageDescriptor { + M::descriptor() + } + + fn merge_from_dyn(&mut self, is: &mut CodedInputStream) -> crate::Result<()> { + self.merge_from(is) + } + + fn write_to_with_cached_sizes_dyn(&self, os: &mut CodedOutputStream) -> crate::Result<()> { + self.write_to_with_cached_sizes(os) + } + + fn compute_size_dyn(&self) -> u64 { + self.compute_size() + } + + fn is_initialized_dyn(&self) -> bool { + self.is_initialized() + } + + fn special_fields_dyn(&self) -> &SpecialFields { + self.special_fields() + } + + fn mut_special_fields_dyn(&mut self) -> &mut SpecialFields { + self.mut_special_fields() + } +} + +impl dyn MessageDyn { + /// Check if all required fields of this object are initialized. + pub fn check_initialized_dyn(&self) -> crate::Result<()> { + if !self.is_initialized_dyn() { + Err( + ProtobufError::MessageNotInitialized(self.descriptor_dyn().name().to_owned()) + .into(), + ) + } else { + Ok(()) + } + } + + /// Write the message to the writer. + pub fn write_to_writer_dyn(&self, w: &mut dyn Write) -> crate::Result<()> { + w.with_coded_output_stream(|os| self.write_to_dyn(os)) + } + + /// Write the message to bytes vec. + pub fn write_to_vec_dyn(&self, v: &mut Vec<u8>) -> crate::Result<()> { + v.with_coded_output_stream(|os| self.write_to_dyn(os)) + } + + /// Write the message to the stream. + /// + /// Results in error if message is not fully initialized. + pub fn write_to_dyn(&self, os: &mut CodedOutputStream) -> crate::Result<()> { + self.check_initialized_dyn()?; + + // cache sizes + let size = self.compute_size_dyn(); + let size = check_message_size(size)?; + os.reserve_additional(size, self.descriptor_dyn().name())?; + self.write_to_with_cached_sizes_dyn(os)?; + + Ok(()) + } + + /// Write the message to the vec, prepend the message with message length + /// encoded as varint. + pub fn write_length_delimited_to_vec_dyn(&self, vec: &mut Vec<u8>) -> crate::Result<()> { + let mut os = CodedOutputStream::vec(vec); + self.write_length_delimited_to_dyn(&mut os)?; + os.flush()?; + Ok(()) + } + + /// Update this message object with fields read from given stream. + pub fn merge_from_bytes_dyn(&mut self, bytes: &[u8]) -> crate::Result<()> { + let mut is = CodedInputStream::from_bytes(bytes); + self.merge_from_dyn(&mut is) + } + + /// Write the message to bytes vec. + /// + /// > **Note**: You can use [`Message::parse_from_bytes`](crate::Message::parse_from_bytes) + /// to do the reverse. + pub fn write_to_bytes_dyn(&self) -> crate::Result<Vec<u8>> { + self.check_initialized_dyn()?; + + let size = self.compute_size_dyn(); + let size = check_message_size(size)?; + let mut v = Vec::new(); + let mut os = CodedOutputStream::vec(&mut v); + os.reserve_additional(size, self.descriptor_dyn().name())?; + self.write_to_with_cached_sizes_dyn(&mut os)?; + os.flush()?; + drop(os); + Ok(v) + } + + /// Write the message to the stream prepending the message with message length + /// encoded as varint. + pub fn write_length_delimited_to_dyn(&self, os: &mut CodedOutputStream) -> crate::Result<()> { + let size = self.compute_size_dyn(); + let size = check_message_size(size)?; + os.reserve_additional_for_length_delimited(size, self.descriptor_dyn().name())?; + os.write_raw_varint32(size)?; + + let pos = os.total_bytes_written(); + + self.write_to_with_cached_sizes_dyn(os)?; + + // Cheap self-check. + assert_eq!(os.total_bytes_written() - pos, size as u64); + + Ok(()) + } + + /// Write the message to the writer, prepend the message with message length + /// encoded as varint. + pub fn write_length_delimited_to_writer_dyn(&self, w: &mut dyn Write) -> crate::Result<()> { + w.with_coded_output_stream(|os| self.write_length_delimited_to_dyn(os)) + } + + /// Write the message to the bytes vec, prepend the message with message length + /// encoded as varint. + pub fn write_length_delimited_to_bytes_dyn(&self) -> crate::Result<Vec<u8>> { + let mut v = Vec::new(); + v.with_coded_output_stream(|os| self.write_length_delimited_to_dyn(os))?; + Ok(v) + } + + /// Get a reference to unknown fields. + pub fn unknown_fields_dyn(&self) -> &UnknownFields { + self.special_fields_dyn().unknown_fields() + } + /// Get a mutable reference to unknown fields. + pub fn mut_unknown_fields_dyn(&mut self) -> &mut UnknownFields { + self.mut_special_fields_dyn().mut_unknown_fields() + } + + /// Downcast `Box<dyn Message>` to specific message type. + /// + /// ``` + /// # use protobuf::{MessageFull, MessageDyn}; + /// # fn foo<MyMessage: MessageFull>(message: Box<dyn MessageDyn>) { + /// let m: Box<dyn MessageDyn> = message; + /// let m: Box<MyMessage> = <dyn MessageDyn>::downcast_box(m).unwrap(); + /// # } + /// ``` + pub fn downcast_box<T: Any>( + self: Box<dyn MessageDyn>, + ) -> std::result::Result<Box<T>, Box<dyn MessageDyn>> { + if Any::type_id(&*self) == TypeId::of::<T>() { + unsafe { + let raw: *mut dyn MessageDyn = Box::into_raw(self); + Ok(Box::from_raw(raw as *mut T)) + } + } else { + Err(self) + } + } + + /// Downcast `&dyn Message` to specific message type. + /// + /// ``` + /// # use protobuf::{MessageFull, MessageDyn}; + /// # fn foo<MyMessage: MessageFull>(message: &dyn MessageDyn) { + /// let m: &dyn MessageDyn = message; + /// let m: &MyMessage = <dyn MessageDyn>::downcast_ref(m).unwrap(); + /// # } + /// ``` + pub fn downcast_ref<'a, M: MessageFull + 'a>(&'a self) -> Option<&'a M> { + if Any::type_id(&*self) == TypeId::of::<M>() { + unsafe { Some(&*(self as *const dyn MessageDyn as *const M)) } + } else { + None + } + } + + /// Downcast `&mut dyn Message` to specific message type. + /// + /// ``` + /// # use protobuf::{MessageFull, MessageDyn}; + /// # fn foo<MyMessage: MessageFull>(message: &mut dyn MessageDyn) { + /// let m: &mut dyn MessageDyn = message; + /// let m: &mut MyMessage = <dyn MessageDyn>::downcast_mut(m).unwrap(); + /// # } + /// ``` + pub fn downcast_mut<'a, M: MessageFull + 'a>(&'a mut self) -> Option<&'a mut M> { + if Any::type_id(&*self) == TypeId::of::<M>() { + unsafe { Some(&mut *(self as *mut dyn MessageDyn as *mut M)) } + } else { + None + } + } + + /// Clone from a `dyn Message` reference. + pub fn clone_box(&self) -> Box<dyn MessageDyn> { + self.descriptor_dyn().clone_message(self) + } + + /// Reflectively compare the messages. + pub fn reflect_eq_dyn(&self, other: &dyn MessageDyn, mode: &ReflectEqMode) -> bool { + MessageDescriptor::reflect_eq_maybe_unrelated(self, other, mode) + } +} + +impl Clone for Box<dyn MessageDyn> { + fn clone(&self) -> Self { + (*self).clone_box() + } +} + +impl PartialEq for Box<dyn MessageDyn> { + fn eq(&self, other: &Box<dyn MessageDyn>) -> bool { + MessageDescriptor::reflect_eq_maybe_unrelated(&**self, &**other, &ReflectEqMode::default()) + } +} + +#[cfg(test)] +mod test { + use crate::descriptor::FileDescriptorProto; + use crate::MessageDyn; + + #[test] + fn downcast_ref() { + let m = FileDescriptorProto::new(); + let d = &m as &dyn MessageDyn; + let c: &FileDescriptorProto = d.downcast_ref().unwrap(); + assert_eq!( + c as *const FileDescriptorProto, + &m as *const FileDescriptorProto + ); + } + + #[test] + fn downcast_mut() { + let mut m = FileDescriptorProto::new(); + let d = &mut m as &mut dyn MessageDyn; + let c: &mut FileDescriptorProto = d.downcast_mut().unwrap(); + assert_eq!( + c as *const FileDescriptorProto, + &m as *const FileDescriptorProto + ); + } + + #[test] + fn downcast_box() { + let m = FileDescriptorProto::new(); + let d: Box<dyn MessageDyn> = Box::new(m); + let mut _c: Box<FileDescriptorProto> = d.downcast_box().unwrap(); + } +} diff --git a/src/message_field.rs b/src/message_field.rs new file mode 100644 index 0000000..c7b4637 --- /dev/null +++ b/src/message_field.rs @@ -0,0 +1,210 @@ +use std::default::Default; +use std::hash::Hash; +use std::ops::Deref; +use std::option; + +use crate::Message; + +/// Wrapper around `Option<Box<T>>`, convenient newtype. +/// +/// # Examples +/// +/// ```no_run +/// # use protobuf::MessageField; +/// # use std::ops::Add; +/// # struct Address { +/// # } +/// # struct Customer { +/// # address: MessageField<Address>, +/// # } +/// # impl Customer { +/// # fn new() -> Customer { unimplemented!() } +/// # } +/// # +/// # +/// # fn make_address() -> Address { unimplemented!() } +/// let mut customer = Customer::new(); +/// +/// // field of type `SingularPtrField` can be initialized like this +/// customer.address = MessageField::some(make_address()); +/// // or using `Option` and `Into` +/// customer.address = Some(make_address()).into(); +/// ``` +#[derive(Clone, Debug, Eq, PartialEq, Hash)] +pub struct MessageField<T>(pub Option<Box<T>>); + +impl<T> MessageField<T> { + /// Construct `SingularPtrField` from given object. + #[inline] + pub fn some(value: T) -> MessageField<T> { + MessageField(Some(Box::new(value))) + } + + /// Construct an empty `SingularPtrField`. + #[inline] + pub const fn none() -> MessageField<T> { + MessageField(None) + } + + /// Construct `SingularPtrField` from optional. + #[inline] + pub fn from_option(option: Option<T>) -> MessageField<T> { + match option { + Some(x) => MessageField::some(x), + None => MessageField::none(), + } + } + + /// True iff this object contains data. + #[inline] + pub fn is_some(&self) -> bool { + self.0.is_some() + } + + /// True iff this object contains no data. + #[inline] + pub fn is_none(&self) -> bool { + self.0.is_none() + } + + /// Convert into `Option<T>`. + #[inline] + pub fn into_option(self) -> Option<T> { + self.0.map(|v| *v) + } + + /// View data as reference option. + #[inline] + pub fn as_ref(&self) -> Option<&T> { + self.0.as_ref().map(|v| &**v) + } + + /// View data as mutable reference option. + #[inline] + pub fn as_mut(&mut self) -> Option<&mut T> { + self.0.as_mut().map(|v| &mut **v) + } + + /// Take the data. + /// Panics if empty + #[inline] + pub fn unwrap(self) -> T { + *self.0.unwrap() + } + + /// Take the data or return supplied default element if empty. + #[inline] + pub fn unwrap_or(self, def: T) -> T { + self.0.map(|v| *v).unwrap_or(def) + } + + /// Take the data or return supplied default element if empty. + #[inline] + pub fn unwrap_or_else<F>(self, f: F) -> T + where + F: FnOnce() -> T, + { + self.0.map(|v| *v).unwrap_or_else(f) + } + + /// Apply given function to contained data to construct another `SingularPtrField`. + /// Returns empty `SingularPtrField` if this object is empty. + #[inline] + pub fn map<U, F>(self, f: F) -> MessageField<U> + where + F: FnOnce(T) -> U, + { + MessageField::from_option(self.into_option().map(f)) + } + + /// View data as iterator. + #[inline] + pub fn iter(&self) -> option::IntoIter<&T> { + self.as_ref().into_iter() + } + + /// View data as mutable iterator. + #[inline] + pub fn mut_iter(&mut self) -> option::IntoIter<&mut T> { + self.as_mut().into_iter() + } + + /// Take data as option, leaving this object empty. + #[inline] + pub fn take(&mut self) -> Option<T> { + self.0.take().map(|v| *v) + } + + /// Clear this object, but do not call destructor of underlying data. + #[inline] + pub fn clear(&mut self) { + self.0 = None; + } +} + +impl<T: Default> MessageField<T> { + /// Get contained data, consume self. Return default value for type if this is empty. + #[inline] + pub fn unwrap_or_default(self) -> T { + *self.0.unwrap_or_default() + } +} + +impl<M: Message> MessageField<M> { + /// Get a reference to contained value or a default instance. + pub fn get_or_default(&self) -> &M { + self.as_ref().unwrap_or_else(|| M::default_instance()) + } + + /// Get a mutable reference to contained value, initialize if not initialized yet. + pub fn mut_or_insert_default(&mut self) -> &mut M { + if self.is_none() { + *self = MessageField::some(Default::default()); + } + self.as_mut().unwrap() + } +} + +/// Get a reference to contained value or a default instance if the field is not initialized. +impl<M: Message> Deref for MessageField<M> { + type Target = M; + + fn deref(&self) -> &Self::Target { + self.get_or_default() + } +} + +/// Get a mutable reference to the message **and** initialize the message if not initialized yet. +/// +/// Note that part about initializing is not conventional. +/// Generally `DerefMut` is not supposed to modify the state. +#[cfg(no)] +impl<M: Message> DerefMut for MessageField<M> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.mut_or_insert_default() + } +} + +impl<T> Default for MessageField<T> { + #[inline] + fn default() -> MessageField<T> { + MessageField::none() + } +} + +/// We don't have `From<Option<Box<T>>> for MessageField<T>` because +/// it would make type inference worse. +impl<T> From<Option<T>> for MessageField<T> { + fn from(o: Option<T>) -> Self { + MessageField::from_option(o) + } +} + +impl<'a, T> IntoIterator for &'a MessageField<T> { + type Item = &'a T; + type IntoIter = option::IntoIter<&'a T>; + + fn into_iter(self) -> option::IntoIter<&'a T> { + self.iter() + } +} diff --git a/src/message_full.rs b/src/message_full.rs new file mode 100644 index 0000000..c6258c1 --- /dev/null +++ b/src/message_full.rs @@ -0,0 +1,47 @@ +use std::fmt; + +use crate::message_dyn::MessageDyn; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::MessageDescriptor; +use crate::reflect::ProtobufValue; +use crate::Message; + +/// Trait implemented for all the generated messages, except when lite runtime is enabled. +/// +/// When lite runtime is enabled, only `MessageLite` is implemented. +/// +/// * Generated messages are generated from `.proto` files +/// * Dynamic messages can be created without code generation using only parsed proto files +/// (see [FileDescriptor::new_dynamic](crate::reflect::FileDescriptor::new_dynamic)). +/// +/// Also, generated messages implement `Default + PartialEq` +/// +/// This trait is sized, there's accompanying [`MessageDyn`](crate::MessageDyn) trait +/// which is implemented for all messages which can be used in functions +/// without making message a function type parameter. +/// +/// ## `Display` +/// +/// [`Display`](fmt::Display) implementation for messages does protobuf text format. +/// See [`text_format`](crate::text_format) for more details. +pub trait MessageFull: Message + ProtobufValue + fmt::Debug + fmt::Display { + /// Get message descriptor for message type. + /// + /// ``` + /// # use protobuf::MessageFull; + /// # fn foo<MyMessage: MessageFull>() { + /// let descriptor = MyMessage::descriptor(); + /// assert_eq!("MyMessage", descriptor.name()); + /// # } + /// ``` + fn descriptor() -> MessageDescriptor; + + /// Reflective equality. + /// + /// # See also + /// + /// [`dyn Message::reflect_eq_dyn()`], `dyn` version of this function. + fn reflect_eq(&self, other: &Self, mode: &ReflectEqMode) -> bool { + <dyn MessageDyn>::reflect_eq_dyn(self, other, mode) + } +} diff --git a/src/misc.rs b/src/misc.rs index faef34f..303ecc8 100644 --- a/src/misc.rs +++ b/src/misc.rs @@ -1,17 +1,7 @@ use std::mem; use std::mem::MaybeUninit; -use std::slice; -/// `Vec::spare_capacity_mut` is not stable until Rust 1.60. -pub(crate) fn vec_spare_capacity_mut<A>(vec: &mut Vec<A>) -> &mut [MaybeUninit<A>] { - // SAFETY: copy-paste from rust stdlib. - unsafe { - slice::from_raw_parts_mut( - vec.as_mut_ptr().add(vec.len()) as *mut MaybeUninit<A>, - vec.capacity() - vec.len(), - ) - } -} +use crate::well_known_types; /// `MaybeUninit::write_slice` is not stable. pub(crate) fn maybe_uninit_write_slice<'a, T>( @@ -43,10 +33,142 @@ pub(crate) unsafe fn maybe_ununit_array_assume_init<T, const N: usize>( (&array as *const _ as *const [T; N]).read() } -/// `MaybeUninit::write` is stable since 1.55. -#[inline] -pub(crate) fn maybe_uninit_write<T>(uninit: &mut MaybeUninit<T>, val: T) -> &mut T { - // SAFETY: copy-paste from rust stdlib. - *uninit = MaybeUninit::new(val); - unsafe { &mut *uninit.as_mut_ptr() } +// bool <-> BoolValue + +impl From<well_known_types::wrappers::BoolValue> for bool { + fn from(inner: well_known_types::wrappers::BoolValue) -> Self { + inner.value + } +} + +impl From<bool> for well_known_types::wrappers::BoolValue { + fn from(inner: bool) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// Vec<u8> <-> BytesValue + +impl From<well_known_types::wrappers::BytesValue> for Vec<u8> { + fn from(inner: well_known_types::wrappers::BytesValue) -> Self { + inner.value + } +} + +impl From<Vec<u8>> for well_known_types::wrappers::BytesValue { + fn from(inner: Vec<u8>) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// f64 <-> DoubleValue + +impl From<well_known_types::wrappers::DoubleValue> for f64 { + fn from(inner: well_known_types::wrappers::DoubleValue) -> Self { + inner.value + } +} + +impl From<f64> for well_known_types::wrappers::DoubleValue { + fn from(inner: f64) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// f32 <-> FloatValue + +impl From<well_known_types::wrappers::FloatValue> for f32 { + fn from(inner: well_known_types::wrappers::FloatValue) -> Self { + inner.value + } +} + +impl From<f32> for well_known_types::wrappers::FloatValue { + fn from(inner: f32) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// i32 <-> Int32Value + +impl From<well_known_types::wrappers::Int32Value> for i32 { + fn from(inner: well_known_types::wrappers::Int32Value) -> Self { + inner.value + } +} + +impl From<i32> for well_known_types::wrappers::Int32Value { + fn from(inner: i32) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// i64 <-> Int64Value + +impl From<well_known_types::wrappers::Int64Value> for i64 { + fn from(inner: well_known_types::wrappers::Int64Value) -> Self { + inner.value + } +} + +impl From<i64> for well_known_types::wrappers::Int64Value { + fn from(inner: i64) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// u32 <-> UInt32Value + +impl From<well_known_types::wrappers::UInt32Value> for u32 { + fn from(inner: well_known_types::wrappers::UInt32Value) -> Self { + inner.value + } +} + +impl From<u32> for well_known_types::wrappers::UInt32Value { + fn from(inner: u32) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// u64 <-> UInt64Value + +impl From<well_known_types::wrappers::UInt64Value> for u64 { + fn from(inner: well_known_types::wrappers::UInt64Value) -> Self { + inner.value + } +} + +impl From<u64> for well_known_types::wrappers::UInt64Value { + fn from(inner: u64) -> Self { + let mut value = Self::new(); + value.value = inner; + value + } +} + +// () <-> Empty + +impl From<well_known_types::empty::Empty> for () { + fn from(_inner: well_known_types::empty::Empty) -> Self {} +} + +impl From<()> for well_known_types::empty::Empty { + fn from(_inner: ()) -> Self { + Self::new() + } } diff --git a/src/oneof.rs b/src/oneof.rs new file mode 100644 index 0000000..6f527b8 --- /dev/null +++ b/src/oneof.rs @@ -0,0 +1,2 @@ +/// Trait implemented by all oneof types in generated code. +pub trait Oneof {} diff --git a/src/oneof_full.rs b/src/oneof_full.rs new file mode 100644 index 0000000..4bd8466 --- /dev/null +++ b/src/oneof_full.rs @@ -0,0 +1,8 @@ +use crate::reflect::OneofDescriptor; +use crate::Oneof; + +/// Implemented by all oneof types when lite runtime is not enabled. +pub trait OneofFull: Oneof { + /// Descriptor object for this oneof. + fn descriptor() -> OneofDescriptor; +} diff --git a/src/owning_ref.rs b/src/owning_ref.rs new file mode 100644 index 0000000..f7d2c5f --- /dev/null +++ b/src/owning_ref.rs @@ -0,0 +1,106 @@ +//! Utility similar to provided by `owning_ref` crate. + +use std::fmt; +use std::fmt::Debug; +use std::ops::Deref; +use std::sync::Arc; + +enum Owner<A: 'static> { + Arc(Arc<A>), + Static(&'static A), +} + +impl<A: 'static> Deref for Owner<A> { + type Target = A; + + fn deref(&self) -> &A { + match self { + Owner::Arc(a) => &*a, + Owner::Static(a) => a, + } + } +} + +pub(crate) struct OwningRef<A: 'static, B: 'static> { + owner: Owner<A>, + ptr: *const B, +} + +unsafe impl<A: Send + Sync + 'static, B: Send + Sync + 'static> Sync for OwningRef<A, B> {} +unsafe impl<A: Send + Sync + 'static, B: Send + Sync + 'static> Send for OwningRef<A, B> {} + +impl<A: 'static, B: 'static> Deref for OwningRef<A, B> { + type Target = B; + + fn deref(&self) -> &B { + // SAFETY: `self.owner` owns the data and it is not movable. + unsafe { &*self.ptr } + } +} + +impl<A: 'static> Clone for Owner<A> { + fn clone(&self) -> Owner<A> { + match self { + Owner::Arc(arc) => Owner::Arc(arc.clone()), + Owner::Static(ptr) => Owner::Static(ptr), + } + } +} + +impl<A: 'static, B: 'static> Clone for OwningRef<A, B> { + fn clone(&self) -> OwningRef<A, B> { + OwningRef { + ptr: self.ptr, + owner: self.owner.clone(), + } + } +} + +impl<A: 'static, B: fmt::Debug + 'static> Debug for OwningRef<A, B> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Debug::fmt(&**self, f) + } +} + +impl<A: 'static> OwningRef<A, A> { + pub(crate) fn new_arc(arc: Arc<A>) -> OwningRef<A, A> { + OwningRef { + ptr: Arc::as_ptr(&arc), + owner: Owner::Arc(arc), + } + } + + pub(crate) fn new_static(ptr: &'static A) -> OwningRef<A, A> { + OwningRef { + ptr, + owner: Owner::Static(ptr), + } + } + + pub(crate) fn owner(&self) -> &A { + &self.owner + } +} + +impl<A: 'static, B: 'static> OwningRef<A, B> { + pub(crate) fn _map<C>(self, f: impl FnOnce(&B) -> &C) -> OwningRef<A, C> { + let ptr = f(&*self); + OwningRef { + ptr, + owner: self.owner, + } + } + + pub(crate) fn flat_map_slice<'x, C, T: FnOnce(&B) -> &[C]>( + &self, + f: T, + ) -> impl Iterator<Item = OwningRef<A, C>> + '_ + where + C: 'static, + { + f(&self).into_iter().map(|ptr| OwningRef { + ptr, + owner: self.owner.clone(), + }) + } +} diff --git a/src/plugin.rs b/src/plugin.rs index 93f2ca8..4251b95 100644 --- a/src/plugin.rs +++ b/src/plugin.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,23 +16,29 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/compiler/plugin.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// The version number of protocol compiler. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.compiler.Version) pub struct Version { // message fields - major: ::std::option::Option<i32>, - minor: ::std::option::Option<i32>, - patch: ::std::option::Option<i32>, - suffix: crate::SingularField<::std::string::String>, + // @@protoc_insertion_point(field:google.protobuf.compiler.Version.major) + pub major: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.compiler.Version.minor) + pub minor: ::std::option::Option<i32>, + // @@protoc_insertion_point(field:google.protobuf.compiler.Version.patch) + pub patch: ::std::option::Option<i32>, + /// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should + /// be empty for mainline stable releases. + // @@protoc_insertion_point(field:google.protobuf.compiler.Version.suffix) + pub suffix: ::std::option::Option<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.compiler.Version.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Version { @@ -47,10 +54,10 @@ impl Version { // optional int32 major = 1; - - pub fn get_major(&self) -> i32 { + pub fn major(&self) -> i32 { self.major.unwrap_or(0) } + pub fn clear_major(&mut self) { self.major = ::std::option::Option::None; } @@ -66,10 +73,10 @@ impl Version { // optional int32 minor = 2; - - pub fn get_minor(&self) -> i32 { + pub fn minor(&self) -> i32 { self.minor.unwrap_or(0) } + pub fn clear_minor(&mut self) { self.minor = ::std::option::Option::None; } @@ -85,10 +92,10 @@ impl Version { // optional int32 patch = 3; - - pub fn get_patch(&self) -> i32 { + pub fn patch(&self) -> i32 { self.patch.unwrap_or(0) } + pub fn clear_patch(&mut self) { self.patch = ::std::option::Option::None; } @@ -104,15 +111,15 @@ impl Version { // optional string suffix = 4; - - pub fn get_suffix(&self) -> &str { + pub fn suffix(&self) -> &str { match self.suffix.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_suffix(&mut self) { - self.suffix.clear(); + self.suffix = ::std::option::Option::None; } pub fn has_suffix(&self) -> bool { @@ -121,14 +128,14 @@ impl Version { // Param is passed by value, moved pub fn set_suffix(&mut self, v: ::std::string::String) { - self.suffix = crate::SingularField::some(v); + self.suffix = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_suffix(&mut self) -> &mut ::std::string::String { if self.suffix.is_none() { - self.suffix.set_default(); + self.suffix = ::std::option::Option::Some(::std::string::String::new()); } self.suffix.as_mut().unwrap() } @@ -137,43 +144,62 @@ impl Version { pub fn take_suffix(&mut self) -> ::std::string::String { self.suffix.take().unwrap_or_else(|| ::std::string::String::new()) } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(4); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "major", + |m: &Version| { &m.major }, + |m: &mut Version| { &mut m.major }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "minor", + |m: &Version| { &m.minor }, + |m: &mut Version| { &mut m.minor }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "patch", + |m: &Version| { &m.patch }, + |m: &mut Version| { &mut m.patch }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "suffix", + |m: &Version| { &m.suffix }, + |m: &mut Version| { &mut m.suffix }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Version>( + "Version", + fields, + oneofs, + ) + } } impl crate::Message for Version { + const NAME: &'static str = "Version"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.major = ::std::option::Option::Some(tmp); + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.major = ::std::option::Option::Some(is.read_int32()?); }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.minor = ::std::option::Option::Some(tmp); + 16 => { + self.minor = ::std::option::Option::Some(is.read_int32()?); }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.patch = ::std::option::Option::Some(tmp); + 24 => { + self.patch = ::std::option::Option::Some(is.read_int32()?); }, - 4 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.suffix)?; + 34 => { + self.suffix = ::std::option::Option::Some(is.read_string()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -182,26 +208,26 @@ impl crate::Message for Version { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if let Some(v) = self.major { - my_size += crate::rt::value_size(1, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(1, v); } if let Some(v) = self.minor { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(2, v); } if let Some(v) = self.patch { - my_size += crate::rt::value_size(3, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(3, v); } - if let Some(ref v) = self.suffix.as_ref() { + if let Some(v) = self.suffix.as_ref() { my_size += crate::rt::string_size(4, &v); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if let Some(v) = self.major { os.write_int32(1, v)?; } @@ -211,116 +237,97 @@ impl crate::Message for Version { if let Some(v) = self.patch { os.write_int32(3, v)?; } - if let Some(ref v) = self.suffix.as_ref() { - os.write_string(4, &v)?; + if let Some(v) = self.suffix.as_ref() { + os.write_string(4, v)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Version { Version::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "major", - |m: &Version| { &m.major }, - |m: &mut Version| { &mut m.major }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "minor", - |m: &Version| { &m.minor }, - |m: &mut Version| { &mut m.minor }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeInt32>( - "patch", - |m: &Version| { &m.patch }, - |m: &mut Version| { &mut m.patch }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "suffix", - |m: &Version| { &m.suffix }, - |m: &mut Version| { &mut m.suffix }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Version>( - "Version", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.major = ::std::option::Option::None; + self.minor = ::std::option::Option::None; + self.patch = ::std::option::Option::None; + self.suffix = ::std::option::Option::None; + self.special_fields.clear(); } fn default_instance() -> &'static Version { - static instance: crate::rt::LazyV2<Version> = crate::rt::LazyV2::INIT; - instance.get(Version::new) + static instance: Version = Version { + major: ::std::option::Option::None, + minor: ::std::option::Option::None, + patch: ::std::option::Option::None, + suffix: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Version { - fn clear(&mut self) { - self.major = ::std::option::Option::None; - self.minor = ::std::option::Option::None; - self.patch = ::std::option::Option::None; - self.suffix.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for Version { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Version").unwrap()).clone() } } -impl ::std::fmt::Debug for Version { +impl ::std::fmt::Display for Version { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Version { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// An encoded CodeGeneratorRequest is written to the plugin's stdin. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.compiler.CodeGeneratorRequest) pub struct CodeGeneratorRequest { // message fields - pub file_to_generate: crate::RepeatedField<::std::string::String>, - parameter: crate::SingularField<::std::string::String>, - pub proto_file: crate::RepeatedField<crate::descriptor::FileDescriptorProto>, - pub compiler_version: crate::SingularPtrField<Version>, + /// The .proto files that were explicitly listed on the command-line. The + /// code generator should generate code only for these files. Each file's + /// descriptor will be included in proto_file, below. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorRequest.file_to_generate) + pub file_to_generate: ::std::vec::Vec<::std::string::String>, + /// The generator parameter passed on the command-line. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorRequest.parameter) + pub parameter: ::std::option::Option<::std::string::String>, + /// FileDescriptorProtos for all files in files_to_generate and everything + /// they import. The files will appear in topological order, so each file + /// appears before any file that imports it. + /// + /// protoc guarantees that all proto_files will be written after + /// the fields above, even though this is not technically guaranteed by the + /// protobuf wire format. This theoretically could allow a plugin to stream + /// in the FileDescriptorProtos and handle them one by one rather than read + /// the entire set into memory at once. However, as of this writing, this + /// is not similarly optimized on protoc's end -- it will store all fields in + /// memory at once before sending them to the plugin. + /// + /// Type names of fields and extensions in the FileDescriptorProto are always + /// fully qualified. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorRequest.proto_file) + pub proto_file: ::std::vec::Vec<crate::descriptor::FileDescriptorProto>, + /// The version number of protocol compiler. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorRequest.compiler_version) + pub compiler_version: crate::MessageField<Version>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.compiler.CodeGeneratorRequest.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a CodeGeneratorRequest { @@ -334,42 +341,17 @@ impl CodeGeneratorRequest { ::std::default::Default::default() } - // repeated string file_to_generate = 1; - - - pub fn get_file_to_generate(&self) -> &[::std::string::String] { - &self.file_to_generate - } - pub fn clear_file_to_generate(&mut self) { - self.file_to_generate.clear(); - } - - // Param is passed by value, moved - pub fn set_file_to_generate(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.file_to_generate = v; - } - - // Mutable pointer to the field. - pub fn mut_file_to_generate(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.file_to_generate - } - - // Take field - pub fn take_file_to_generate(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.file_to_generate, crate::RepeatedField::new()) - } - // optional string parameter = 2; - - pub fn get_parameter(&self) -> &str { + pub fn parameter(&self) -> &str { match self.parameter.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_parameter(&mut self) { - self.parameter.clear(); + self.parameter = ::std::option::Option::None; } pub fn has_parameter(&self) -> bool { @@ -378,14 +360,14 @@ impl CodeGeneratorRequest { // Param is passed by value, moved pub fn set_parameter(&mut self, v: ::std::string::String) { - self.parameter = crate::SingularField::some(v); + self.parameter = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_parameter(&mut self) -> &mut ::std::string::String { if self.parameter.is_none() { - self.parameter.set_default(); + self.parameter = ::std::option::Option::Some(::std::string::String::new()); } self.parameter.as_mut().unwrap() } @@ -395,66 +377,40 @@ impl CodeGeneratorRequest { self.parameter.take().unwrap_or_else(|| ::std::string::String::new()) } - // repeated .google.protobuf.FileDescriptorProto proto_file = 15; - - - pub fn get_proto_file(&self) -> &[crate::descriptor::FileDescriptorProto] { - &self.proto_file - } - pub fn clear_proto_file(&mut self) { - self.proto_file.clear(); - } - - // Param is passed by value, moved - pub fn set_proto_file(&mut self, v: crate::RepeatedField<crate::descriptor::FileDescriptorProto>) { - self.proto_file = v; - } - - // Mutable pointer to the field. - pub fn mut_proto_file(&mut self) -> &mut crate::RepeatedField<crate::descriptor::FileDescriptorProto> { - &mut self.proto_file - } - - // Take field - pub fn take_proto_file(&mut self) -> crate::RepeatedField<crate::descriptor::FileDescriptorProto> { - ::std::mem::replace(&mut self.proto_file, crate::RepeatedField::new()) - } - - // optional .google.protobuf.compiler.Version compiler_version = 3; - - - pub fn get_compiler_version(&self) -> &Version { - self.compiler_version.as_ref().unwrap_or_else(|| <Version as crate::Message>::default_instance()) - } - pub fn clear_compiler_version(&mut self) { - self.compiler_version.clear(); - } - - pub fn has_compiler_version(&self) -> bool { - self.compiler_version.is_some() - } - - // Param is passed by value, moved - pub fn set_compiler_version(&mut self, v: Version) { - self.compiler_version = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_compiler_version(&mut self) -> &mut Version { - if self.compiler_version.is_none() { - self.compiler_version.set_default(); - } - self.compiler_version.as_mut().unwrap() - } - - // Take field - pub fn take_compiler_version(&mut self) -> Version { - self.compiler_version.take().unwrap_or_else(|| Version::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(4); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "file_to_generate", + |m: &CodeGeneratorRequest| { &m.file_to_generate }, + |m: &mut CodeGeneratorRequest| { &mut m.file_to_generate }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "parameter", + |m: &CodeGeneratorRequest| { &m.parameter }, + |m: &mut CodeGeneratorRequest| { &mut m.parameter }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "proto_file", + |m: &CodeGeneratorRequest| { &m.proto_file }, + |m: &mut CodeGeneratorRequest| { &mut m.proto_file }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, Version>( + "compiler_version", + |m: &CodeGeneratorRequest| { &m.compiler_version }, + |m: &mut CodeGeneratorRequest| { &mut m.compiler_version }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<CodeGeneratorRequest>( + "CodeGeneratorRequest", + fields, + oneofs, + ) } } impl crate::Message for CodeGeneratorRequest { + const NAME: &'static str = "CodeGeneratorRequest"; + fn is_initialized(&self) -> bool { for v in &self.proto_file { if !v.is_initialized() { @@ -469,24 +425,23 @@ impl crate::Message for CodeGeneratorRequest { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.file_to_generate)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.file_to_generate.push(is.read_string()?); }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.parameter)?; + 18 => { + self.parameter = ::std::option::Option::Some(is.read_string()?); }, - 15 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.proto_file)?; + 122 => { + self.proto_file.push(is.read_message()?); }, - 3 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.compiler_version)?; + 26 => { + crate::rt::read_singular_message_into_field(is, &mut self.compiler_version)?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -495,150 +450,117 @@ impl crate::Message for CodeGeneratorRequest { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.file_to_generate { my_size += crate::rt::string_size(1, &value); }; - if let Some(ref v) = self.parameter.as_ref() { + if let Some(v) = self.parameter.as_ref() { my_size += crate::rt::string_size(2, &v); } for value in &self.proto_file { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if let Some(ref v) = self.compiler_version.as_ref() { + if let Some(v) = self.compiler_version.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.file_to_generate { os.write_string(1, &v)?; }; - if let Some(ref v) = self.parameter.as_ref() { - os.write_string(2, &v)?; + if let Some(v) = self.parameter.as_ref() { + os.write_string(2, v)?; } for v in &self.proto_file { - os.write_tag(15, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(15, v, os)?; }; - if let Some(ref v) = self.compiler_version.as_ref() { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.compiler_version.as_ref() { + crate::rt::write_message_field_with_cached_size(3, v, os)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> CodeGeneratorRequest { CodeGeneratorRequest::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "file_to_generate", - |m: &CodeGeneratorRequest| { &m.file_to_generate }, - |m: &mut CodeGeneratorRequest| { &mut m.file_to_generate }, - )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "parameter", - |m: &CodeGeneratorRequest| { &m.parameter }, - |m: &mut CodeGeneratorRequest| { &mut m.parameter }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::descriptor::FileDescriptorProto>>( - "proto_file", - |m: &CodeGeneratorRequest| { &m.proto_file }, - |m: &mut CodeGeneratorRequest| { &mut m.proto_file }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<Version>>( - "compiler_version", - |m: &CodeGeneratorRequest| { &m.compiler_version }, - |m: &mut CodeGeneratorRequest| { &mut m.compiler_version }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<CodeGeneratorRequest>( - "CodeGeneratorRequest", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.file_to_generate.clear(); + self.parameter = ::std::option::Option::None; + self.proto_file.clear(); + self.compiler_version.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static CodeGeneratorRequest { - static instance: crate::rt::LazyV2<CodeGeneratorRequest> = crate::rt::LazyV2::INIT; - instance.get(CodeGeneratorRequest::new) + static instance: CodeGeneratorRequest = CodeGeneratorRequest { + file_to_generate: ::std::vec::Vec::new(), + parameter: ::std::option::Option::None, + proto_file: ::std::vec::Vec::new(), + compiler_version: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for CodeGeneratorRequest { - fn clear(&mut self) { - self.file_to_generate.clear(); - self.parameter.clear(); - self.proto_file.clear(); - self.compiler_version.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for CodeGeneratorRequest { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("CodeGeneratorRequest").unwrap()).clone() } } -impl ::std::fmt::Debug for CodeGeneratorRequest { +impl ::std::fmt::Display for CodeGeneratorRequest { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for CodeGeneratorRequest { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// The plugin writes an encoded CodeGeneratorResponse to stdout. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.compiler.CodeGeneratorResponse) pub struct CodeGeneratorResponse { // message fields - error: crate::SingularField<::std::string::String>, - supported_features: ::std::option::Option<u64>, - pub file: crate::RepeatedField<CodeGeneratorResponse_File>, + /// Error message. If non-empty, code generation failed. The plugin process + /// should exit with status code zero even if it reports an error in this way. + /// + /// This should be used to indicate errors in .proto files which prevent the + /// code generator from generating correct code. Errors which indicate a + /// problem in protoc itself -- such as the input CodeGeneratorRequest being + /// unparseable -- should be reported by writing a message to stderr and + /// exiting with a non-zero status code. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.error) + pub error: ::std::option::Option<::std::string::String>, + /// A bitmask of supported features that the code generator supports. + /// This is a bitwise "or" of values from the Feature enum. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.supported_features) + pub supported_features: ::std::option::Option<u64>, + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.file) + pub file: ::std::vec::Vec<code_generator_response::File>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.compiler.CodeGeneratorResponse.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a CodeGeneratorResponse { @@ -654,15 +576,15 @@ impl CodeGeneratorResponse { // optional string error = 1; - - pub fn get_error(&self) -> &str { + pub fn error(&self) -> &str { match self.error.as_ref() { - Some(v) => &v, + Some(v) => v, None => "", } } + pub fn clear_error(&mut self) { - self.error.clear(); + self.error = ::std::option::Option::None; } pub fn has_error(&self) -> bool { @@ -671,14 +593,14 @@ impl CodeGeneratorResponse { // Param is passed by value, moved pub fn set_error(&mut self, v: ::std::string::String) { - self.error = crate::SingularField::some(v); + self.error = ::std::option::Option::Some(v); } // Mutable pointer to the field. // If field is not initialized, it is initialized with default value first. pub fn mut_error(&mut self) -> &mut ::std::string::String { if self.error.is_none() { - self.error.set_default(); + self.error = ::std::option::Option::Some(::std::string::String::new()); } self.error.as_mut().unwrap() } @@ -690,10 +612,10 @@ impl CodeGeneratorResponse { // optional uint64 supported_features = 2; - - pub fn get_supported_features(&self) -> u64 { + pub fn supported_features(&self) -> u64 { self.supported_features.unwrap_or(0) } + pub fn clear_supported_features(&mut self) { self.supported_features = ::std::option::Option::None; } @@ -707,61 +629,53 @@ impl CodeGeneratorResponse { self.supported_features = ::std::option::Option::Some(v); } - // repeated .google.protobuf.compiler.CodeGeneratorResponse.File file = 15; - - - pub fn get_file(&self) -> &[CodeGeneratorResponse_File] { - &self.file - } - pub fn clear_file(&mut self) { - self.file.clear(); - } - - // Param is passed by value, moved - pub fn set_file(&mut self, v: crate::RepeatedField<CodeGeneratorResponse_File>) { - self.file = v; - } - - // Mutable pointer to the field. - pub fn mut_file(&mut self) -> &mut crate::RepeatedField<CodeGeneratorResponse_File> { - &mut self.file - } - - // Take field - pub fn take_file(&mut self) -> crate::RepeatedField<CodeGeneratorResponse_File> { - ::std::mem::replace(&mut self.file, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "error", + |m: &CodeGeneratorResponse| { &m.error }, + |m: &mut CodeGeneratorResponse| { &mut m.error }, + )); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( + "supported_features", + |m: &CodeGeneratorResponse| { &m.supported_features }, + |m: &mut CodeGeneratorResponse| { &mut m.supported_features }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "file", + |m: &CodeGeneratorResponse| { &m.file }, + |m: &mut CodeGeneratorResponse| { &mut m.file }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<CodeGeneratorResponse>( + "CodeGeneratorResponse", + fields, + oneofs, + ) } } impl crate::Message for CodeGeneratorResponse { + const NAME: &'static str = "CodeGeneratorResponse"; + fn is_initialized(&self) -> bool { - for v in &self.file { - if !v.is_initialized() { - return false; - } - }; true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.error)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.error = ::std::option::Option::Some(is.read_string()?); }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint64()?; - self.supported_features = ::std::option::Option::Some(tmp); + 16 => { + self.supported_features = ::std::option::Option::Some(is.read_uint64()?); }, - 15 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.file)?; + 122 => { + self.file.push(is.read_message()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -770,504 +684,477 @@ impl crate::Message for CodeGeneratorResponse { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - if let Some(ref v) = self.error.as_ref() { + if let Some(v) = self.error.as_ref() { my_size += crate::rt::string_size(1, &v); } if let Some(v) = self.supported_features { - my_size += crate::rt::value_size(2, v, crate::wire_format::WireTypeVarint); + my_size += crate::rt::uint64_size(2, v); } for value in &self.file { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.error.as_ref() { - os.write_string(1, &v)?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.error.as_ref() { + os.write_string(1, v)?; } if let Some(v) = self.supported_features { os.write_uint64(2, v)?; } for v in &self.file { - os.write_tag(15, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(15, v, os)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> CodeGeneratorResponse { CodeGeneratorResponse::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( - "error", - |m: &CodeGeneratorResponse| { &m.error }, - |m: &mut CodeGeneratorResponse| { &mut m.error }, - )); - fields.push(crate::reflect::accessor::make_option_accessor::<_, crate::types::ProtobufTypeUint64>( - "supported_features", - |m: &CodeGeneratorResponse| { &m.supported_features }, - |m: &mut CodeGeneratorResponse| { &mut m.supported_features }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<CodeGeneratorResponse_File>>( - "file", - |m: &CodeGeneratorResponse| { &m.file }, - |m: &mut CodeGeneratorResponse| { &mut m.file }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<CodeGeneratorResponse>( - "CodeGeneratorResponse", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.error = ::std::option::Option::None; + self.supported_features = ::std::option::Option::None; + self.file.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static CodeGeneratorResponse { - static instance: crate::rt::LazyV2<CodeGeneratorResponse> = crate::rt::LazyV2::INIT; - instance.get(CodeGeneratorResponse::new) + static instance: CodeGeneratorResponse = CodeGeneratorResponse { + error: ::std::option::Option::None, + supported_features: ::std::option::Option::None, + file: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for CodeGeneratorResponse { - fn clear(&mut self) { - self.error.clear(); - self.supported_features = ::std::option::Option::None; - self.file.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for CodeGeneratorResponse { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("CodeGeneratorResponse").unwrap()).clone() } } -impl ::std::fmt::Debug for CodeGeneratorResponse { +impl ::std::fmt::Display for CodeGeneratorResponse { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for CodeGeneratorResponse { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct CodeGeneratorResponse_File { - // message fields - name: crate::SingularField<::std::string::String>, - insertion_point: crate::SingularField<::std::string::String>, - content: crate::SingularField<::std::string::String>, - pub generated_code_info: crate::SingularPtrField<crate::descriptor::GeneratedCodeInfo>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a CodeGeneratorResponse_File { - fn default() -> &'a CodeGeneratorResponse_File { - <CodeGeneratorResponse_File as crate::Message>::default_instance() - } -} - -impl CodeGeneratorResponse_File { - pub fn new() -> CodeGeneratorResponse_File { - ::std::default::Default::default() - } - - // optional string name = 1; - - - pub fn get_name(&self) -> &str { - match self.name.as_ref() { - Some(v) => &v, - None => "", +/// Nested message and enums of message `CodeGeneratorResponse` +pub mod code_generator_response { + /// Represents a single generated file. + #[derive(PartialEq,Clone,Default,Debug)] + // @@protoc_insertion_point(message:google.protobuf.compiler.CodeGeneratorResponse.File) + pub struct File { + // message fields + /// The file name, relative to the output directory. The name must not + /// contain "." or ".." components and must be relative, not be absolute (so, + /// the file cannot lie outside the output directory). "/" must be used as + /// the path separator, not "\". + /// + /// If the name is omitted, the content will be appended to the previous + /// file. This allows the generator to break large files into small chunks, + /// and allows the generated text to be streamed back to protoc so that large + /// files need not reside completely in memory at one time. Note that as of + /// this writing protoc does not optimize for this -- it will read the entire + /// CodeGeneratorResponse before writing files to disk. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.File.name) + pub name: ::std::option::Option<::std::string::String>, + /// If non-empty, indicates that the named file should already exist, and the + /// content here is to be inserted into that file at a defined insertion + /// point. This feature allows a code generator to extend the output + /// produced by another code generator. The original generator may provide + /// insertion points by placing special annotations in the file that look + /// like: + /// @@protoc_insertion_point(NAME) + /// The annotation can have arbitrary text before and after it on the line, + /// which allows it to be placed in a comment. NAME should be replaced with + /// an identifier naming the point -- this is what other generators will use + /// as the insertion_point. Code inserted at this point will be placed + /// immediately above the line containing the insertion point (thus multiple + /// insertions to the same point will come out in the order they were added). + /// The double-@ is intended to make it unlikely that the generated code + /// could contain things that look like insertion points by accident. + /// + /// For example, the C++ code generator places the following line in the + /// .pb.h files that it generates: + /// // @@protoc_insertion_point(namespace_scope) + /// This line appears within the scope of the file's package namespace, but + /// outside of any particular class. Another plugin can then specify the + /// insertion_point "namespace_scope" to generate additional classes or + /// other declarations that should be placed in this scope. + /// + /// Note that if the line containing the insertion point begins with + /// whitespace, the same whitespace will be added to every line of the + /// inserted text. This is useful for languages like Python, where + /// indentation matters. In these languages, the insertion point comment + /// should be indented the same amount as any inserted code will need to be + /// in order to work correctly in that context. + /// + /// The code generator that generates the initial file and the one which + /// inserts into it must both run as part of a single invocation of protoc. + /// Code generators are executed in the order in which they appear on the + /// command line. + /// + /// If |insertion_point| is present, |name| must also be present. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.File.insertion_point) + pub insertion_point: ::std::option::Option<::std::string::String>, + /// The file contents. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.File.content) + pub content: ::std::option::Option<::std::string::String>, + /// Information describing the file content being inserted. If an insertion + /// point is used, this information will be appropriately offset and inserted + /// into the code generation metadata for the generated files. + // @@protoc_insertion_point(field:google.protobuf.compiler.CodeGeneratorResponse.File.generated_code_info) + pub generated_code_info: crate::MessageField<crate::descriptor::GeneratedCodeInfo>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.compiler.CodeGeneratorResponse.File.special_fields) + pub special_fields: crate::SpecialFields, + } + + impl<'a> ::std::default::Default for &'a File { + fn default() -> &'a File { + <File as crate::Message>::default_instance() } } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - pub fn has_name(&self) -> bool { - self.name.is_some() - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = crate::SingularField::some(v); - } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - if self.name.is_none() { - self.name.set_default(); + impl File { + pub fn new() -> File { + ::std::default::Default::default() } - self.name.as_mut().unwrap() - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - self.name.take().unwrap_or_else(|| ::std::string::String::new()) - } - - // optional string insertion_point = 2; + // optional string name = 1; - pub fn get_insertion_point(&self) -> &str { - match self.insertion_point.as_ref() { - Some(v) => &v, - None => "", + pub fn name(&self) -> &str { + match self.name.as_ref() { + Some(v) => v, + None => "", + } } - } - pub fn clear_insertion_point(&mut self) { - self.insertion_point.clear(); - } - - pub fn has_insertion_point(&self) -> bool { - self.insertion_point.is_some() - } - - // Param is passed by value, moved - pub fn set_insertion_point(&mut self, v: ::std::string::String) { - self.insertion_point = crate::SingularField::some(v); - } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_insertion_point(&mut self) -> &mut ::std::string::String { - if self.insertion_point.is_none() { - self.insertion_point.set_default(); + pub fn clear_name(&mut self) { + self.name = ::std::option::Option::None; } - self.insertion_point.as_mut().unwrap() - } - - // Take field - pub fn take_insertion_point(&mut self) -> ::std::string::String { - self.insertion_point.take().unwrap_or_else(|| ::std::string::String::new()) - } - // optional string content = 15; - - - pub fn get_content(&self) -> &str { - match self.content.as_ref() { - Some(v) => &v, - None => "", + pub fn has_name(&self) -> bool { + self.name.is_some() } - } - pub fn clear_content(&mut self) { - self.content.clear(); - } - pub fn has_content(&self) -> bool { - self.content.is_some() - } + // Param is passed by value, moved + pub fn set_name(&mut self, v: ::std::string::String) { + self.name = ::std::option::Option::Some(v); + } - // Param is passed by value, moved - pub fn set_content(&mut self, v: ::std::string::String) { - self.content = crate::SingularField::some(v); - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_name(&mut self) -> &mut ::std::string::String { + if self.name.is_none() { + self.name = ::std::option::Option::Some(::std::string::String::new()); + } + self.name.as_mut().unwrap() + } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_content(&mut self) -> &mut ::std::string::String { - if self.content.is_none() { - self.content.set_default(); + // Take field + pub fn take_name(&mut self) -> ::std::string::String { + self.name.take().unwrap_or_else(|| ::std::string::String::new()) } - self.content.as_mut().unwrap() - } - // Take field - pub fn take_content(&mut self) -> ::std::string::String { - self.content.take().unwrap_or_else(|| ::std::string::String::new()) - } + // optional string insertion_point = 2; - // optional .google.protobuf.GeneratedCodeInfo generated_code_info = 16; + pub fn insertion_point(&self) -> &str { + match self.insertion_point.as_ref() { + Some(v) => v, + None => "", + } + } + pub fn clear_insertion_point(&mut self) { + self.insertion_point = ::std::option::Option::None; + } - pub fn get_generated_code_info(&self) -> &crate::descriptor::GeneratedCodeInfo { - self.generated_code_info.as_ref().unwrap_or_else(|| <crate::descriptor::GeneratedCodeInfo as crate::Message>::default_instance()) - } - pub fn clear_generated_code_info(&mut self) { - self.generated_code_info.clear(); - } + pub fn has_insertion_point(&self) -> bool { + self.insertion_point.is_some() + } - pub fn has_generated_code_info(&self) -> bool { - self.generated_code_info.is_some() - } + // Param is passed by value, moved + pub fn set_insertion_point(&mut self, v: ::std::string::String) { + self.insertion_point = ::std::option::Option::Some(v); + } - // Param is passed by value, moved - pub fn set_generated_code_info(&mut self, v: crate::descriptor::GeneratedCodeInfo) { - self.generated_code_info = crate::SingularPtrField::some(v); - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_insertion_point(&mut self) -> &mut ::std::string::String { + if self.insertion_point.is_none() { + self.insertion_point = ::std::option::Option::Some(::std::string::String::new()); + } + self.insertion_point.as_mut().unwrap() + } - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_generated_code_info(&mut self) -> &mut crate::descriptor::GeneratedCodeInfo { - if self.generated_code_info.is_none() { - self.generated_code_info.set_default(); + // Take field + pub fn take_insertion_point(&mut self) -> ::std::string::String { + self.insertion_point.take().unwrap_or_else(|| ::std::string::String::new()) } - self.generated_code_info.as_mut().unwrap() - } - // Take field - pub fn take_generated_code_info(&mut self) -> crate::descriptor::GeneratedCodeInfo { - self.generated_code_info.take().unwrap_or_else(|| crate::descriptor::GeneratedCodeInfo::new()) - } -} + // optional string content = 15; -impl crate::Message for CodeGeneratorResponse_File { - fn is_initialized(&self) -> bool { - for v in &self.generated_code_info { - if !v.is_initialized() { - return false; + pub fn content(&self) -> &str { + match self.content.as_ref() { + Some(v) => v, + None => "", } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.name)?; - }, - 2 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.insertion_point)?; - }, - 15 => { - crate::rt::read_singular_string_into(wire_type, is, &mut self.content)?; - }, - 16 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.generated_code_info)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; } - ::std::result::Result::Ok(()) - } - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let Some(ref v) = self.name.as_ref() { - my_size += crate::rt::string_size(1, &v); - } - if let Some(ref v) = self.insertion_point.as_ref() { - my_size += crate::rt::string_size(2, &v); - } - if let Some(ref v) = self.content.as_ref() { - my_size += crate::rt::string_size(15, &v); + pub fn clear_content(&mut self) { + self.content = ::std::option::Option::None; } - if let Some(ref v) = self.generated_code_info.as_ref() { - let len = v.compute_size(); - my_size += 2 + crate::rt::compute_raw_varint32_size(len) + len; - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let Some(ref v) = self.name.as_ref() { - os.write_string(1, &v)?; - } - if let Some(ref v) = self.insertion_point.as_ref() { - os.write_string(2, &v)?; + pub fn has_content(&self) -> bool { + self.content.is_some() } - if let Some(ref v) = self.content.as_ref() { - os.write_string(15, &v)?; - } - if let Some(ref v) = self.generated_code_info.as_ref() { - os.write_tag(16, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } + // Param is passed by value, moved + pub fn set_content(&mut self, v: ::std::string::String) { + self.content = ::std::option::Option::Some(v); + } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } + // Mutable pointer to the field. + // If field is not initialized, it is initialized with default value first. + pub fn mut_content(&mut self) -> &mut ::std::string::String { + if self.content.is_none() { + self.content = ::std::option::Option::Some(::std::string::String::new()); + } + self.content.as_mut().unwrap() + } - fn new() -> CodeGeneratorResponse_File { - CodeGeneratorResponse_File::new() - } + // Take field + pub fn take_content(&mut self) -> ::std::string::String { + self.content.take().unwrap_or_else(|| ::std::string::String::new()) + } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + pub(in super) fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(4); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "name", - |m: &CodeGeneratorResponse_File| { &m.name }, - |m: &mut CodeGeneratorResponse_File| { &mut m.name }, + |m: &File| { &m.name }, + |m: &mut File| { &mut m.name }, )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "insertion_point", - |m: &CodeGeneratorResponse_File| { &m.insertion_point }, - |m: &mut CodeGeneratorResponse_File| { &mut m.insertion_point }, + |m: &File| { &m.insertion_point }, + |m: &mut File| { &mut m.insertion_point }, )); - fields.push(crate::reflect::accessor::make_singular_field_accessor::<_, crate::types::ProtobufTypeString>( + fields.push(crate::reflect::rt::v2::make_option_accessor::<_, _>( "content", - |m: &CodeGeneratorResponse_File| { &m.content }, - |m: &mut CodeGeneratorResponse_File| { &mut m.content }, + |m: &File| { &m.content }, + |m: &mut File| { &mut m.content }, )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::descriptor::GeneratedCodeInfo>>( + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, crate::descriptor::GeneratedCodeInfo>( "generated_code_info", - |m: &CodeGeneratorResponse_File| { &m.generated_code_info }, - |m: &mut CodeGeneratorResponse_File| { &mut m.generated_code_info }, + |m: &File| { &m.generated_code_info }, + |m: &mut File| { &mut m.generated_code_info }, )); - crate::reflect::MessageDescriptor::new_pb_name::<CodeGeneratorResponse_File>( + crate::reflect::GeneratedMessageDescriptorData::new_2::<File>( "CodeGeneratorResponse.File", fields, - file_descriptor_proto() + oneofs, ) - }) + } } - fn default_instance() -> &'static CodeGeneratorResponse_File { - static instance: crate::rt::LazyV2<CodeGeneratorResponse_File> = crate::rt::LazyV2::INIT; - instance.get(CodeGeneratorResponse_File::new) - } -} + impl crate::Message for File { + const NAME: &'static str = "File"; -impl crate::Clear for CodeGeneratorResponse_File { - fn clear(&mut self) { - self.name.clear(); - self.insertion_point.clear(); - self.content.clear(); - self.generated_code_info.clear(); - self.unknown_fields.clear(); + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = ::std::option::Option::Some(is.read_string()?); + }, + 18 => { + self.insertion_point = ::std::option::Option::Some(is.read_string()?); + }, + 122 => { + self.content = ::std::option::Option::Some(is.read_string()?); + }, + 130 => { + crate::rt::read_singular_message_into_field(is, &mut self.generated_code_info)?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let Some(v) = self.name.as_ref() { + my_size += crate::rt::string_size(1, &v); + } + if let Some(v) = self.insertion_point.as_ref() { + my_size += crate::rt::string_size(2, &v); + } + if let Some(v) = self.content.as_ref() { + my_size += crate::rt::string_size(15, &v); + } + if let Some(v) = self.generated_code_info.as_ref() { + let len = v.compute_size(); + my_size += 2 + crate::rt::compute_raw_varint64_size(len) + len; + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let Some(v) = self.name.as_ref() { + os.write_string(1, v)?; + } + if let Some(v) = self.insertion_point.as_ref() { + os.write_string(2, v)?; + } + if let Some(v) = self.content.as_ref() { + os.write_string(15, v)?; + } + if let Some(v) = self.generated_code_info.as_ref() { + crate::rt::write_message_field_with_cached_size(16, v, os)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> File { + File::new() + } + + fn clear(&mut self) { + self.name = ::std::option::Option::None; + self.insertion_point = ::std::option::Option::None; + self.content = ::std::option::Option::None; + self.generated_code_info.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static File { + static instance: File = File { + name: ::std::option::Option::None, + insertion_point: ::std::option::Option::None, + content: ::std::option::Option::None, + generated_code_info: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } } -} -impl ::std::fmt::Debug for CodeGeneratorResponse_File { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) + impl crate::MessageFull for File { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().message_by_package_relative_name("CodeGeneratorResponse.File").unwrap()).clone() + } } -} -impl crate::reflect::ProtobufValue for CodeGeneratorResponse_File { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) + impl ::std::fmt::Display for File { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } } -} -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum CodeGeneratorResponse_Feature { - FEATURE_NONE = 0, - FEATURE_PROTO3_OPTIONAL = 1, -} + impl crate::reflect::ProtobufValue for File { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; + } -impl crate::ProtobufEnum for CodeGeneratorResponse_Feature { - fn value(&self) -> i32 { - *self as i32 + /// Sync with code_generator.h. + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.compiler.CodeGeneratorResponse.Feature) + pub enum Feature { + // @@protoc_insertion_point(enum_value:google.protobuf.compiler.CodeGeneratorResponse.Feature.FEATURE_NONE) + FEATURE_NONE = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.compiler.CodeGeneratorResponse.Feature.FEATURE_PROTO3_OPTIONAL) + FEATURE_PROTO3_OPTIONAL = 1, } - fn from_i32(value: i32) -> ::std::option::Option<CodeGeneratorResponse_Feature> { - match value { - 0 => ::std::option::Option::Some(CodeGeneratorResponse_Feature::FEATURE_NONE), - 1 => ::std::option::Option::Some(CodeGeneratorResponse_Feature::FEATURE_PROTO3_OPTIONAL), - _ => ::std::option::Option::None + impl crate::Enum for Feature { + const NAME: &'static str = "Feature"; + + fn value(&self) -> i32 { + *self as i32 } - } - fn values() -> &'static [Self] { - static values: &'static [CodeGeneratorResponse_Feature] = &[ - CodeGeneratorResponse_Feature::FEATURE_NONE, - CodeGeneratorResponse_Feature::FEATURE_PROTO3_OPTIONAL, + fn from_i32(value: i32) -> ::std::option::Option<Feature> { + match value { + 0 => ::std::option::Option::Some(Feature::FEATURE_NONE), + 1 => ::std::option::Option::Some(Feature::FEATURE_PROTO3_OPTIONAL), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [Feature] = &[ + Feature::FEATURE_NONE, + Feature::FEATURE_PROTO3_OPTIONAL, ]; - values } - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<CodeGeneratorResponse_Feature>("CodeGeneratorResponse.Feature", file_descriptor_proto()) - }) - } -} + impl crate::EnumFull for Feature { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("CodeGeneratorResponse.Feature").unwrap()).clone() + } -impl ::std::marker::Copy for CodeGeneratorResponse_Feature { -} + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } + } -impl ::std::default::Default for CodeGeneratorResponse_Feature { - fn default() -> Self { - CodeGeneratorResponse_Feature::FEATURE_NONE + impl ::std::default::Default for Feature { + fn default() -> Self { + Feature::FEATURE_NONE + } } -} -impl crate::reflect::ProtobufValue for CodeGeneratorResponse_Feature { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) + impl Feature { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Feature>("CodeGeneratorResponse.Feature") + } } } @@ -1515,14 +1402,36 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x14\n\r\n\x05\x04\x02\x02\x02\x03\x12\x04\xb5\x01\x17\x19\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(1); + deps.push(crate::descriptor::file_descriptor().clone()); + let mut messages = ::std::vec::Vec::with_capacity(4); + messages.push(Version::generated_message_descriptor_data()); + messages.push(CodeGeneratorRequest::generated_message_descriptor_data()); + messages.push(CodeGeneratorResponse::generated_message_descriptor_data()); + messages.push(code_generator_response::File::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(1); + enums.push(code_generator_response::Feature::generated_enum_descriptor_data()); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/reflect/acc/mod.rs b/src/reflect/acc/mod.rs index 288c183..408c41c 100644 --- a/src/reflect/acc/mod.rs +++ b/src/reflect/acc/mod.rs @@ -1,31 +1,43 @@ -#![doc(hidden)] +use crate::message_dyn::MessageDyn; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::ReflectFieldRef; -use crate::reflect::acc::v1::FieldAccessorFunctions; -use crate::reflect::acc::v1::FieldAccessorImpl; -use crate::reflect::acc::v1::FieldAccessorTrait; -use crate::Message; +pub(crate) mod v2; -pub(crate) mod v1; - -pub(crate) enum Accessor { - V1(Box<dyn FieldAccessorTrait + 'static>), +#[derive(Debug)] +pub(crate) enum GeneratedFieldAccessor { + V2(AccessorV2), } /// Accessor object is constructed in generated code. /// Should not be used directly. +#[derive(Debug)] pub struct FieldAccessor { - pub(crate) name: &'static str, - pub(crate) accessor: Accessor, + pub(crate) _name: &'static str, + pub(crate) accessor: GeneratedFieldAccessor, +} + +impl GeneratedFieldAccessor { + pub(crate) fn get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectFieldRef<'a> { + match self { + GeneratedFieldAccessor::V2(AccessorV2::Singular(ref a)) => { + ReflectFieldRef::Optional(a.accessor.get_field(m)) + } + GeneratedFieldAccessor::V2(AccessorV2::Repeated(ref a)) => { + ReflectFieldRef::Repeated(a.accessor.get_repeated(m)) + } + GeneratedFieldAccessor::V2(AccessorV2::Map(ref a)) => { + ReflectFieldRef::Map(a.accessor.get_reflect(m)) + } + } + } } impl FieldAccessor { - pub(crate) fn new_v1<M: Message>( - name: &'static str, - fns: FieldAccessorFunctions<M>, - ) -> FieldAccessor { + pub(crate) fn new(name: &'static str, accessor: AccessorV2) -> FieldAccessor { FieldAccessor { - name, - accessor: Accessor::V1(Box::new(FieldAccessorImpl { fns })), + _name: name, + accessor: GeneratedFieldAccessor::V2(accessor), } } } diff --git a/src/reflect/acc/v1.rs b/src/reflect/acc/v1.rs deleted file mode 100644 index 4c55f8f..0000000 --- a/src/reflect/acc/v1.rs +++ /dev/null @@ -1,792 +0,0 @@ -#![doc(hidden)] - -//! Version 1 reflection accessors. - -use std::collections::HashMap; -use std::fmt; -use std::hash::Hash; - -use crate::enums::ProtobufEnum; -use crate::message::message_down_cast; -use crate::message::Message; -use crate::reflect::map::ReflectMap; -use crate::reflect::optional::ReflectOptional; -use crate::reflect::repeated::ReflectRepeated; -use crate::reflect::repeated::ReflectRepeatedEnum; -use crate::reflect::repeated::ReflectRepeatedMessage; -use crate::reflect::rt::FieldAccessor; -use crate::reflect::EnumValueDescriptor; -use crate::reflect::ProtobufValue; -use crate::reflect::ReflectFieldRef; -use crate::reflect::ReflectValueRef; -use crate::repeated::RepeatedField; -use crate::singular::SingularField; -use crate::singular::SingularPtrField; -use crate::types::*; - -/// this trait should not be used directly, use `FieldDescriptor` instead -pub trait FieldAccessorTrait: Sync + 'static { - fn has_field_generic(&self, m: &dyn Message) -> bool; - fn len_field_generic(&self, m: &dyn Message) -> usize; - // TODO: should it return default value or panic on unset field? - fn get_message_generic<'a>(&self, m: &'a dyn Message) -> &'a dyn Message; - fn get_enum_generic(&self, m: &dyn Message) -> &'static EnumValueDescriptor; - fn get_str_generic<'a>(&self, m: &'a dyn Message) -> &'a str; - fn get_bytes_generic<'a>(&self, m: &'a dyn Message) -> &'a [u8]; - fn get_u32_generic(&self, m: &dyn Message) -> u32; - fn get_u64_generic(&self, m: &dyn Message) -> u64; - fn get_i32_generic(&self, m: &dyn Message) -> i32; - fn get_i64_generic(&self, m: &dyn Message) -> i64; - fn get_bool_generic(&self, m: &dyn Message) -> bool; - fn get_f32_generic(&self, m: &dyn Message) -> f32; - fn get_f64_generic(&self, m: &dyn Message) -> f64; - - fn get_reflect<'a>(&self, m: &'a dyn Message) -> ReflectFieldRef<'a>; -} - -pub(crate) trait GetSingularMessage<M>: Sync { - fn get_message<'a>(&self, m: &'a M) -> &'a dyn Message; -} - -struct GetSingularMessageImpl<M, N> { - get: for<'a> fn(&'a M) -> &'a N, -} - -impl<M: Message, N: Message + 'static> GetSingularMessage<M> for GetSingularMessageImpl<M, N> { - fn get_message<'a>(&self, m: &'a M) -> &'a dyn Message { - (self.get)(m) - } -} - -pub(crate) trait GetSingularEnum<M>: Sync { - fn get_enum(&self, m: &M) -> &'static EnumValueDescriptor; -} - -struct GetSingularEnumImpl<M, E> { - get: fn(&M) -> E, -} - -impl<M: Message, E: ProtobufEnum> GetSingularEnum<M> for GetSingularEnumImpl<M, E> { - fn get_enum(&self, m: &M) -> &'static EnumValueDescriptor { - (self.get)(m).descriptor() - } -} - -trait GetRepeatedMessage<M>: Sync { - fn len_field(&self, m: &M) -> usize; - fn get_message_item<'a>(&self, m: &'a M, index: usize) -> &'a dyn Message; - fn reflect_repeated_message<'a>(&self, m: &'a M) -> Box<dyn ReflectRepeatedMessage<'a> + 'a>; -} - -trait GetRepeatedEnum<M: Message + 'static>: Sync { - fn len_field(&self, m: &M) -> usize; - fn get_enum_item(&self, m: &M, index: usize) -> &'static EnumValueDescriptor; - fn reflect_repeated_enum<'a>(&self, m: &'a M) -> Box<dyn ReflectRepeatedEnum<'a> + 'a>; -} - -pub(crate) trait GetSetCopyFns<M>: Sync { - fn get_field<'a>(&self, m: &'a M) -> ReflectValueRef<'a>; -} - -struct GetSetCopyFnsImpl<M, V: ProtobufValue + Copy> { - get: fn(&M) -> V, - _set: fn(&mut M, V), -} - -impl<M, V: ProtobufValue + Copy> GetSetCopyFns<M> for GetSetCopyFnsImpl<M, V> { - fn get_field<'a>(&self, m: &'a M) -> ReflectValueRef<'a> { - (&(self.get)(m) as &dyn ProtobufValue).as_ref_copy() - } -} - -pub(crate) enum SingularGetSet<M> { - Copy(Box<dyn GetSetCopyFns<M>>), - String(for<'a> fn(&'a M) -> &'a str, fn(&mut M, String)), - Bytes(for<'a> fn(&'a M) -> &'a [u8], fn(&mut M, Vec<u8>)), - Enum(Box<dyn GetSingularEnum<M> + 'static>), - Message(Box<dyn GetSingularMessage<M> + 'static>), -} - -impl<M: Message + 'static> SingularGetSet<M> { - fn get_ref<'a>(&self, m: &'a M) -> ReflectValueRef<'a> { - match self { - &SingularGetSet::Copy(ref copy) => copy.get_field(m), - &SingularGetSet::String(get, _) => ReflectValueRef::String(get(m)), - &SingularGetSet::Bytes(get, _) => ReflectValueRef::Bytes(get(m)), - &SingularGetSet::Enum(ref get) => ReflectValueRef::Enum(get.get_enum(m)), - &SingularGetSet::Message(ref get) => ReflectValueRef::Message(get.get_message(m)), - } - } -} - -pub(crate) trait FieldAccessor2<M, R: ?Sized>: Sync -where - M: Message + 'static, -{ - fn get_field<'a>(&self, _: &'a M) -> &'a R; - fn mut_field<'a>(&self, _: &'a mut M) -> &'a mut R; -} - -struct MessageGetMut<M, L> -where - M: Message + 'static, -{ - get_field: for<'a> fn(&'a M) -> &'a L, - mut_field: for<'a> fn(&'a mut M) -> &'a mut L, -} - -pub(crate) enum FieldAccessorFunctions<M> { - // up to 1.0.24 optional or required - SingularHasGetSet { - has: fn(&M) -> bool, - get_set: SingularGetSet<M>, - }, - // protobuf 3 simple field - Simple(Box<dyn FieldAccessor2<M, dyn ProtobufValue>>), - // optional, required or message - Optional(Box<dyn FieldAccessor2<M, dyn ReflectOptional>>), - // repeated - Repeated(Box<dyn FieldAccessor2<M, dyn ReflectRepeated>>), - // protobuf 3 map - Map(Box<dyn FieldAccessor2<M, dyn ReflectMap>>), -} - -impl<M> fmt::Debug for FieldAccessorFunctions<M> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &FieldAccessorFunctions::SingularHasGetSet { .. } => { - write!(f, "SingularHasGetSet {{ .. }}") - } - &FieldAccessorFunctions::Simple(..) => write!(f, "Simple(..)"), - &FieldAccessorFunctions::Optional(..) => write!(f, "Optional(..)"), - &FieldAccessorFunctions::Repeated(..) => write!(f, "Repeated(..)"), - &FieldAccessorFunctions::Map(..) => write!(f, "Map(..)"), - } - } -} - -pub(crate) struct FieldAccessorImpl<M> { - pub(crate) fns: FieldAccessorFunctions<M>, -} - -impl<M: Message> FieldAccessorImpl<M> { - fn get_value_option<'a>(&self, m: &'a M) -> Option<ReflectValueRef<'a>> { - match self.fns { - FieldAccessorFunctions::Repeated(..) | FieldAccessorFunctions::Map(..) => { - panic!("repeated") - } - FieldAccessorFunctions::Simple(ref a) => Some(a.get_field(m).as_ref()), - FieldAccessorFunctions::Optional(ref a) => { - a.get_field(m).to_option().map(|v| v.as_ref()) - } - FieldAccessorFunctions::SingularHasGetSet { - ref has, - ref get_set, - } => { - if !has(m) { - None - } else { - Some(get_set.get_ref(m)) - } - } - } - } -} - -impl<M: Message + 'static> FieldAccessorTrait for FieldAccessorImpl<M> { - fn has_field_generic(&self, m: &dyn Message) -> bool { - match self.fns { - FieldAccessorFunctions::SingularHasGetSet { has, .. } => has(message_down_cast(m)), - FieldAccessorFunctions::Optional(ref a) => { - a.get_field(message_down_cast(m)).to_option().is_some() - } - FieldAccessorFunctions::Simple(ref a) => { - a.get_field(message_down_cast(m)).is_non_zero() - } - FieldAccessorFunctions::Map(..) | FieldAccessorFunctions::Repeated(..) => { - panic!("has_xxx is not implemented for repeated"); - } - } - } - - fn len_field_generic(&self, m: &dyn Message) -> usize { - match self.fns { - FieldAccessorFunctions::Repeated(ref a) => a.get_field(message_down_cast(m)).len(), - FieldAccessorFunctions::Map(ref a) => a.get_field(message_down_cast(m)).len(), - FieldAccessorFunctions::Simple(..) - | FieldAccessorFunctions::SingularHasGetSet { .. } - | FieldAccessorFunctions::Optional(..) => { - panic!("not a repeated field"); - } - } - } - - fn get_message_generic<'a>(&self, m: &'a dyn Message) -> &'a dyn Message { - match self.fns { - FieldAccessorFunctions::SingularHasGetSet { - get_set: SingularGetSet::Message(ref get), - .. - } => get.get_message(message_down_cast(m)), - FieldAccessorFunctions::Optional(ref t) => { - match t - .get_field(message_down_cast(m)) - .to_option() - .expect("field unset") - .as_ref() - { - ReflectValueRef::Message(m) => m, - _ => panic!("not a message"), - } - } - ref fns => panic!("unknown accessor type: {:?}", fns), - } - } - - fn get_enum_generic(&self, m: &dyn Message) -> &'static EnumValueDescriptor { - match self.fns { - FieldAccessorFunctions::SingularHasGetSet { - get_set: SingularGetSet::Enum(ref get), - .. - } => get.get_enum(message_down_cast(m)), - FieldAccessorFunctions::Optional(ref t) => { - match t - .get_field(message_down_cast(m)) - .to_option() - .expect("field unset") - .as_ref() - { - ReflectValueRef::Enum(e) => e, - _ => panic!("not an enum"), - } - } - FieldAccessorFunctions::Simple(ref t) => { - match t.get_field(message_down_cast(m)).as_ref() { - ReflectValueRef::Enum(e) => e, - _ => panic!("not an enum"), - } - } - ref fns => panic!("unknown accessor type: {:?}", fns), - } - } - - fn get_str_generic<'a>(&self, m: &'a dyn Message) -> &'a str { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::String(v)) => v, - Some(_) => panic!("wrong type"), - None => "", // TODO: check type - } - } - - fn get_bytes_generic<'a>(&self, m: &'a dyn Message) -> &'a [u8] { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::Bytes(v)) => v, - Some(_) => panic!("wrong type"), - None => b"", // TODO: check type - } - } - - fn get_u32_generic(&self, m: &dyn Message) -> u32 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::U32(v)) => v, - Some(_) => panic!("wrong type"), - None => 0, // TODO: check type - } - } - - fn get_u64_generic(&self, m: &dyn Message) -> u64 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::U64(v)) => v, - Some(_) => panic!("wrong type"), - None => 0, // TODO: check type - } - } - - fn get_i32_generic(&self, m: &dyn Message) -> i32 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::I32(v)) => v, - Some(_) => panic!("wrong type"), - None => 0, // TODO: check type - } - } - - fn get_i64_generic(&self, m: &dyn Message) -> i64 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::I64(v)) => v, - Some(_) => panic!("wrong type"), - None => 0, // TODO: check type - } - } - - fn get_bool_generic(&self, m: &dyn Message) -> bool { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::Bool(v)) => v, - Some(_) => panic!("wrong type"), - None => false, // TODO: check type - } - } - - fn get_f32_generic(&self, m: &dyn Message) -> f32 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::F32(v)) => v, - Some(_) => panic!("wrong type"), - None => 0.0, // TODO: check type - } - } - - fn get_f64_generic(&self, m: &dyn Message) -> f64 { - match self.get_value_option(message_down_cast(m)) { - Some(ReflectValueRef::F64(v)) => v, - Some(_) => panic!("wrong type"), - None => 0.0, // TODO: check type - } - } - - fn get_reflect<'a>(&self, m: &'a dyn Message) -> ReflectFieldRef<'a> { - match self.fns { - FieldAccessorFunctions::Repeated(ref accessor2) => { - ReflectFieldRef::Repeated(accessor2.get_field(message_down_cast(m))) - } - FieldAccessorFunctions::Map(ref accessor2) => { - ReflectFieldRef::Map(accessor2.get_field(message_down_cast(m))) - } - FieldAccessorFunctions::Optional(ref accessor2) => ReflectFieldRef::Optional( - accessor2 - .get_field(message_down_cast(m)) - .to_option() - .map(|v| v.as_ref()), - ), - FieldAccessorFunctions::Simple(ref accessor2) => ReflectFieldRef::Optional({ - let v = accessor2.get_field(message_down_cast(m)); - if v.is_non_zero() { - Some(v.as_ref()) - } else { - None - } - }), - FieldAccessorFunctions::SingularHasGetSet { - ref has, - ref get_set, - } => ReflectFieldRef::Optional(if has(message_down_cast(m)) { - Some(get_set.get_ref(message_down_cast(m))) - } else { - None - }), - } - } -} - -// singular - -fn set_panic<A, B>(_: &mut A, _: B) { - panic!() -} - -// TODO: make_singular_xxx_accessor are used only for oneof fields -// oneof codegen should be changed - -pub fn make_singular_u32_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> u32, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_i32_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> i32, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_u64_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> u64, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_i64_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> i64, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_f32_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> f32, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_f64_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> f64, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_bool_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> bool, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Copy(Box::new(GetSetCopyFnsImpl { - get, - _set: set_panic, - })), - }, - ) -} - -pub fn make_singular_enum_accessor<M: Message + 'static, E: ProtobufEnum + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: fn(&M) -> E, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Enum(Box::new(GetSingularEnumImpl { get })), - }, - ) -} - -pub fn make_singular_string_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: for<'a> fn(&'a M) -> &'a str, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::String(get, set_panic), - }, - ) -} - -pub fn make_singular_bytes_accessor<M: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: for<'a> fn(&'a M) -> &'a [u8], -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Bytes(get, set_panic), - }, - ) -} - -pub fn make_singular_message_accessor<M: Message + 'static, F: Message + 'static>( - name: &'static str, - has: fn(&M) -> bool, - get: for<'a> fn(&'a M) -> &'a F, -) -> FieldAccessor { - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::SingularHasGetSet { - has, - get_set: SingularGetSet::Message(Box::new(GetSingularMessageImpl { get })), - }, - ) -} - -// repeated - -impl<M, V> FieldAccessor2<M, dyn ReflectRepeated> for MessageGetMut<M, Vec<V>> -where - M: Message + 'static, - V: ProtobufValue + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectRepeated { - (self.get_field)(m) as &dyn ReflectRepeated - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectRepeated { - (self.mut_field)(m) as &mut dyn ReflectRepeated - } -} - -pub fn make_vec_accessor<M, V>( - name: &'static str, - get_vec: for<'a> fn(&'a M) -> &'a Vec<V::Value>, - mut_vec: for<'a> fn(&'a mut M) -> &'a mut Vec<V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Repeated(Box::new(MessageGetMut::<M, Vec<V::Value>> { - get_field: get_vec, - mut_field: mut_vec, - })), - ) -} - -impl<M, V> FieldAccessor2<M, dyn ReflectRepeated> for MessageGetMut<M, RepeatedField<V>> -where - M: Message + 'static, - V: ProtobufValue + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectRepeated { - (self.get_field)(m) as &dyn ReflectRepeated - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectRepeated { - (self.mut_field)(m) as &mut dyn ReflectRepeated - } -} - -pub fn make_repeated_field_accessor<M, V>( - name: &'static str, - get_vec: for<'a> fn(&'a M) -> &'a RepeatedField<V::Value>, - mut_vec: for<'a> fn(&'a mut M) -> &'a mut RepeatedField<V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Repeated(Box::new(MessageGetMut::<M, RepeatedField<V::Value>> { - get_field: get_vec, - mut_field: mut_vec, - })), - ) -} - -impl<M, V> FieldAccessor2<M, dyn ReflectOptional> for MessageGetMut<M, Option<V>> -where - M: Message + 'static, - V: ProtobufValue + Clone + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectOptional { - (self.get_field)(m) as &dyn ReflectOptional - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectOptional { - (self.mut_field)(m) as &mut dyn ReflectOptional - } -} - -pub fn make_option_accessor<M, V>( - name: &'static str, - get_field: for<'a> fn(&'a M) -> &'a Option<V::Value>, - mut_field: for<'a> fn(&'a mut M) -> &'a mut Option<V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Optional(Box::new(MessageGetMut::<M, Option<V::Value>> { - get_field, - mut_field, - })), - ) -} - -impl<M, V> FieldAccessor2<M, dyn ReflectOptional> for MessageGetMut<M, SingularField<V>> -where - M: Message + 'static, - V: ProtobufValue + Clone + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectOptional { - (self.get_field)(m) as &dyn ReflectOptional - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectOptional { - (self.mut_field)(m) as &mut dyn ReflectOptional - } -} - -pub fn make_singular_field_accessor<M, V>( - name: &'static str, - get_field: for<'a> fn(&'a M) -> &'a SingularField<V::Value>, - mut_field: for<'a> fn(&'a mut M) -> &'a mut SingularField<V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Optional(Box::new(MessageGetMut::<M, SingularField<V::Value>> { - get_field, - mut_field, - })), - ) -} - -impl<M, V> FieldAccessor2<M, dyn ReflectOptional> for MessageGetMut<M, SingularPtrField<V>> -where - M: Message + 'static, - V: ProtobufValue + Clone + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectOptional { - (self.get_field)(m) as &dyn ReflectOptional - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectOptional { - (self.mut_field)(m) as &mut dyn ReflectOptional - } -} - -pub fn make_singular_ptr_field_accessor<M, V>( - name: &'static str, - get_field: for<'a> fn(&'a M) -> &'a SingularPtrField<V::Value>, - mut_field: for<'a> fn(&'a mut M) -> &'a mut SingularPtrField<V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Optional(Box::new( - MessageGetMut::<M, SingularPtrField<V::Value>> { - get_field, - mut_field, - }, - )), - ) -} - -impl<M, V> FieldAccessor2<M, dyn ProtobufValue> for MessageGetMut<M, V> -where - M: Message + 'static, - V: ProtobufValue + Clone + 'static, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ProtobufValue { - (self.get_field)(m) as &dyn ProtobufValue - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ProtobufValue { - (self.mut_field)(m) as &mut dyn ProtobufValue - } -} - -pub fn make_simple_field_accessor<M, V>( - name: &'static str, - get_field: for<'a> fn(&'a M) -> &'a V::Value, - mut_field: for<'a> fn(&'a mut M) -> &'a mut V::Value, -) -> FieldAccessor -where - M: Message + 'static, - V: ProtobufType + 'static, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Simple(Box::new(MessageGetMut::<M, V::Value> { - get_field, - mut_field, - })), - ) -} - -impl<M, K, V> FieldAccessor2<M, dyn ReflectMap> for MessageGetMut<M, HashMap<K, V>> -where - M: Message + 'static, - K: ProtobufValue + 'static, - V: ProtobufValue + 'static, - K: Hash + Eq, -{ - fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectMap { - (self.get_field)(m) as &dyn ReflectMap - } - - fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectMap { - (self.mut_field)(m) as &mut dyn ReflectMap - } -} - -pub fn make_map_accessor<M, K, V>( - name: &'static str, - get_field: for<'a> fn(&'a M) -> &'a HashMap<K::Value, V::Value>, - mut_field: for<'a> fn(&'a mut M) -> &'a mut HashMap<K::Value, V::Value>, -) -> FieldAccessor -where - M: Message + 'static, - K: ProtobufType + 'static, - V: ProtobufType + 'static, - <K as ProtobufType>::Value: Hash + Eq, -{ - FieldAccessor::new_v1( - name, - FieldAccessorFunctions::Map(Box::new(MessageGetMut::<M, HashMap<K::Value, V::Value>> { - get_field, - mut_field, - })), - ) -} diff --git a/src/reflect/acc/v2/map.rs b/src/reflect/acc/v2/map.rs new file mode 100644 index 0000000..3d8df8b --- /dev/null +++ b/src/reflect/acc/v2/map.rs @@ -0,0 +1,90 @@ +use std::collections::HashMap; +use std::fmt; +use std::hash::Hash; + +use crate::message_dyn::MessageDyn; +use crate::message_full::MessageFull; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::acc::FieldAccessor; +use crate::reflect::map::ReflectMapMut; +use crate::reflect::map::ReflectMapRef; +use crate::reflect::runtime_types::RuntimeTypeHashable; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::RuntimeType; + +pub(crate) trait MapFieldAccessor: Send + Sync + 'static { + fn get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectMapRef<'a>; + fn mut_reflect<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectMapMut<'a>; + fn element_type(&self) -> (RuntimeType, RuntimeType); +} + +pub(crate) struct MapFieldAccessorHolder { + pub accessor: Box<dyn MapFieldAccessor>, +} + +impl<'a> fmt::Debug for MapFieldAccessorHolder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MapFieldAccessorHolder").finish() + } +} + +struct MapFieldAccessorImpl<M, K, V> +where + M: MessageFull, + K: ProtobufValue, + V: ProtobufValue, +{ + get_field: fn(&M) -> &HashMap<K, V>, + mut_field: fn(&mut M) -> &mut HashMap<K, V>, +} + +impl<M, K, V> MapFieldAccessor for MapFieldAccessorImpl<M, K, V> +where + M: MessageFull, + K: ProtobufValue + Eq + Hash, + K::RuntimeType: RuntimeTypeHashable, + V: ProtobufValue, +{ + fn get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectMapRef<'a> { + let m = m.downcast_ref().unwrap(); + let map = (self.get_field)(m); + ReflectMapRef::new(map) + } + + fn mut_reflect<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectMapMut<'a> { + let m = m.downcast_mut().unwrap(); + let map = (self.mut_field)(m); + ReflectMapMut::new(map) + } + + fn element_type(&self) -> (RuntimeType, RuntimeType) { + ( + K::RuntimeType::runtime_type_box(), + V::RuntimeType::runtime_type_box(), + ) + } +} + +/// Make accessor for map field +pub fn make_map_simpler_accessor<M, K, V>( + name: &'static str, + get_field: for<'a> fn(&'a M) -> &'a HashMap<K, V>, + mut_field: for<'a> fn(&'a mut M) -> &'a mut HashMap<K, V>, +) -> FieldAccessor +where + M: MessageFull + 'static, + K: ProtobufValue + Hash + Eq, + K::RuntimeType: RuntimeTypeHashable, + V: ProtobufValue, +{ + FieldAccessor::new( + name, + AccessorV2::Map(MapFieldAccessorHolder { + accessor: Box::new(MapFieldAccessorImpl::<M, K, V> { + get_field, + mut_field, + }), + }), + ) +} diff --git a/src/reflect/acc/v2/mod.rs b/src/reflect/acc/v2/mod.rs new file mode 100644 index 0000000..d3962b5 --- /dev/null +++ b/src/reflect/acc/v2/mod.rs @@ -0,0 +1,14 @@ +use crate::reflect::acc::v2::map::MapFieldAccessorHolder; +use crate::reflect::acc::v2::repeated::RepeatedFieldAccessorHolder; +use crate::reflect::acc::v2::singular::SingularFieldAccessorHolder; + +pub(crate) mod map; +pub(crate) mod repeated; +pub(crate) mod singular; + +#[derive(Debug)] +pub(crate) enum AccessorV2 { + Singular(SingularFieldAccessorHolder), + Repeated(RepeatedFieldAccessorHolder), + Map(MapFieldAccessorHolder), +} diff --git a/src/reflect/acc/v2/repeated.rs b/src/reflect/acc/v2/repeated.rs new file mode 100644 index 0000000..78afdf2 --- /dev/null +++ b/src/reflect/acc/v2/repeated.rs @@ -0,0 +1,114 @@ +use std::fmt; +use std::marker; + +use crate::message_dyn::MessageDyn; +use crate::message_full::MessageFull; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::acc::FieldAccessor; +use crate::reflect::repeated::ReflectRepeated; +use crate::reflect::repeated::ReflectRepeatedMut; +use crate::reflect::repeated::ReflectRepeatedRef; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::RuntimeType; + +pub(crate) trait RepeatedFieldAccessor: Send + Sync + 'static { + fn get_repeated<'a>(&self, m: &'a dyn MessageDyn) -> ReflectRepeatedRef<'a>; + fn mut_repeated<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectRepeatedMut<'a>; + fn element_type(&self) -> RuntimeType; +} + +pub(crate) struct RepeatedFieldAccessorHolder { + pub accessor: Box<dyn RepeatedFieldAccessor>, +} + +impl<'a> fmt::Debug for RepeatedFieldAccessorHolder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RepeatedFieldAccessorHolder").finish() + } +} + +trait RepeatedFieldGetMut<M, R: ?Sized>: Send + Sync + 'static +where + M: MessageFull + 'static, +{ + fn get_field<'a>(&self, message: &'a M) -> &'a R; + fn mut_field<'a>(&self, message: &'a mut M) -> &'a mut R; +} + +struct RepeatedFieldGetMutImpl<M, L> +where + M: MessageFull + 'static, +{ + get_field: for<'a> fn(&'a M) -> &'a L, + mut_field: for<'a> fn(&'a mut M) -> &'a mut L, +} + +impl<M, V> RepeatedFieldGetMut<M, dyn ReflectRepeated> for RepeatedFieldGetMutImpl<M, Vec<V>> +where + M: MessageFull + 'static, + V: ProtobufValue, +{ + fn get_field<'a>(&self, m: &'a M) -> &'a dyn ReflectRepeated { + (self.get_field)(m) as &dyn ReflectRepeated + } + + fn mut_field<'a>(&self, m: &'a mut M) -> &'a mut dyn ReflectRepeated { + (self.mut_field)(m) as &mut dyn ReflectRepeated + } +} + +struct RepeatedFieldAccessorImpl<M, V> +where + M: MessageFull, + V: ProtobufValue, +{ + fns: Box<dyn RepeatedFieldGetMut<M, dyn ReflectRepeated>>, + _marker: marker::PhantomData<V>, +} + +impl<M, V> RepeatedFieldAccessor for RepeatedFieldAccessorImpl<M, V> +where + M: MessageFull, + V: ProtobufValue, +{ + fn get_repeated<'a>(&self, m: &'a dyn MessageDyn) -> ReflectRepeatedRef<'a> { + let m = m.downcast_ref().unwrap(); + let repeated = self.fns.get_field(m); + ReflectRepeatedRef::new(repeated) + } + + fn mut_repeated<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectRepeatedMut<'a> { + let m = m.downcast_mut().unwrap(); + let repeated = self.fns.mut_field(m); + ReflectRepeatedMut::new(repeated) + } + + fn element_type(&self) -> RuntimeType { + V::RuntimeType::runtime_type_box() + } +} + +/// Make accessor for `Vec` field +pub fn make_vec_simpler_accessor<M, V>( + name: &'static str, + get_vec: for<'a> fn(&'a M) -> &'a Vec<V>, + mut_vec: for<'a> fn(&'a mut M) -> &'a mut Vec<V>, +) -> FieldAccessor +where + M: MessageFull + 'static, + V: ProtobufValue, +{ + FieldAccessor::new( + name, + AccessorV2::Repeated(RepeatedFieldAccessorHolder { + accessor: Box::new(RepeatedFieldAccessorImpl::<M, V> { + fns: Box::new(RepeatedFieldGetMutImpl::<M, Vec<V>> { + get_field: get_vec, + mut_field: mut_vec, + }), + _marker: marker::PhantomData::<V>, + }), + }), + ) +} diff --git a/src/reflect/acc/v2/singular/mod.rs b/src/reflect/acc/v2/singular/mod.rs new file mode 100644 index 0000000..a152007 --- /dev/null +++ b/src/reflect/acc/v2/singular/mod.rs @@ -0,0 +1,331 @@ +use std::fmt; +use std::marker; + +use crate::message_dyn::MessageDyn; +use crate::message_field::MessageField; +use crate::message_full::MessageFull; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::acc::FieldAccessor; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::runtime_types::RuntimeTypeWithDeref; +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectOptionalRef; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::EnumFull; +use crate::EnumOrUnknown; + +pub(crate) mod oneof; + +/// This trait should not be used directly, use `FieldDescriptor` instead +pub(crate) trait SingularFieldAccessor: Send + Sync + 'static { + fn get_field<'a>(&self, m: &'a dyn MessageDyn) -> ReflectOptionalRef<'a>; + fn mut_field_or_default<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectValueMut<'a>; + fn set_field(&self, m: &mut dyn MessageDyn, value: ReflectValueBox); + fn clear_field(&self, m: &mut dyn MessageDyn); +} + +pub(crate) struct SingularFieldAccessorHolder { + pub accessor: Box<dyn SingularFieldAccessor>, +} + +impl SingularFieldAccessorHolder { + fn new<M>( + get_field: impl for<'a> Fn(&'a M) -> ReflectOptionalRef<'a> + Send + Sync + 'static, + mut_field_or_default: impl for<'a> Fn(&'a mut M) -> ReflectValueMut<'a> + Send + Sync + 'static, + set_field: impl Fn(&mut M, ReflectValueBox) + Send + Sync + 'static, + clear_field: impl Fn(&mut M) + Send + Sync + 'static, + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + { + struct Impl<M, G, H, S, C> { + get_field: G, + mut_field_or_default: H, + set_field: S, + clear_field: C, + _marker: marker::PhantomData<M>, + } + + impl<M, G, H, S, C> SingularFieldAccessor for Impl<M, G, H, S, C> + where + M: MessageFull, + G: for<'a> Fn(&'a M) -> ReflectOptionalRef<'a> + Send + Sync + 'static, + H: for<'a> Fn(&'a mut M) -> ReflectValueMut<'a> + Send + Sync + 'static, + S: Fn(&mut M, ReflectValueBox) + Send + Sync + 'static, + C: Fn(&mut M) + Send + Sync + 'static, + { + fn get_field<'a>(&self, m: &'a dyn MessageDyn) -> ReflectOptionalRef<'a> { + (self.get_field)(m.downcast_ref::<M>().unwrap()) + } + + fn mut_field_or_default<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectValueMut<'a> { + (self.mut_field_or_default)(m.downcast_mut::<M>().unwrap()) + } + + fn set_field(&self, m: &mut dyn MessageDyn, value: ReflectValueBox) { + (self.set_field)(m.downcast_mut::<M>().unwrap(), value); + } + + fn clear_field(&self, m: &mut dyn MessageDyn) { + (self.clear_field)(m.downcast_mut::<M>().unwrap()); + } + } + + SingularFieldAccessorHolder { + accessor: Box::new(Impl { + get_field, + mut_field_or_default, + set_field, + clear_field, + _marker: marker::PhantomData, + }), + } + } + + fn new_get_mut<M, V>( + get_field: for<'a> fn(&'a M) -> &'a V, + mut_field: for<'a> fn(&'a mut M) -> &'a mut V, + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + V: ProtobufValue, + { + Self::new( + move |m| { + let v = (get_field)(m); + ReflectOptionalRef::new_filter_non_zero(v) + }, + move |m| V::RuntimeType::as_mut((mut_field)(m)), + move |m, value| V::RuntimeType::set_from_value_box((mut_field)(m), value), + move |m| { + let default_value = V::RuntimeType::default_value_ref().to_box(); + V::RuntimeType::set_from_value_box((mut_field)(m), default_value); + }, + ) + } + + fn new_get_option_mut_option<M, V>( + get_field: for<'a> fn(&'a M) -> &'a Option<V>, + mut_field: for<'a> fn(&'a mut M) -> &'a mut Option<V>, + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + V: ProtobufValue, + { + Self::new( + move |m| ReflectOptionalRef::new_from_option((get_field)(m).as_ref()), + move |_m| unimplemented!(), + move |m, value| { + *(mut_field)(m) = Some(V::RuntimeType::from_value_box(value).expect("wrong type")) + }, + move |m| *(mut_field)(m) = None, + ) + } + + fn new_get_mut_message<M, V>( + get_field: for<'a> fn(&'a M) -> &'a MessageField<V>, + mut_field: for<'a> fn(&'a mut M) -> &'a mut MessageField<V>, + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + V: MessageFull, + { + Self::new( + move |m| ReflectOptionalRef::new_from_option((get_field)(m).as_ref()), + move |m| { + let option = (mut_field)(m); + if option.as_ref().is_none() { + *option = MessageField::some(V::default()); + } + V::RuntimeType::as_mut(option.as_mut().unwrap()) + }, + move |m, value| { + *(mut_field)(m) = + MessageField::some(V::RuntimeType::from_value_box(value).expect("wrong type")) + }, + move |m| { + *(mut_field)(m) = MessageField::none(); + }, + ) + } + + pub(crate) fn new_get_option_set_enum<M, E>( + get: fn(&M) -> Option<EnumOrUnknown<E>>, + set: fn(&mut M, EnumOrUnknown<E>), + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + E: EnumFull, + { + Self::new( + move |m| { + let value = (get)(m); + match value { + Some(v) => ReflectOptionalRef::some(ReflectValueRef::Enum( + E::enum_descriptor(), + v.value(), + )), + None => ReflectOptionalRef::none_from::<EnumOrUnknown<E>>(), + } + }, + |_m| panic!("cannot get mutable pointer"), + move |m, value| match value { + ReflectValueBox::Enum(e, v) => { + assert_eq!(E::enum_descriptor(), e); + (set)(m, EnumOrUnknown::from_i32(v)); + } + _ => panic!("expecting enum value"), + }, + move |m| { + (set)(m, EnumOrUnknown::from_i32(0)); + }, + ) + } + + pub(crate) fn new_has_get_set<M, V>( + has: fn(&M) -> bool, + get: fn(&M) -> V, + set: fn(&mut M, V), + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + V: ProtobufValue + Copy, + { + Self::new( + move |m| { + if (has)(m) { + ReflectOptionalRef::some(V::RuntimeType::into_static_value_ref((get)(m))) + } else { + ReflectOptionalRef::none_from::<V>() + } + }, + |_m| unimplemented!(), + move |m, value| (set)(m, value.downcast::<V>().expect("wrong type")), + move |m| { + if (has)(m) { + (set)(m, V::default()); + } + }, + ) + } + + pub(crate) fn new_has_get_set_deref<M, V>( + has: fn(&M) -> bool, + get: for<'a> fn(&'a M) -> &'a <V::RuntimeType as RuntimeTypeWithDeref>::DerefTarget, + set: fn(&mut M, V), + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + V: ProtobufValue, + V::RuntimeType: RuntimeTypeWithDeref, + { + Self::new( + move |m| { + if (has)(m) { + ReflectOptionalRef::some( + <V::RuntimeType as RuntimeTypeWithDeref>::deref_as_ref((get)(m)), + ) + } else { + ReflectOptionalRef::none_from::<V>() + } + }, + |_m| unimplemented!(), + move |m, value| (set)(m, value.downcast::<V>().expect("message")), + move |m| { + if (has)(m) { + (set)(m, V::default()); + } + }, + ) + } + + pub(crate) fn new_has_get_mut_set<M, F>( + has_field: fn(&M) -> bool, + get_field: for<'a> fn(&'a M) -> &'a F, + mut_field: for<'a> fn(&'a mut M) -> &'a mut F, + set_field: fn(&mut M, F), + ) -> SingularFieldAccessorHolder + where + M: MessageFull, + F: MessageFull, + { + Self::new( + move |m| { + if (has_field)(m) { + ReflectOptionalRef::some(F::RuntimeType::as_ref((get_field)(m))) + } else { + ReflectOptionalRef::none_from::<F>() + } + }, + move |m| F::RuntimeType::as_mut((mut_field)(m)), + move |m, value| (set_field)(m, value.downcast::<F>().expect("message")), + move |m| { + if (has_field)(m) { + (set_field)(m, F::default()); + } + }, + ) + } +} + +impl<'a> fmt::Debug for SingularFieldAccessorHolder { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SingularFieldAccessorHolder").finish() + } +} + +/// Make accessor for `SingularPtrField` +pub fn make_message_field_accessor<M, V>( + name: &'static str, + get_field: for<'a> fn(&'a M) -> &'a MessageField<V>, + mut_field: for<'a> fn(&'a mut M) -> &'a mut MessageField<V>, +) -> FieldAccessor +where + M: MessageFull, + V: MessageFull, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_get_mut_message( + get_field, mut_field, + )), + ) +} + +/// Make accessor for `Option<C>` field +pub fn make_option_accessor<M, V>( + name: &'static str, + get_field: for<'a> fn(&'a M) -> &'a Option<V>, + mut_field: for<'a> fn(&'a mut M) -> &'a mut Option<V>, +) -> FieldAccessor +where + M: MessageFull, + V: ProtobufValue, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_get_option_mut_option( + get_field, mut_field, + )), + ) +} + +/// Make accessor for simple field +pub fn make_simpler_field_accessor<M, V>( + name: &'static str, + get_field: for<'a> fn(&'a M) -> &'a V, + mut_field: for<'a> fn(&'a mut M) -> &'a mut V, +) -> FieldAccessor +where + M: MessageFull, + V: ProtobufValue, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_get_mut( + get_field, mut_field, + )), + ) +} diff --git a/src/reflect/acc/v2/singular/oneof.rs b/src/reflect/acc/v2/singular/oneof.rs new file mode 100644 index 0000000..3436150 --- /dev/null +++ b/src/reflect/acc/v2/singular/oneof.rs @@ -0,0 +1,85 @@ +use crate::reflect::acc::v2::singular::SingularFieldAccessorHolder; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::acc::FieldAccessor; +use crate::reflect::runtime_types::RuntimeTypeWithDeref; +use crate::reflect::ProtobufValue; +use crate::EnumFull; +use crate::EnumOrUnknown; +use crate::MessageFull; + +/// Make accessor for `oneof` `message` field +pub fn make_oneof_message_has_get_mut_set_accessor<M, F>( + name: &'static str, + has_field: fn(&M) -> bool, + get_field: for<'a> fn(&'a M) -> &'a F, + mut_field: for<'a> fn(&'a mut M) -> &'a mut F, + set_field: fn(&mut M, F), +) -> FieldAccessor +where + M: MessageFull, + F: MessageFull, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_has_get_mut_set( + has_field, get_field, mut_field, set_field, + )), + ) +} + +/// Make accessor for `Copy` field +pub fn make_oneof_copy_has_get_set_simpler_accessors<M, V>( + name: &'static str, + has: fn(&M) -> bool, + get: fn(&M) -> V, + set: fn(&mut M, V), +) -> FieldAccessor +where + M: MessageFull, + V: ProtobufValue + Copy, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_has_get_set(has, get, set)), + ) +} + +/// Make accessor for `Copy` field +pub fn make_oneof_enum_accessors<M, E>( + name: &'static str, + get: fn(&M) -> Option<EnumOrUnknown<E>>, + set: fn(&mut M, EnumOrUnknown<E>), + // TODO: remove this + _default_value: E, +) -> FieldAccessor +where + M: MessageFull, + E: EnumFull, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_get_option_set_enum( + get, set, + )), + ) +} + +/// Make accessor for `oneof` field +pub fn make_oneof_deref_has_get_set_simpler_accessor<M, F>( + name: &'static str, + has: fn(&M) -> bool, + get: for<'a> fn(&'a M) -> &'a <F::RuntimeType as RuntimeTypeWithDeref>::DerefTarget, + set: fn(&mut M, F), +) -> FieldAccessor +where + M: MessageFull + 'static, + F: ProtobufValue, + F::RuntimeType: RuntimeTypeWithDeref, +{ + FieldAccessor::new( + name, + AccessorV2::Singular(SingularFieldAccessorHolder::new_has_get_set_deref( + has, get, set, + )), + ) +} diff --git a/src/reflect/accessor/mod.rs b/src/reflect/accessor/mod.rs deleted file mode 100644 index 9fa97de..0000000 --- a/src/reflect/accessor/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -#![doc(hidden)] - -pub use crate::reflect::acc::v1::make_map_accessor; -pub use crate::reflect::acc::v1::make_option_accessor; -pub use crate::reflect::acc::v1::make_repeated_field_accessor; -pub use crate::reflect::acc::v1::make_simple_field_accessor; -pub use crate::reflect::acc::v1::make_singular_bool_accessor; -pub use crate::reflect::acc::v1::make_singular_bytes_accessor; -pub use crate::reflect::acc::v1::make_singular_enum_accessor; -pub use crate::reflect::acc::v1::make_singular_f32_accessor; -pub use crate::reflect::acc::v1::make_singular_f64_accessor; -pub use crate::reflect::acc::v1::make_singular_field_accessor; -pub use crate::reflect::acc::v1::make_singular_i32_accessor; -pub use crate::reflect::acc::v1::make_singular_i64_accessor; -pub use crate::reflect::acc::v1::make_singular_message_accessor; -pub use crate::reflect::acc::v1::make_singular_ptr_field_accessor; -pub use crate::reflect::acc::v1::make_singular_string_accessor; -pub use crate::reflect::acc::v1::make_singular_u32_accessor; -pub use crate::reflect::acc::v1::make_singular_u64_accessor; -pub use crate::reflect::acc::v1::make_vec_accessor; -pub use crate::reflect::acc::v1::FieldAccessorTrait; diff --git a/src/reflect/dynamic/map.rs b/src/reflect/dynamic/map.rs new file mode 100644 index 0000000..902f9bf --- /dev/null +++ b/src/reflect/dynamic/map.rs @@ -0,0 +1,217 @@ +use std::collections::hash_map; +use std::collections::HashMap; +use std::fmt; +use std::hash::Hash; + +use crate::reflect::map::ReflectMap; +use crate::reflect::map::ReflectMapIter; +use crate::reflect::map::ReflectMapIterTrait; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +#[derive(Clone)] +enum Maps { + U32(HashMap<u32, ReflectValueBox>), + I32(HashMap<i32, ReflectValueBox>), + U64(HashMap<u64, ReflectValueBox>), + I64(HashMap<i64, ReflectValueBox>), + Bool(HashMap<bool, ReflectValueBox>), + String(HashMap<String, ReflectValueBox>), +} + +impl fmt::Debug for Maps { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Maps::U32(map) => fmt::Debug::fmt(map, f), + Maps::I32(map) => fmt::Debug::fmt(map, f), + Maps::U64(map) => fmt::Debug::fmt(map, f), + Maps::I64(map) => fmt::Debug::fmt(map, f), + Maps::Bool(map) => fmt::Debug::fmt(map, f), + Maps::String(map) => fmt::Debug::fmt(map, f), + } + } +} + +impl Maps { + fn len(&self) -> usize { + match self { + Maps::U32(m) => m.len(), + Maps::I32(m) => m.len(), + Maps::U64(m) => m.len(), + Maps::I64(m) => m.len(), + Maps::Bool(m) => m.len(), + Maps::String(m) => m.len(), + } + } + + fn is_empty(&self) -> bool { + match self { + Maps::U32(m) => m.is_empty(), + Maps::I32(m) => m.is_empty(), + Maps::U64(m) => m.is_empty(), + Maps::I64(m) => m.is_empty(), + Maps::Bool(m) => m.is_empty(), + Maps::String(m) => m.is_empty(), + } + } + + fn clear(&mut self) { + match self { + Maps::U32(m) => m.clear(), + Maps::I32(m) => m.clear(), + Maps::U64(m) => m.clear(), + Maps::I64(m) => m.clear(), + Maps::Bool(m) => m.clear(), + Maps::String(m) => m.clear(), + } + } + + fn key_type(&self) -> RuntimeType { + match self { + Maps::U32(..) => RuntimeType::U32, + Maps::I32(..) => RuntimeType::I32, + Maps::U64(..) => RuntimeType::U64, + Maps::I64(..) => RuntimeType::I64, + Maps::Bool(..) => RuntimeType::Bool, + Maps::String(..) => RuntimeType::String, + } + } +} + +#[derive(Clone)] +pub(crate) struct DynamicMap { + /// Type of value. + /// + /// Type of key is defined by the maps key. + value: RuntimeType, + maps: Maps, +} + +impl fmt::Debug for DynamicMap { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.maps, f) + } +} + +impl DynamicMap { + pub fn new(key: RuntimeType, value: RuntimeType) -> DynamicMap { + DynamicMap { + value, + maps: match key { + RuntimeType::U32 => Maps::U32(HashMap::new()), + RuntimeType::I32 => Maps::I32(HashMap::new()), + RuntimeType::U64 => Maps::U64(HashMap::new()), + RuntimeType::I64 => Maps::I64(HashMap::new()), + RuntimeType::Bool => Maps::Bool(HashMap::new()), + RuntimeType::String => Maps::String(HashMap::new()), + t => panic!("type cannot be hashmap key: {}", t), + }, + } + } +} + +struct DynamicMapIterImpl<'a, K: ProtobufValue + Eq + Hash + 'static> { + iter: hash_map::Iter<'a, K, ReflectValueBox>, + value: &'a RuntimeType, +} + +impl<'a, K: ProtobufValue + Eq + Hash + 'static> ReflectMapIterTrait<'a> + for DynamicMapIterImpl<'a, K> +{ + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { + self.iter + .next() + .map(|(k, v)| (K::RuntimeType::as_ref(k), v.as_value_ref())) + } + + fn key_type(&self) -> RuntimeType { + K::RuntimeType::runtime_type_box() + } + + fn value_type(&self) -> RuntimeType { + self.value.clone() + } +} + +impl ReflectMap for DynamicMap { + fn reflect_iter(&self) -> ReflectMapIter { + match &self.maps { + Maps::U32(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + Maps::I32(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + Maps::U64(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + Maps::I64(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + Maps::Bool(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + Maps::String(m) => ReflectMapIter::new(DynamicMapIterImpl { + iter: m.iter(), + value: &self.value, + }), + } + } + + fn len(&self) -> usize { + self.maps.len() + } + + fn is_empty(&self) -> bool { + self.maps.is_empty() + } + + fn get<'a>(&'a self, key: ReflectValueRef) -> Option<ReflectValueRef<'a>> { + match (&self.maps, key) { + (Maps::U32(m), ReflectValueRef::U32(v)) => m.get(&v), + (Maps::U64(m), ReflectValueRef::U64(v)) => m.get(&v), + (Maps::I32(m), ReflectValueRef::I32(v)) => m.get(&v), + (Maps::I64(m), ReflectValueRef::I64(v)) => m.get(&v), + (Maps::Bool(m), ReflectValueRef::Bool(v)) => m.get(&v), + (Maps::String(m), ReflectValueRef::String(v)) => m.get(&*v), + _ => None, + } + .map(ReflectValueBox::as_value_ref) + } + + fn insert(&mut self, key: ReflectValueBox, value: ReflectValueBox) { + assert!(value.get_type() == self.value); + match (&mut self.maps, &key) { + (Maps::U32(m), ReflectValueBox::U32(k)) => m.insert(*k, value), + (Maps::U64(m), ReflectValueBox::U64(k)) => m.insert(*k, value), + (Maps::I32(m), ReflectValueBox::I32(k)) => m.insert(*k, value), + (Maps::I64(m), ReflectValueBox::I64(k)) => m.insert(*k, value), + (Maps::Bool(m), ReflectValueBox::Bool(k)) => m.insert(*k, value), + (Maps::String(m), _) => match key { + ReflectValueBox::String(k) => m.insert(k, value), + _ => panic!("wrong key type"), + }, + _ => panic!("wrong key type"), + }; + } + + fn clear(&mut self) { + self.maps.clear() + } + + fn key_type(&self) -> RuntimeType { + self.maps.key_type() + } + + fn value_type(&self) -> RuntimeType { + self.value.clone() + } +} diff --git a/src/reflect/dynamic/mod.rs b/src/reflect/dynamic/mod.rs new file mode 100644 index 0000000..96fa202 --- /dev/null +++ b/src/reflect/dynamic/mod.rs @@ -0,0 +1,665 @@ +use std::any::Any; +use std::any::TypeId; +use std::fmt; + +use crate::descriptor::field_descriptor_proto::Type; +use crate::message_dyn::MessageDyn; +use crate::reflect::dynamic::map::DynamicMap; +use crate::reflect::dynamic::optional::DynamicOptional; +use crate::reflect::dynamic::repeated::DynamicRepeated; +use crate::reflect::map::ReflectMap; +use crate::reflect::protobuf_type_box::ProtobufType; +use crate::reflect::repeated::ReflectRepeated; +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::FieldDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::ReflectFieldRef; +use crate::reflect::ReflectMapMut; +use crate::reflect::ReflectMapRef; +use crate::reflect::ReflectRepeatedMut; +use crate::reflect::ReflectRepeatedRef; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeFieldType; +use crate::reflect::Syntax; +use crate::rt::bytes_size; +use crate::rt::compute_raw_varint32_size; +use crate::rt::compute_raw_varint64_size; +use crate::rt::int32_size; +use crate::rt::int64_size; +use crate::rt::map::read_map_template; +use crate::rt::sint32_size; +use crate::rt::sint64_size; +use crate::rt::string_size; +use crate::rt::tag_size; +use crate::rt::uint32_size; +use crate::rt::uint64_size; +use crate::rt::unknown_fields_size; +use crate::rt::unknown_or_group::read_unknown_or_skip_group_with_tag_unpacked; +use crate::rt::vec_packed_bool_size; +use crate::rt::vec_packed_double_size; +use crate::rt::vec_packed_fixed32_size; +use crate::rt::vec_packed_fixed64_size; +use crate::rt::vec_packed_float_size; +use crate::rt::vec_packed_int32_size; +use crate::rt::vec_packed_int64_size; +use crate::rt::vec_packed_sfixed32_size; +use crate::rt::vec_packed_sfixed64_size; +use crate::rt::vec_packed_sint32_size; +use crate::rt::vec_packed_sint64_size; +use crate::rt::vec_packed_uint32_size; +use crate::rt::vec_packed_uint64_size; +use crate::text_format; +use crate::wire_format::WireType; +use crate::CodedInputStream; +use crate::CodedOutputStream; +use crate::SpecialFields; +use crate::UnknownFields; + +pub(crate) mod map; +pub(crate) mod optional; +pub(crate) mod repeated; + +#[derive(Debug, Clone)] +enum DynamicFieldValue { + Singular(DynamicOptional), + Repeated(DynamicRepeated), + Map(DynamicMap), +} + +impl DynamicFieldValue { + fn as_ref(&self) -> ReflectFieldRef { + match self { + DynamicFieldValue::Singular(v) => ReflectFieldRef::Optional(v.reflect_singlar_ref()), + DynamicFieldValue::Repeated(r) => ReflectFieldRef::Repeated(ReflectRepeatedRef::new(r)), + DynamicFieldValue::Map(m) => ReflectFieldRef::Map(ReflectMapRef::new(m)), + } + } + + fn clear(&mut self) { + match self { + DynamicFieldValue::Singular(o) => o.clear(), + DynamicFieldValue::Repeated(r) => r.clear(), + DynamicFieldValue::Map(m) => m.clear(), + } + } +} + +impl DynamicFieldValue { + fn default_for_field(field: &FieldDescriptor) -> DynamicFieldValue { + match field.runtime_field_type() { + RuntimeFieldType::Singular(s) => DynamicFieldValue::Singular(DynamicOptional::none(s)), + RuntimeFieldType::Repeated(r) => DynamicFieldValue::Repeated(DynamicRepeated::new(r)), + RuntimeFieldType::Map(k, v) => DynamicFieldValue::Map(DynamicMap::new(k, v)), + } + } +} + +#[derive(Debug, Clone)] +pub(crate) struct DynamicMessage { + descriptor: MessageDescriptor, + /// Fields by index in the description. + /// This field is lazy-init: it is empty when created. + fields: Box<[DynamicFieldValue]>, + special_fields: SpecialFields, +} + +impl DynamicMessage { + pub(crate) fn new(descriptor: MessageDescriptor) -> DynamicMessage { + DynamicMessage { + descriptor, + fields: Vec::new().into_boxed_slice(), + special_fields: SpecialFields::new(), + } + } + + pub(crate) fn descriptor(&self) -> &MessageDescriptor { + &self.descriptor + } + + fn init_fields(&mut self) { + if self.fields.is_empty() { + self.fields = self + .descriptor + .fields() + .map(|f| DynamicFieldValue::default_for_field(&f)) + .collect(); + } + } + + pub(crate) fn get_reflect<'a>(&'a self, field: &FieldDescriptor) -> ReflectFieldRef<'a> { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + if self.fields.is_empty() { + ReflectFieldRef::default_for_field(field) + } else { + self.fields[index].as_ref() + } + } + + pub fn clear_field(&mut self, field: &FieldDescriptor) { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + if self.fields.is_empty() { + return; + } + + self.fields[index].clear(); + } + + fn clear_oneof_group_fields_except(&mut self, field: &FieldDescriptor) { + if let Some(oneof) = field.containing_oneof_including_synthetic() { + for next in oneof.fields() { + if &next == field { + continue; + } + self.clear_field(&next); + } + } + } + + pub(crate) fn mut_singular_field_or_default<'a>( + &'a mut self, + field: &FieldDescriptor, + ) -> ReflectValueMut<'a> { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + self.init_fields(); + self.clear_oneof_group_fields_except(field); + match &mut self.fields[index] { + DynamicFieldValue::Singular(f) => f.mut_or_default(), + _ => panic!("Not a singular field"), + } + } + + pub(crate) fn mut_repeated<'a>( + &'a mut self, + field: &FieldDescriptor, + ) -> ReflectRepeatedMut<'a> { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + self.init_fields(); + self.clear_oneof_group_fields_except(field); + match &mut self.fields[index] { + DynamicFieldValue::Repeated(r) => ReflectRepeatedMut::new(r), + _ => panic!("Not a repeated field: {}", field), + } + } + + pub(crate) fn mut_map<'a>(&'a mut self, field: &FieldDescriptor) -> ReflectMapMut<'a> { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + self.init_fields(); + self.clear_oneof_group_fields_except(field); + match &mut self.fields[index] { + DynamicFieldValue::Map(m) => ReflectMapMut::new(m), + _ => panic!("Not a map field: {}", field), + } + } + + pub(crate) fn set_field(&mut self, field: &FieldDescriptor, value: ReflectValueBox) { + let (descriptor, index) = field.regular(); + assert_eq!(self.descriptor, descriptor); + self.init_fields(); + self.clear_oneof_group_fields_except(field); + match &mut self.fields[index] { + DynamicFieldValue::Singular(s) => s.set(value), + _ => panic!("Not a singular field: {}", field), + } + } + + pub(crate) fn downcast_ref(message: &dyn MessageDyn) -> &DynamicMessage { + assert!(Any::type_id(&*message) == TypeId::of::<DynamicMessage>()); + unsafe { &*(message as *const dyn MessageDyn as *const DynamicMessage) } + } + + pub(crate) fn downcast_mut(message: &mut dyn MessageDyn) -> &mut DynamicMessage { + assert!(Any::type_id(&*message) == TypeId::of::<DynamicMessage>()); + unsafe { &mut *(message as *mut dyn MessageDyn as *mut DynamicMessage) } + } + + fn for_each_field_to_write( + &self, + handler: &mut impl ForEachSingularFieldToWrite, + ) -> crate::Result<()> { + let is_proto3 = self.descriptor.file_descriptor().syntax() == Syntax::Proto3; + for field_desc in self.descriptor.fields() { + let field_number = field_desc.proto().number() as u32; + match field_desc.runtime_field_type() { + RuntimeFieldType::Singular(..) => { + if let Some(v) = field_desc.get_singular(self) { + // Ignore default value for proto3. + if !is_proto3 || v.is_non_zero() { + handler.field(field_desc.proto().type_(), field_number, &v)?; + } + } + } + RuntimeFieldType::Repeated(..) => { + let repeated = field_desc.get_repeated(self); + if field_desc.proto().options.get_or_default().packed() { + handler.repeated_packed( + field_desc.proto().type_(), + field_number, + &repeated, + )?; + } else { + for i in 0..repeated.len() { + let v = repeated.get(i); + handler.field(field_desc.proto().type_(), field_number, &v)?; + } + } + } + RuntimeFieldType::Map(_, _) => { + let map = field_desc.get_map(self); + let (key_type, value_type) = field_desc.map_proto_type(); + for (k, v) in &map { + handler.map_field_entry( + field_number, + &k, + key_type.t(), + &v, + value_type.t(), + )?; + } + } + } + } + + handler.unknown_fields(&self.special_fields.unknown_fields())?; + Ok(()) + } +} + +trait ForEachSingularFieldToWrite { + fn field(&mut self, t: Type, number: u32, value: &ReflectValueRef) -> crate::Result<()>; + fn repeated_packed( + &mut self, + t: Type, + number: u32, + value: &ReflectRepeatedRef, + ) -> crate::Result<()>; + fn map_field_entry( + &mut self, + number: u32, + key: &ReflectValueRef, + kt: Type, + value: &ReflectValueRef, + vt: Type, + ) -> crate::Result<()>; + fn unknown_fields(&mut self, unknown_fields: &UnknownFields) -> crate::Result<()>; +} + +impl fmt::Display for DynamicMessage { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + text_format::fmt(self, f) + } +} + +impl MessageDyn for DynamicMessage { + fn descriptor_dyn(&self) -> MessageDescriptor { + self.descriptor.clone() + } + + fn is_initialized_dyn(&self) -> bool { + if self.descriptor.is_initialized_is_always_true() { + return true; + } + + for f in self.descriptor.fields() { + let fv = self.get_reflect(&f); + match fv { + ReflectFieldRef::Optional(s) => match s.value() { + None => { + if f.is_required() { + return false; + } + } + Some(v) => { + if !v.is_initialized() { + return false; + } + } + }, + ReflectFieldRef::Repeated(r) => { + for v in &r { + if !v.is_initialized() { + return false; + } + } + } + ReflectFieldRef::Map(m) => { + for (_k, v) in &m { + // Keys cannot be messages, so only check values. + if !v.is_initialized() { + return false; + } + } + } + } + } + true + } + + fn merge_from_dyn(&mut self, is: &mut CodedInputStream) -> crate::Result<()> { + while !is.eof()? { + let (field, wire_type) = is.read_tag_unpack()?; + let field_desc = match self.descriptor.field_by_number(field) { + Some(f) => f, + None => { + read_unknown_or_skip_group_with_tag_unpacked( + field, + wire_type, + is, + &mut self.special_fields.mut_unknown_fields(), + )?; + continue; + } + }; + match field_desc.runtime_field_type() { + RuntimeFieldType::Singular(rtb) => { + let pt = ProtobufType::new(rtb, field_desc.proto().type_())?; + let value = pt.read(is, wire_type)?; + self.set_field(&field_desc, value); + } + RuntimeFieldType::Repeated(rtb) => { + let pt = ProtobufType::new(rtb, field_desc.proto().type_())?; + let mut repeated = self.mut_repeated(&field_desc); + pt.read_repeated_into(is, wire_type, &mut repeated)?; + } + RuntimeFieldType::Map(..) => { + let (key_type, value_type) = field_desc.map_proto_type(); + let mut map = self.mut_map(&field_desc); + let mut key = key_type.runtime().default_value_box(); + let mut value = value_type.runtime().default_value_box(); + read_map_template( + wire_type, + is, + |wire_type, is| { + key = key_type.read(is, wire_type)?; + Ok(()) + }, + |wire_type, is| { + value = value_type.read(is, wire_type)?; + Ok(()) + }, + )?; + map.insert(key, value); + } + } + } + Ok(()) + } + + fn write_to_with_cached_sizes_dyn(&self, os: &mut CodedOutputStream) -> crate::Result<()> { + struct Handler<'a, 'o> { + os: &'a mut CodedOutputStream<'o>, + } + + impl<'a, 'o> ForEachSingularFieldToWrite for Handler<'a, 'o> { + fn field( + &mut self, + t: Type, + number: u32, + value: &ReflectValueRef, + ) -> crate::Result<()> { + singular_write_to(t, number, value, self.os) + } + + fn repeated_packed( + &mut self, + t: Type, + number: u32, + value: &ReflectRepeatedRef, + ) -> crate::Result<()> { + repeated_write_to(t, number, value, self.os) + } + + fn map_field_entry( + &mut self, + number: u32, + key: &ReflectValueRef, + kt: Type, + value: &ReflectValueRef, + vt: Type, + ) -> crate::Result<()> { + let entry_data_size = compute_map_entry_field_data_size(key, kt, value, vt); + self.os.write_tag(number, WireType::LengthDelimited)?; + self.os.write_raw_varint32(entry_data_size as u32)?; + singular_write_to(kt, 1, key, self.os)?; + singular_write_to(vt, 2, value, self.os)?; + Ok(()) + } + + fn unknown_fields(&mut self, unknown_fields: &UnknownFields) -> crate::Result<()> { + self.os.write_unknown_fields(unknown_fields) + } + } + + let mut handler = Handler { os }; + + self.for_each_field_to_write(&mut handler) + } + + fn compute_size_dyn(&self) -> u64 { + struct Handler { + m_size: u64, + } + + impl ForEachSingularFieldToWrite for Handler { + fn field( + &mut self, + t: Type, + number: u32, + value: &ReflectValueRef, + ) -> crate::Result<()> { + self.m_size += compute_singular_size(t, number, value); + Ok(()) + } + + fn repeated_packed( + &mut self, + t: Type, + number: u32, + value: &ReflectRepeatedRef, + ) -> crate::Result<()> { + self.m_size += compute_repeated_packed_size(t, number, value); + Ok(()) + } + + fn map_field_entry( + &mut self, + number: u32, + key: &ReflectValueRef, + kt: Type, + value: &ReflectValueRef, + vt: Type, + ) -> crate::Result<()> { + let entry_data_size = compute_map_entry_field_data_size(key, kt, value, vt); + self.m_size += tag_size(number) + + compute_raw_varint32_size(entry_data_size as u32) + + entry_data_size; + Ok(()) + } + + fn unknown_fields(&mut self, unknown_fields: &UnknownFields) -> crate::Result<()> { + self.m_size += unknown_fields_size(unknown_fields); + Ok(()) + } + } + + let mut handler = Handler { m_size: 0 }; + + self.for_each_field_to_write(&mut handler) + .expect("compute_size should not fail"); + + handler.m_size + } + + fn special_fields_dyn(&self) -> &SpecialFields { + &self.special_fields + } + + fn mut_special_fields_dyn(&mut self) -> &mut SpecialFields { + &mut self.special_fields + } +} + +/// Write singular field to output stream +fn singular_write_to( + proto_type: Type, + field_number: u32, + v: &ReflectValueRef, + os: &mut CodedOutputStream, +) -> crate::Result<()> { + match proto_type { + Type::TYPE_ENUM => { + let enum_v = v.to_enum_value().unwrap(); + os.write_enum(field_number, enum_v) + } + Type::TYPE_MESSAGE => { + let msg_v = v.to_message().unwrap(); + os.write_message_dyn(field_number, &*msg_v) + } + Type::TYPE_GROUP => { + unimplemented!() + } + Type::TYPE_UINT32 => os.write_uint32(field_number, v.to_u32().unwrap()), + Type::TYPE_UINT64 => os.write_uint64(field_number, v.to_u64().unwrap()), + Type::TYPE_INT32 => os.write_int32(field_number, v.to_i32().unwrap()), + Type::TYPE_INT64 => os.write_int64(field_number, v.to_i64().unwrap()), + Type::TYPE_SINT32 => os.write_sint32(field_number, v.to_i32().unwrap()), + Type::TYPE_SINT64 => os.write_sint64(field_number, v.to_i64().unwrap()), + Type::TYPE_FIXED32 => os.write_fixed32(field_number, v.to_u32().unwrap()), + Type::TYPE_FIXED64 => os.write_fixed64(field_number, v.to_u64().unwrap()), + Type::TYPE_SFIXED64 => os.write_sfixed64(field_number, v.to_i64().unwrap()), + Type::TYPE_SFIXED32 => os.write_sfixed32(field_number, v.to_i32().unwrap()), + Type::TYPE_BOOL => os.write_bool(field_number, v.to_bool().unwrap()), + Type::TYPE_STRING => os.write_string(field_number, v.to_str().unwrap()), + Type::TYPE_BYTES => os.write_bytes(field_number, v.to_bytes().unwrap()), + Type::TYPE_FLOAT => os.write_float(field_number, v.to_f32().unwrap()), + Type::TYPE_DOUBLE => os.write_double(field_number, v.to_f64().unwrap()), + } +} + +/// Compute singular field size +fn compute_singular_size(proto_type: Type, field_number: u32, v: &ReflectValueRef) -> u64 { + match proto_type { + Type::TYPE_ENUM => { + let enum_v = v.to_enum_value().unwrap(); + int32_size(field_number, enum_v) + } + Type::TYPE_MESSAGE => { + let msg_v = v.to_message().unwrap(); + let len = msg_v.compute_size_dyn(); + tag_size(field_number) + compute_raw_varint64_size(len) + len + } + Type::TYPE_GROUP => { + unimplemented!() + } + Type::TYPE_UINT32 => { + let typed_v = v.to_u32().unwrap(); + uint32_size(field_number, typed_v) + } + Type::TYPE_UINT64 => { + let typed_v = v.to_u64().unwrap(); + uint64_size(field_number, typed_v) + } + Type::TYPE_INT32 => { + let typed_v = v.to_i32().unwrap(); + int32_size(field_number, typed_v) + } + Type::TYPE_INT64 => { + let typed_v = v.to_i64().unwrap(); + int64_size(field_number, typed_v) + } + Type::TYPE_SINT32 => { + let typed_v = v.to_i32().unwrap(); + sint32_size(field_number, typed_v) + } + Type::TYPE_SINT64 => { + let typed_v = v.to_i64().unwrap(); + sint64_size(field_number, typed_v) + } + Type::TYPE_FIXED32 => tag_size(field_number) + 4, + Type::TYPE_FIXED64 => tag_size(field_number) + 8, + Type::TYPE_SFIXED32 => tag_size(field_number) + 4, + Type::TYPE_SFIXED64 => tag_size(field_number) + 8, + Type::TYPE_BOOL => tag_size(field_number) + 1, + Type::TYPE_STRING => { + let typed_v = v.to_str().unwrap(); + string_size(field_number, typed_v) + } + Type::TYPE_BYTES => { + let typed_v = v.to_bytes().unwrap(); + bytes_size(field_number, typed_v) + } + Type::TYPE_FLOAT => tag_size(field_number) + 4, + Type::TYPE_DOUBLE => tag_size(field_number) + 8, + } +} + +fn compute_repeated_packed_size( + proto_type: Type, + field_number: u32, + v: &ReflectRepeatedRef, +) -> u64 { + match proto_type { + Type::TYPE_INT32 => vec_packed_int32_size(field_number, v.data_i32()), + Type::TYPE_INT64 => vec_packed_int64_size(field_number, v.data_i64()), + Type::TYPE_UINT32 => vec_packed_uint32_size(field_number, v.data_u32()), + Type::TYPE_UINT64 => vec_packed_uint64_size(field_number, v.data_u64()), + Type::TYPE_SINT32 => vec_packed_sint32_size(field_number, v.data_i32()), + Type::TYPE_SINT64 => vec_packed_sint64_size(field_number, v.data_i64()), + Type::TYPE_FIXED32 => vec_packed_fixed32_size(field_number, v.data_u32()), + Type::TYPE_FIXED64 => vec_packed_fixed64_size(field_number, v.data_u64()), + Type::TYPE_SFIXED32 => vec_packed_sfixed32_size(field_number, v.data_i32()), + Type::TYPE_SFIXED64 => vec_packed_sfixed64_size(field_number, v.data_i64()), + Type::TYPE_FLOAT => vec_packed_float_size(field_number, v.data_f32()), + Type::TYPE_DOUBLE => vec_packed_double_size(field_number, v.data_f64()), + Type::TYPE_BOOL => vec_packed_bool_size(field_number, v.data_bool()), + Type::TYPE_STRING => panic!("strings cannot be packed"), + Type::TYPE_BYTES => panic!("bytes cannot be packed"), + Type::TYPE_ENUM => vec_packed_int32_size(field_number, v.data_enum_values()), + Type::TYPE_MESSAGE => panic!("messages cannot be packed"), + Type::TYPE_GROUP => panic!("groups cannot be packed"), + } +} + +fn repeated_write_to( + proto_type: Type, + field_number: u32, + v: &ReflectRepeatedRef, + os: &mut CodedOutputStream, +) -> crate::Result<()> { + match proto_type { + Type::TYPE_INT32 => os.write_repeated_packed_int32(field_number, v.data_i32()), + Type::TYPE_INT64 => os.write_repeated_packed_int64(field_number, v.data_i64()), + Type::TYPE_UINT64 => os.write_repeated_packed_uint64(field_number, v.data_u64()), + Type::TYPE_FIXED64 => os.write_repeated_packed_fixed64(field_number, v.data_u64()), + Type::TYPE_FIXED32 => os.write_repeated_packed_fixed32(field_number, v.data_u32()), + Type::TYPE_UINT32 => os.write_repeated_packed_uint32(field_number, v.data_u32()), + Type::TYPE_SINT32 => os.write_repeated_packed_sint32(field_number, v.data_i32()), + Type::TYPE_SINT64 => os.write_repeated_packed_sint64(field_number, v.data_i64()), + Type::TYPE_SFIXED32 => os.write_repeated_packed_sfixed32(field_number, v.data_i32()), + Type::TYPE_SFIXED64 => os.write_repeated_packed_sfixed64(field_number, v.data_i64()), + Type::TYPE_BOOL => os.write_repeated_packed_bool(field_number, v.data_bool()), + Type::TYPE_FLOAT => os.write_repeated_packed_float(field_number, v.data_f32()), + Type::TYPE_DOUBLE => os.write_repeated_packed_double(field_number, v.data_f64()), + Type::TYPE_ENUM => os.write_repeated_packed_int32(field_number, v.data_enum_values()), + Type::TYPE_STRING => panic!("strings cannot be packed"), + Type::TYPE_BYTES => panic!("bytes cannot be packed"), + Type::TYPE_GROUP => panic!("groups cannot be packed"), + Type::TYPE_MESSAGE => panic!("messages cannot be packed"), + } +} + +fn compute_map_entry_field_data_size( + key: &ReflectValueRef, + kt: Type, + value: &ReflectValueRef, + vt: Type, +) -> u64 { + let key_size = compute_singular_size(kt, 1, key); + let value_size = compute_singular_size(vt, 2, value); + key_size + value_size +} diff --git a/src/reflect/dynamic/optional.rs b/src/reflect/dynamic/optional.rs new file mode 100644 index 0000000..b9cc7ea --- /dev/null +++ b/src/reflect/dynamic/optional.rs @@ -0,0 +1,39 @@ +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::ReflectOptionalRef; +use crate::reflect::ReflectValueBox; +use crate::reflect::RuntimeType; + +#[derive(Debug, Clone)] +pub(crate) struct DynamicOptional { + elem: RuntimeType, + value: Option<ReflectValueBox>, +} + +impl DynamicOptional { + pub(crate) fn none(elem: RuntimeType) -> DynamicOptional { + DynamicOptional { elem, value: None } + } + + pub(crate) fn mut_or_default(&mut self) -> ReflectValueMut { + if let None = self.value { + self.value = Some(self.elem.default_value_ref().to_box()); + } + self.value.as_mut().unwrap().as_value_mut() + } + + pub(crate) fn clear(&mut self) { + self.value = None; + } + + pub(crate) fn set(&mut self, value: ReflectValueBox) { + assert_eq!(value.get_type(), self.elem); + self.value = Some(value); + } + + pub(crate) fn reflect_singlar_ref(&self) -> ReflectOptionalRef { + match &self.value { + Some(value) => ReflectOptionalRef::some(value.as_value_ref()), + None => ReflectOptionalRef::none(self.elem.clone()), + } + } +} diff --git a/src/reflect/dynamic/repeated.rs b/src/reflect/dynamic/repeated.rs new file mode 100644 index 0000000..40c0411 --- /dev/null +++ b/src/reflect/dynamic/repeated.rs @@ -0,0 +1,296 @@ +use crate::reflect::repeated::drain_iter::ReflectRepeatedDrainIter; +use crate::reflect::repeated::iter::ReflectRepeatedIter; +use crate::reflect::repeated::ReflectRepeated; +use crate::reflect::EnumDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::MessageRef; +use crate::reflect::ReflectRepeatedMut; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; +use crate::MessageDyn; + +/// Container of repeated values for dynamic messages. +/// +/// It is logically similar to `Vec<ReflectValueBox>`, but: +/// * more efficient +/// * asserts all the elements are of the same type, the type which is specified at construction +#[derive(Debug, Clone)] +pub(crate) enum DynamicRepeated { + U32(Vec<u32>), + U64(Vec<u64>), + I32(Vec<i32>), + I64(Vec<i64>), + F32(Vec<f32>), + F64(Vec<f64>), + Bool(Vec<bool>), + String(Vec<String>), + Bytes(Vec<Vec<u8>>), + Enum(EnumDescriptor, Vec<i32>), + Message(MessageDescriptor, Vec<Box<dyn MessageDyn>>), +} + +impl ReflectRepeated for DynamicRepeated { + fn reflect_iter(&self) -> ReflectRepeatedIter { + match self { + DynamicRepeated::U32(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::U64(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::I32(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::I64(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::F32(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::F64(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::Bool(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::String(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::Bytes(v) => ReflectRepeatedIter::new_slice(&v), + DynamicRepeated::Enum(descriptor, v) => ReflectRepeatedIter::new( + v.iter() + .map(|v| ReflectValueRef::Enum(descriptor.clone(), *v)), + ), + DynamicRepeated::Message(_descriptor, v) => ReflectRepeatedIter::new( + v.iter() + .map(|v| ReflectValueRef::Message(MessageRef::new(&**v))), + ), + } + } + + fn reflect_drain_iter(&mut self) -> ReflectRepeatedDrainIter { + match self { + DynamicRepeated::U32(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::U64(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::I32(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::I64(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::F32(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::F64(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::Bool(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::String(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::Bytes(v) => ReflectRepeatedDrainIter::new_vec(v), + DynamicRepeated::Enum(descriptor, v) => ReflectRepeatedDrainIter::new( + v.drain(..) + .map(|v| ReflectValueBox::Enum(descriptor.clone(), v)), + ), + DynamicRepeated::Message(_descriptor, v) => { + ReflectRepeatedDrainIter::new(v.drain(..).map(|v| ReflectValueBox::Message(v))) + } + } + } + + fn len(&self) -> usize { + match self { + DynamicRepeated::U32(v) => v.len(), + DynamicRepeated::U64(v) => v.len(), + DynamicRepeated::I32(v) => v.len(), + DynamicRepeated::I64(v) => v.len(), + DynamicRepeated::F32(v) => v.len(), + DynamicRepeated::F64(v) => v.len(), + DynamicRepeated::Bool(v) => v.len(), + DynamicRepeated::String(v) => v.len(), + DynamicRepeated::Bytes(v) => v.len(), + DynamicRepeated::Enum(.., v) => v.len(), + DynamicRepeated::Message(.., v) => v.len(), + } + } + + fn get(&self, index: usize) -> ReflectValueRef { + match self { + DynamicRepeated::U32(v) => ReflectValueRef::U32(v[index]), + DynamicRepeated::U64(v) => ReflectValueRef::U64(v[index]), + DynamicRepeated::I32(v) => ReflectValueRef::I32(v[index]), + DynamicRepeated::I64(v) => ReflectValueRef::I64(v[index]), + DynamicRepeated::F32(v) => ReflectValueRef::F32(v[index]), + DynamicRepeated::F64(v) => ReflectValueRef::F64(v[index]), + DynamicRepeated::Bool(v) => ReflectValueRef::Bool(v[index]), + DynamicRepeated::String(v) => ReflectValueRef::String(&v[index]), + DynamicRepeated::Bytes(v) => ReflectValueRef::Bytes(&v[index]), + DynamicRepeated::Enum(descriptor, v) => { + ReflectValueRef::Enum(descriptor.clone(), v[index]) + } + DynamicRepeated::Message(_descriptor, v) => { + ReflectValueRef::Message(MessageRef::from(&*v[index])) + } + } + } + + fn set(&mut self, index: usize, value: ReflectValueBox) { + match self { + DynamicRepeated::U32(v) => v.set(index, value), + DynamicRepeated::U64(v) => v.set(index, value), + DynamicRepeated::I32(v) => v.set(index, value), + DynamicRepeated::I64(v) => v.set(index, value), + DynamicRepeated::F32(v) => v.set(index, value), + DynamicRepeated::F64(v) => v.set(index, value), + DynamicRepeated::Bool(v) => v.set(index, value), + DynamicRepeated::String(v) => v.set(index, value), + DynamicRepeated::Bytes(v) => v.set(index, value), + DynamicRepeated::Enum(descriptor, vs) => match value { + ReflectValueBox::Enum(value_description, v) => { + assert_eq!(*descriptor, value_description); + vs[index] = v; + } + _ => panic!("Expected enum value"), + }, + DynamicRepeated::Message(descriptor, vs) => match value { + ReflectValueBox::Message(message) => { + assert_eq!(*descriptor, message.descriptor_dyn()); + vs[index] = message; + } + _ => panic!("Expected message value"), + }, + } + } + + fn push(&mut self, value: ReflectValueBox) { + match self { + DynamicRepeated::U32(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::U64(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::I32(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::I64(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::F32(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::F64(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::Bool(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::String(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::Bytes(vs) => ReflectRepeated::push(vs, value), + DynamicRepeated::Enum(descriptor, vs) => match value { + ReflectValueBox::Enum(value_description, v) => { + assert_eq!(*descriptor, value_description); + vs.push(v); + } + _ => panic!("Expected enum value"), + }, + DynamicRepeated::Message(descriptor, vs) => match value { + ReflectValueBox::Message(message) => { + assert_eq!(*descriptor, message.descriptor_dyn()); + vs.push(message); + } + _ => panic!("Expected message value"), + }, + } + } + + fn reflect_extend(&mut self, values: ReflectRepeatedMut) { + match self { + DynamicRepeated::U32(vs) => vs.extend(values.repeated.data_u32()), + DynamicRepeated::U64(vs) => vs.extend(values.repeated.data_u64()), + DynamicRepeated::I32(vs) => vs.extend(values.repeated.data_i32()), + DynamicRepeated::I64(vs) => vs.extend(values.repeated.data_i64()), + DynamicRepeated::F32(vs) => vs.extend(values.repeated.data_f32()), + DynamicRepeated::F64(vs) => vs.extend(values.repeated.data_f64()), + DynamicRepeated::Bool(vs) => vs.extend(values.repeated.data_bool()), + _ => { + // Default less efficient implementation. + for value in values.repeated.reflect_drain_iter() { + self.push(value); + } + } + } + } + + fn clear(&mut self) { + match self { + DynamicRepeated::U32(vs) => vs.clear(), + DynamicRepeated::U64(vs) => vs.clear(), + DynamicRepeated::I32(vs) => vs.clear(), + DynamicRepeated::I64(vs) => vs.clear(), + DynamicRepeated::F32(vs) => vs.clear(), + DynamicRepeated::F64(vs) => vs.clear(), + DynamicRepeated::Bool(vs) => vs.clear(), + DynamicRepeated::String(vs) => vs.clear(), + DynamicRepeated::Bytes(vs) => vs.clear(), + DynamicRepeated::Enum(_descriptor, vs) => vs.clear(), + DynamicRepeated::Message(_descriptor, vs) => vs.clear(), + } + } + + fn element_type(&self) -> RuntimeType { + match self { + DynamicRepeated::U32(..) => RuntimeType::U32, + DynamicRepeated::U64(..) => RuntimeType::U64, + DynamicRepeated::I32(..) => RuntimeType::I32, + DynamicRepeated::I64(..) => RuntimeType::I64, + DynamicRepeated::F32(..) => RuntimeType::F32, + DynamicRepeated::F64(..) => RuntimeType::F64, + DynamicRepeated::Bool(..) => RuntimeType::Bool, + DynamicRepeated::String(..) => RuntimeType::String, + DynamicRepeated::Bytes(..) => RuntimeType::VecU8, + DynamicRepeated::Enum(descriptor, _vs) => RuntimeType::Enum(descriptor.clone()), + DynamicRepeated::Message(descriptor, _vs) => RuntimeType::Message(descriptor.clone()), + } + } + + fn data_enum_values(&self) -> &[i32] { + match self { + DynamicRepeated::Enum(_descriptor, vs) => &vs, + _ => panic!("Expected enum value"), + } + } + + fn data_bool(&self) -> &[bool] { + match self { + DynamicRepeated::Bool(vs) => &vs, + _ => panic!("Expected bool value"), + } + } + + fn data_u32(&self) -> &[u32] { + match self { + DynamicRepeated::U32(vs) => &vs, + _ => panic!("Expected u32 value"), + } + } + + fn data_u64(&self) -> &[u64] { + match self { + DynamicRepeated::U64(vs) => &vs, + _ => panic!("Expected u64 value"), + } + } + + fn data_i32(&self) -> &[i32] { + match self { + DynamicRepeated::I32(vs) => &vs, + _ => panic!("Expected i32 value"), + } + } + + fn data_i64(&self) -> &[i64] { + match self { + DynamicRepeated::I64(vs) => &vs, + _ => panic!("Expected i64 value"), + } + } + + fn data_f32(&self) -> &[f32] { + match self { + DynamicRepeated::F32(vs) => &vs, + _ => panic!("Expected f32 value"), + } + } + + fn data_f64(&self) -> &[f64] { + match self { + DynamicRepeated::F64(vs) => &vs, + _ => panic!("Expected f64 value"), + } + } +} + +impl DynamicRepeated { + pub fn new(elem: RuntimeType) -> DynamicRepeated { + match elem { + RuntimeType::U32 => DynamicRepeated::U32(Vec::new()), + RuntimeType::U64 => DynamicRepeated::U64(Vec::new()), + RuntimeType::I32 => DynamicRepeated::I32(Vec::new()), + RuntimeType::I64 => DynamicRepeated::I64(Vec::new()), + RuntimeType::F32 => DynamicRepeated::F32(Vec::new()), + RuntimeType::F64 => DynamicRepeated::F64(Vec::new()), + RuntimeType::Bool => DynamicRepeated::Bool(Vec::new()), + RuntimeType::String => DynamicRepeated::String(Vec::new()), + RuntimeType::VecU8 => DynamicRepeated::Bytes(Vec::new()), + RuntimeType::Enum(enum_descriptor) => { + DynamicRepeated::Enum(enum_descriptor, Vec::new()) + } + RuntimeType::Message(message_descriptor) => { + DynamicRepeated::Message(message_descriptor, Vec::new()) + } + } + } +} diff --git a/src/reflect/enums.rs b/src/reflect/enums.rs deleted file mode 100644 index a25be6f..0000000 --- a/src/reflect/enums.rs +++ /dev/null @@ -1,128 +0,0 @@ -use std::collections::HashMap; - -use crate::descriptor::EnumDescriptorProto; -use crate::descriptor::EnumValueDescriptorProto; -use crate::descriptor::FileDescriptorProto; -use crate::descriptorx::find_enum_by_rust_name; -use crate::reflect::find_message_or_enum::find_message_or_enum; -use crate::reflect::find_message_or_enum::MessageOrEnum; -use crate::ProtobufEnum; - -/// Description for enum variant. -/// -/// Used in reflection. -#[derive(Clone, Debug)] -pub struct EnumValueDescriptor { - proto: &'static EnumValueDescriptorProto, -} - -impl Copy for EnumValueDescriptor {} - -impl EnumValueDescriptor { - /// Name of enum variant as specified in proto file - pub fn name(&self) -> &'static str { - self.proto.get_name() - } - - /// `i32` value of the enum variant - pub fn value(&self) -> i32 { - self.proto.get_number() - } -} - -/// Dynamic representation of enum type. -/// -/// Can be used in reflective operations. -pub struct EnumDescriptor { - proto: &'static EnumDescriptorProto, - values: Vec<EnumValueDescriptor>, - - index_by_name: HashMap<String, usize>, - index_by_number: HashMap<i32, usize>, -} - -impl EnumDescriptor { - /// Enum name as given in `.proto` file - pub fn name(&self) -> &'static str { - self.proto.get_name() - } - - /// `EnumDescriptor` for enum type - pub fn for_type<E: ProtobufEnum>() -> &'static EnumDescriptor { - E::enum_descriptor_static() - } - - /// Create new enum descriptor. - /// - /// This function is called by generated code, and should not be called manually. - #[deprecated( - since = "2.12", - note = "Please regenerate .rs files from .proto files to use newer APIs" - )] - pub fn new(rust_name: &'static str, file: &'static FileDescriptorProto) -> EnumDescriptor { - let proto = find_enum_by_rust_name(file, rust_name); - let mut index_by_name = HashMap::new(); - let mut index_by_number = HashMap::new(); - for (i, v) in proto.en.get_value().iter().enumerate() { - index_by_number.insert(v.get_number(), i); - index_by_name.insert(v.get_name().to_string(), i); - } - EnumDescriptor { - proto: proto.en, - values: proto - .en - .get_value() - .iter() - .map(|v| EnumValueDescriptor { proto: v }) - .collect(), - index_by_name: index_by_name, - index_by_number: index_by_number, - } - } - - /// Create new enum descriptor. - /// - /// This function is called by generated code, and should not be called manually. - pub fn new_pb_name<E>( - name_in_file: &'static str, - file: &'static FileDescriptorProto, - ) -> EnumDescriptor - where - E: ProtobufEnum, - { - let (_path_to_package, proto) = match find_message_or_enum(file, name_in_file) { - (path_to_package, MessageOrEnum::Enum(e)) => (path_to_package, e), - (_, MessageOrEnum::Message(_)) => panic!("not an enum"), - }; - - let mut index_by_name = HashMap::new(); - let mut index_by_number = HashMap::new(); - for (i, v) in proto.get_value().iter().enumerate() { - index_by_number.insert(v.get_number(), i); - index_by_name.insert(v.get_name().to_string(), i); - } - EnumDescriptor { - proto, - values: proto - .get_value() - .iter() - .map(|v| EnumValueDescriptor { proto: v }) - .collect(), - index_by_name: index_by_name, - index_by_number: index_by_number, - } - } - - /// Find enum value by name - pub fn value_by_name<'a>(&'a self, name: &str) -> &'a EnumValueDescriptor { - // TODO: clone is weird - let &index = self.index_by_name.get(&name.to_string()).unwrap(); - &self.values[index] - } - - /// Find enum value by number - pub fn value_by_number<'a>(&'a self, number: i32) -> &'a EnumValueDescriptor { - let &index = self.index_by_number.get(&number).unwrap(); - &self.values[index] - } -} diff --git a/src/reflect/enums/generated.rs b/src/reflect/enums/generated.rs new file mode 100644 index 0000000..63d4b03 --- /dev/null +++ b/src/reflect/enums/generated.rs @@ -0,0 +1,56 @@ +//! Generated code support for enum descriptors. + +use std::any::TypeId; + +use crate::descriptor::FileDescriptorProto; +use crate::EnumFull; +use crate::EnumOrUnknown; + +#[doc(hidden)] +pub struct GeneratedEnumDescriptorData { + pub(crate) name_in_file: &'static str, + type_id: TypeId, + enum_or_unknown_type_id: TypeId, +} + +impl GeneratedEnumDescriptorData { + #[doc(hidden)] + pub fn new<E>(name_in_file: &'static str) -> GeneratedEnumDescriptorData + where + E: EnumFull, + { + GeneratedEnumDescriptorData { + name_in_file, + type_id: TypeId::of::<E>(), + enum_or_unknown_type_id: TypeId::of::<EnumOrUnknown<E>>(), + } + } +} + +#[derive(Debug)] +pub(crate) struct GeneratedEnumDescriptor { + /// Type id of `<E>` + pub(crate) type_id: TypeId, + /// Type id of `<ProtobufEnumOrUnknown<E>>` + pub(crate) _enum_or_unknown_type_id: TypeId, +} + +impl GeneratedEnumDescriptor { + pub(crate) fn new( + data: GeneratedEnumDescriptorData, + file_descriptor_proto: &'static FileDescriptorProto, + ) -> GeneratedEnumDescriptor { + let GeneratedEnumDescriptorData { + name_in_file, + type_id, + enum_or_unknown_type_id, + } = data; + + let _ = (name_in_file, file_descriptor_proto); + + GeneratedEnumDescriptor { + type_id, + _enum_or_unknown_type_id: enum_or_unknown_type_id, + } + } +} diff --git a/src/reflect/enums/mod.rs b/src/reflect/enums/mod.rs new file mode 100644 index 0000000..4081c4a --- /dev/null +++ b/src/reflect/enums/mod.rs @@ -0,0 +1,293 @@ +use std::any::TypeId; +use std::fmt; +use std::fmt::Formatter; +use std::hash::Hash; + +use crate::descriptor::EnumDescriptorProto; +use crate::descriptor::EnumValueDescriptorProto; +use crate::enums::Enum; +use crate::reflect::enums::generated::GeneratedEnumDescriptor; +use crate::reflect::file::index::EnumIndices; +use crate::reflect::file::FileDescriptorImpl; +use crate::reflect::FileDescriptor; +use crate::reflect::MessageDescriptor; +use crate::EnumFull; + +pub(crate) mod generated; + +/// Description for enum variant. +/// +/// Used in reflection. +#[derive(Clone, Eq, PartialEq, Hash)] +pub struct EnumValueDescriptor { + pub(crate) enum_descriptor: EnumDescriptor, + pub(crate) index: usize, +} + +fn _assert_send_sync() { + fn _assert_send_sync<T: Send + Sync>() {} + _assert_send_sync::<EnumValueDescriptor>(); +} + +impl fmt::Debug for EnumValueDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("EnumValueDescriptor") + .field("enum_descriptor", &self.enum_descriptor) + .field("name", &self.name()) + .finish() + } +} + +impl fmt::Display for EnumValueDescriptor { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + write!(f, "{}.{}", self.enum_descriptor, self.name()) + } +} + +impl EnumValueDescriptor { + pub(crate) fn new(enum_descriptor: EnumDescriptor, index: usize) -> EnumValueDescriptor { + EnumValueDescriptor { + enum_descriptor, + index, + } + } + + /// `.proto` object which declared this value. + pub fn proto(&self) -> &EnumValueDescriptorProto { + &self.enum_descriptor.proto().value[self.index] + } + + /// Name of enum variant as specified in proto file + pub fn name(&self) -> &str { + self.proto().name() + } + + /// Fully qualified enum value name: fully qualified enum name followed by value name. + pub fn full_name(&self) -> String { + self.to_string() + } + + /// `i32` value of the enum variant + pub fn value(&self) -> i32 { + self.proto().number() + } + + /// Get descriptor of enum holding this value. + pub fn enum_descriptor(&self) -> &EnumDescriptor { + &self.enum_descriptor + } + + /// Convert this value descriptor into proper enum object. + /// + /// ``` + /// # use protobuf::well_known_types::struct_::NullValue; + /// # use protobuf::EnumFull; + /// # use protobuf::reflect::EnumValueDescriptor; + /// + /// # if !cfg!(miri) { + /// let value: EnumValueDescriptor = NullValue::NULL_VALUE.descriptor(); + /// let null: Option<NullValue> = value.cast(); + /// assert_eq!(Some(NullValue::NULL_VALUE), null); + /// # } + /// ``` + pub fn cast<E: EnumFull>(&self) -> Option<E> { + if self.enum_descriptor != E::enum_descriptor() { + return None; + } + E::from_i32(self.value()) + } +} + +/// Dynamic representation of enum type. +/// +/// Can be used in reflective operations. +#[derive(Clone, Eq, PartialEq, Hash)] +pub struct EnumDescriptor { + file_descriptor: FileDescriptor, + index: usize, +} + +impl fmt::Display for EnumDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.full_name()) + } +} + +impl fmt::Debug for EnumDescriptor { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("EnumDescriptor") + .field("full_name", &self.full_name()) + .finish_non_exhaustive() + } +} + +impl EnumDescriptor { + pub(crate) fn new(file_descriptor: FileDescriptor, index: usize) -> EnumDescriptor { + EnumDescriptor { + file_descriptor, + index, + } + } + + fn get_impl(&self) -> EnumDescriptorImplRef { + match &self.file_descriptor.imp { + FileDescriptorImpl::Generated(g) => { + EnumDescriptorImplRef::Generated(&g.enums[self.index]) + } + FileDescriptorImpl::Dynamic(..) => EnumDescriptorImplRef::Dynamic, + } + } + + /// Descriptor objects which defined this enum. + pub fn proto(&self) -> &EnumDescriptorProto { + &self.index_entry().proto + } + + /// Enum name as given in `.proto` file + pub fn name(&self) -> &str { + self.proto().name() + } + + fn index_entry(&self) -> &EnumIndices { + self.file_descriptor.enum_indices(self.index) + } + + /// Fully qualified protobuf name of enum + pub fn full_name(&self) -> &str { + &self.index_entry().full_name + } + + /// Name relative to the package where the message is declared. + pub fn name_to_package(&self) -> &str { + &self.index_entry().name_to_package + } + + /// Get `EnumDescriptor` object for given enum type + pub fn for_type<E: EnumFull>() -> EnumDescriptor { + E::enum_descriptor() + } + + /// Get a message containing this message, or `None` if this message is declared at file level. + pub fn enclosing_message(&self) -> Option<MessageDescriptor> { + self.index_entry() + .enclosing_message + .map(|i| MessageDescriptor::new(self.file_descriptor.clone(), i)) + } + + /// This enum values + pub fn values<'a>(&'a self) -> impl Iterator<Item = EnumValueDescriptor> + 'a { + let value_len = self.proto().value.len(); + (0..value_len).map(move |index| EnumValueDescriptor { + enum_descriptor: self.clone(), + index, + }) + } + + /// Find enum variant by name + pub fn value_by_name(&self, name: &str) -> Option<EnumValueDescriptor> { + let index = *self.file_descriptor.common().enums[self.index] + .index_by_name + .get(name)?; + Some(EnumValueDescriptor { + enum_descriptor: self.clone(), + index, + }) + } + + /// Find enum variant by number + pub fn value_by_number(&self, number: i32) -> Option<EnumValueDescriptor> { + let index = *self.file_descriptor.common().enums[self.index] + .index_by_number + .get(&number)?; + Some(self.value_by_index(index)) + } + + /// Get enum variant by index (as declared in `.proto` file). + pub fn value_by_index(&self, index: usize) -> EnumValueDescriptor { + assert!(index < self.proto().value.len()); + EnumValueDescriptor { + enum_descriptor: self.clone(), + index, + } + } + + /// Default enum value (first variant). + pub fn default_value(&self) -> EnumValueDescriptor { + EnumValueDescriptor { + enum_descriptor: self.clone(), + index: 0, + } + } + + /// Find enum variant by number or return default (first) enum value + pub fn value_by_number_or_default(&self, number: i32) -> EnumValueDescriptor { + self.value_by_number(number) + .unwrap_or_else(|| self.default_value()) + } + + /// Check if this enum descriptor corresponds given enum type + /// + /// ``` + /// # use protobuf::EnumFull; + /// # use protobuf::descriptor::field_descriptor_proto::Label; + /// # use protobuf::reflect::EnumDescriptor; + /// + /// # if !cfg!(miri) { + /// let descriptor: EnumDescriptor = Label::enum_descriptor(); + /// + /// assert!(descriptor.is::<Label>()) + /// } + /// ``` + pub fn is<E: Enum>(&self) -> bool { + match self.get_impl() { + EnumDescriptorImplRef::Generated(g) => g.type_id == TypeId::of::<E>(), + EnumDescriptorImplRef::Dynamic => false, + } + } +} + +enum EnumDescriptorImplRef { + Generated(&'static GeneratedEnumDescriptor), + Dynamic, +} + +#[cfg(test)] +mod test { + use crate::descriptor::field_descriptor_proto::Label; + use crate::descriptor::field_descriptor_proto::Type; + use crate::descriptor::FieldDescriptorProto; + use crate::well_known_types::struct_::NullValue; + use crate::EnumFull; + use crate::MessageFull; + + #[test] + #[cfg_attr(miri, ignore)] // Too slow on Miri. + fn enclosing_message() { + assert_eq!( + Some(FieldDescriptorProto::descriptor()), + Type::enum_descriptor().enclosing_message() + ); + assert_eq!(None, NullValue::enum_descriptor().enclosing_message()); + } + + #[test] + #[cfg_attr(miri, ignore)] // Too slow on Miri. + fn to_string() { + assert_eq!( + "google.protobuf.FieldDescriptorProto.Label", + Label::enum_descriptor().to_string() + ); + assert_eq!( + "google.protobuf.FieldDescriptorProto.Label", + Label::enum_descriptor().full_name() + ); + assert_eq!( + "google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED", + Label::LABEL_REPEATED.descriptor().to_string() + ); + assert_eq!( + "google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED", + Label::LABEL_REPEATED.descriptor().full_name() + ); + } +} diff --git a/src/reflect/error.rs b/src/reflect/error.rs new file mode 100644 index 0000000..0b975cf --- /dev/null +++ b/src/reflect/error.rs @@ -0,0 +1,26 @@ +#[derive(Debug, thiserror::Error)] +pub(crate) enum ReflectError { + #[error("Message `{}` not found in files: {}", .0, .1)] + MessageNotFoundInFiles(String, String), + #[error("Dependency `{}` of `{}` not found; all deps: {}", .0, .1, .2)] + DependencyNotFound(String, String, String), + #[error("Non-unique dependencies given: {}", .0)] + NonUniqueDependencies(String), + #[error("Non-unique field name: `{0}`")] + NonUniqueFieldName(String), + #[error("Non-unique file descriptor: `{0}`")] + NonUniqueFileDescriptor(String), + #[error("Cycle in provided file descriptors")] + CycleInFileDescriptors, + #[error("Map entry message name must end with `Entry`")] + MapEntryNameMustEndWithEntry, + #[error("Map entry message must have no extensions, nested messages or enums")] + MapEntryMustHaveNo, + #[error( + "Map entry message must have two optional fields, \ + numbered 1 and 2 and named `key` and `value`" + )] + MapEntryIncorrectFields, + #[error("Could not parse default value for field {0}")] + CouldNotParseDefaultValueForField(String), +} diff --git a/src/reflect/field.rs b/src/reflect/field.rs deleted file mode 100644 index 09ee222..0000000 --- a/src/reflect/field.rs +++ /dev/null @@ -1,245 +0,0 @@ -use crate::descriptor::FieldDescriptorProto; -use crate::descriptor::FieldDescriptorProto_Label; -use crate::json::json_name; -use crate::message::Message; -use crate::reflect::acc::Accessor; -use crate::reflect::acc::FieldAccessor; -use crate::reflect::map::ReflectMap; -use crate::reflect::repeated::ReflectRepeated; -use crate::reflect::EnumValueDescriptor; -use crate::reflect::ReflectValueRef; - -/// Reference to a value stored in a field, optional, repeated or map. -// TODO: implement Eq -pub enum ReflectFieldRef<'a> { - /// Singular field, optional or required in proto3 and just plain field in proto3 - Optional(Option<ReflectValueRef<'a>>), - /// Repeated field - Repeated(&'a dyn ReflectRepeated), - /// Map field - Map(&'a dyn ReflectMap), -} - -/// Field descriptor. -/// -/// Can be used for runtime reflection. -pub struct FieldDescriptor { - proto: &'static FieldDescriptorProto, - accessor: FieldAccessor, - json_name: String, -} - -impl FieldDescriptor { - pub(crate) fn new( - accessor: FieldAccessor, - proto: &'static FieldDescriptorProto, - ) -> FieldDescriptor { - assert_eq!(proto.get_name(), accessor.name); - let json_name = if !proto.get_json_name().is_empty() { - proto.get_json_name().to_string() - } else { - json_name(proto.get_name()) - }; - FieldDescriptor { - proto, - accessor, - // probably could be lazy-init - json_name, - } - } - - /// Get `.proto` description of field - pub fn proto(&self) -> &'static FieldDescriptorProto { - self.proto - } - - /// Field name as specified in `.proto` file - pub fn name(&self) -> &'static str { - self.proto.get_name() - } - - /// JSON field name. - /// - /// Can be different from `.proto` field name. - /// - /// See [JSON mapping][json] for details. - /// - /// [json]: https://developers.google.com/protocol-buffers/docs/proto3#json - pub fn json_name(&self) -> &str { - &self.json_name - } - - /// If this field repeated? - pub fn is_repeated(&self) -> bool { - self.proto.get_label() == FieldDescriptorProto_Label::LABEL_REPEATED - } - - /// Check if field is set in given message. - /// - /// For repeated field or map field return `true` if - /// collection is not empty. - /// - /// # Panics - /// - /// If this field belongs to a different message type. - pub fn has_field(&self, m: &dyn Message) -> bool { - match &self.accessor.accessor { - Accessor::V1(a) => a.has_field_generic(m), - } - } - - /// Return length of repeated field. - /// - /// For singular field return `1` if field is set and `0` otherwise. - /// - /// # Panics - /// - /// If this field belongs to a different message type. - pub fn len_field(&self, m: &dyn Message) -> usize { - match &self.accessor.accessor { - Accessor::V1(a) => a.len_field_generic(m), - } - } - - /// Get message field or default instance if field is unset. - /// - /// # Panics - /// If this field belongs to a different message type or - /// field type is not message. - pub fn get_message<'a>(&self, m: &'a dyn Message) -> &'a dyn Message { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_message_generic(m), - } - } - - /// Get `enum` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `enum`. - pub fn get_enum(&self, m: &dyn Message) -> &'static EnumValueDescriptor { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_enum_generic(m), - } - } - - /// Get `string` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `string`. - pub fn get_str<'a>(&self, m: &'a dyn Message) -> &'a str { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_str_generic(m), - } - } - - /// Get `bytes` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `bytes`. - pub fn get_bytes<'a>(&self, m: &'a dyn Message) -> &'a [u8] { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_bytes_generic(m), - } - } - - /// Get `u32` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `u32`. - pub fn get_u32(&self, m: &dyn Message) -> u32 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_u32_generic(m), - } - } - - /// Get `u64` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `u64`. - pub fn get_u64(&self, m: &dyn Message) -> u64 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_u64_generic(m), - } - } - - /// Get `i32` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `i32`. - pub fn get_i32(&self, m: &dyn Message) -> i32 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_i32_generic(m), - } - } - - /// Get `i64` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `i64`. - pub fn get_i64(&self, m: &dyn Message) -> i64 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_i64_generic(m), - } - } - - /// Get `bool` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type or - /// field type is not singular `bool`. - pub fn get_bool(&self, m: &dyn Message) -> bool { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_bool_generic(m), - } - } - - /// Get `float` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type or - /// field type is not singular `float`. - pub fn get_f32(&self, m: &dyn Message) -> f32 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_f32_generic(m), - } - } - - /// Get `double` field. - /// - /// # Panics - /// - /// If this field belongs to a different message type - /// or field type is not singular `double`. - pub fn get_f64(&self, m: &dyn Message) -> f64 { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_f64_generic(m), - } - } - - /// Get field of any type. - /// - /// # Panics - /// - /// If this field belongs to a different message type. - pub fn get_reflect<'a>(&self, m: &'a dyn Message) -> ReflectFieldRef<'a> { - match &self.accessor.accessor { - Accessor::V1(a) => a.get_reflect(m), - } - } -} diff --git a/src/reflect/field/dynamic.rs b/src/reflect/field/dynamic.rs new file mode 100644 index 0000000..f8bc1b3 --- /dev/null +++ b/src/reflect/field/dynamic.rs @@ -0,0 +1,36 @@ +use crate::message_dyn::MessageDyn; +use crate::reflect::dynamic::DynamicMessage; +use crate::reflect::FieldDescriptor; +use crate::reflect::ReflectFieldRef; +use crate::reflect::ReflectMapMut; +use crate::reflect::ReflectRepeatedMut; +use crate::reflect::ReflectValueBox; + +pub(crate) struct DynamicFieldDescriptorRef<'a> { + pub(crate) field: &'a FieldDescriptor, +} + +impl<'a> DynamicFieldDescriptorRef<'a> { + pub(crate) fn get_reflect<'b>(&self, message: &'b dyn MessageDyn) -> ReflectFieldRef<'b> { + DynamicMessage::downcast_ref(message).get_reflect(&self.field) + } + + pub(crate) fn mut_repeated<'b>( + &self, + message: &'b mut dyn MessageDyn, + ) -> ReflectRepeatedMut<'b> { + DynamicMessage::downcast_mut(message).mut_repeated(&self.field) + } + + pub(crate) fn mut_map<'b>(&self, message: &'b mut dyn MessageDyn) -> ReflectMapMut<'b> { + DynamicMessage::downcast_mut(message).mut_map(&self.field) + } + + pub(crate) fn set_field(&self, message: &mut dyn MessageDyn, value: ReflectValueBox) { + DynamicMessage::downcast_mut(message).set_field(&self.field, value) + } + + pub(crate) fn clear_field(&self, message: &mut dyn MessageDyn) { + DynamicMessage::downcast_mut(message).clear_field(&self.field) + } +} diff --git a/src/reflect/field/index.rs b/src/reflect/field/index.rs new file mode 100644 index 0000000..2e34c72 --- /dev/null +++ b/src/reflect/field/index.rs @@ -0,0 +1,201 @@ +use protobuf_support::json_name::json_name; + +use crate::descriptor::field_descriptor_proto::Type; +use crate::descriptor::FieldDescriptorProto; +use crate::descriptor::FileDescriptorProto; +use crate::owning_ref::OwningRef; +use crate::reflect::error::ReflectError; +use crate::reflect::field::protobuf_field_type::ProtobufFieldType; +use crate::reflect::file::building::FileDescriptorBuilding; +use crate::reflect::protobuf_type_box::ProtobufType; +use crate::reflect::EnumDescriptor; +use crate::reflect::EnumValueDescriptor; +use crate::reflect::FieldDescriptor; +use crate::reflect::FileDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +#[derive(Debug)] +pub(crate) enum ForwardProtobufTypeBox { + ProtobufTypeBox(ProtobufType), + CurrentFileEnum(usize), + CurrentFileMessage(usize), +} + +impl ForwardProtobufTypeBox { + pub(crate) fn message(message: MessageDescriptor) -> ForwardProtobufTypeBox { + ForwardProtobufTypeBox::ProtobufTypeBox(ProtobufType::message(message)) + } + + pub(crate) fn enumeration(enumeration: EnumDescriptor) -> ForwardProtobufTypeBox { + ForwardProtobufTypeBox::ProtobufTypeBox(ProtobufType::enumeration(enumeration)) + } + + pub(crate) fn from_proto_type(t: Type) -> ForwardProtobufTypeBox { + ForwardProtobufTypeBox::ProtobufTypeBox(ProtobufType::from_proto_type(t)) + } + + pub(crate) fn resolve(&self, file: &FileDescriptor) -> ProtobufType { + match self { + ForwardProtobufTypeBox::ProtobufTypeBox(t) => t.clone(), + ForwardProtobufTypeBox::CurrentFileMessage(m) => { + ProtobufType::message(MessageDescriptor::new(file.clone(), *m)) + } + ForwardProtobufTypeBox::CurrentFileEnum(m) => { + ProtobufType::enumeration(EnumDescriptor::new(file.clone(), *m)) + } + } + } + + pub(crate) fn resolve_message(&self, file: &FileDescriptor) -> MessageDescriptor { + match self.resolve(file).runtime() { + RuntimeType::Message(m) => m.clone(), + _ => panic!("not message"), + } + } +} + +#[derive(Debug)] +pub(crate) enum ForwardProtobufFieldType { + Singular(ForwardProtobufTypeBox), + Repeated(ForwardProtobufTypeBox), + Map(ForwardProtobufTypeBox, ForwardProtobufTypeBox), +} + +impl ForwardProtobufFieldType { + pub(crate) fn resolve(&self, file: &FileDescriptor) -> ProtobufFieldType { + match self { + ForwardProtobufFieldType::Singular(t) => ProtobufFieldType::Singular(t.resolve(file)), + ForwardProtobufFieldType::Repeated(t) => ProtobufFieldType::Repeated(t.resolve(file)), + ForwardProtobufFieldType::Map(k, v) => { + ProtobufFieldType::Map(k.resolve(file), v.resolve(file)) + } + } + } +} + +#[derive(Debug)] +pub(crate) enum FieldDefaultValue { + ReflectValueBox(ReflectValueBox), + Enum(usize), +} + +#[derive(Debug)] +pub(crate) enum FieldKind { + MessageField( + /// Message index. + usize, + ), + Extension( + /// Message index or `None` for file. + Option<usize>, + ForwardProtobufTypeBox, + ), +} + +#[derive(Debug)] +pub(crate) struct FieldIndex { + pub(crate) proto: OwningRef<FileDescriptorProto, FieldDescriptorProto>, + pub(crate) kind: FieldKind, + pub(crate) json_name: String, + pub(crate) field_type: ForwardProtobufFieldType, + pub(crate) default_value: Option<FieldDefaultValue>, +} + +impl FieldIndex { + fn enum_default_value( + field: &FieldDescriptorProto, + building: &FileDescriptorBuilding, + ) -> crate::Result<FieldDefaultValue> { + let en = building.find_enum(field.type_name()); + let (n, _) = match en + .value + .iter() + .enumerate() + .find(|(_n, v)| v.name() == field.default_value()) + { + Some(v) => v, + None => Err(ReflectError::CouldNotParseDefaultValueForField( + field.name().to_owned(), + ))?, + }; + Ok(FieldDefaultValue::Enum(n)) + } + + fn parse_default_value( + field: &FieldDescriptorProto, + building: &FileDescriptorBuilding, + ) -> crate::Result<FieldDefaultValue> { + Ok(FieldDefaultValue::ReflectValueBox(match field.type_() { + Type::TYPE_GROUP | Type::TYPE_MESSAGE => { + return Err(ReflectError::CouldNotParseDefaultValueForField( + field.name().to_owned(), + ) + .into()); + } + Type::TYPE_ENUM => { + return Self::enum_default_value(field, building); + } + t => RuntimeType::from_proto_type(t) + .parse_proto_default_value(field.default_value()) + .map_err(|()| { + ReflectError::CouldNotParseDefaultValueForField(field.name().to_owned()) + })?, + })) + } + + pub(crate) fn index( + containing_message: Option<usize>, + field: OwningRef<FileDescriptorProto, FieldDescriptorProto>, + building: &FileDescriptorBuilding, + ) -> crate::Result<FieldIndex> { + let default_value = if field.has_default_value() { + Some(Self::parse_default_value(&field, building)?) + } else { + None + }; + + let json_name = if !field.json_name().is_empty() { + field.json_name().to_owned() + } else { + json_name(field.name()) + }; + + let extendee = if field.has_extendee() { + Some(building.resolve_message(field.extendee())?) + } else { + None + }; + + let kind = match (containing_message, extendee) { + (Some(m), None) => FieldKind::MessageField(m), + (m, Some(extendee)) => FieldKind::Extension(m, extendee), + (None, None) => panic!("field must be in a message or an extension"), + }; + + let field_type = building.resolve_field_type(&field)?; + Ok(FieldIndex { + proto: field, + kind, + default_value, + json_name, + field_type, + }) + } + + pub(crate) fn default_value<'a>(&'a self, field: &FieldDescriptor) -> ReflectValueRef<'a> { + match &self.default_value { + Some(FieldDefaultValue::ReflectValueBox(v)) => v.as_value_ref(), + Some(FieldDefaultValue::Enum(v)) => match field.singular_runtime_type() { + RuntimeType::Enum(e) => { + let ev = EnumValueDescriptor::new(e.clone(), *v); + ReflectValueRef::from(ev) + } + t => panic!("wrong type {:?} for default value enum", t), + }, + None => field.singular_runtime_type().default_value_ref(), + } + } +} diff --git a/src/reflect/field/mod.rs b/src/reflect/field/mod.rs new file mode 100644 index 0000000..3da38ca --- /dev/null +++ b/src/reflect/field/mod.rs @@ -0,0 +1,585 @@ +use std::fmt; + +use crate::descriptor::field_descriptor_proto; +use crate::descriptor::FieldDescriptorProto; +use crate::message_dyn::MessageDyn; +use crate::reflect::acc::v2::map::MapFieldAccessorHolder; +use crate::reflect::acc::v2::repeated::RepeatedFieldAccessorHolder; +use crate::reflect::acc::v2::singular::SingularFieldAccessorHolder; +use crate::reflect::acc::v2::AccessorV2; +use crate::reflect::acc::GeneratedFieldAccessor; +use crate::reflect::dynamic::DynamicMessage; +use crate::reflect::field::dynamic::DynamicFieldDescriptorRef; +use crate::reflect::field::index::FieldIndex; +use crate::reflect::field::index::FieldKind; +use crate::reflect::field::protobuf_field_type::ProtobufFieldType; +use crate::reflect::field::runtime_field_type::RuntimeFieldType; +use crate::reflect::map::ReflectMapMut; +use crate::reflect::map::ReflectMapRef; +use crate::reflect::message::message_ref::MessageRef; +use crate::reflect::message::MessageDescriptorImplRef; +use crate::reflect::oneof::OneofDescriptor; +use crate::reflect::protobuf_type_box::ProtobufType; +use crate::reflect::reflect_eq::ReflectEq; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::repeated::ReflectRepeatedMut; +use crate::reflect::repeated::ReflectRepeatedRef; +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::FileDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::ReflectOptionalRef; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +pub(crate) mod dynamic; +pub(crate) mod index; +pub(crate) mod protobuf_field_type; +pub(crate) mod runtime_field_type; + +/// Reference to a value stored in a field, optional, repeated or map. +#[derive(PartialEq)] +pub enum ReflectFieldRef<'a> { + /// Singular field, optional or required in proto3 and just plain field in proto3 + Optional(ReflectOptionalRef<'a>), + /// Repeated field + Repeated(ReflectRepeatedRef<'a>), + /// Map field + Map(ReflectMapRef<'a>), +} + +impl<'a> ReflectFieldRef<'a> { + pub(crate) fn default_for_field(field: &FieldDescriptor) -> ReflectFieldRef<'a> { + match field.runtime_field_type() { + RuntimeFieldType::Singular(elem) => { + ReflectFieldRef::Optional(ReflectOptionalRef::none(elem)) + } + RuntimeFieldType::Repeated(elem) => { + ReflectFieldRef::Repeated(ReflectRepeatedRef::new_empty(elem)) + } + RuntimeFieldType::Map(k, v) => ReflectFieldRef::Map(ReflectMapRef::new_empty(k, v)), + } + } +} + +impl<'a> ReflectEq for ReflectFieldRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + match (self, that) { + (ReflectFieldRef::Optional(a), ReflectFieldRef::Optional(b)) => { + match (a.value(), b.value()) { + (Some(av), Some(bv)) => av.reflect_eq(&bv, mode), + (None, None) => true, + _ => false, + } + } + (ReflectFieldRef::Repeated(a), ReflectFieldRef::Repeated(b)) => a.reflect_eq(b, mode), + (ReflectFieldRef::Map(a), ReflectFieldRef::Map(b)) => a.reflect_eq(b, mode), + _ => false, + } + } +} + +fn _assert_sync<'a>() { + fn _assert_send_sync<T: Sync>() {} + _assert_send_sync::<ReflectFieldRef<'a>>(); +} + +/// Field descriptor. +/// +/// Can be used for runtime reflection. +#[derive(Eq, PartialEq, Clone)] +pub struct FieldDescriptor { + pub(crate) file_descriptor: FileDescriptor, + pub(crate) index: usize, +} + +impl fmt::Display for FieldDescriptor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.index().kind { + FieldKind::MessageField(m) => write!( + f, + "{}.{}", + self.file_descriptor.message_by_index(*m), + self.name() + ), + FieldKind::Extension(Some(m), _) => write!( + f, + "{}.{}", + self.file_descriptor.message_by_index(*m), + self.name() + ), + FieldKind::Extension(None, _) => { + if self.file_descriptor.proto().package().is_empty() { + write!(f, "{}", self.name()) + } else { + write!( + f, + "{}.{}", + self.file_descriptor.proto().package(), + self.name() + ) + } + } + } + } +} + +impl FieldDescriptor { + pub(crate) fn regular(&self) -> (MessageDescriptor, usize) { + match self.index().kind { + FieldKind::MessageField(_) => { + let m = self.containing_message(); + ( + m.clone(), + self.index - m.index().message_index.first_field_index, + ) + } + // TODO: implement and remove. + _ => panic!("regular field"), + } + } + + pub(crate) fn file_descriptor(&self) -> &FileDescriptor { + &self.file_descriptor + } + + /// Get `.proto` description of field + pub fn proto(&self) -> &FieldDescriptorProto { + &self.index().proto + } + + /// Field name as specified in `.proto` file. + pub fn name(&self) -> &str { + self.proto().name() + } + + /// Field number as specified in `.proto` file. + pub fn number(&self) -> i32 { + self.proto().number() + } + + /// Fully qualified name of the field: fully qualified name of the declaring type + /// followed by the field name. + /// + /// Declaring type is a message (for regular field or extensions) or a package + /// (for top-level extensions). + pub fn full_name(&self) -> String { + self.to_string() + } + + /// Oneof descriptor containing this field. Do not skip synthetic oneofs. + pub fn containing_oneof_including_synthetic(&self) -> Option<OneofDescriptor> { + if let FieldKind::MessageField(..) = self.index().kind { + let proto = self.proto(); + if proto.has_oneof_index() { + Some(OneofDescriptor { + file_descriptor: self.file_descriptor().clone(), + index: self.containing_message().index().oneofs.start + + proto.oneof_index() as usize, + }) + } else { + None + } + } else { + None + } + } + + /// Oneof containing this field. + /// + /// Return `None` if this field is not part of oneof or if it is synthetic oneof. + pub fn containing_oneof(&self) -> Option<OneofDescriptor> { + self.containing_oneof_including_synthetic() + .filter(|o| !o.is_synthetic()) + } + + /// Message which declares this field (for extension, **not** the message we extend). + fn _declaring_message(&self) -> Option<MessageDescriptor> { + match &self.index().kind { + FieldKind::MessageField(m) => Some(self.file_descriptor.message_by_index(*m)), + FieldKind::Extension(m, _) => Some(self.file_descriptor.message_by_index(*m.as_ref()?)), + } + } + + /// Message which contains this field. + /// + /// For extension fields, this is the message being extended. + pub fn containing_message(&self) -> MessageDescriptor { + match &self.index().kind { + FieldKind::MessageField(m) => self.file_descriptor().message_by_index(*m), + FieldKind::Extension(_, extendee) => extendee.resolve_message(self.file_descriptor()), + } + } + + fn index(&self) -> &FieldIndex { + &self.file_descriptor.common().fields[self.index] + } + + fn index_with_message_lifetime<'a>(&self, m: &'a dyn MessageDyn) -> &'a FieldIndex { + let (descriptor, index) = self.regular(); + let file_fields = match self.singular() { + SingularFieldAccessorRef::Generated(..) => { + &descriptor + .file_descriptor + .common_for_generated_descriptor() + .fields + } + SingularFieldAccessorRef::Dynamic(..) => { + &DynamicMessage::downcast_ref(m) + .descriptor() + .file_descriptor + .common() + .fields + } + }; + &descriptor.index().message_index.slice_fields(file_fields)[index] + } + + /// JSON field name. + /// + /// Can be different from `.proto` field name. + /// + /// See [JSON mapping][json] for details. + /// + /// [json]: https://developers.google.com/protocol-buffers/docs/proto3#json + pub fn json_name(&self) -> &str { + &self.index().json_name + } + + /// If this field is optional or required. + pub fn is_singular(&self) -> bool { + match self.proto().label() { + field_descriptor_proto::Label::LABEL_REQUIRED => true, + field_descriptor_proto::Label::LABEL_OPTIONAL => true, + field_descriptor_proto::Label::LABEL_REPEATED => false, + } + } + + /// Is this field required. + pub fn is_required(&self) -> bool { + self.proto().label() == field_descriptor_proto::Label::LABEL_REQUIRED + } + + /// If this field repeated or map? + pub fn is_repeated_or_map(&self) -> bool { + self.proto().label() == field_descriptor_proto::Label::LABEL_REPEATED + } + + /// Is this field repeated, but not map field? + pub fn is_repeated(&self) -> bool { + match self.runtime_field_type() { + RuntimeFieldType::Repeated(..) => true, + _ => false, + } + } + + fn get_impl(&self) -> FieldDescriptorImplRef { + let (descriptor, index) = self.regular(); + match descriptor.get_impl() { + MessageDescriptorImplRef::Generated(g) => { + FieldDescriptorImplRef::Generated(&g.non_map().fields[index].accessor) + } + MessageDescriptorImplRef::Dynamic => { + FieldDescriptorImplRef::Dynamic(DynamicFieldDescriptorRef { field: self }) + } + } + } + + /// If this field a map field? + pub fn is_map(&self) -> bool { + match self.runtime_field_type() { + RuntimeFieldType::Map(..) => true, + _ => false, + } + } + + /// Check if field is set in given message. + /// + /// For repeated field or map field return `true` if + /// collection is not empty. + /// + /// # Panics + /// + /// If this field belongs to a different message type. + pub fn has_field(&self, m: &dyn MessageDyn) -> bool { + match self.get_reflect(m) { + ReflectFieldRef::Optional(v) => v.value().is_some(), + ReflectFieldRef::Repeated(r) => !r.is_empty(), + ReflectFieldRef::Map(m) => !m.is_empty(), + } + } + + // accessors + + fn singular(&self) -> SingularFieldAccessorRef { + match self.get_impl() { + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2( + AccessorV2::Singular(ref a), + )) => SingularFieldAccessorRef::Generated(a), + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => { + panic!("not a singular field: {}", self) + } + FieldDescriptorImplRef::Dynamic(d) => SingularFieldAccessorRef::Dynamic(d), + } + } + + fn repeated(&self) -> RepeatedFieldAccessorRef { + match self.get_impl() { + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2( + AccessorV2::Repeated(ref a), + )) => RepeatedFieldAccessorRef::Generated(a), + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => { + panic!("not a repeated field: {}", self) + } + FieldDescriptorImplRef::Dynamic(d) => RepeatedFieldAccessorRef::Dynamic(d), + } + } + + fn map(&self) -> MapFieldAccessorRef { + match self.get_impl() { + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(AccessorV2::Map( + ref a, + ))) => MapFieldAccessorRef::Generated(a), + FieldDescriptorImplRef::Generated(GeneratedFieldAccessor::V2(..)) => { + panic!("not a map field: {}", self) + } + FieldDescriptorImplRef::Dynamic(d) => MapFieldAccessorRef::Dynamic(d), + } + } + + /// Obtain type of map key and value. + pub(crate) fn map_proto_type(&self) -> (ProtobufType, ProtobufType) { + match self.protobuf_field_type() { + ProtobufFieldType::Map(k, v) => (k, v), + _ => panic!("not a map field: {}", self), + } + } + + /// Get message field or default instance if field is unset. + /// + /// # Panics + /// If this field belongs to a different message type or + /// field type is not message. + pub fn get_message<'a>(&self, m: &'a dyn MessageDyn) -> MessageRef<'a> { + match self.get_singular_field_or_default(m) { + ReflectValueRef::Message(m) => m, + _ => panic!("not message field: {}", self), + } + } + + /// Get a mutable reference to a message field. + /// Initialize field with default message if unset. + /// + /// # Panics + /// + /// If this field belongs to a different message type or + /// field type is not singular message. + pub fn mut_message<'a>(&self, m: &'a mut dyn MessageDyn) -> &'a mut dyn MessageDyn { + match self.mut_singular_field_or_default(m) { + ReflectValueMut::Message(m) => m, + } + } + + /// Default value. + /// + /// # Panics + /// + /// If field is not singular. + pub fn singular_default_value(&self) -> ReflectValueRef { + self.index().default_value(self) + } + + /// Get singular field value. + /// + /// Return field default value if field is unset. + /// + /// # Panics + /// + /// If this field belongs to a different message type or fields is not singular. + pub fn get_singular_field_or_default<'a>(&self, m: &'a dyn MessageDyn) -> ReflectValueRef<'a> { + match self.get_singular(m) { + Some(m) => m, + None => self.index_with_message_lifetime(m).default_value(self), + } + } + + // Not public because it is not implemented for all types + fn mut_singular_field_or_default<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectValueMut<'a> { + match self.singular() { + SingularFieldAccessorRef::Generated(g) => g.accessor.mut_field_or_default(m), + SingularFieldAccessorRef::Dynamic(..) => { + DynamicMessage::downcast_mut(m).mut_singular_field_or_default(self) + } + } + } + + /// Runtime representation of singular field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or field is not singular. + pub fn singular_runtime_type(&self) -> RuntimeType { + match self.runtime_field_type() { + RuntimeFieldType::Singular(s) => s, + _ => panic!("Not a singular field: {}", self), + } + } + + /// Set singular field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or + /// field is not singular or value is of different type. + pub fn set_singular_field(&self, m: &mut dyn MessageDyn, value: ReflectValueBox) { + match self.singular() { + SingularFieldAccessorRef::Generated(g) => g.accessor.set_field(m, value), + SingularFieldAccessorRef::Dynamic(d) => d.set_field(m, value), + } + } + + /// Clear a field. + pub fn clear_field(&self, m: &mut dyn MessageDyn) { + if self.is_singular() { + match self.singular() { + SingularFieldAccessorRef::Generated(g) => g.accessor.clear_field(m), + SingularFieldAccessorRef::Dynamic(d) => d.clear_field(m), + } + } else if self.is_repeated() { + self.mut_repeated(m).clear(); + } else if self.is_map() { + self.mut_map(m).clear(); + } + } + + /// Dynamic representation of field type with wire type. + pub(crate) fn protobuf_field_type(&self) -> ProtobufFieldType { + self.index().field_type.resolve(self.file_descriptor()) + } + + /// Dynamic representation of field type. + pub fn runtime_field_type(&self) -> RuntimeFieldType { + self.protobuf_field_type().runtime() + } + + /// Get field of any type. + /// + /// # Panics + /// + /// If this field belongs to a different message type. + pub fn get_reflect<'a>(&self, m: &'a dyn MessageDyn) -> ReflectFieldRef<'a> { + match self.get_impl() { + FieldDescriptorImplRef::Generated(g) => g.get_reflect(m), + FieldDescriptorImplRef::Dynamic(d) => d.get_reflect(m), + } + } + + /// Get singular field value. + /// + /// Return `None` if field is unset. + /// + /// # Panics + /// + /// If this field belongs to a different message type or fields is not singular. + pub fn get_singular<'a>(&self, m: &'a dyn MessageDyn) -> Option<ReflectValueRef<'a>> { + match self.get_reflect(m) { + ReflectFieldRef::Optional(o) => o.value(), + _ => panic!("not a singular field"), + } + } + + // repeated + + /// Get repeated field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or field is not repeated. + pub fn get_repeated<'a>(&self, m: &'a dyn MessageDyn) -> ReflectRepeatedRef<'a> { + match self.get_reflect(m) { + ReflectFieldRef::Repeated(r) => r, + _ => panic!("not a repeated field"), + } + } + + /// Get a mutable reference to `repeated` field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or field is not `repeated`. + pub fn mut_repeated<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectRepeatedMut<'a> { + match self.repeated() { + RepeatedFieldAccessorRef::Generated(g) => g.accessor.mut_repeated(m), + RepeatedFieldAccessorRef::Dynamic(d) => d.mut_repeated(m), + } + } + + // map + + /// Get `map` field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or field is not `map`. + pub fn get_map<'a>(&self, m: &'a dyn MessageDyn) -> ReflectMapRef<'a> { + match self.get_reflect(m) { + ReflectFieldRef::Map(m) => m, + _ => panic!("not a map field"), + } + } + + /// Get a mutable reference to `map` field. + /// + /// # Panics + /// + /// If this field belongs to a different message type or field is not `map`. + pub fn mut_map<'a>(&self, m: &'a mut dyn MessageDyn) -> ReflectMapMut<'a> { + match self.map() { + MapFieldAccessorRef::Generated(g) => g.accessor.mut_reflect(m), + MapFieldAccessorRef::Dynamic(d) => d.mut_map(m), + } + } +} + +enum SingularFieldAccessorRef<'a> { + Generated(&'a SingularFieldAccessorHolder), + Dynamic(DynamicFieldDescriptorRef<'a>), +} + +enum RepeatedFieldAccessorRef<'a> { + Generated(&'a RepeatedFieldAccessorHolder), + Dynamic(DynamicFieldDescriptorRef<'a>), +} + +enum MapFieldAccessorRef<'a> { + Generated(&'a MapFieldAccessorHolder), + Dynamic(DynamicFieldDescriptorRef<'a>), +} + +pub(crate) enum FieldDescriptorImplRef<'a> { + Generated(&'static GeneratedFieldAccessor), + Dynamic(DynamicFieldDescriptorRef<'a>), +} + +#[cfg(test)] +mod test { + use std::collections::HashMap; + + use crate::descriptor::DescriptorProto; + use crate::reflect::ReflectValueBox; + use crate::well_known_types::struct_::Struct; + use crate::well_known_types::struct_::Value; + use crate::MessageFull; + + #[test] + #[cfg_attr(miri, ignore)] + fn display() { + let field = DescriptorProto::descriptor() + .field_by_name("enum_type") + .unwrap(); + assert_eq!( + "google.protobuf.DescriptorProto.enum_type", + field.to_string() + ); + } +} diff --git a/src/reflect/field/protobuf_field_type.rs b/src/reflect/field/protobuf_field_type.rs new file mode 100644 index 0000000..c50de04 --- /dev/null +++ b/src/reflect/field/protobuf_field_type.rs @@ -0,0 +1,25 @@ +use crate::reflect::protobuf_type_box::ProtobufType; +use crate::reflect::RuntimeFieldType; + +/// Reflective representation of field type plus wire type. +pub(crate) enum ProtobufFieldType { + /// Singular field (required, optional for proto2 or singular for proto3) + Singular(ProtobufType), + /// Repeated field + Repeated(ProtobufType), + /// Map field + Map(ProtobufType, ProtobufType), +} + +impl ProtobufFieldType { + /// Drop wire type from the type. + pub fn runtime(&self) -> RuntimeFieldType { + match self { + ProtobufFieldType::Singular(t) => RuntimeFieldType::Singular(t.runtime().clone()), + ProtobufFieldType::Repeated(t) => RuntimeFieldType::Repeated(t.runtime().clone()), + ProtobufFieldType::Map(kt, vt) => { + RuntimeFieldType::Map(kt.runtime().clone(), vt.runtime().clone()) + } + } + } +} diff --git a/src/reflect/field/runtime_field_type.rs b/src/reflect/field/runtime_field_type.rs new file mode 100644 index 0000000..eba549b --- /dev/null +++ b/src/reflect/field/runtime_field_type.rs @@ -0,0 +1,11 @@ +use crate::reflect::RuntimeType; + +/// Reflective representation of field type. +pub enum RuntimeFieldType { + /// Singular field (required, optional for proto2 or singular for proto3) + Singular(RuntimeType), + /// Repeated field + Repeated(RuntimeType), + /// Map field + Map(RuntimeType, RuntimeType), +} diff --git a/src/reflect/file/building.rs b/src/reflect/file/building.rs new file mode 100644 index 0000000..fb9eb54 --- /dev/null +++ b/src/reflect/file/building.rs @@ -0,0 +1,168 @@ +use std::collections::HashMap; +use std::iter; + +use crate::descriptor::field_descriptor_proto; +use crate::descriptor::DescriptorProto; +use crate::descriptor::EnumDescriptorProto; +use crate::descriptor::FieldDescriptorProto; +use crate::descriptor::FileDescriptorProto; +use crate::reflect::error::ReflectError; +use crate::reflect::field::index::ForwardProtobufFieldType; +use crate::reflect::field::index::ForwardProtobufTypeBox; +use crate::reflect::file::index::MessageIndices; +use crate::reflect::find_message_or_enum::find_message_or_enum; +use crate::reflect::find_message_or_enum::MessageOrEnum; +use crate::reflect::name::protobuf_name_starts_with_package; +use crate::reflect::runtime_type_box::RuntimeType; +use crate::reflect::FileDescriptor; + +pub(crate) struct FileDescriptorBuilding<'a> { + pub(crate) current_file_descriptor: &'a FileDescriptorProto, + pub(crate) deps_with_public: &'a [FileDescriptor], + pub(crate) message_by_name_to_package: &'a HashMap<String, usize>, + pub(crate) messages: &'a [MessageIndices], + pub(crate) enums_by_name_to_package: &'a HashMap<String, usize>, +} + +impl<'a> FileDescriptorBuilding<'a> { + fn all_descriptors(&self) -> impl Iterator<Item = &'a FileDescriptorProto> { + iter::once(self.current_file_descriptor) + .chain(self.deps_with_public.iter().map(|d| d.proto())) + } + + pub fn find_enum(&self, full_name: &str) -> &'a EnumDescriptorProto { + assert!(full_name.starts_with(".")); + + for file in self.all_descriptors() { + if let Some(name_to_package) = + protobuf_name_starts_with_package(full_name, file.package()) + { + if let Some((_, me)) = find_message_or_enum(file, name_to_package) { + match me { + MessageOrEnum::Enum(e) => return e, + MessageOrEnum::Message(_) => panic!("not an enum: {}", full_name), + } + } + } + } + + panic!( + "enum not found: {}, in files: {}", + full_name, + self.all_files_str() + ); + } + + fn all_files_str(&self) -> String { + self.all_descriptors() + .map(|d| d.name()) + .collect::<Vec<_>>() + .join(", ") + } + + pub(crate) fn resolve_field_type( + &self, + field: &FieldDescriptorProto, + ) -> crate::Result<ForwardProtobufFieldType> { + Ok(match field.label() { + field_descriptor_proto::Label::LABEL_OPTIONAL + | field_descriptor_proto::Label::LABEL_REQUIRED => { + ForwardProtobufFieldType::Singular(self.resolve_field_element_type(field)?) + } + field_descriptor_proto::Label::LABEL_REPEATED => { + let element = self.resolve_field_element_type(field)?; + let type_proto = match &element { + ForwardProtobufTypeBox::CurrentFileMessage(m) => { + Some(&*self.messages[*m].proto) + } + ForwardProtobufTypeBox::ProtobufTypeBox(t) => match t.runtime() { + RuntimeType::Message(m) => Some(m.proto()), + _ => None, + }, + _ => None, + }; + match type_proto { + Some(m) if m.options.get_or_default().map_entry() => self.map_field(m)?, + _ => ForwardProtobufFieldType::Repeated(element), + } + } + }) + } + + fn resolve_field_element_type( + &self, + field: &FieldDescriptorProto, + ) -> crate::Result<ForwardProtobufTypeBox> { + Ok(match field.type_() { + field_descriptor_proto::Type::TYPE_MESSAGE + | field_descriptor_proto::Type::TYPE_GROUP => { + self.resolve_message(field.type_name())? + } + field_descriptor_proto::Type::TYPE_ENUM => { + if let Some(name_to_package) = protobuf_name_starts_with_package( + field.type_name(), + self.current_file_descriptor.package(), + ) { + if let Some(index) = self.enums_by_name_to_package.get(name_to_package) { + return Ok(ForwardProtobufTypeBox::CurrentFileEnum(*index)); + } + } + for dep in self.deps_with_public { + if let Some(m) = dep.enum_by_full_name(field.type_name()) { + return Ok(ForwardProtobufTypeBox::enumeration(m)); + } + } + panic!( + "enum not found: {}; files: {}", + field.type_name(), + self.all_files_str() + ); + } + t => ForwardProtobufTypeBox::from_proto_type(t), + }) + } + + pub(crate) fn resolve_message(&self, type_name: &str) -> crate::Result<ForwardProtobufTypeBox> { + if let Some(name_to_package) = + protobuf_name_starts_with_package(type_name, self.current_file_descriptor.package()) + { + if let Some(index) = self.message_by_name_to_package.get(name_to_package) { + return Ok(ForwardProtobufTypeBox::CurrentFileMessage(*index)); + } + } + for dep in self.deps_with_public { + if let Some(m) = dep.message_by_full_name(type_name) { + return Ok(ForwardProtobufTypeBox::message(m)); + } + } + Err(ReflectError::MessageNotFoundInFiles(type_name.to_owned(), self.all_files_str()).into()) + } + + fn map_field(&self, type_proto: &DescriptorProto) -> crate::Result<ForwardProtobufFieldType> { + assert!(type_proto.name().ends_with("Entry")); + + assert_eq!(0, type_proto.extension.len()); + assert_eq!(0, type_proto.extension_range.len()); + assert_eq!(0, type_proto.nested_type.len()); + assert_eq!(0, type_proto.enum_type.len()); + + assert_eq!(2, type_proto.field.len()); + let key = &type_proto.field[0]; + let value = &type_proto.field[1]; + + assert_eq!("key", key.name()); + assert_eq!("value", value.name()); + + assert_eq!(1, key.number()); + assert_eq!(2, value.number()); + + assert_eq!(field_descriptor_proto::Label::LABEL_OPTIONAL, key.label()); + assert_eq!(field_descriptor_proto::Label::LABEL_OPTIONAL, value.label()); + + // It is OK to resolve using current descriptor because map field + // should always point to the same file. + let key = self.resolve_field_element_type(key)?; + let value = self.resolve_field_element_type(value)?; + Ok(ForwardProtobufFieldType::Map(key, value)) + } +} diff --git a/src/reflect/file/dynamic.rs b/src/reflect/file/dynamic.rs new file mode 100644 index 0000000..f577c92 --- /dev/null +++ b/src/reflect/file/dynamic.rs @@ -0,0 +1,63 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use crate::descriptor::FileDescriptorProto; +use crate::owning_ref::OwningRef; +use crate::reflect::error::ReflectError; +use crate::reflect::file::index::FileDescriptorCommon; +use crate::reflect::FileDescriptor; + +#[derive(Debug)] +pub(crate) struct DynamicFileDescriptor { + pub(crate) proto: Arc<FileDescriptorProto>, + pub(crate) common: FileDescriptorCommon, +} + +impl DynamicFileDescriptor { + pub(crate) fn new( + proto: FileDescriptorProto, + dependencies: &[FileDescriptor], + ) -> crate::Result<DynamicFileDescriptor> { + // Remove undeclared dependencies. + let dependencies_index: HashMap<_, &FileDescriptor> = + dependencies.iter().map(|d| (d.proto().name(), d)).collect(); + + if dependencies_index.len() != dependencies.len() { + return Err(ReflectError::NonUniqueDependencies( + dependencies + .iter() + .map(|d| d.proto().name()) + .collect::<Vec<_>>() + .join(", "), + ) + .into()); + } + + let dependencies: Vec<FileDescriptor> = proto + .dependency + .iter() + .map(|d| { + let dep = dependencies_index.get(d.as_str()); + match dep { + Some(dep) => Ok((*dep).clone()), + None => Err(ReflectError::DependencyNotFound( + d.clone(), + proto.name().to_owned(), + dependencies + .iter() + .map(|d| d.proto().name()) + .collect::<Vec<_>>() + .join(", "), + ) + .into()), + } + }) + .collect::<crate::Result<Vec<_>>>()?; + + let proto = Arc::new(proto); + + let common = FileDescriptorCommon::new(OwningRef::new_arc(proto.clone()), dependencies)?; + + Ok(DynamicFileDescriptor { proto, common }) + } +} diff --git a/src/reflect/file/fds.rs b/src/reflect/file/fds.rs new file mode 100644 index 0000000..f469b6c --- /dev/null +++ b/src/reflect/file/fds.rs @@ -0,0 +1,68 @@ +use std::collections::HashMap; +use std::collections::HashSet; +use std::mem; + +use protobuf_support::toposort::toposort; + +use crate::descriptor::FileDescriptorProto; +use crate::reflect::error::ReflectError; +use crate::reflect::FileDescriptor; + +pub(crate) fn build_fds( + protos: Vec<FileDescriptorProto>, + dependencies: &[FileDescriptor], +) -> crate::Result<Vec<FileDescriptor>> { + let mut index_by_name: HashMap<&str, usize> = HashMap::new(); + for (i, proto) in protos.iter().enumerate() { + let prev = index_by_name.insert(proto.name(), i); + if prev.is_some() { + return Err(ReflectError::NonUniqueFileDescriptor(proto.name().to_owned()).into()); + } + } + + let sorted = match toposort(0..protos.len(), |&i| { + protos[i] + .dependency + .iter() + .filter_map(|d| index_by_name.get(d.as_str()).copied()) + }) { + Ok(s) => s, + Err(_) => return Err(ReflectError::CycleInFileDescriptors.into()), + }; + + let mut built_descriptors_by_index = vec![None; protos.len()]; + + let mut protos: Vec<Option<FileDescriptorProto>> = protos.into_iter().map(Some).collect(); + + let mut all_descriptors = dependencies.to_vec(); + for f in sorted { + let proto = mem::take(&mut protos[f]).unwrap(); + let d = FileDescriptor::new_dynamic(proto, &all_descriptors)?; + all_descriptors.push(d.clone()); + built_descriptors_by_index[f] = Some(d); + } + + Ok(built_descriptors_by_index + .into_iter() + .map(Option::unwrap) + .collect()) +} + +pub(crate) fn fds_extend_with_public(file_descriptors: Vec<FileDescriptor>) -> Vec<FileDescriptor> { + let mut visited = HashSet::new(); + + let mut r = Vec::new(); + let mut stack = file_descriptors; + stack.reverse(); + + while let Some(f) = stack.pop() { + if !visited.insert(f.proto().name().to_owned()) { + continue; + } + + stack.extend(f.public_deps()); + + r.push(f); + } + r +} diff --git a/src/reflect/file/generated.rs b/src/reflect/file/generated.rs new file mode 100644 index 0000000..54c60dd --- /dev/null +++ b/src/reflect/file/generated.rs @@ -0,0 +1,101 @@ +use std::collections::HashMap; +use std::fmt; +use std::fmt::Formatter; + +use crate::descriptor::FileDescriptorProto; +use crate::owning_ref::OwningRef; +use crate::reflect::enums::generated::GeneratedEnumDescriptor; +use crate::reflect::file::index::FileDescriptorCommon; +use crate::reflect::message::generated::GeneratedMessageDescriptor; +use crate::reflect::oneof::generated::GeneratedOneofDescriptor; +use crate::reflect::FileDescriptor; +use crate::reflect::GeneratedEnumDescriptorData; +use crate::reflect::GeneratedMessageDescriptorData; + +/// Reflection for objects defined in `.proto` file (messages, enums, etc). +#[doc(hidden)] +pub struct GeneratedFileDescriptor { + pub(crate) proto: &'static FileDescriptorProto, + pub(crate) messages: Vec<GeneratedMessageDescriptor>, + pub(crate) enums: Vec<GeneratedEnumDescriptor>, + pub(crate) oneofs: Vec<GeneratedOneofDescriptor>, + pub(crate) common: FileDescriptorCommon, +} + +impl fmt::Debug for GeneratedFileDescriptor { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + f.debug_struct("GeneratedFileDescriptor") + .field("proto.name", &self.proto.name()) + .finish_non_exhaustive() + } +} + +impl GeneratedFileDescriptor { + /// This function is called from generated code. + pub fn new_generated( + file_descriptor_proto: &'static FileDescriptorProto, + dependencies: Vec<FileDescriptor>, + messages: Vec<GeneratedMessageDescriptorData>, + enums: Vec<GeneratedEnumDescriptorData>, + ) -> GeneratedFileDescriptor { + let common = + FileDescriptorCommon::new(OwningRef::new_static(file_descriptor_proto), dependencies) + .unwrap(); + + let mut messages: HashMap<&str, GeneratedMessageDescriptorData> = messages + .into_iter() + .map(|m| (m.protobuf_name_to_package, m)) + .collect(); + + let mut enums: HashMap<&str, GeneratedEnumDescriptorData> = + enums.into_iter().map(|e| (e.name_in_file, e)).collect(); + + let mut oneofs = Vec::new(); + for oneof in &common.oneofs { + let message = &common.messages[oneof.containing_message]; + let message_proto = &message.proto; + let oneof_proto = &message_proto.oneof_decl[oneof.index_in_containing_message]; + let message = messages.get(message.name_to_package.as_str()).unwrap(); + let oneof_data = &message.oneofs.iter().find(|o| o.name == oneof_proto.name()); + if oneof.synthetic { + assert!(oneof_data.is_none()); + oneofs.push(GeneratedOneofDescriptor::new_synthetic()) + } else { + let oneof = GeneratedOneofDescriptor::new(oneof_data.unwrap()); + oneofs.push(oneof); + } + } + + let messages = common + .messages + .iter() + .map(|message_index| { + if message_index.proto.options.map_entry() { + GeneratedMessageDescriptor::new_map_entry() + } else { + let message = messages + .remove(message_index.name_to_package.as_str()) + .unwrap(); + GeneratedMessageDescriptor::new(message, file_descriptor_proto, &common) + } + }) + .collect(); + + let enums = common + .enums + .iter() + .map(|enum_index| { + let en = enums.remove(enum_index.name_to_package.as_str()).unwrap(); + GeneratedEnumDescriptor::new(en, file_descriptor_proto) + }) + .collect(); + + GeneratedFileDescriptor { + proto: file_descriptor_proto, + messages, + enums, + oneofs, + common, + } + } +} diff --git a/src/reflect/file/index.rs b/src/reflect/file/index.rs new file mode 100644 index 0000000..f574357 --- /dev/null +++ b/src/reflect/file/index.rs @@ -0,0 +1,421 @@ +use std::collections::HashMap; +use std::ops::Range; + +use crate::descriptor::field_descriptor_proto::Label; +use crate::descriptor::DescriptorProto; +use crate::descriptor::EnumDescriptorProto; +use crate::descriptor::FileDescriptorProto; +use crate::owning_ref::OwningRef; +use crate::reflect::error::ReflectError; +use crate::reflect::field::index::FieldIndex; +use crate::reflect::file::building::FileDescriptorBuilding; +use crate::reflect::file::fds::fds_extend_with_public; +use crate::reflect::message::is_initialized_is_always_true::compute_is_initialized_is_always_true; +use crate::reflect::name::concat_paths; +use crate::reflect::service::index::ServiceIndex; +use crate::reflect::FileDescriptor; + +#[derive(Debug)] +pub(crate) struct MessageIndices { + pub(crate) proto: OwningRef<FileDescriptorProto, DescriptorProto>, + pub(crate) name_to_package: String, + pub(crate) full_name: String, + pub(crate) enclosing_message: Option<usize>, + pub(crate) nested_messages: Vec<usize>, + pub(crate) nested_enums: Range<usize>, + pub(crate) oneofs: Range<usize>, + pub(crate) map_entry: bool, + pub(crate) message_index: MessageFieldIndices, + pub(crate) is_initialized_is_always_true: bool, +} + +#[derive(Debug, Default)] +pub(crate) struct MessageFieldIndices { + /// Index of the first field in global field index. + pub(crate) first_field_index: usize, + pub(crate) field_count: usize, + /// Extensions follow fields in global field index. + pub(crate) extension_count: usize, + // Following fields map to the local field index. + pub(crate) field_index_by_name: HashMap<String, usize>, + pub(crate) field_index_by_name_or_json_name: HashMap<String, usize>, + pub(crate) field_index_by_number: HashMap<u32, usize>, +} + +impl MessageFieldIndices { + pub(crate) fn regular_field_range(&self) -> Range<usize> { + self.first_field_index..(self.first_field_index + self.field_count) + } + + pub(crate) fn extension_field_range(&self) -> Range<usize> { + self.first_field_index + self.field_count + ..self.first_field_index + self.field_count + self.extension_count + } + + pub(crate) fn slice_fields<'a>(&self, file_fields: &'a [FieldIndex]) -> &'a [FieldIndex] { + &file_fields[self.first_field_index..self.first_field_index + self.field_count] + } +} + +#[derive(Debug)] +pub(crate) struct EnumIndices { + pub(crate) proto: OwningRef<FileDescriptorProto, EnumDescriptorProto>, + pub(crate) name_to_package: String, + pub(crate) full_name: String, + pub(crate) enclosing_message: Option<usize>, + pub(crate) index_by_name: HashMap<String, usize>, + pub(crate) index_by_number: HashMap<i32, usize>, +} + +impl EnumIndices { + pub(crate) fn new( + name_to_package: String, + enclosing_message: Option<usize>, + proto: OwningRef<FileDescriptorProto, EnumDescriptorProto>, + file: &FileDescriptorProto, + ) -> EnumIndices { + let mut index_by_name = HashMap::new(); + let mut index_by_number = HashMap::new(); + for (i, v) in proto.value.iter().enumerate() { + index_by_number.insert(v.number(), i); + index_by_name.insert(v.name().to_owned(), i); + } + let full_name = concat_paths(file.package(), &name_to_package); + EnumIndices { + proto, + full_name, + name_to_package, + enclosing_message, + index_by_name, + index_by_number, + } + } +} + +#[derive(Debug)] +pub(crate) struct OneofIndices { + pub(crate) containing_message: usize, + pub(crate) index_in_containing_message: usize, + /// Synthetic oneof for proto3 optional field. + pub(crate) synthetic: bool, + pub(crate) fields: Vec<usize>, +} + +/// Common `FileDescriptor` data for generated and dynamic file descriptors. +#[derive(Debug)] +pub(crate) struct FileDescriptorCommon { + /// Direct dependencies of this file. + pub(crate) dependencies: Vec<FileDescriptor>, + /// All messages in this file. + pub(crate) messages: Vec<MessageIndices>, + pub(crate) message_by_name_to_package: HashMap<String, usize>, + pub(crate) top_level_messages: Vec<usize>, + pub(crate) enums: Vec<EnumIndices>, + pub(crate) enums_by_name_to_package: HashMap<String, usize>, + pub(crate) oneofs: Vec<OneofIndices>, + pub(crate) services: Vec<ServiceIndex>, + pub(crate) first_extension_field_index: usize, + /// All fields followed by file-level extensions. + pub(crate) fields: Vec<FieldIndex>, +} + +impl FileDescriptorCommon { + pub(crate) fn extension_field_range(&self) -> Range<usize> { + self.first_extension_field_index..self.fields.len() + } + + pub(crate) fn new( + file: OwningRef<FileDescriptorProto, FileDescriptorProto>, + dependencies: Vec<FileDescriptor>, + ) -> crate::Result<FileDescriptorCommon> { + let deps_with_public = fds_extend_with_public(dependencies.clone()); + + let mut messages = Vec::new(); + let mut enums = Vec::new(); + let mut oneofs = Vec::new(); + let mut top_level_messages = Vec::new(); + + // Top-level enums start with zero + for e in file.flat_map_slice(|f| &f.enum_type) { + enums.push(EnumIndices::new(e.name().to_owned(), None, e, file.owner())); + } + + for message in file.flat_map_slice(|f| &f.message_type) { + let message_index = Self::index_message_and_inners( + file.owner(), + message, + None, + "", + &mut messages, + &mut enums, + &mut oneofs, + )?; + top_level_messages.push(message_index); + } + + let message_by_name_to_package = Self::build_message_by_name_to_package(&messages); + let enums_by_name_to_package = Self::build_enum_by_name_to_package(&enums); + + let mut services = Vec::new(); + + for service in &file.service { + let service_index = ServiceIndex::index( + service, + &FileDescriptorBuilding { + current_file_descriptor: file.owner(), + deps_with_public: &deps_with_public, + message_by_name_to_package: &message_by_name_to_package, + messages: &messages, + enums_by_name_to_package: &enums_by_name_to_package, + }, + )?; + services.push(service_index); + } + + let mut fields = Vec::new(); + + Self::build_message_index( + file.owner(), + &deps_with_public, + &mut messages, + &mut fields, + &message_by_name_to_package, + &enums_by_name_to_package, + )?; + + let first_extension_field_index = fields.len(); + for ext in file.flat_map_slice(|f| &f.extension) { + fields.push(FieldIndex::index( + None, + ext, + &FileDescriptorBuilding { + current_file_descriptor: file.owner(), + deps_with_public: &deps_with_public, + message_by_name_to_package: &message_by_name_to_package, + messages: &messages, + enums_by_name_to_package: &enums_by_name_to_package, + }, + )?); + } + + compute_is_initialized_is_always_true(&mut messages, &fields, file.owner()); + + Ok(FileDescriptorCommon { + dependencies, + messages, + message_by_name_to_package, + enums, + top_level_messages, + enums_by_name_to_package, + oneofs, + services, + first_extension_field_index, + fields, + }) + } + + fn is_map_entry(message: &DescriptorProto) -> crate::Result<bool> { + // Must be consistent with + // DescriptorBuilder::ValidateMapEntry + + if !message.options.map_entry() { + return Ok(false); + } + + if !message.name().ends_with("Entry") { + return Err(ReflectError::MapEntryNameMustEndWithEntry.into()); + } + if !message.extension.is_empty() + || !message.extension_range.is_empty() + || !message.nested_type.is_empty() + || !message.enum_type.is_empty() + { + return Err(ReflectError::MapEntryMustHaveNo.into()); + } + + if message.field.len() != 2 { + return Err(ReflectError::MapEntryIncorrectFields.into()); + } + + let key = &message.field[0]; + let value = &message.field[1]; + + if key.number() != 1 + || key.name() != "key" + || key.label() != Label::LABEL_OPTIONAL + || value.number() != 2 + || value.name() != "value" + || value.label() != Label::LABEL_OPTIONAL + { + return Err(ReflectError::MapEntryIncorrectFields.into()); + } + + Ok(true) + } + + fn index_message_and_inners( + file: &FileDescriptorProto, + message: OwningRef<FileDescriptorProto, DescriptorProto>, + parent: Option<usize>, + parent_name_to_package: &str, + messages: &mut Vec<MessageIndices>, + enums: &mut Vec<EnumIndices>, + oneofs: &mut Vec<OneofIndices>, + ) -> crate::Result<usize> { + let name_to_package = concat_paths(parent_name_to_package, message.name()); + + let message_index = messages.len(); + messages.push(MessageIndices { + proto: message.clone(), + full_name: concat_paths(file.package(), &name_to_package), + name_to_package: name_to_package.clone(), + enclosing_message: parent, + nested_messages: Vec::with_capacity(message.nested_type.len()), + nested_enums: enums.len()..enums.len() + message.enum_type.len(), + oneofs: oneofs.len()..oneofs.len() + message.oneof_decl.len(), + message_index: MessageFieldIndices::default(), + map_entry: Self::is_map_entry(&message)?, + // Initialized later. + is_initialized_is_always_true: false, + }); + + for e in message.flat_map_slice(|m| &m.enum_type) { + enums.push(EnumIndices::new( + concat_paths(&name_to_package, e.name()), + Some(message_index), + e, + file, + )); + } + + for (i, _oneof) in message.oneof_decl.iter().enumerate() { + let fields: Vec<_> = message + .field + .iter() + .enumerate() + .filter(|(_, f)| f.has_oneof_index() && f.oneof_index() == i as i32) + .collect(); + let synthetic = fields.len() == 1 && fields[0].1.proto3_optional(); + oneofs.push(OneofIndices { + containing_message: message_index, + index_in_containing_message: i, + synthetic, + fields: fields.iter().map(|(i, _)| *i).collect(), + }); + } + + for nested in message.flat_map_slice(|m| &m.nested_type) { + let nested_index = Self::index_message_and_inners( + file, + nested, + Some(message_index), + &name_to_package, + messages, + enums, + oneofs, + )?; + messages[message_index].nested_messages.push(nested_index); + } + + Ok(message_index) + } + + fn build_message_by_name_to_package(messages: &[MessageIndices]) -> HashMap<String, usize> { + messages + .iter() + .enumerate() + .map(|(i, m)| (m.name_to_package.to_owned(), i)) + .collect() + } + + fn build_enum_by_name_to_package(enums: &[EnumIndices]) -> HashMap<String, usize> { + enums + .iter() + .enumerate() + .map(|(i, e)| (e.name_to_package.to_owned(), i)) + .collect() + } + + fn build_message_index( + file: &FileDescriptorProto, + deps_with_public: &[FileDescriptor], + messages: &mut [MessageIndices], + fields: &mut Vec<FieldIndex>, + message_by_name_to_package: &HashMap<String, usize>, + enums_by_name_to_package: &HashMap<String, usize>, + ) -> crate::Result<()> { + for i in 0..messages.len() { + let message_proto = &messages[i].proto; + let building = FileDescriptorBuilding { + current_file_descriptor: file, + deps_with_public, + message_by_name_to_package, + messages, + enums_by_name_to_package, + }; + let message_index = Self::index_message(i, message_proto, &building, fields)?; + messages[i].message_index = message_index; + } + Ok(()) + } + + fn index_message( + message_index: usize, + proto: &OwningRef<FileDescriptorProto, DescriptorProto>, + building: &FileDescriptorBuilding, + fields: &mut Vec<FieldIndex>, + ) -> crate::Result<MessageFieldIndices> { + let mut index_by_name = HashMap::new(); + let mut index_by_name_or_json_name = HashMap::new(); + let mut index_by_number = HashMap::new(); + + let first_field_index = fields.len(); + + for field in proto.flat_map_slice(|m| &m.field) { + fields.push(FieldIndex::index(Some(message_index), field, building)?); + } + + let field_count = proto.field.len(); + + for (i, f) in proto.field.iter().enumerate() { + let field_index = &fields[first_field_index + i]; + + if index_by_number.insert(f.number() as u32, i).is_some() { + return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); + } + if index_by_name.insert(f.name().to_owned(), i).is_some() { + return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); + } + if index_by_name_or_json_name + .insert(f.name().to_owned(), i) + .is_some() + { + return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); + } + + if field_index.json_name != f.name() { + if index_by_name_or_json_name + .insert(field_index.json_name.clone(), i) + .is_some() + { + return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); + } + } + } + + for ext in proto.flat_map_slice(|m| &m.extension) { + fields.push(FieldIndex::index(Some(message_index), ext, building)?); + } + + let extension_count = proto.extension.len(); + + Ok(MessageFieldIndices { + first_field_index, + field_count, + extension_count, + field_index_by_name: index_by_name, + field_index_by_name_or_json_name: index_by_name_or_json_name, + field_index_by_number: index_by_number, + }) + } +} diff --git a/src/reflect/file/mod.rs b/src/reflect/file/mod.rs new file mode 100644 index 0000000..068840b --- /dev/null +++ b/src/reflect/file/mod.rs @@ -0,0 +1,283 @@ +use std::collections::HashSet; +use std::hash::Hash; +use std::hash::Hasher; +use std::sync::Arc; + +use crate::descriptor::DescriptorProto; +use crate::descriptor::FileDescriptorProto; +use crate::reflect::file::dynamic::DynamicFileDescriptor; +use crate::reflect::file::fds::build_fds; +use crate::reflect::file::index::EnumIndices; +use crate::reflect::file::index::FileDescriptorCommon; +use crate::reflect::file::index::MessageIndices; +use crate::reflect::name::protobuf_name_starts_with_package; +use crate::reflect::service::ServiceDescriptor; +use crate::reflect::EnumDescriptor; +use crate::reflect::FieldDescriptor; +use crate::reflect::GeneratedFileDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::Syntax; + +pub(crate) mod building; +pub(crate) mod dynamic; +pub(crate) mod fds; +pub(crate) mod generated; +pub(crate) mod index; +pub(crate) mod syntax; + +#[derive(Clone, Debug)] +pub(crate) enum FileDescriptorImpl { + Generated(&'static GeneratedFileDescriptor), + Dynamic(Arc<DynamicFileDescriptor>), +} + +impl PartialEq for FileDescriptorImpl { + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (FileDescriptorImpl::Generated(a), FileDescriptorImpl::Generated(b)) => { + *a as *const GeneratedFileDescriptor == *b as *const GeneratedFileDescriptor + } + (FileDescriptorImpl::Dynamic(a), FileDescriptorImpl::Dynamic(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +impl Hash for FileDescriptorImpl { + fn hash<H: Hasher>(&self, state: &mut H) { + match self { + FileDescriptorImpl::Generated(g) => { + Hash::hash(&(*g as *const GeneratedFileDescriptor), state) + } + FileDescriptorImpl::Dynamic(a) => { + Hash::hash(&(&**a as *const DynamicFileDescriptor), state) + } + } + } +} + +impl Eq for FileDescriptorImpl {} + +/// Reflection for objects defined in `.proto` file (messages, enums, etc). +/// +/// The object is refcounted: clone is shallow. +/// +/// The equality performs pointer comparison: two clones of the same `FileDescriptor` +/// objects are equal, but two `FileDescriptor` objects created from the same `FileDescriptorProto` +/// objects are **not** equal. +#[derive(Clone, PartialEq, Eq, Hash, Debug)] +pub struct FileDescriptor { + pub(crate) imp: FileDescriptorImpl, +} + +impl FileDescriptor { + pub(crate) fn common(&self) -> &FileDescriptorCommon { + match &self.imp { + FileDescriptorImpl::Generated(g) => &g.common, + FileDescriptorImpl::Dynamic(d) => &d.common, + } + } + + /// Same as `common`, but returns `&'static`. + pub(crate) fn common_for_generated_descriptor(&self) -> &'static FileDescriptorCommon { + match &self.imp { + FileDescriptorImpl::Generated(g) => &g.common, + FileDescriptorImpl::Dynamic(..) => panic!("not generated"), + } + } + + pub(crate) fn message_indices(&self, index: usize) -> &MessageIndices { + &self.common().messages[index] + } + + pub(crate) fn message_by_index(&self, index: usize) -> MessageDescriptor { + MessageDescriptor { + file_descriptor: self.clone(), + index, + } + } + + pub(crate) fn message_proto_by_index(&self, index: usize) -> &DescriptorProto { + &self.common().messages[index].proto + } + + pub(crate) fn enum_indices(&self, index: usize) -> &EnumIndices { + &self.common().enums[index] + } + + /// The file name. + pub fn name(&self) -> &str { + self.proto().name() + } + + /// Protobuf package. + pub fn package(&self) -> &str { + self.proto().package() + } + + /// Syntax of current file. + pub fn syntax(&self) -> Syntax { + Syntax::parse(self.proto().syntax()).unwrap_or(Syntax::Proto2) + } + + /// Top-level messages. + pub fn messages(&self) -> impl Iterator<Item = MessageDescriptor> + '_ { + self.common() + .top_level_messages + .iter() + .map(|i| MessageDescriptor::new(self.clone(), *i)) + } + + /// Get top-level enums. + pub fn enums(&self) -> impl Iterator<Item = EnumDescriptor> + '_ { + self.proto() + .enum_type + .iter() + .enumerate() + .map(|(i, _)| EnumDescriptor::new(self.clone(), i)) + } + + /// Get services defined in `.proto` file. + pub fn services(&self) -> impl Iterator<Item = ServiceDescriptor> + '_ { + self.proto() + .service + .iter() + .enumerate() + .map(|(i, _)| ServiceDescriptor::new(self.clone(), i)) + } + + /// Extension fields. + pub fn extensions(&self) -> impl Iterator<Item = FieldDescriptor> + '_ { + self.common() + .extension_field_range() + .map(move |index| FieldDescriptor { + file_descriptor: self.clone(), + index, + }) + } + + /// Find message by name relative to the package. + /// + /// Only search in the current file, not in any dependencies. + pub fn message_by_package_relative_name(&self, name: &str) -> Option<MessageDescriptor> { + self.common() + .message_by_name_to_package + .get(name) + .map(|&index| MessageDescriptor::new(self.clone(), index)) + } + + /// Find message by name relative to the package. + /// + /// Only search in the current file, not in any dependencies. + pub fn enum_by_package_relative_name(&self, name: &str) -> Option<EnumDescriptor> { + self.common() + .enums_by_name_to_package + .get(name) + .map(|&index| EnumDescriptor::new(self.clone(), index)) + } + + /// Find message by fully-qualified name. + /// + /// Only search in the current file, not in any dependencies. + pub fn message_by_full_name(&self, name: &str) -> Option<MessageDescriptor> { + if let Some(name_to_package) = + protobuf_name_starts_with_package(name, self.proto().package()) + { + self.message_by_package_relative_name(name_to_package) + } else { + None + } + } + + /// Find enum by name fully-qualified name. + /// + /// Only search in the current file, not in any dependencies. + pub fn enum_by_full_name(&self, name: &str) -> Option<EnumDescriptor> { + if let Some(name_to_package) = + protobuf_name_starts_with_package(name, self.proto().package()) + { + self.enum_by_package_relative_name(name_to_package) + } else { + None + } + } + + /// This function is called from generated code, it is not stable, and should not be called. + #[doc(hidden)] + pub fn new_generated_2(generated: &'static GeneratedFileDescriptor) -> FileDescriptor { + FileDescriptor { + imp: FileDescriptorImpl::Generated(generated), + } + } + + /// Dynamic message created from [`FileDescriptorProto`] without generated files. + pub fn new_dynamic( + proto: FileDescriptorProto, + dependencies: &[FileDescriptor], + ) -> crate::Result<FileDescriptor> { + Ok(FileDescriptor { + imp: FileDescriptorImpl::Dynamic(Arc::new(DynamicFileDescriptor::new( + proto, + dependencies, + )?)), + }) + } + + /// Create a set of file descriptors from individual file descriptors. + pub fn new_dynamic_fds( + protos: Vec<FileDescriptorProto>, + dependencies: &[FileDescriptor], + ) -> crate::Result<Vec<FileDescriptor>> { + build_fds(protos, dependencies) + } + + /// `.proto` data for this file. + pub fn proto(&self) -> &FileDescriptorProto { + match &self.imp { + FileDescriptorImpl::Generated(g) => &g.proto, + FileDescriptorImpl::Dynamic(d) => &d.proto, + } + } + + /// Direct dependencies of this file. + pub fn deps(&self) -> &[FileDescriptor] { + &self.common().dependencies + } + + /// Subset of dependencies which are public + pub fn public_deps(&self) -> impl Iterator<Item = FileDescriptor> + '_ { + self.proto() + .public_dependency + .iter() + .map(|&i| self.deps()[i as usize].clone()) + } + + fn _all_files(&self) -> Vec<&FileDescriptor> { + let mut r = Vec::new(); + let mut visited = HashSet::new(); + + let mut stack = Vec::new(); + stack.push(self); + while let Some(file) = stack.pop() { + if !visited.insert(file) { + continue; + } + + r.push(file); + stack.extend(file.deps()); + } + + r + } +} + +#[cfg(test)] +mod test { + use crate::descriptor; + + #[test] + #[cfg_attr(miri, ignore)] + fn eq() { + assert!(descriptor::file_descriptor() == &descriptor::file_descriptor().clone()); + } +} diff --git a/src/reflect/file/syntax.rs b/src/reflect/file/syntax.rs new file mode 100644 index 0000000..a1b4bd0 --- /dev/null +++ b/src/reflect/file/syntax.rs @@ -0,0 +1,24 @@ +use crate::descriptor::FileDescriptorProto; + +/// `.proto` file syntax. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub enum Syntax { + /// `syntax = "proto2"`. + Proto2, + /// `syntax = "proto3"`. + Proto3, +} + +impl Syntax { + pub(crate) fn parse(syntax: &str) -> Option<Syntax> { + match syntax { + "" | "proto2" => Some(Syntax::Proto2), + "proto3" => Some(Syntax::Proto3), + _ => None, + } + } + + pub(crate) fn of_file(file: &FileDescriptorProto) -> Syntax { + Syntax::parse(file.syntax()).unwrap_or(Syntax::Proto2) + } +} diff --git a/src/reflect/find_message_or_enum.rs b/src/reflect/find_message_or_enum.rs index 7ee3915..32d69d5 100644 --- a/src/reflect/find_message_or_enum.rs +++ b/src/reflect/find_message_or_enum.rs @@ -11,12 +11,12 @@ impl<'a> MessageOrEnum<'a> { fn from_two_options( m: Option<&'a DescriptorProto>, e: Option<&'a EnumDescriptorProto>, - ) -> MessageOrEnum<'a> { + ) -> Option<MessageOrEnum<'a>> { match (m, e) { (Some(_), Some(_)) => panic!("enum and message with the same name"), - (Some(m), None) => MessageOrEnum::Message(m), - (None, Some(e)) => MessageOrEnum::Enum(e), - (None, None) => panic!("not found"), + (Some(m), None) => Some(MessageOrEnum::Message(m)), + (None, Some(e)) => Some(MessageOrEnum::Enum(e)), + (None, None) => None, } } } @@ -24,17 +24,17 @@ impl<'a> MessageOrEnum<'a> { pub(crate) fn find_message_or_enum<'a>( file: &'a FileDescriptorProto, name_to_package: &str, -) -> (String, MessageOrEnum<'a>) { +) -> Option<(String, MessageOrEnum<'a>)> { + assert!(!name_to_package.starts_with(".")); + assert!(!name_to_package.is_empty()); + let mut path = name_to_package.split('.'); let first = path.next().unwrap(); - let child_message = file - .get_message_type() - .iter() - .find(|m| m.get_name() == first); - let child_enum = file.get_enum_type().iter().find(|e| e.get_name() == first); + let child_message = file.message_type.iter().find(|m| m.name() == first); + let child_enum = file.enum_type.iter().find(|e| e.name() == first); let mut package_to_name = String::new(); - let mut me = MessageOrEnum::from_two_options(child_message, child_enum); + let mut me = MessageOrEnum::from_two_options(child_message, child_enum)?; for name in path { let message = match me { @@ -45,18 +45,12 @@ pub(crate) fn find_message_or_enum<'a>( if !package_to_name.is_empty() { package_to_name.push_str("."); } - package_to_name.push_str(message.get_name()); - - let child_message = message - .get_nested_type() - .iter() - .find(|m| m.get_name() == name); - let child_enum = message - .get_enum_type() - .iter() - .find(|e| e.get_name() == name); - me = MessageOrEnum::from_two_options(child_message, child_enum) + package_to_name.push_str(message.name()); + + let child_message = message.nested_type.iter().find(|m| m.name() == name); + let child_enum = message.enum_type.iter().find(|e| e.name() == name); + me = MessageOrEnum::from_two_options(child_message, child_enum)?; } - (package_to_name, me) + Some((package_to_name, me)) } diff --git a/src/reflect/map.rs b/src/reflect/map.rs deleted file mode 100644 index c6aff60..0000000 --- a/src/reflect/map.rs +++ /dev/null @@ -1,66 +0,0 @@ -use std::collections::hash_map; -use std::collections::HashMap; -use std::hash::Hash; - -use super::value::ProtobufValue; - -/// Implemented for `HashMap` with appropriate keys and values -pub trait ReflectMap: 'static { - fn reflect_iter(&self) -> ReflectMapIter; - - fn len(&self) -> usize; -} - -impl<K: ProtobufValue + Eq + Hash + 'static, V: ProtobufValue + 'static> ReflectMap - for HashMap<K, V> -{ - fn reflect_iter<'a>(&'a self) -> ReflectMapIter<'a> { - ReflectMapIter { - imp: Box::new(ReflectMapIterImpl::<'a, K, V> { iter: self.iter() }), - } - } - - fn len(&self) -> usize { - HashMap::len(self) - } -} - -trait ReflectMapIterTrait<'a> { - fn next(&mut self) -> Option<(&'a dyn ProtobufValue, &'a dyn ProtobufValue)>; -} - -struct ReflectMapIterImpl<'a, K: Eq + Hash + 'static, V: 'static> { - iter: hash_map::Iter<'a, K, V>, -} - -impl<'a, K: ProtobufValue + Eq + Hash + 'static, V: ProtobufValue + 'static> ReflectMapIterTrait<'a> - for ReflectMapIterImpl<'a, K, V> -{ - fn next(&mut self) -> Option<(&'a dyn ProtobufValue, &'a dyn ProtobufValue)> { - match self.iter.next() { - Some((k, v)) => Some((k as &dyn ProtobufValue, v as &dyn ProtobufValue)), - None => None, - } - } -} - -pub struct ReflectMapIter<'a> { - imp: Box<dyn ReflectMapIterTrait<'a> + 'a>, -} - -impl<'a> Iterator for ReflectMapIter<'a> { - type Item = (&'a dyn ProtobufValue, &'a dyn ProtobufValue); - - fn next(&mut self) -> Option<(&'a dyn ProtobufValue, &'a dyn ProtobufValue)> { - self.imp.next() - } -} - -impl<'a> IntoIterator for &'a dyn ReflectMap { - type IntoIter = ReflectMapIter<'a>; - type Item = (&'a dyn ProtobufValue, &'a dyn ProtobufValue); - - fn into_iter(self) -> Self::IntoIter { - self.reflect_iter() - } -} diff --git a/src/reflect/map/empty.rs b/src/reflect/map/empty.rs new file mode 100644 index 0000000..5ac908d --- /dev/null +++ b/src/reflect/map/empty.rs @@ -0,0 +1,73 @@ +use std::fmt; + +use crate::reflect::map::ReflectMapIter; +use crate::reflect::map::ReflectMapIterTrait; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +#[derive(Clone)] +pub(crate) struct DynamicEmptyMap { + key_type: RuntimeType, + value_type: RuntimeType, +} + +impl DynamicEmptyMap { + pub(crate) fn new(key_type: RuntimeType, value_type: RuntimeType) -> DynamicEmptyMap { + Self { + key_type, + value_type, + } + } + + pub(crate) fn len(&self) -> usize { + 0 + } + + pub(crate) fn is_empty(&self) -> bool { + true + } + + pub(crate) fn get<'a>(&'a self, _key: ReflectValueRef) -> Option<ReflectValueRef<'a>> { + None + } + + pub(crate) fn key_type(&self) -> RuntimeType { + self.key_type.clone() + } + + pub(crate) fn value_type(&self) -> RuntimeType { + self.value_type.clone() + } + + pub(crate) fn reflect_iter(&self) -> ReflectMapIter { + ReflectMapIter::new(DynamicEmptyMapIter { + key_type: self.key_type.clone(), + value_type: self.value_type.clone(), + }) + } +} + +impl fmt::Debug for DynamicEmptyMap { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_map().finish() + } +} + +struct DynamicEmptyMapIter { + key_type: RuntimeType, + value_type: RuntimeType, +} + +impl<'a> ReflectMapIterTrait<'a> for DynamicEmptyMapIter { + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { + None + } + + fn key_type(&self) -> RuntimeType { + self.key_type.clone() + } + + fn value_type(&self) -> RuntimeType { + self.value_type.clone() + } +} diff --git a/src/reflect/map/generated.rs b/src/reflect/map/generated.rs new file mode 100644 index 0000000..ccece69 --- /dev/null +++ b/src/reflect/map/generated.rs @@ -0,0 +1,77 @@ +use std::collections::hash_map; +use std::collections::HashMap; +use std::hash::Hash; + +use crate::reflect::map::ReflectMap; +use crate::reflect::map::ReflectMapIter; +use crate::reflect::map::ReflectMapIterTrait; +use crate::reflect::runtime_types::RuntimeTypeHashable; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +impl<K, V> ReflectMap for HashMap<K, V> +where + K: ProtobufValue + Eq + Hash, + V: ProtobufValue, + K::RuntimeType: RuntimeTypeHashable, +{ + fn reflect_iter<'a>(&'a self) -> ReflectMapIter<'a> { + ReflectMapIter::new(GeneratedMapIterImpl::<'a, K, V> { iter: self.iter() }) + } + + fn len(&self) -> usize { + HashMap::len(self) + } + + fn is_empty(&self) -> bool { + self.is_empty() + } + + fn get<'a>(&'a self, key: ReflectValueRef) -> Option<ReflectValueRef<'a>> { + <K::RuntimeType as RuntimeTypeHashable>::hash_map_get(self, key).map(V::RuntimeType::as_ref) + } + + fn insert(&mut self, key: ReflectValueBox, value: ReflectValueBox) { + let key: K = key.downcast().expect("wrong key type"); + let value: V = value.downcast().expect("wrong value type"); + self.insert(key, value); + } + + fn clear(&mut self) { + self.clear(); + } + + fn key_type(&self) -> RuntimeType { + K::RuntimeType::runtime_type_box() + } + + fn value_type(&self) -> RuntimeType { + V::RuntimeType::runtime_type_box() + } +} + +struct GeneratedMapIterImpl<'a, K: Eq + Hash + 'static, V: 'static> { + iter: hash_map::Iter<'a, K, V>, +} + +impl<'a, K: ProtobufValue + Eq + Hash, V: ProtobufValue> ReflectMapIterTrait<'a> + for GeneratedMapIterImpl<'a, K, V> +{ + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { + match self.iter.next() { + Some((k, v)) => Some((K::RuntimeType::as_ref(k), V::RuntimeType::as_ref(v))), + None => None, + } + } + + fn key_type(&self) -> RuntimeType { + K::RuntimeType::runtime_type_box() + } + + fn value_type(&self) -> RuntimeType { + V::RuntimeType::runtime_type_box() + } +} diff --git a/src/reflect/map/mod.rs b/src/reflect/map/mod.rs new file mode 100644 index 0000000..5ec3fd8 --- /dev/null +++ b/src/reflect/map/mod.rs @@ -0,0 +1,281 @@ +use std::fmt; +use std::fmt::Debug; +use std::fmt::Formatter; + +use crate::reflect::map::empty::DynamicEmptyMap; +use crate::reflect::reflect_eq::ReflectEq; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +mod empty; +mod generated; + +/// Implemented for `HashMap` with appropriate keys and values +pub(crate) trait ReflectMap: Debug + Send + Sync + 'static { + fn reflect_iter(&self) -> ReflectMapIter; + + fn len(&self) -> usize; + + fn is_empty(&self) -> bool; + + fn get<'a>(&'a self, key: ReflectValueRef) -> Option<ReflectValueRef<'a>>; + + fn insert(&mut self, key: ReflectValueBox, value: ReflectValueBox); + + fn clear(&mut self); + + fn key_type(&self) -> RuntimeType; + + fn value_type(&self) -> RuntimeType; +} + +pub(crate) trait ReflectMapIterTrait<'a> { + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)>; + fn key_type(&self) -> RuntimeType; + fn value_type(&self) -> RuntimeType; +} + +pub struct ReflectMapIter<'a> { + imp: Box<dyn ReflectMapIterTrait<'a> + 'a>, +} + +impl<'a> ReflectMapIter<'a> { + pub(crate) fn new<I: ReflectMapIterTrait<'a> + 'a>(imp: I) -> ReflectMapIter<'a> { + ReflectMapIter { imp: Box::new(imp) } + } +} + +impl<'a> Iterator for ReflectMapIter<'a> { + type Item = (ReflectValueRef<'a>, ReflectValueRef<'a>); + + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { + self.imp.next() + } +} + +impl<'a> IntoIterator for &'a dyn ReflectMap { + type Item = (ReflectValueRef<'a>, ReflectValueRef<'a>); + type IntoIter = ReflectMapIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.reflect_iter() + } +} + +#[derive(Clone)] +enum ReflectMapRefImpl<'a> { + Generated(&'a dyn ReflectMap), + DynamicEmpty(DynamicEmptyMap), +} + +impl<'a> fmt::Debug for ReflectMapRefImpl<'a> { + fn fmt(&self, f: &mut Formatter) -> fmt::Result { + match self { + ReflectMapRefImpl::Generated(m) => fmt::Debug::fmt(m, f), + ReflectMapRefImpl::DynamicEmpty(m) => fmt::Debug::fmt(m, f), + } + } +} + +/// Dynamic reference to `map` field +#[derive(Clone)] +pub struct ReflectMapRef<'a> { + imp: ReflectMapRefImpl<'a>, +} + +/// Dynamic mutable reference to `map` field +pub struct ReflectMapMut<'a> { + map: &'a mut dyn ReflectMap, +} + +impl<'a> fmt::Debug for ReflectMapRef<'a> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.imp, f) + } +} + +impl<'a> fmt::Debug for ReflectMapMut<'a> { + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.map, f) + } +} + +impl<'a> ReflectMapRef<'a> { + pub(crate) fn new(map: &'a dyn ReflectMap) -> ReflectMapRef<'a> { + ReflectMapRef { + imp: ReflectMapRefImpl::Generated(map), + } + } + + pub(crate) fn new_empty(key: RuntimeType, value: RuntimeType) -> ReflectMapRef<'a> { + ReflectMapRef { + imp: ReflectMapRefImpl::DynamicEmpty(DynamicEmptyMap::new(key, value)), + } + } + + /// Size of the map + pub fn len(&self) -> usize { + match &self.imp { + ReflectMapRefImpl::Generated(map) => map.len(), + ReflectMapRefImpl::DynamicEmpty(map) => map.len(), + } + } + + /// Is map empty? + pub fn is_empty(&self) -> bool { + match &self.imp { + ReflectMapRefImpl::Generated(map) => map.is_empty(), + ReflectMapRefImpl::DynamicEmpty(map) => map.is_empty(), + } + } + + /// Find a value by given key. + pub fn get(&self, key: ReflectValueRef) -> Option<ReflectValueRef> { + match &self.imp { + ReflectMapRefImpl::Generated(map) => map.get(key), + ReflectMapRefImpl::DynamicEmpty(map) => map.get(key), + } + } + + /// Map key type + pub fn key_type(&self) -> RuntimeType { + match &self.imp { + ReflectMapRefImpl::Generated(map) => map.key_type(), + ReflectMapRefImpl::DynamicEmpty(map) => map.key_type(), + } + } + + /// Map value type + pub fn value_type(&self) -> RuntimeType { + match &self.imp { + ReflectMapRefImpl::Generated(map) => map.value_type(), + ReflectMapRefImpl::DynamicEmpty(map) => map.value_type(), + } + } +} + +impl<'a> PartialEq for ReflectMapRef<'a> { + fn eq(&self, other: &Self) -> bool { + self.reflect_eq(other, &ReflectEqMode::default()) + } +} + +impl<'a> ReflectEq for ReflectMapRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + let len = self.len(); + + if len != that.len() { + return false; + } + + if self.key_type() != that.key_type() { + return false; + } + if self.value_type() != that.value_type() { + return false; + } + + for (k, va) in self { + let vb = match that.get(k) { + Some(v) => v, + None => return false, + }; + + if !va.reflect_eq(&vb, mode) { + return false; + } + } + + true + } +} + +impl<'a> ReflectMapMut<'a> { + pub(crate) fn new(map: &'a mut dyn ReflectMap) -> ReflectMapMut<'a> { + ReflectMapMut { map } + } + + fn as_ref(&'a self) -> ReflectMapRef<'a> { + ReflectMapRef::new(self.map) + } + + /// Map key type + pub fn key_type(&self) -> RuntimeType { + self.map.key_type() + } + + /// Map value type + pub fn value_type(&self) -> RuntimeType { + self.map.value_type() + } + + /// Number of map entries + pub fn len(&self) -> usize { + self.as_ref().len() + } + + /// Is this map empty? + pub fn is_empty(&self) -> bool { + self.as_ref().is_empty() + } + + /// Find a value for given key + pub fn get(&self, key: ReflectValueRef) -> Option<ReflectValueRef> { + self.map.get(key) + } + + /// Insert a value into the map. + /// + /// # Panics + /// + /// If given key has an incompatible key type. + pub fn insert(&mut self, key: ReflectValueBox, value: ReflectValueBox) { + self.map.insert(key, value) + } + + /// Clear + pub fn clear(&mut self) { + self.map.clear(); + } +} + +/// Iterator over map +pub struct ReflectMapRefIter<'a> { + iter: ReflectMapIter<'a>, +} + +impl<'a> ReflectMapRefIter<'a> { + fn _key_type(&self) -> RuntimeType { + self.iter.imp.key_type() + } + + fn _value_type(&self) -> RuntimeType { + self.iter.imp.value_type() + } +} + +impl<'a> Iterator for ReflectMapRefIter<'a> { + type Item = (ReflectValueRef<'a>, ReflectValueRef<'a>); + + fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { + self.iter.next() + } +} + +impl<'a, 'b: 'a> IntoIterator for &'b ReflectMapRef<'a> { + type Item = (ReflectValueRef<'a>, ReflectValueRef<'a>); + type IntoIter = ReflectMapRefIter<'a>; + + fn into_iter(self) -> ReflectMapRefIter<'a> { + match &self.imp { + ReflectMapRefImpl::Generated(map) => ReflectMapRefIter { + iter: map.reflect_iter(), + }, + ReflectMapRefImpl::DynamicEmpty(map) => ReflectMapRefIter { + iter: map.reflect_iter(), + }, + } + } +} diff --git a/src/reflect/message.rs b/src/reflect/message.rs deleted file mode 100644 index 0db9821..0000000 --- a/src/reflect/message.rs +++ /dev/null @@ -1,282 +0,0 @@ -use std::collections::HashMap; -use std::marker; - -use crate::descriptor::DescriptorProto; -use crate::descriptor::FileDescriptorProto; -use crate::descriptorx::find_message_by_rust_name; -use crate::reflect::acc::FieldAccessor; -use crate::reflect::find_message_or_enum::find_message_or_enum; -use crate::reflect::find_message_or_enum::MessageOrEnum; -use crate::reflect::FieldDescriptor; -use crate::Message; - -trait MessageFactory: Send + Sync + 'static { - fn new_instance(&self) -> Box<dyn Message>; -} - -struct MessageFactoryImpl<M>(marker::PhantomData<M>); - -impl<M> MessageFactory for MessageFactoryImpl<M> -where - M: 'static + Message + Default + Clone + PartialEq, -{ - fn new_instance(&self) -> Box<dyn Message> { - let m: M = Default::default(); - Box::new(m) - } -} - -/// Dynamic message type -pub struct MessageDescriptor { - full_name: String, - proto: &'static DescriptorProto, - factory: &'static dyn MessageFactory, - fields: Vec<FieldDescriptor>, - - index_by_name: HashMap<String, usize>, - index_by_name_or_json_name: HashMap<String, usize>, - index_by_number: HashMap<u32, usize>, -} - -impl MessageDescriptor { - /// Get underlying `DescriptorProto` object. - pub fn get_proto(&self) -> &DescriptorProto { - self.proto - } - - /// Get a message descriptor for given message type - pub fn for_type<M: Message>() -> &'static MessageDescriptor { - M::descriptor_static() - } - - fn compute_full_name(package: &str, path_to_package: &str, proto: &DescriptorProto) -> String { - let mut full_name = package.to_owned(); - if path_to_package.len() != 0 { - if full_name.len() != 0 { - full_name.push('.'); - } - full_name.push_str(path_to_package); - } - if full_name.len() != 0 { - full_name.push('.'); - } - full_name.push_str(proto.get_name()); - full_name - } - - // Non-generic part of `new` is a separate function - // to reduce code bloat from multiple instantiations. - fn new_non_generic_by_rust_name( - rust_name: &'static str, - fields: Vec<FieldAccessor>, - file: &'static FileDescriptorProto, - factory: &'static dyn MessageFactory, - ) -> MessageDescriptor { - let proto = find_message_by_rust_name(file, rust_name); - - let mut field_proto_by_name = HashMap::new(); - for field_proto in proto.message.get_field() { - field_proto_by_name.insert(field_proto.get_name(), field_proto); - } - - let mut index_by_name = HashMap::new(); - let mut index_by_name_or_json_name = HashMap::new(); - let mut index_by_number = HashMap::new(); - - let mut full_name = file.get_package().to_string(); - if full_name.len() > 0 { - full_name.push('.'); - } - full_name.push_str(proto.message.get_name()); - - let fields: Vec<_> = fields - .into_iter() - .map(|f| { - let proto = *field_proto_by_name.get(&f.name).unwrap(); - FieldDescriptor::new(f, proto) - }) - .collect(); - for (i, f) in fields.iter().enumerate() { - assert!(index_by_number - .insert(f.proto().get_number() as u32, i) - .is_none()); - assert!(index_by_name - .insert(f.proto().get_name().to_owned(), i) - .is_none()); - assert!(index_by_name_or_json_name - .insert(f.proto().get_name().to_owned(), i) - .is_none()); - - let json_name = f.json_name().to_owned(); - - if json_name != f.proto().get_name() { - assert!(index_by_name_or_json_name.insert(json_name, i).is_none()); - } - } - MessageDescriptor { - full_name, - proto: proto.message, - factory, - fields, - index_by_name, - index_by_name_or_json_name, - index_by_number, - } - } - - // Non-generic part of `new` is a separate function - // to reduce code bloat from multiple instantiations. - fn new_non_generic_by_pb_name( - protobuf_name_to_package: &'static str, - fields: Vec<FieldAccessor>, - file_descriptor_proto: &'static FileDescriptorProto, - factory: &'static dyn MessageFactory, - ) -> MessageDescriptor { - let (path_to_package, proto) = - match find_message_or_enum(file_descriptor_proto, protobuf_name_to_package) { - (path_to_package, MessageOrEnum::Message(m)) => (path_to_package, m), - (_, MessageOrEnum::Enum(_)) => panic!("not a message"), - }; - - let mut field_proto_by_name = HashMap::new(); - for field_proto in proto.get_field() { - field_proto_by_name.insert(field_proto.get_name(), field_proto); - } - - let mut index_by_name = HashMap::new(); - let mut index_by_name_or_json_name = HashMap::new(); - let mut index_by_number = HashMap::new(); - - let full_name = MessageDescriptor::compute_full_name( - file_descriptor_proto.get_package(), - &path_to_package, - &proto, - ); - let fields: Vec<_> = fields - .into_iter() - .map(|f| { - let proto = *field_proto_by_name.get(&f.name).unwrap(); - FieldDescriptor::new(f, proto) - }) - .collect(); - - for (i, f) in fields.iter().enumerate() { - assert!(index_by_number - .insert(f.proto().get_number() as u32, i) - .is_none()); - assert!(index_by_name - .insert(f.proto().get_name().to_owned(), i) - .is_none()); - assert!(index_by_name_or_json_name - .insert(f.proto().get_name().to_owned(), i) - .is_none()); - - let json_name = f.json_name().to_owned(); - - if json_name != f.proto().get_name() { - assert!(index_by_name_or_json_name.insert(json_name, i).is_none()); - } - } - MessageDescriptor { - full_name, - proto, - factory, - fields, - index_by_name, - index_by_name_or_json_name, - index_by_number, - } - } - - /// Construct a new message descriptor. - /// - /// This operation is called from generated code and rarely - /// need to be called directly. - #[doc(hidden)] - #[deprecated( - since = "2.12", - note = "Please regenerate .rs files from .proto files to use newer APIs" - )] - pub fn new<M: 'static + Message + Default + Clone + PartialEq>( - rust_name: &'static str, - fields: Vec<FieldAccessor>, - file: &'static FileDescriptorProto, - ) -> MessageDescriptor { - let factory = &MessageFactoryImpl(marker::PhantomData::<M>); - MessageDescriptor::new_non_generic_by_rust_name(rust_name, fields, file, factory) - } - - /// Construct a new message descriptor. - /// - /// This operation is called from generated code and rarely - /// need to be called directly. - #[doc(hidden)] - pub fn new_pb_name<M: 'static + Message + Default + Clone + PartialEq>( - protobuf_name_to_package: &'static str, - fields: Vec<FieldAccessor>, - file_descriptor_proto: &'static FileDescriptorProto, - ) -> MessageDescriptor { - let factory = &MessageFactoryImpl(marker::PhantomData::<M>); - MessageDescriptor::new_non_generic_by_pb_name( - protobuf_name_to_package, - fields, - file_descriptor_proto, - factory, - ) - } - - /// New empty message - pub fn new_instance(&self) -> Box<dyn Message> { - self.factory.new_instance() - } - - /// Message name as given in `.proto` file - pub fn name(&self) -> &'static str { - self.proto.get_name() - } - - /// Fully qualified protobuf message name - pub fn full_name(&self) -> &str { - &self.full_name[..] - } - - /// Message field descriptors. - pub fn fields(&self) -> &[FieldDescriptor] { - &self.fields - } - - /// Find message field by protobuf field name - /// - /// Note: protobuf field name might be different for Rust field name. - pub fn get_field_by_name<'a>(&'a self, name: &str) -> Option<&'a FieldDescriptor> { - let &index = self.index_by_name.get(name)?; - Some(&self.fields[index]) - } - - /// Find message field by field name or field JSON name - pub fn get_field_by_name_or_json_name<'a>(&'a self, name: &str) -> Option<&'a FieldDescriptor> { - let &index = self.index_by_name_or_json_name.get(name)?; - Some(&self.fields[index]) - } - - /// Find message field by field name - pub fn get_field_by_number(&self, number: u32) -> Option<&FieldDescriptor> { - let &index = self.index_by_number.get(&number)?; - Some(&self.fields[index]) - } - - /// Find field by name - // TODO: deprecate - pub fn field_by_name<'a>(&'a self, name: &str) -> &'a FieldDescriptor { - // TODO: clone is weird - let &index = self.index_by_name.get(&name.to_string()).unwrap(); - &self.fields[index] - } - - /// Find field by number - // TODO: deprecate - pub fn field_by_number<'a>(&'a self, number: u32) -> &'a FieldDescriptor { - let &index = self.index_by_number.get(&number).unwrap(); - &self.fields[index] - } -} diff --git a/src/reflect/message/generated.rs b/src/reflect/message/generated.rs new file mode 100644 index 0000000..45e3ded --- /dev/null +++ b/src/reflect/message/generated.rs @@ -0,0 +1,135 @@ +//! Generated messages reflection support. + +use std::fmt; +use std::marker; + +use crate::descriptor::FileDescriptorProto; +use crate::message_dyn::MessageDyn; +use crate::message_full::MessageFull; +use crate::reflect::acc::FieldAccessor; +use crate::reflect::file::index::FileDescriptorCommon; +use crate::reflect::find_message_or_enum::find_message_or_enum; +use crate::reflect::find_message_or_enum::MessageOrEnum; +use crate::reflect::GeneratedOneofDescriptorData; + +/// Sized to dynamic reflection operations. +pub(crate) trait MessageFactory: Send + Sync + 'static { + fn new_instance(&self) -> Box<dyn MessageDyn>; + fn default_instance(&self) -> &dyn MessageDyn; + fn clone(&self, message: &dyn MessageDyn) -> Box<dyn MessageDyn>; + fn eq(&self, a: &dyn MessageDyn, b: &dyn MessageDyn) -> bool; +} + +impl<'a> fmt::Debug for &'a dyn MessageFactory { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessageFactory").finish() + } +} + +/// The only message factory implementation. +pub(crate) struct MessageFactoryImpl<M>(pub marker::PhantomData<M>); + +impl<M> MessageFactory for MessageFactoryImpl<M> +where + M: MessageFull, +{ + fn new_instance(&self) -> Box<dyn MessageDyn> { + let m: M = Default::default(); + Box::new(m) + } + + fn default_instance(&self) -> &dyn MessageDyn { + M::default_instance() as &dyn MessageDyn + } + + fn clone(&self, message: &dyn MessageDyn) -> Box<dyn MessageDyn> { + let m: &M = message.downcast_ref().expect("wrong message type"); + Box::new(m.clone()) + } + + fn eq(&self, a: &dyn MessageDyn, b: &dyn MessageDyn) -> bool { + let a: &M = a.downcast_ref().expect("wrong message type"); + let b: &M = b.downcast_ref().expect("wrong message type"); + a == b + } +} + +#[doc(hidden)] +pub struct GeneratedMessageDescriptorData { + pub(crate) protobuf_name_to_package: &'static str, + pub(crate) fields: Vec<FieldAccessor>, + pub(crate) factory: &'static dyn MessageFactory, + pub(crate) oneofs: Vec<GeneratedOneofDescriptorData>, +} + +impl GeneratedMessageDescriptorData { + /// Construct a new message descriptor. + /// + /// This operation is called from generated code and rarely + /// need to be called directly. + /// + /// This function is not a part of public API. + #[doc(hidden)] + pub fn new_2<M: MessageFull>( + protobuf_name_to_package: &'static str, + fields: Vec<FieldAccessor>, + oneofs: Vec<GeneratedOneofDescriptorData>, + ) -> GeneratedMessageDescriptorData { + let factory = &MessageFactoryImpl(marker::PhantomData::<M>); + GeneratedMessageDescriptorData { + protobuf_name_to_package, + fields, + factory, + oneofs, + } + } +} + +#[derive(Debug)] +pub(crate) struct NonMapMessageDescriptor { + pub(crate) factory: &'static dyn MessageFactory, + + pub(crate) fields: Vec<FieldAccessor>, +} + +#[derive(Debug)] +pub(crate) struct GeneratedMessageDescriptor { + pub(crate) non_map: Option<NonMapMessageDescriptor>, +} + +impl GeneratedMessageDescriptor { + pub(crate) fn new_map_entry() -> GeneratedMessageDescriptor { + GeneratedMessageDescriptor { non_map: None } + } + + pub(crate) fn new( + data: GeneratedMessageDescriptorData, + file_descriptor_proto: &'static FileDescriptorProto, + _file_index: &FileDescriptorCommon, + ) -> GeneratedMessageDescriptor { + let GeneratedMessageDescriptorData { + protobuf_name_to_package, + fields, + factory, + oneofs: _, + } = data; + + let (_path_to_package, _proto) = + match find_message_or_enum(file_descriptor_proto, protobuf_name_to_package) { + Some((path_to_package, MessageOrEnum::Message(m))) => (path_to_package, m), + Some((_, MessageOrEnum::Enum(_))) => panic!("not a message"), + None => panic!("not found"), + }; + + GeneratedMessageDescriptor { + non_map: Some(NonMapMessageDescriptor { factory, fields }), + } + } + + pub(crate) fn non_map(&self) -> &NonMapMessageDescriptor { + match &self.non_map { + Some(non_map) => non_map, + None => panic!("map message"), + } + } +} diff --git a/src/reflect/message/is_initialized_is_always_true.rs b/src/reflect/message/is_initialized_is_always_true.rs new file mode 100644 index 0000000..e40b56d --- /dev/null +++ b/src/reflect/message/is_initialized_is_always_true.rs @@ -0,0 +1,151 @@ +use std::collections::HashMap; +use std::collections::HashSet; + +use crate::descriptor::field_descriptor_proto::Label; +use crate::descriptor::FileDescriptorProto; +use crate::reflect::field::index::FieldIndex; +use crate::reflect::field::index::ForwardProtobufFieldType; +use crate::reflect::field::index::ForwardProtobufTypeBox; +use crate::reflect::file::index::MessageIndices; +use crate::reflect::MessageDescriptor; +use crate::reflect::RuntimeType; +use crate::reflect::Syntax; + +pub(crate) fn compute_is_initialized_is_always_true( + messages: &mut [MessageIndices], + file_fields: &[FieldIndex], + file: &FileDescriptorProto, +) { + for message in messages.iter_mut() { + message.is_initialized_is_always_true = + is_initialized_is_always_true_ignoring_deps(message, file); + } + + // Map from a message to messages who include it. E.g. for: + // ``` + // 0: message A {} + // 1: message B { A a = 10; } + // ``` + // This map will contain: `{0: [1]}` + let mut rdeps: HashMap<usize, Vec<usize>> = HashMap::new(); + + for i in 0..messages.len() { + let message = &mut messages[i]; + + if !message.is_initialized_is_always_true { + continue; + } + + let mut is_initialized_is_always_true = true; + for ft in message_field_messages(message, file_fields) { + match ft { + MessageType::ThisFile(j) => { + rdeps.entry(j).or_default().push(i); + } + MessageType::OtherFile(m) => { + if !m.is_initialized_is_always_true() { + is_initialized_is_always_true = false; + } + } + } + } + message.is_initialized_is_always_true = is_initialized_is_always_true; + } + + let mut invalidated: HashSet<usize> = HashSet::new(); + let mut invalidate_stack: Vec<usize> = Vec::new(); + + for i in 0..messages.len() { + let message = &messages[i]; + if message.is_initialized_is_always_true { + continue; + } + + invalidate_stack.push(i); + } + + while let Some(i) = invalidate_stack.pop() { + if !invalidated.insert(i) { + continue; + } + + messages[i].is_initialized_is_always_true = false; + let next = rdeps.get(&i).map(|v| v.as_slice()).unwrap_or_default(); + for next in next { + invalidate_stack.push(*next); + } + } +} + +enum MessageType<'m> { + ThisFile(usize), + OtherFile(&'m MessageDescriptor), +} + +fn message_field_messages<'a>( + message: &'a MessageIndices, + file_fields: &'a [FieldIndex], +) -> impl Iterator<Item = MessageType<'a>> + 'a { + message_field_types(message, file_fields).filter_map(|f| match f { + ForwardProtobufTypeBox::ProtobufTypeBox(t) => match t.runtime() { + RuntimeType::Message(m) => Some(MessageType::OtherFile(m)), + _ => None, + }, + ForwardProtobufTypeBox::CurrentFileEnum(_) => None, + ForwardProtobufTypeBox::CurrentFileMessage(i) => Some(MessageType::ThisFile(*i)), + }) +} + +fn message_field_types<'a>( + message: &'a MessageIndices, + file_fields: &'a [FieldIndex], +) -> impl Iterator<Item = &'a ForwardProtobufTypeBox> { + enum Either<A, B> { + Left(A), + Right(B), + } + + impl<T, A: Iterator<Item = T>, B: Iterator<Item = T>> Iterator for Either<A, B> { + type Item = T; + + fn next(&mut self) -> Option<T> { + match self { + Either::Left(a) => a.next(), + Either::Right(b) => b.next(), + } + } + } + + message + .message_index + .slice_fields(file_fields) + .iter() + .flat_map(|f| match &f.field_type { + ForwardProtobufFieldType::Singular(t) => Either::Left([t].into_iter()), + ForwardProtobufFieldType::Repeated(t) => Either::Left([t].into_iter()), + ForwardProtobufFieldType::Map(k, v) => Either::Right([k, v].into_iter()), + }) +} + +fn is_initialized_is_always_true_ignoring_deps( + message: &MessageIndices, + file: &FileDescriptorProto, +) -> bool { + // Shortcut. + if Syntax::of_file(file) == Syntax::Proto3 { + return true; + } + + // We don't support extensions properly but if we did, + // extensions should have been checked for `is_initialized`. + if !message.proto.extension_range.is_empty() { + return false; + } + + for field in &message.proto.field { + if field.label() == Label::LABEL_REQUIRED { + return false; + } + } + true +} diff --git a/src/reflect/message/message_ref.rs b/src/reflect/message/message_ref.rs new file mode 100644 index 0000000..1ca5638 --- /dev/null +++ b/src/reflect/message/message_ref.rs @@ -0,0 +1,83 @@ +use std::fmt; +use std::ops::Deref; + +use crate::message_dyn::MessageDyn; +use crate::reflect::dynamic::DynamicMessage; +use crate::reflect::reflect_eq::ReflectEq; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::MessageDescriptor; +use crate::MessageFull; + +#[derive(Clone, Debug)] +enum MessageRefImpl<'a> { + Message(&'a dyn MessageDyn), + EmptyDynamic(DynamicMessage), +} + +/// Wrapper around either [`MessageFull`] reference or a container for an empty dynamic message. +#[derive(Clone, Debug)] +pub struct MessageRef<'a> { + imp: MessageRefImpl<'a>, +} + +impl<'a> fmt::Display for MessageRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self.deref(), f) + } +} + +impl<'a> From<&'a dyn MessageDyn> for MessageRef<'a> { + fn from(m: &'a dyn MessageDyn) -> Self { + MessageRef { + imp: MessageRefImpl::Message(m), + } + } +} + +impl<'a, M: MessageFull> From<&'a M> for MessageRef<'a> { + fn from(m: &'a M) -> Self { + MessageRef { + imp: MessageRefImpl::Message(m), + } + } +} + +impl<'a> ReflectEq for MessageRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + let ad = self.descriptor_dyn(); + let bd = that.descriptor_dyn(); + ad == bd && ad.reflect_eq(&**self, &**that, mode) + } +} + +impl<'a> MessageRef<'a> { + /// Wrap a message. + pub fn new(message: &'a dyn MessageDyn) -> MessageRef<'a> { + MessageRef { + imp: MessageRefImpl::Message(message), + } + } + + /// Default (empty) instance of given message type. + pub fn default_instance(message: &MessageDescriptor) -> MessageRef<'static> { + // Note we create a native generated instance for generated types + // and dynamic message for dynamic types. + match message.default_instance() { + Some(m) => MessageRef::new(m), + None => MessageRef { + imp: MessageRefImpl::EmptyDynamic(DynamicMessage::new(message.clone())), + }, + } + } +} + +impl<'a> Deref for MessageRef<'a> { + type Target = dyn MessageDyn; + + fn deref(&self) -> &dyn MessageDyn { + match &self.imp { + MessageRefImpl::Message(m) => *m, + MessageRefImpl::EmptyDynamic(e) => e, + } + } +} diff --git a/src/reflect/message/mod.rs b/src/reflect/message/mod.rs new file mode 100644 index 0000000..583fa3b --- /dev/null +++ b/src/reflect/message/mod.rs @@ -0,0 +1,380 @@ +use std::fmt; +use std::io::Read; + +use crate::descriptor::DescriptorProto; +use crate::descriptor::FileDescriptorProto; +use crate::message_dyn::MessageDyn; +use crate::message_full::MessageFull; +use crate::reflect::dynamic::DynamicMessage; +use crate::reflect::file::index::MessageIndices; +use crate::reflect::file::FileDescriptorImpl; +use crate::reflect::message::generated::GeneratedMessageDescriptor; +use crate::reflect::reflect_eq::ReflectEq; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::EnumDescriptor; +use crate::reflect::FieldDescriptor; +use crate::reflect::FileDescriptor; +use crate::reflect::OneofDescriptor; +use crate::CodedInputStream; + +pub(crate) mod generated; +pub(crate) mod is_initialized_is_always_true; +pub(crate) mod message_ref; + +/// Dynamic representation of message type. +/// +/// Used for reflection. +#[derive(Clone, Eq, PartialEq, Hash)] +pub struct MessageDescriptor { + pub(crate) file_descriptor: FileDescriptor, + pub(crate) index: usize, +} + +impl fmt::Display for MessageDescriptor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.full_name()) + } +} + +impl fmt::Debug for MessageDescriptor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("MessageDescriptor").finish_non_exhaustive() + } +} + +impl MessageDescriptor { + pub(crate) fn new(file_descriptor: FileDescriptor, index: usize) -> MessageDescriptor { + MessageDescriptor { + file_descriptor, + index, + } + } + + /// Get underlying `DescriptorProto` object. + pub fn proto(&self) -> &DescriptorProto { + self.file_descriptor.message_proto_by_index(self.index) + } + + /// Message name as specified in `.proto` file. + pub fn name(&self) -> &str { + self.proto().name() + } + + fn index_entry(&self) -> &MessageIndices { + self.file_descriptor.message_indices(self.index) + } + + /// Get a message descriptor for given message type + pub fn for_type<M: MessageFull>() -> MessageDescriptor { + M::descriptor() + } + + /// Messages declared in this messages. + pub fn nested_messages(&self) -> impl Iterator<Item = MessageDescriptor> + '_ { + self.index_entry() + .nested_messages + .iter() + .map(|i| MessageDescriptor::new(self.file_descriptor.clone(), *i)) + } + + /// Get enums declared in this message. + pub fn nested_enums(&self) -> impl Iterator<Item = EnumDescriptor> + '_ { + self.index_entry() + .nested_enums + .clone() + .map(|i| EnumDescriptor::new(self.file_descriptor.clone(), i)) + } + + /// Get a message containing this message, or `None` if this message is declared at file level. + pub fn enclosing_message(&self) -> Option<MessageDescriptor> { + self.index_entry() + .enclosing_message + .map(|i| MessageDescriptor::new(self.file_descriptor.clone(), i)) + } + + pub(crate) fn get_impl(&self) -> MessageDescriptorImplRef { + match &self.file_descriptor.imp { + FileDescriptorImpl::Generated(g) => { + MessageDescriptorImplRef::Generated(&g.messages[self.index]) + } + FileDescriptorImpl::Dynamic(..) => MessageDescriptorImplRef::Dynamic, + } + } + + /// [`FileDescriptor`] containing this message. + pub fn file_descriptor(&self) -> &FileDescriptor { + &self.file_descriptor + } + + /// `FileDescriptorProto` containg this message type + pub fn file_descriptor_proto(&self) -> &FileDescriptorProto { + self.file_descriptor().proto() + } + + /// This message descriptor is a map entry. + pub fn is_map_entry(&self) -> bool { + self.index().map_entry + } + + fn assert_not_map_entry(&self) { + assert!( + !self.is_map_entry(), + "message is map entry: {}", + self.full_name() + ); + } + + /// Message is considered always initialized. + #[doc(hidden)] + pub fn is_initialized_is_always_true(&self) -> bool { + self.index().is_initialized_is_always_true + } + + /// New empty message. + /// + /// # Panics + /// + /// If this message is a map entry message. + pub fn new_instance(&self) -> Box<dyn MessageDyn> { + self.assert_not_map_entry(); + match self.get_impl() { + MessageDescriptorImplRef::Generated(g) => g.non_map().factory.new_instance(), + MessageDescriptorImplRef::Dynamic => Box::new(DynamicMessage::new(self.clone())), + } + } + + /// Shared immutable empty message. + /// + /// Returns `None` for dynamic message. + /// + /// # Panics + /// + /// If this message is a map entry message. + pub fn default_instance(&self) -> Option<&'static dyn MessageDyn> { + self.assert_not_map_entry(); + match self.get_impl() { + MessageDescriptorImplRef::Generated(g) => Some(g.non_map().factory.default_instance()), + MessageDescriptorImplRef::Dynamic => None, + } + } + + /// Clone a message + pub(crate) fn clone_message(&self, message: &dyn MessageDyn) -> Box<dyn MessageDyn> { + assert!(&message.descriptor_dyn() == self); + match self.get_impl() { + MessageDescriptorImplRef::Generated(g) => g.non_map().factory.clone(message), + MessageDescriptorImplRef::Dynamic => { + let message: &DynamicMessage = DynamicMessage::downcast_ref(message); + Box::new(message.clone()) + } + } + } + + /// Check if two messages equal. + /// + /// # Panics + /// + /// Is any message has different type than this descriptor. + pub fn eq(&self, a: &dyn MessageDyn, b: &dyn MessageDyn) -> bool { + match self.get_impl() { + MessageDescriptorImplRef::Generated(g) => g.non_map().factory.eq(a, b), + MessageDescriptorImplRef::Dynamic => unimplemented!(), + } + } + + /// Similar to `eq`, but considers `NaN` values equal. + /// + /// # Panics + /// + /// Is any message has different type than this descriptor. + pub(crate) fn reflect_eq( + &self, + a: &dyn MessageDyn, + b: &dyn MessageDyn, + mode: &ReflectEqMode, + ) -> bool { + // Explicitly force panic even if field list is empty + assert_eq!(self, &a.descriptor_dyn()); + assert_eq!(self, &b.descriptor_dyn()); + + for field in self.fields() { + let af = field.get_reflect(a); + let bf = field.get_reflect(b); + if !af.reflect_eq(&bf, mode) { + return false; + } + } + true + } + + pub(crate) fn reflect_eq_maybe_unrelated( + a: &dyn MessageDyn, + b: &dyn MessageDyn, + mode: &ReflectEqMode, + ) -> bool { + let ad = a.descriptor_dyn(); + let bd = b.descriptor_dyn(); + ad == bd && ad.reflect_eq(a, b, mode) + } + + /// Fully qualified protobuf message name + pub fn full_name(&self) -> &str { + &self.index_entry().full_name + } + + /// Name relative to the package where the message is declared. + pub fn name_to_package(&self) -> &str { + &self.index_entry().name_to_package + } + + /// Nested oneofs including synthetic. + pub fn all_oneofs<'a>(&'a self) -> impl Iterator<Item = OneofDescriptor> + 'a { + self.index_entry() + .oneofs + .clone() + .map(move |i| OneofDescriptor { + file_descriptor: self.file_descriptor.clone(), + index: i, + }) + } + + /// Non-synthetic oneofs. + pub fn oneofs<'a>(&'a self) -> impl Iterator<Item = OneofDescriptor> + 'a { + self.all_oneofs().filter(|oneof| !oneof.is_synthetic()) + } + + /// Get message oneof by name (**not implemented**). + pub fn oneof_by_name(&self, name: &str) -> Option<OneofDescriptor> { + self.all_oneofs().find(|oneof| oneof.name() == name) + } + + /// Message field descriptors. + pub fn fields<'a>(&'a self) -> impl Iterator<Item = FieldDescriptor> + 'a { + self.index() + .message_index + .regular_field_range() + .map(move |index| FieldDescriptor { + file_descriptor: self.file_descriptor.clone(), + index, + }) + } + + /// Extension fields. + pub fn extensions(&self) -> impl Iterator<Item = FieldDescriptor> + '_ { + self.index() + .message_index + .extension_field_range() + .map(move |index| FieldDescriptor { + file_descriptor: self.file_descriptor.clone(), + index, + }) + } + + pub(crate) fn index(&self) -> &MessageIndices { + &self.file_descriptor.common().messages[self.index] + } + + pub(crate) fn field_by_index(&self, index: usize) -> FieldDescriptor { + FieldDescriptor { + file_descriptor: self.file_descriptor.clone(), + index: self.index().message_index.first_field_index + index, + } + } + + /// Find message field by protobuf field name + /// + /// Note: protobuf field name might be different for Rust field name. + // TODO: return value, not pointer, pointer is not compatible with dynamic message + pub fn field_by_name(&self, name: &str) -> Option<FieldDescriptor> { + let &index = self.index().message_index.field_index_by_name.get(name)?; + Some(self.field_by_index(index)) + } + + /// Find message field by field name or field JSON name + pub fn field_by_name_or_json_name<'a>(&'a self, name: &str) -> Option<FieldDescriptor> { + let &index = self + .index() + .message_index + .field_index_by_name_or_json_name + .get(name)?; + Some(self.field_by_index(index)) + } + + /// Find message field by field name + pub fn field_by_number(&self, number: u32) -> Option<FieldDescriptor> { + let &index = self + .index() + .message_index + .field_index_by_number + .get(&number)?; + Some(self.field_by_index(index)) + } + + /// Parse message from stream. + pub fn parse_from(&self, is: &mut CodedInputStream) -> crate::Result<Box<dyn MessageDyn>> { + let mut r = self.new_instance(); + r.merge_from_dyn(is)?; + r.check_initialized_dyn()?; + Ok(r) + } + + /// Parse message from reader. + /// Parse stops on EOF or when error encountered. + pub fn parse_from_reader(&self, reader: &mut dyn Read) -> crate::Result<Box<dyn MessageDyn>> { + let mut is = CodedInputStream::new(reader); + let r = self.parse_from(&mut is)?; + is.check_eof()?; + Ok(r) + } + + /// Parse message from byte array. + pub fn parse_from_bytes(&self, bytes: &[u8]) -> crate::Result<Box<dyn MessageDyn>> { + let mut is = CodedInputStream::from_bytes(bytes); + let r = self.parse_from(&mut is)?; + is.check_eof()?; + Ok(r) + } +} + +pub(crate) enum MessageDescriptorImplRef { + Generated(&'static GeneratedMessageDescriptor), + Dynamic, +} + +#[cfg(test)] +mod test { + use crate::descriptor::descriptor_proto::ExtensionRange; + use crate::descriptor::field_descriptor_proto::Type; + use crate::descriptor::DescriptorProto; + use crate::descriptor::FieldDescriptorProto; + use crate::EnumFull; + use crate::MessageFull; + + #[test] + #[cfg_attr(miri, ignore)] // Too slow on Miri. + fn nested_messages() { + assert!(DescriptorProto::descriptor() + .nested_messages() + .collect::<Vec<_>>() + .contains(&ExtensionRange::descriptor())); + } + + #[test] + #[cfg_attr(miri, ignore)] // Too slow on Miri. + fn nested_enums() { + assert!(FieldDescriptorProto::descriptor() + .nested_enums() + .collect::<Vec<_>>() + .contains(&Type::enum_descriptor())); + } + + #[test] + #[cfg_attr(miri, ignore)] // Too slow on Miri. + fn enclosing_message() { + assert_eq!( + Some(DescriptorProto::descriptor()), + ExtensionRange::descriptor().enclosing_message() + ); + assert_eq!(None, DescriptorProto::descriptor().enclosing_message()); + } +} diff --git a/src/reflect/mod.rs b/src/reflect/mod.rs index e120e16..c01c0e7 100644 --- a/src/reflect/mod.rs +++ b/src/reflect/mod.rs @@ -1,28 +1,75 @@ -//! Reflection implementation for protobuf types. - -use crate::message::Message; +//! # Reflection implementation for protobuf data +//! +//! ## Generated vs dynamic +//! +//! rust-protobuf supports reflection for both: +//! * generated messages (generated rust code) +//! * dynamic messages (created from arbitrary `FileDescriptorProto` without code generation) +//! +//! The API to work with these types of messages is the same. +//! +//! ## API +//! +//! The API roughly follows Google protobuf C++ and Java API. +//! Some minor adjustements are made to make code more idiomatic to rust. mod acc; -pub mod accessor; +mod dynamic; mod enums; +pub(crate) mod error; mod field; +mod file; mod find_message_or_enum; mod map; -mod message; +pub(crate) mod message; +mod oneof; mod optional; +mod protobuf_type_box; mod repeated; -mod value; +mod runtime_type_box; +mod service; +mod type_dynamic; +pub(crate) mod value; -pub use self::value::ProtobufValue; -pub use self::value::ReflectValueRef; -#[doc(hidden)] -#[deprecated(since = "2.11", note = "Use ReflectValueRef instead")] -pub use self::value::ReflectValueRef as ProtobufValueRef; +// Runtime type types are public, but not visible in public API. +pub(crate) mod runtime_types; + +pub(crate) mod types; + +pub(crate) mod reflect_eq; pub mod rt; +pub(crate) mod name; + +#[doc(hidden)] +pub use self::enums::generated::GeneratedEnumDescriptorData; pub use self::enums::EnumDescriptor; pub use self::enums::EnumValueDescriptor; +pub use self::field::runtime_field_type::RuntimeFieldType; pub use self::field::FieldDescriptor; pub use self::field::ReflectFieldRef; +#[doc(hidden)] +pub use self::file::generated::GeneratedFileDescriptor; +pub use self::file::syntax::Syntax; +pub use self::file::FileDescriptor; +pub use self::map::ReflectMapMut; +pub use self::map::ReflectMapRef; +#[doc(hidden)] +pub use self::message::generated::GeneratedMessageDescriptorData; +pub use self::message::message_ref::MessageRef; pub use self::message::MessageDescriptor; +#[doc(hidden)] +pub use self::oneof::generated::GeneratedOneofDescriptorData; +pub use self::oneof::OneofDescriptor; +pub use self::optional::ReflectOptionalRef; +pub use self::reflect_eq::ReflectEq; +pub use self::reflect_eq::ReflectEqMode; +pub use self::repeated::ReflectRepeatedMut; +pub use self::repeated::ReflectRepeatedRef; +pub use self::runtime_type_box::RuntimeType; +pub use self::service::MethodDescriptor; +pub use self::service::ServiceDescriptor; +pub use self::value::value_box::ReflectValueBox; +pub use self::value::value_ref::ReflectValueRef; +pub use self::value::ProtobufValue; diff --git a/src/reflect/name.rs b/src/reflect/name.rs new file mode 100644 index 0000000..7fd39af --- /dev/null +++ b/src/reflect/name.rs @@ -0,0 +1,53 @@ +pub(crate) fn concat_paths(a: &str, b: &str) -> String { + if a.is_empty() { + b.to_owned() + } else if b.is_empty() { + b.to_owned() + } else { + format!("{}.{}", a, b) + } +} + +pub(crate) fn protobuf_name_starts_with_package<'a>( + name: &'a str, + package: &str, +) -> Option<&'a str> { + assert!( + !package.starts_with("."), + "package must not start with dot: {}", + package + ); + + assert!( + name.starts_with("."), + "full name must start with dot: {}", + name + ); + let name = &name[1..]; + // assert!(!name.starts_with("."), "full name must not start with dot: {}", name); + + if package.is_empty() { + Some(name) + } else { + if name.starts_with(package) { + let rem = &name[package.len()..]; + if rem.starts_with(".") { + Some(&rem[1..]) + } else { + None + } + } else { + None + } + } +} + +#[test] +fn test_protobuf_name_starts_with_package() { + assert_eq!( + Some("bar"), + protobuf_name_starts_with_package(".foo.bar", "foo") + ); + assert_eq!(None, protobuf_name_starts_with_package(".foo", "foo")); + assert_eq!(Some("foo"), protobuf_name_starts_with_package(".foo", "")); +} diff --git a/src/reflect/oneof/generated.rs b/src/reflect/oneof/generated.rs new file mode 100644 index 0000000..6ed1a0b --- /dev/null +++ b/src/reflect/oneof/generated.rs @@ -0,0 +1,30 @@ +use crate::OneofFull; + +#[doc(hidden)] +pub struct GeneratedOneofDescriptorData { + pub(crate) name: &'static str, +} + +impl GeneratedOneofDescriptorData { + #[doc(hidden)] + pub fn new<O>(name: &'static str) -> GeneratedOneofDescriptorData + where + O: OneofFull, + { + GeneratedOneofDescriptorData { name } + } +} + +#[derive(Debug)] +pub(crate) struct GeneratedOneofDescriptor {} + +impl GeneratedOneofDescriptor { + /// Synthetic oneof for proto3 optional field. + pub(crate) fn new_synthetic() -> GeneratedOneofDescriptor { + GeneratedOneofDescriptor {} + } + + pub(crate) fn new(_data: &GeneratedOneofDescriptorData) -> GeneratedOneofDescriptor { + GeneratedOneofDescriptor {} + } +} diff --git a/src/reflect/oneof/mod.rs b/src/reflect/oneof/mod.rs new file mode 100644 index 0000000..6c33bd9 --- /dev/null +++ b/src/reflect/oneof/mod.rs @@ -0,0 +1,79 @@ +pub(crate) mod generated; + +use crate::descriptor::OneofDescriptorProto; +use crate::reflect::file::index::OneofIndices; +use crate::reflect::file::FileDescriptorImpl; +use crate::reflect::oneof::generated::GeneratedOneofDescriptor; +use crate::reflect::FieldDescriptor; +use crate::reflect::FileDescriptor; +use crate::reflect::MessageDescriptor; + +/// Oneof descriptor. +#[derive(Eq, PartialEq, Clone, Debug)] +pub struct OneofDescriptor { + pub(crate) file_descriptor: FileDescriptor, + pub(crate) index: usize, +} + +pub(crate) enum OneofDescriptorImplRef { + Generated(&'static GeneratedOneofDescriptor), + Dynamic, +} + +impl OneofDescriptor { + fn index_entry(&self) -> &OneofIndices { + &self.file_descriptor.common().oneofs[self.index] + } + + /// `.proto` part associated with this descriptor + pub fn proto(&self) -> &OneofDescriptorProto { + let index_entry = self.index_entry(); + let message_descriptor = self + .file_descriptor + .message_proto_by_index(index_entry.containing_message); + &message_descriptor.oneof_decl[index_entry.index_in_containing_message] + } + + /// Oneof name as specified in `.proto` file. + pub fn name(&self) -> &str { + self.proto().name() + } + + #[allow(dead_code)] + pub(crate) fn _get_impl(&self) -> OneofDescriptorImplRef { + match &self.file_descriptor.imp { + FileDescriptorImpl::Generated(g) => { + OneofDescriptorImplRef::Generated(&g.oneofs[self.index]) + } + FileDescriptorImpl::Dynamic(..) => OneofDescriptorImplRef::Dynamic, + } + } + + /// Message which contains this oneof. + pub fn containing_message(&self) -> MessageDescriptor { + MessageDescriptor { + file_descriptor: self.file_descriptor.clone(), + index: self.index_entry().containing_message, + } + } + + /// This oneof is not present in sources. + pub fn is_synthetic(&self) -> bool { + self.index_entry().synthetic + } + + /// Fully qualified name of oneof (fully qualified name of enclosing message + /// followed by oneof name). + pub fn full_name(&self) -> String { + format!("{}.{}", self.containing_message(), self.name()) + } + + /// Fields in this oneof. + pub fn fields<'a>(&'a self) -> impl Iterator<Item = FieldDescriptor> + 'a { + let message = self.containing_message(); + self.index_entry() + .fields + .iter() + .map(move |&i| message.field_by_index(i)) + } +} diff --git a/src/reflect/optional.rs b/src/reflect/optional.rs deleted file mode 100644 index f719a2c..0000000 --- a/src/reflect/optional.rs +++ /dev/null @@ -1,49 +0,0 @@ -use std::mem; - -use super::value::ProtobufValue; -use crate::singular::*; - -pub trait ReflectOptional: 'static { - fn to_option(&self) -> Option<&dyn ProtobufValue>; - - fn set_value(&mut self, value: &dyn ProtobufValue); -} - -impl<V: ProtobufValue + Clone + 'static> ReflectOptional for Option<V> { - fn to_option(&self) -> Option<&dyn ProtobufValue> { - self.as_ref().map(|v| v as &dyn ProtobufValue) - } - - fn set_value(&mut self, value: &dyn ProtobufValue) { - match value.as_any().downcast_ref::<V>() { - Some(v) => mem::replace(self, Some(v.clone())), - None => panic!(), - }; - } -} - -impl<V: ProtobufValue + Clone + 'static> ReflectOptional for SingularField<V> { - fn to_option(&self) -> Option<&dyn ProtobufValue> { - self.as_ref().map(|v| v as &dyn ProtobufValue) - } - - fn set_value(&mut self, value: &dyn ProtobufValue) { - match value.as_any().downcast_ref::<V>() { - Some(v) => mem::replace(self, SingularField::some(v.clone())), - None => panic!(), - }; - } -} - -impl<V: ProtobufValue + Clone + 'static> ReflectOptional for SingularPtrField<V> { - fn to_option(&self) -> Option<&dyn ProtobufValue> { - self.as_ref().map(|v| v as &dyn ProtobufValue) - } - - fn set_value(&mut self, value: &dyn ProtobufValue) { - match value.as_any().downcast_ref::<V>() { - Some(v) => mem::replace(self, SingularPtrField::some(v.clone())), - None => panic!(), - }; - } -} diff --git a/src/reflect/optional/mod.rs b/src/reflect/optional/mod.rs new file mode 100644 index 0000000..9d34a30 --- /dev/null +++ b/src/reflect/optional/mod.rs @@ -0,0 +1,74 @@ +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectEq; +use crate::reflect::ReflectEqMode; +use crate::reflect::ReflectValueRef; +use crate::reflect::RuntimeType; + +enum Impl<'a> { + None(RuntimeType), + Some(ReflectValueRef<'a>), +} + +/// Singular field field and value type. +pub struct ReflectOptionalRef<'a>(Impl<'a>); + +impl<'a> PartialEq for ReflectOptionalRef<'a> { + fn eq(&self, other: &Self) -> bool { + self.reflect_eq(other, &ReflectEqMode::default()) + } +} + +impl<'a> ReflectEq for ReflectOptionalRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + match (&self.0, &that.0) { + (Impl::None(at), Impl::None(bt)) => at == bt, + (Impl::Some(a), Impl::Some(b)) => a.reflect_eq(b, mode), + (Impl::None(_), Impl::Some(_)) | (Impl::Some(_), Impl::None(_)) => false, + } + } +} + +impl<'a> ReflectOptionalRef<'a> { + /// No value. + pub fn none(elem: RuntimeType) -> ReflectOptionalRef<'a> { + ReflectOptionalRef(Impl::None(elem)) + } + + /// Has value. + pub fn some(value: ReflectValueRef<'a>) -> ReflectOptionalRef<'a> { + ReflectOptionalRef(Impl::Some(value)) + } + + pub(crate) fn none_from<V: ProtobufValue>() -> ReflectOptionalRef<'a> { + ReflectOptionalRef::none(V::RuntimeType::runtime_type_box()) + } + + pub(crate) fn some_from<V: ProtobufValue>(value: &'a V) -> ReflectOptionalRef<'a> { + ReflectOptionalRef::some(V::RuntimeType::as_ref(value)) + } + + pub(crate) fn new_filter_non_zero<V: ProtobufValue>(v: &'a V) -> ReflectOptionalRef<'a> { + if V::RuntimeType::is_non_zero(v) { + ReflectOptionalRef::some_from(v) + } else { + ReflectOptionalRef::none_from::<V>() + } + } + + pub(crate) fn new_from_option<V: ProtobufValue>(v: Option<&'a V>) -> ReflectOptionalRef<'a> { + if let Some(v) = v { + ReflectOptionalRef::some_from(v) + } else { + ReflectOptionalRef::none_from::<V>() + } + } + + /// Obtain the value, drop the type. + pub fn value(&self) -> Option<ReflectValueRef<'a>> { + match &self.0 { + Impl::None(_) => None, + Impl::Some(v) => Some(v.clone()), + } + } +} diff --git a/src/reflect/protobuf_type_box.rs b/src/reflect/protobuf_type_box.rs new file mode 100644 index 0000000..e60739f --- /dev/null +++ b/src/reflect/protobuf_type_box.rs @@ -0,0 +1,225 @@ +use crate::descriptor::field_descriptor_proto::Type; +use crate::error::ProtobufError; +use crate::error::WireError; +use crate::reflect::EnumDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectRepeatedMut; +use crate::reflect::ReflectValueBox; +use crate::reflect::RuntimeType; +use crate::wire_format::WireType; +use crate::CodedInputStream; + +/// Runtime type and protobuf type. +#[derive(Debug, Clone)] +pub(crate) struct ProtobufType { + /// Runtime type. + runtime: RuntimeType, + /// Wire type. + t: Type, +} + +impl ProtobufType { + pub(crate) fn runtime(&self) -> &RuntimeType { + &self.runtime + } + + pub(crate) fn t(&self) -> Type { + self.t + } + + pub(crate) fn _into_runtime(self) -> RuntimeType { + self.runtime + } + + pub(crate) fn message(message: MessageDescriptor) -> ProtobufType { + ProtobufType::new(RuntimeType::Message(message), Type::TYPE_MESSAGE).unwrap() + } + + pub(crate) fn enumeration(enumeration: EnumDescriptor) -> ProtobufType { + ProtobufType::new(RuntimeType::Enum(enumeration), Type::TYPE_ENUM).unwrap() + } + + pub(crate) fn from_proto_type(t: Type) -> ProtobufType { + ProtobufType::new(RuntimeType::from_proto_type(t), t).unwrap() + } + + pub(crate) fn new(runtime: RuntimeType, t: Type) -> crate::Result<ProtobufType> { + match (t, &runtime) { + (Type::TYPE_INT32, RuntimeType::I32) => {} + (Type::TYPE_INT64, RuntimeType::I64) => {} + (Type::TYPE_UINT32, RuntimeType::U32) => {} + (Type::TYPE_UINT64, RuntimeType::U64) => {} + (Type::TYPE_SINT32, RuntimeType::I32) => {} + (Type::TYPE_SINT64, RuntimeType::I64) => {} + (Type::TYPE_FIXED32, RuntimeType::U32) => {} + (Type::TYPE_FIXED64, RuntimeType::U64) => {} + (Type::TYPE_SFIXED32, RuntimeType::I32) => {} + (Type::TYPE_SFIXED64, RuntimeType::I64) => {} + (Type::TYPE_FLOAT, RuntimeType::F32) => {} + (Type::TYPE_DOUBLE, RuntimeType::F64) => {} + (Type::TYPE_BOOL, RuntimeType::Bool) => {} + (Type::TYPE_STRING, RuntimeType::String) => {} + (Type::TYPE_BYTES, RuntimeType::VecU8) => {} + (Type::TYPE_MESSAGE, RuntimeType::Message(..)) => {} + (Type::TYPE_ENUM, RuntimeType::Enum(..)) => {} + (Type::TYPE_GROUP, ..) => return Err(ProtobufError::GroupIsNotImplemented.into()), + _ => return Err(ProtobufError::IncompatibleProtobufTypeAndRuntimeType.into()), + } + Ok(ProtobufType { runtime, t }) + } + + pub(crate) fn read( + &self, + is: &mut CodedInputStream, + wire_type: WireType, + ) -> crate::Result<ReflectValueBox> { + if wire_type != WireType::for_type(self.t) { + return Err(WireError::UnexpectedWireType(wire_type).into()); + } + Ok(match self.t { + Type::TYPE_DOUBLE => ReflectValueBox::F64(is.read_double()?), + Type::TYPE_FLOAT => ReflectValueBox::F32(is.read_float()?), + Type::TYPE_INT64 => ReflectValueBox::I64(is.read_int64()?), + Type::TYPE_UINT64 => ReflectValueBox::U64(is.read_uint64()?), + Type::TYPE_INT32 => ReflectValueBox::I32(is.read_int32()?), + Type::TYPE_FIXED64 => ReflectValueBox::U64(is.read_fixed64()?), + Type::TYPE_FIXED32 => ReflectValueBox::U32(is.read_fixed32()?), + Type::TYPE_BOOL => ReflectValueBox::Bool(is.read_bool()?), + Type::TYPE_UINT32 => ReflectValueBox::U32(is.read_uint32()?), + Type::TYPE_SFIXED32 => ReflectValueBox::I32(is.read_sfixed32()?), + Type::TYPE_SFIXED64 => ReflectValueBox::I64(is.read_sfixed64()?), + Type::TYPE_SINT32 => ReflectValueBox::I32(is.read_sint32()?), + Type::TYPE_SINT64 => ReflectValueBox::I64(is.read_sint64()?), + Type::TYPE_STRING => ReflectValueBox::String(is.read_string()?), + Type::TYPE_BYTES => ReflectValueBox::Bytes(is.read_bytes()?), + Type::TYPE_ENUM => match &self.runtime { + RuntimeType::Enum(e) => { + let v = is.read_enum_value()?; + ReflectValueBox::Enum(e.clone(), v) + } + _ => unreachable!(), + }, + Type::TYPE_GROUP => return Err(ProtobufError::GroupIsNotImplemented.into()), + Type::TYPE_MESSAGE => match &self.runtime { + RuntimeType::Message(m) => ReflectValueBox::Message(is.read_message_dyn(m)?), + _ => unreachable!(), + }, + }) + } + + pub(crate) fn read_repeated_into( + &self, + is: &mut CodedInputStream, + wire_type: WireType, + repeated: &mut ReflectRepeatedMut, + ) -> crate::Result<()> { + if wire_type == WireType::for_type(self.t) { + let value = self.read(is, wire_type)?; + repeated.push(value); + Ok(()) + } else if wire_type == WireType::LengthDelimited { + fn extend<V: ProtobufValue>(repeated: &mut ReflectRepeatedMut, mut v: Vec<V>) { + repeated.extend(ReflectRepeatedMut::new(&mut v)); + } + + match self.t { + Type::TYPE_INT32 => { + let mut v = Vec::new(); + is.read_repeated_packed_int32_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_INT64 => { + let mut v = Vec::new(); + is.read_repeated_packed_int64_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_UINT32 => { + let mut v = Vec::new(); + is.read_repeated_packed_uint32_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_UINT64 => { + let mut v = Vec::new(); + is.read_repeated_packed_uint64_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_SINT32 => { + let mut v = Vec::new(); + is.read_repeated_packed_sint32_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_SINT64 => { + let mut v = Vec::new(); + is.read_repeated_packed_sint64_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_FIXED32 => { + let mut v = Vec::new(); + is.read_repeated_packed_fixed32_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_FIXED64 => { + let mut v = Vec::new(); + is.read_repeated_packed_fixed64_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_SFIXED32 => { + let mut v = Vec::new(); + is.read_repeated_packed_sfixed32_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_SFIXED64 => { + let mut v = Vec::new(); + is.read_repeated_packed_sfixed64_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_FLOAT => { + let mut v = Vec::new(); + is.read_repeated_packed_float_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_DOUBLE => { + let mut v = Vec::new(); + is.read_repeated_packed_double_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_BOOL => { + let mut v = Vec::new(); + is.read_repeated_packed_bool_into(&mut v)?; + extend(repeated, v); + Ok(()) + } + Type::TYPE_ENUM => match &self.runtime { + RuntimeType::Enum(e) => { + let mut v = Vec::new(); + is.read_repeated_packed_enum_values_into(&mut v)?; + for e_v in v { + repeated.push(ReflectValueBox::Enum(e.clone(), e_v)); + } + Ok(()) + } + _ => unreachable!(), + }, + Type::TYPE_GROUP => Err(ProtobufError::GroupIsNotImplemented.into()), + Type::TYPE_MESSAGE | Type::TYPE_STRING | Type::TYPE_BYTES => { + Err(WireError::UnexpectedWireType(wire_type).into()) + } + } + } else { + Err(WireError::UnexpectedWireType(wire_type).into()) + } + } +} diff --git a/src/reflect/reflect_eq.rs b/src/reflect/reflect_eq.rs new file mode 100644 index 0000000..cfa23ed --- /dev/null +++ b/src/reflect/reflect_eq.rs @@ -0,0 +1,33 @@ +/// Parameter for [`ReflectEq`]. +#[derive(Debug, Default)] +pub struct ReflectEqMode { + /// When `true`, `NaN` values are considered equal to each other. + pub nan_equal: bool, + _non_exhausitve: (), +} + +impl ReflectEqMode { + /// Default equality, similar to `#[derive(PartialEq)]`. + pub fn default() -> ReflectEqMode { + Default::default() + } + + /// Equality where float `NaN` values are considered equal to each other. + /// + /// Useful in tests. + pub fn nan_equal() -> ReflectEqMode { + ReflectEqMode { + nan_equal: true, + ..Default::default() + } + } +} + +/// Special version of eq. +/// +/// With `mode` [`ReflectEqMode::default()`], should be equivalent +/// to `#[derive(PartialEq)]`. +pub trait ReflectEq { + /// Perform the equality comparison. + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool; +} diff --git a/src/reflect/repeated.rs b/src/reflect/repeated.rs deleted file mode 100644 index 710de3e..0000000 --- a/src/reflect/repeated.rs +++ /dev/null @@ -1,191 +0,0 @@ -use std::slice; - -use super::value::ProtobufValue; -use super::value::ReflectValueRef; -use crate::repeated::RepeatedField; - -pub trait ReflectRepeated: 'static { - fn reflect_iter(&self) -> ReflectRepeatedIter; - fn len(&self) -> usize; - fn get(&self, index: usize) -> &dyn ProtobufValue; -} - -impl<V: ProtobufValue + 'static> ReflectRepeated for Vec<V> { - fn reflect_iter<'a>(&'a self) -> ReflectRepeatedIter<'a> { - ReflectRepeatedIter { - imp: Box::new(ReflectRepeatedIterImplSlice::<'a, V> { iter: self.iter() }), - } - } - - fn len(&self) -> usize { - Vec::len(self) - } - - fn get(&self, index: usize) -> &dyn ProtobufValue { - &self[index] - } -} - -// useless -impl<V: ProtobufValue + 'static> ReflectRepeated for [V] { - fn reflect_iter<'a>(&'a self) -> ReflectRepeatedIter<'a> { - ReflectRepeatedIter { - imp: Box::new(ReflectRepeatedIterImplSlice::<'a, V> { iter: self.iter() }), - } - } - - fn len(&self) -> usize { - <[_]>::len(self) - } - - fn get(&self, index: usize) -> &dyn ProtobufValue { - &self[index] - } -} - -impl<V: ProtobufValue + 'static> ReflectRepeated for RepeatedField<V> { - fn reflect_iter<'a>(&'a self) -> ReflectRepeatedIter<'a> { - ReflectRepeatedIter { - imp: Box::new(ReflectRepeatedIterImplSlice::<'a, V> { iter: self.iter() }), - } - } - - fn len(&self) -> usize { - RepeatedField::len(self) - } - - fn get(&self, index: usize) -> &dyn ProtobufValue { - &self[index] - } -} - -trait ReflectRepeatedIterTrait<'a> { - fn next(&mut self) -> Option<&'a dyn ProtobufValue>; -} - -struct ReflectRepeatedIterImplSlice<'a, V: ProtobufValue + 'static> { - iter: slice::Iter<'a, V>, -} - -impl<'a, V: ProtobufValue + 'static> ReflectRepeatedIterTrait<'a> - for ReflectRepeatedIterImplSlice<'a, V> -{ - fn next(&mut self) -> Option<&'a dyn ProtobufValue> { - self.iter.next().map(|v| v as &dyn ProtobufValue) - } -} - -pub struct ReflectRepeatedIter<'a> { - imp: Box<dyn ReflectRepeatedIterTrait<'a> + 'a>, -} - -impl<'a> Iterator for ReflectRepeatedIter<'a> { - type Item = &'a dyn ProtobufValue; - - fn next(&mut self) -> Option<Self::Item> { - self.imp.next() - } -} - -impl<'a> IntoIterator for &'a dyn ReflectRepeated { - type IntoIter = ReflectRepeatedIter<'a>; - type Item = &'a dyn ProtobufValue; - - fn into_iter(self) -> Self::IntoIter { - self.reflect_iter() - } -} - -pub trait ReflectRepeatedEnum<'a> { - fn len(&self) -> usize; - - fn get(&self, index: usize) -> ReflectValueRef<'a>; -} - -pub trait ReflectRepeatedMessage<'a> { - fn len(&self) -> usize; - - fn get(&self, index: usize) -> ReflectValueRef<'a>; -} - -pub enum ReflectRepeatedRef<'a> { - Generic(&'a dyn ReflectRepeated), - U32(&'a [u32]), - U64(&'a [u64]), - I32(&'a [i32]), - I64(&'a [i64]), - F32(&'a [f32]), - F64(&'a [f64]), - Bool(&'a [bool]), - String(&'a [String]), - Bytes(&'a [Vec<u8>]), - Enum(Box<dyn ReflectRepeatedEnum<'a> + 'a>), - Message(Box<dyn ReflectRepeatedMessage<'a> + 'a>), -} - -impl<'a> ReflectRepeatedRef<'a> { - fn len(&self) -> usize { - match *self { - ReflectRepeatedRef::Generic(ref r) => r.len(), - ReflectRepeatedRef::U32(ref r) => r.len(), - ReflectRepeatedRef::U64(ref r) => r.len(), - ReflectRepeatedRef::I32(ref r) => r.len(), - ReflectRepeatedRef::I64(ref r) => r.len(), - ReflectRepeatedRef::F32(ref r) => r.len(), - ReflectRepeatedRef::F64(ref r) => r.len(), - ReflectRepeatedRef::Bool(ref r) => r.len(), - ReflectRepeatedRef::String(ref r) => r.len(), - ReflectRepeatedRef::Bytes(ref r) => r.len(), - ReflectRepeatedRef::Enum(ref r) => r.len(), - ReflectRepeatedRef::Message(ref r) => r.len(), - } - } - - fn get(&self, index: usize) -> ReflectValueRef<'a> { - match *self { - ReflectRepeatedRef::Generic(ref r) => r.get(index).as_ref(), - ReflectRepeatedRef::U32(ref r) => ReflectValueRef::U32(r[index]), - ReflectRepeatedRef::U64(ref r) => ReflectValueRef::U64(r[index]), - ReflectRepeatedRef::I32(ref r) => ReflectValueRef::I32(r[index]), - ReflectRepeatedRef::I64(ref r) => ReflectValueRef::I64(r[index]), - ReflectRepeatedRef::F32(ref r) => ReflectValueRef::F32(r[index]), - ReflectRepeatedRef::F64(ref r) => ReflectValueRef::F64(r[index]), - ReflectRepeatedRef::Bool(ref r) => ReflectValueRef::Bool(r[index]), - ReflectRepeatedRef::String(ref r) => ReflectValueRef::String(&r[index]), - ReflectRepeatedRef::Bytes(ref r) => ReflectValueRef::Bytes(&r[index]), - ReflectRepeatedRef::Enum(ref r) => r.get(index), - ReflectRepeatedRef::Message(ref r) => r.get(index), - } - } -} - -pub struct ReflectRepeatedRefIter<'a> { - repeated: &'a ReflectRepeatedRef<'a>, - pos: usize, -} - -impl<'a> Iterator for ReflectRepeatedRefIter<'a> { - type Item = ReflectValueRef<'a>; - - fn next(&mut self) -> Option<Self::Item> { - if self.pos < self.repeated.len() { - let pos = self.pos; - self.pos += 1; - Some(self.repeated.get(pos)) - } else { - None - } - } -} - -impl<'a> IntoIterator for &'a ReflectRepeatedRef<'a> { - type IntoIter = ReflectRepeatedRefIter<'a>; - type Item = ReflectValueRef<'a>; - - fn into_iter(self) -> Self::IntoIter { - ReflectRepeatedRefIter { - repeated: self, - pos: 0, - } - } -} diff --git a/src/reflect/repeated/drain_iter.rs b/src/reflect/repeated/drain_iter.rs new file mode 100644 index 0000000..67d41fd --- /dev/null +++ b/src/reflect/repeated/drain_iter.rs @@ -0,0 +1,27 @@ +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueBox; + +pub(crate) struct ReflectRepeatedDrainIter<'a> { + imp: Box<dyn Iterator<Item = ReflectValueBox> + 'a>, +} + +impl<'a> ReflectRepeatedDrainIter<'a> { + pub(crate) fn new( + imp: impl Iterator<Item = ReflectValueBox> + 'a, + ) -> ReflectRepeatedDrainIter<'a> { + ReflectRepeatedDrainIter { imp: Box::new(imp) } + } + + pub(crate) fn new_vec<V: ProtobufValue>(v: &'a mut Vec<V>) -> ReflectRepeatedDrainIter<'a> { + ReflectRepeatedDrainIter::new(v.drain(..).map(V::RuntimeType::into_value_box)) + } +} + +impl<'a> Iterator for ReflectRepeatedDrainIter<'a> { + type Item = ReflectValueBox; + + fn next(&mut self) -> Option<Self::Item> { + self.imp.next() + } +} diff --git a/src/reflect/repeated/iter.rs b/src/reflect/repeated/iter.rs new file mode 100644 index 0000000..68c072e --- /dev/null +++ b/src/reflect/repeated/iter.rs @@ -0,0 +1,29 @@ +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueRef; + +pub(crate) struct ReflectRepeatedIter<'a> { + imp: Box<dyn Iterator<Item = ReflectValueRef<'a>> + 'a>, +} + +impl<'a> ReflectRepeatedIter<'a> { + pub(crate) fn new( + iter: impl Iterator<Item = ReflectValueRef<'a>> + 'a, + ) -> ReflectRepeatedIter<'a> { + ReflectRepeatedIter { + imp: Box::new(iter), + } + } + + pub(crate) fn new_slice<V: ProtobufValue>(slice: &'a [V]) -> ReflectRepeatedIter<'a> { + ReflectRepeatedIter::new(slice.into_iter().map(V::RuntimeType::as_ref)) + } +} + +impl<'a> Iterator for ReflectRepeatedIter<'a> { + type Item = ReflectValueRef<'a>; + + fn next(&mut self) -> Option<ReflectValueRef<'a>> { + self.imp.next() + } +} diff --git a/src/reflect/repeated/mod.rs b/src/reflect/repeated/mod.rs new file mode 100644 index 0000000..f8af5e4 --- /dev/null +++ b/src/reflect/repeated/mod.rs @@ -0,0 +1,521 @@ +pub(crate) mod drain_iter; +pub(crate) mod iter; +mod transmute; +mod vec_downcast; + +use std::any::type_name; +use std::fmt; + +use crate::reflect::dynamic::repeated::DynamicRepeated; +use crate::reflect::reflect_eq::ReflectEq; +use crate::reflect::reflect_eq::ReflectEqMode; +use crate::reflect::repeated::drain_iter::ReflectRepeatedDrainIter; +use crate::reflect::repeated::iter::ReflectRepeatedIter; +use crate::reflect::repeated::transmute::transmute_ref_if_eq; +use crate::reflect::repeated::vec_downcast::VecMutVariant; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::value::value_ref::ReflectValueRef; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueBox; +use crate::reflect::RuntimeType; + +pub(crate) trait ReflectRepeated: Sync + 'static + fmt::Debug { + fn reflect_iter(&self) -> ReflectRepeatedIter; + fn reflect_drain_iter(&mut self) -> ReflectRepeatedDrainIter; + fn len(&self) -> usize; + fn get(&self, index: usize) -> ReflectValueRef; + /// Set element at index. + /// + /// # Panics + /// + /// * if index is out of bounds + /// * if the element type does not match the collection element type + fn set(&mut self, index: usize, value: ReflectValueBox); + /// Append element. + /// + /// # Panics + /// + /// * if the element type does not match the collection element type + fn push(&mut self, value: ReflectValueBox); + + fn reflect_extend(&mut self, values: ReflectRepeatedMut); + + fn clear(&mut self); + /// Get the collection element type. + fn element_type(&self) -> RuntimeType; + + /// Get array data for enum elements. + /// + /// # Panics + /// + /// * if the element type is not an enum + fn data_enum_values(&self) -> &[i32]; + + /// Get array data if the element type is bool. + fn data_bool(&self) -> &[bool]; + /// Get array data if the element type is i32. + fn data_i32(&self) -> &[i32]; + /// Get array data if the element type is u32. + fn data_u32(&self) -> &[u32]; + /// Get array data if the element type is i64. + fn data_i64(&self) -> &[i64]; + /// Get array data if the element type is u64. + fn data_u64(&self) -> &[u64]; + /// Get array data if the element type is f32. + fn data_f32(&self) -> &[f32]; + /// Get array data if the element type is f64. + fn data_f64(&self) -> &[f64]; +} + +fn data_impl<V: ProtobufValue, X: ProtobufValue>(v: &Vec<V>) -> &[X] { + match transmute_ref_if_eq::<_, Vec<X>>(v) { + Ok(v) => v.as_slice(), + Err(_) => panic!("not {}", type_name::<X>()), + } +} + +impl<V: ProtobufValue> ReflectRepeated for Vec<V> { + fn reflect_iter<'a>(&'a self) -> ReflectRepeatedIter<'a> { + ReflectRepeatedIter::new_slice(self.as_slice()) + } + + fn reflect_drain_iter<'a>(&'a mut self) -> ReflectRepeatedDrainIter<'a> { + ReflectRepeatedDrainIter::new_vec(self) + } + + fn len(&self) -> usize { + Vec::len(self) + } + + fn get(&self, index: usize) -> ReflectValueRef { + V::RuntimeType::as_ref(&self[index]) + } + + fn set(&mut self, index: usize, value: ReflectValueBox) { + let value = value.downcast().expect("wrong type"); + self[index] = value; + } + + fn push(&mut self, value: ReflectValueBox) { + let value = value.downcast().expect("wrong type"); + self.push(value) + } + + fn reflect_extend(&mut self, values: ReflectRepeatedMut) { + match VecMutVariant::downcast(self) { + Some(VecMutVariant::U32(v)) => v.extend(values.repeated.data_u32()), + Some(VecMutVariant::U64(v)) => v.extend(values.repeated.data_u64()), + Some(VecMutVariant::I32(v)) => v.extend(values.repeated.data_i32()), + Some(VecMutVariant::I64(v)) => v.extend(values.repeated.data_i64()), + Some(VecMutVariant::F32(v)) => v.extend(values.repeated.data_f32()), + Some(VecMutVariant::F64(v)) => v.extend(values.repeated.data_f64()), + Some(VecMutVariant::Bool(v)) => v.extend(values.repeated.data_bool()), + None => { + for value in values.repeated.reflect_drain_iter() { + // Less efficient. + ReflectRepeated::push(self, value); + } + } + } + } + + fn clear(&mut self) { + self.clear() + } + + fn element_type(&self) -> RuntimeType { + V::RuntimeType::runtime_type_box() + } + + fn data_enum_values(&self) -> &[i32] { + V::RuntimeType::cast_to_enum_values(&self) + } + + fn data_bool(&self) -> &[bool] { + data_impl(self) + } + + fn data_i32(&self) -> &[i32] { + data_impl(self) + } + + fn data_u32(&self) -> &[u32] { + data_impl(self) + } + + fn data_i64(&self) -> &[i64] { + data_impl(self) + } + + fn data_u64(&self) -> &[u64] { + data_impl(self) + } + + fn data_f32(&self) -> &[f32] { + data_impl(self) + } + + fn data_f64(&self) -> &[f64] { + data_impl(self) + } +} + +impl<'a> IntoIterator for &'a dyn ReflectRepeated { + type Item = ReflectValueRef<'a>; + type IntoIter = ReflectRepeatedIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.reflect_iter() + } +} + +#[derive(Clone)] +enum ReflectRepeatedRefImpl<'a> { + Generated(&'a dyn ReflectRepeated), + DynamicEmpty(DynamicRepeated), +} + +impl<'a> fmt::Debug for ReflectRepeatedRefImpl<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ReflectRepeatedRefImpl::Generated(r) => fmt::Debug::fmt(r, f), + ReflectRepeatedRefImpl::DynamicEmpty(r) => fmt::Debug::fmt(r, f), + } + } +} + +/// Dynamic reference to repeated field +#[derive(Clone)] +pub struct ReflectRepeatedRef<'a> { + imp: ReflectRepeatedRefImpl<'a>, +} + +/// Dynamic mutable reference to repeated field +pub struct ReflectRepeatedMut<'a> { + pub(crate) repeated: &'a mut dyn ReflectRepeated, +} + +impl<'a> ReflectRepeatedRef<'a> { + pub(crate) fn new(repeated: &'a dyn ReflectRepeated) -> ReflectRepeatedRef<'a> { + ReflectRepeatedRef { + imp: ReflectRepeatedRefImpl::Generated(repeated), + } + } + + pub(crate) fn new_empty(elem: RuntimeType) -> ReflectRepeatedRef<'static> { + ReflectRepeatedRef { + imp: ReflectRepeatedRefImpl::DynamicEmpty(DynamicRepeated::new(elem)), + } + } + + /// Number of elements in repeated field + pub fn len(&self) -> usize { + match &self.imp { + ReflectRepeatedRefImpl::Generated(g) => g.len(), + ReflectRepeatedRefImpl::DynamicEmpty(d) => d.len(), + } + } + + /// Repeated field is empty + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Get item by index + // TODO: replace with index + pub fn get(&self, index: usize) -> ReflectValueRef<'a> { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.get(index), + ReflectRepeatedRefImpl::DynamicEmpty(..) => panic!("empty"), + } + } + + /// Runtime type of element + pub fn element_type(&self) -> RuntimeType { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.element_type(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.element_type(), + } + } + + pub(crate) fn data_enum_values(&self) -> &[i32] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_enum_values(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_enum_values(), + } + } + + pub(crate) fn data_bool(&self) -> &[bool] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_bool(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_bool(), + } + } + + pub(crate) fn data_u32(&self) -> &[u32] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_u32(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_u32(), + } + } + + pub(crate) fn data_i32(&self) -> &[i32] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_i32(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_i32(), + } + } + + pub(crate) fn data_u64(&self) -> &[u64] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_u64(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_u64(), + } + } + + pub(crate) fn data_i64(&self) -> &[i64] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_i64(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_i64(), + } + } + + pub(crate) fn data_f32(&self) -> &[f32] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_f32(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_f32(), + } + } + + pub(crate) fn data_f64(&self) -> &[f64] { + match &self.imp { + ReflectRepeatedRefImpl::Generated(r) => r.data_f64(), + ReflectRepeatedRefImpl::DynamicEmpty(r) => r.data_f64(), + } + } +} + +impl<'a> ReflectEq for ReflectRepeatedRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + let len = self.len(); + + if len != that.len() { + return false; + } + + if self.element_type() != that.element_type() { + return false; + } + + for i in 0..len { + let a = self.get(i); + let b = that.get(i); + if !a.reflect_eq(&b, mode) { + return false; + } + } + + true + } +} + +impl<'a> PartialEq for ReflectRepeatedRef<'a> { + fn eq(&self, other: &Self) -> bool { + self.reflect_eq(other, &ReflectEqMode::default()) + } +} + +impl<'a> PartialEq<[ReflectValueBox]> for ReflectRepeatedRef<'a> { + fn eq(&self, other: &[ReflectValueBox]) -> bool { + if self.len() != other.len() { + return false; + } + + for i in 0..self.len() { + if self.get(i) != other[i] { + return false; + } + } + + return true; + } +} + +impl<'a> PartialEq<ReflectRepeatedRef<'a>> for [ReflectValueBox] { + fn eq(&self, other: &ReflectRepeatedRef) -> bool { + other == self + } +} + +impl<'a> PartialEq<Vec<ReflectValueBox>> for ReflectRepeatedRef<'a> { + fn eq(&self, other: &Vec<ReflectValueBox>) -> bool { + self == other.as_slice() + } +} + +impl<'a> PartialEq<ReflectRepeatedRef<'a>> for Vec<ReflectValueBox> { + fn eq(&self, other: &ReflectRepeatedRef) -> bool { + self.as_slice() == other + } +} + +impl<'a> ReflectRepeatedMut<'a> { + pub(crate) fn new(repeated: &'a mut dyn ReflectRepeated) -> ReflectRepeatedMut<'a> { + ReflectRepeatedMut { repeated } + } + + fn as_ref(&'a self) -> ReflectRepeatedRef<'a> { + ReflectRepeatedRef::new(self.repeated) + } + + /// Number of elements in repeated field + pub fn len(&self) -> usize { + self.repeated.len() + } + + /// Self-explanatory + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Get an item by index + /// + /// Note: return immutable reference. + pub fn get(&'a self, index: usize) -> ReflectValueRef<'a> { + self.repeated.get(index) + } + + /// Runtime type of element + pub fn element_type(&self) -> RuntimeType { + self.repeated.element_type() + } + + /// Set a value at given index. + /// + /// # Panics + /// + /// If index if out of range or value type does not match container element type + pub fn set(&mut self, index: usize, value: ReflectValueBox) { + self.repeated.set(index, value); + } + + /// Push an item to repeated field. + /// + /// # Panics + /// + /// If index if out of range or value type does not match container element type + pub fn push(&mut self, value: ReflectValueBox) { + self.repeated.push(value); + } + + pub(crate) fn extend(&mut self, values: ReflectRepeatedMut) { + self.repeated.reflect_extend(values); + } + + /// Self-explanatory + pub fn clear(&mut self) { + self.repeated.clear(); + } +} + +/// Iterator over repeated field. +pub struct ReflectRepeatedRefIter<'a> { + repeated: ReflectRepeatedRef<'a>, + index: usize, +} + +impl<'a> Iterator for ReflectRepeatedRefIter<'a> { + type Item = ReflectValueRef<'a>; + + fn next(&mut self) -> Option<Self::Item> { + let index = self.index; + if index != self.repeated.len() { + let r = self.repeated.get(index); + self.index += 1; + Some(r) + } else { + None + } + } +} + +impl<'a> IntoIterator for &'a ReflectRepeatedRef<'a> { + type Item = ReflectValueRef<'a>; + type IntoIter = ReflectRepeatedRefIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + ReflectRepeatedRefIter { + repeated: self.clone(), + index: 0, + } + } +} + +impl<'a> IntoIterator for ReflectRepeatedRef<'a> { + type Item = ReflectValueRef<'a>; + type IntoIter = ReflectRepeatedRefIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + ReflectRepeatedRefIter { + repeated: self, + index: 0, + } + } +} + +impl<'a> IntoIterator for &'a ReflectRepeatedMut<'a> { + type Item = ReflectValueRef<'a>; + type IntoIter = ReflectRepeatedRefIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.as_ref().into_iter() + } +} + +impl<'a> fmt::Debug for ReflectRepeatedRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&self.imp, f) + } +} + +impl<'a> fmt::Debug for ReflectRepeatedMut<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self.repeated, f) + } +} + +impl<'a> PartialEq for ReflectRepeatedMut<'a> { + fn eq(&self, other: &Self) -> bool { + self.as_ref() == other.as_ref() + } +} + +impl<'a> PartialEq<ReflectRepeatedRef<'a>> for ReflectRepeatedMut<'a> { + fn eq(&self, other: &ReflectRepeatedRef) -> bool { + PartialEq::eq(&self.as_ref(), other) + } +} + +impl<'a> PartialEq<[ReflectValueBox]> for ReflectRepeatedMut<'a> { + fn eq(&self, other: &[ReflectValueBox]) -> bool { + PartialEq::eq(&self.as_ref(), other) + } +} + +impl<'a> PartialEq<ReflectRepeatedMut<'a>> for [ReflectValueBox] { + fn eq(&self, other: &ReflectRepeatedMut) -> bool { + PartialEq::eq(self, &other.as_ref()) + } +} + +impl<'a> PartialEq<Vec<ReflectValueBox>> for ReflectRepeatedMut<'a> { + fn eq(&self, other: &Vec<ReflectValueBox>) -> bool { + self == other.as_slice() + } +} + +impl<'a> PartialEq<ReflectRepeatedMut<'a>> for Vec<ReflectValueBox> { + fn eq(&self, other: &ReflectRepeatedMut) -> bool { + self.as_slice() == other + } +} diff --git a/src/reflect/repeated/transmute.rs b/src/reflect/repeated/transmute.rs new file mode 100644 index 0000000..36d9e0c --- /dev/null +++ b/src/reflect/repeated/transmute.rs @@ -0,0 +1,19 @@ +use std::any::TypeId; + +pub(crate) fn transmute_mut_if_eq<A: 'static, B: 'static>(a: &mut A) -> Result<&mut B, &mut A> { + if TypeId::of::<A>() == TypeId::of::<B>() { + // SAFETY: we check type before transmuting. + Ok(unsafe { &mut *(a as *mut A as *mut B) }) + } else { + Err(a) + } +} + +pub(crate) fn transmute_ref_if_eq<A: 'static, B: 'static>(a: &A) -> Result<&B, &A> { + if TypeId::of::<A>() == TypeId::of::<B>() { + // SAFETY: we check type before transmuting. + Ok(unsafe { &*(a as *const A as *const B) }) + } else { + Err(a) + } +} diff --git a/src/reflect/repeated/vec_downcast.rs b/src/reflect/repeated/vec_downcast.rs new file mode 100644 index 0000000..4bf44ae --- /dev/null +++ b/src/reflect/repeated/vec_downcast.rs @@ -0,0 +1,47 @@ +use crate::reflect::repeated::transmute::transmute_mut_if_eq; +use crate::reflect::ProtobufValue; + +pub(crate) enum VecMutVariant<'a> { + U32(&'a mut Vec<u32>), + U64(&'a mut Vec<u64>), + I32(&'a mut Vec<i32>), + I64(&'a mut Vec<i64>), + F32(&'a mut Vec<f32>), + F64(&'a mut Vec<f64>), + Bool(&'a mut Vec<bool>), +} + +impl<'a> VecMutVariant<'a> { + pub(crate) fn downcast<V: ProtobufValue>(vec: &'a mut Vec<V>) -> Option<VecMutVariant<'a>> { + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::U32(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::U64(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::I32(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::I64(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::F32(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::F64(vec)), + Err(vec) => vec, + }; + let vec = match transmute_mut_if_eq(vec) { + Ok(vec) => return Some(VecMutVariant::Bool(vec)), + Err(vec) => vec, + }; + let _ = vec; + None + } +} diff --git a/src/reflect/rt/mod.rs b/src/reflect/rt/mod.rs index d715d92..43479ef 100644 --- a/src/reflect/rt/mod.rs +++ b/src/reflect/rt/mod.rs @@ -2,4 +2,7 @@ #![doc(hidden)] +pub mod v2; + pub use crate::reflect::acc::FieldAccessor; +pub use crate::reflect::runtime_types::RuntimeTypeMessage; diff --git a/src/reflect/rt/v2.rs b/src/reflect/rt/v2.rs new file mode 100644 index 0000000..ef3077b --- /dev/null +++ b/src/reflect/rt/v2.rs @@ -0,0 +1,13 @@ +//! This module contains functions references for reflection in generated code. + +#![doc(hidden)] + +pub use crate::reflect::acc::v2::map::make_map_simpler_accessor; +pub use crate::reflect::acc::v2::repeated::make_vec_simpler_accessor; +pub use crate::reflect::acc::v2::singular::make_message_field_accessor; +pub use crate::reflect::acc::v2::singular::make_option_accessor; +pub use crate::reflect::acc::v2::singular::make_simpler_field_accessor; +pub use crate::reflect::acc::v2::singular::oneof::make_oneof_copy_has_get_set_simpler_accessors; +pub use crate::reflect::acc::v2::singular::oneof::make_oneof_deref_has_get_set_simpler_accessor; +pub use crate::reflect::acc::v2::singular::oneof::make_oneof_enum_accessors; +pub use crate::reflect::acc::v2::singular::oneof::make_oneof_message_has_get_mut_set_accessor; diff --git a/src/reflect/runtime_type_box.rs b/src/reflect/runtime_type_box.rs new file mode 100644 index 0000000..e1eec48 --- /dev/null +++ b/src/reflect/runtime_type_box.rs @@ -0,0 +1,151 @@ +use std::fmt; + +use protobuf_support::lexer::float::parse_protobuf_float; +use protobuf_support::lexer::str_lit::StrLit; + +use crate::descriptor::field_descriptor_proto; +use crate::reflect::EnumDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::MessageRef; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; + +/// Runtime representation of elementary protobuf type. +#[derive(Debug, Clone, Eq, PartialEq)] +pub enum RuntimeType { + /// `i32` + I32, + /// `i64` + I64, + /// `u32` + U32, + /// `u64` + U64, + /// `f32` + F32, + /// `f64` + F64, + /// `bool` + Bool, + /// [`String`](std::string::String) + String, + /// [`Vec<u8>`](std::vec::Vec) + VecU8, + /// `enum` + Enum(EnumDescriptor), + /// `message` + Message(MessageDescriptor), +} + +impl RuntimeType { + pub(crate) fn default_value_ref(&self) -> ReflectValueRef<'static> { + match self { + RuntimeType::I32 => ReflectValueRef::I32(0), + RuntimeType::I64 => ReflectValueRef::I64(0), + RuntimeType::U32 => ReflectValueRef::U32(0), + RuntimeType::U64 => ReflectValueRef::U64(0), + RuntimeType::F32 => ReflectValueRef::F32(0.0), + RuntimeType::F64 => ReflectValueRef::F64(0.0), + RuntimeType::Bool => ReflectValueRef::Bool(false), + RuntimeType::String => ReflectValueRef::String(""), + RuntimeType::VecU8 => ReflectValueRef::Bytes(b""), + RuntimeType::Enum(e) => ReflectValueRef::Enum(e.clone(), e.default_value().value()), + RuntimeType::Message(m) => ReflectValueRef::Message(MessageRef::default_instance(m)), + } + } + + pub(crate) fn default_value_box(&self) -> ReflectValueBox { + self.default_value_ref().to_box() + } + + /// Rust type from protobuf type. + /// + /// # Panics + /// + /// Panics for message or enum types (because they can't be resolved without context). + pub(crate) fn from_proto_type(t: field_descriptor_proto::Type) -> RuntimeType { + match t { + field_descriptor_proto::Type::TYPE_UINT32 => RuntimeType::U32, + field_descriptor_proto::Type::TYPE_UINT64 => RuntimeType::U64, + field_descriptor_proto::Type::TYPE_INT32 => RuntimeType::I32, + field_descriptor_proto::Type::TYPE_INT64 => RuntimeType::I64, + field_descriptor_proto::Type::TYPE_SINT32 => RuntimeType::I32, + field_descriptor_proto::Type::TYPE_SINT64 => RuntimeType::I64, + field_descriptor_proto::Type::TYPE_FIXED32 => RuntimeType::U32, + field_descriptor_proto::Type::TYPE_FIXED64 => RuntimeType::U64, + field_descriptor_proto::Type::TYPE_SFIXED64 => RuntimeType::I64, + field_descriptor_proto::Type::TYPE_SFIXED32 => RuntimeType::I32, + field_descriptor_proto::Type::TYPE_BOOL => RuntimeType::Bool, + field_descriptor_proto::Type::TYPE_STRING => RuntimeType::String, + field_descriptor_proto::Type::TYPE_BYTES => RuntimeType::VecU8, + field_descriptor_proto::Type::TYPE_FLOAT => RuntimeType::F32, + field_descriptor_proto::Type::TYPE_DOUBLE => RuntimeType::F64, + field_descriptor_proto::Type::TYPE_ENUM + | field_descriptor_proto::Type::TYPE_MESSAGE + | field_descriptor_proto::Type::TYPE_GROUP => panic!( + "{:?} cannot be converted to runtime type without context", + t + ), + } + } + + pub(crate) fn parse_proto_default_value(&self, value: &str) -> Result<ReflectValueBox, ()> { + match self { + // For booleans, "true" or "false" + RuntimeType::Bool => { + if value == "true" { + Ok(ReflectValueBox::Bool(true)) + } else if value == "false" { + Ok(ReflectValueBox::Bool(false)) + } else { + Err(()) + } + } + RuntimeType::I32 => value.parse().map_err(|_| ()).map(ReflectValueBox::I32), + RuntimeType::I64 => value.parse().map_err(|_| ()).map(ReflectValueBox::I64), + RuntimeType::U32 => value.parse().map_err(|_| ()).map(ReflectValueBox::U32), + RuntimeType::U64 => value.parse().map_err(|_| ()).map(ReflectValueBox::U64), + RuntimeType::F32 => parse_protobuf_float(value) + .map_err(|_| ()) + .map(|v| ReflectValueBox::F32(v as f32)), + RuntimeType::F64 => parse_protobuf_float(value) + .map_err(|_| ()) + .map(ReflectValueBox::F64), + // For strings, contains the default text contents (not escaped in any way) + RuntimeType::String => Ok(ReflectValueBox::String(value.to_owned())), + // For bytes, contains the C escaped value. All bytes >= 128 are escaped + RuntimeType::VecU8 => StrLit { + escaped: value.to_owned(), + } + .decode_bytes() + .map_err(|_| ()) + .map(ReflectValueBox::Bytes), + RuntimeType::Enum(_) => { + // Handled outside. + Err(()) + } + RuntimeType::Message(_) => { + // Message cannot have default value. + Err(()) + } + } + } +} + +impl fmt::Display for RuntimeType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RuntimeType::I32 => write!(f, "i32"), + RuntimeType::I64 => write!(f, "i64"), + RuntimeType::U32 => write!(f, "u32"), + RuntimeType::U64 => write!(f, "u64"), + RuntimeType::F32 => write!(f, "f32"), + RuntimeType::F64 => write!(f, "f64"), + RuntimeType::Bool => write!(f, "bool"), + RuntimeType::String => write!(f, "String"), + RuntimeType::VecU8 => write!(f, "Vec<u8>"), + RuntimeType::Enum(e) => write!(f, "{}", e.full_name()), + RuntimeType::Message(m) => write!(f, "{}", m.full_name()), + } + } +} diff --git a/src/reflect/runtime_types.rs b/src/reflect/runtime_types.rs new file mode 100644 index 0000000..26bfe96 --- /dev/null +++ b/src/reflect/runtime_types.rs @@ -0,0 +1,877 @@ +//! Implementations of `RuntimeType` for all types. + +use std::collections::HashMap; +use std::fmt; +use std::marker; + +#[cfg(feature = "bytes")] +use bytes::Bytes; + +#[cfg(feature = "bytes")] +use crate::chars::Chars; +use crate::descriptor::field_descriptor_proto::Type; +use crate::enum_or_unknown::EnumOrUnknown; +use crate::message_full::MessageFull; +use crate::reflect::runtime_type_box::RuntimeType; +use crate::reflect::types::ProtobufTypeBool; +use crate::reflect::types::ProtobufTypeBytes; +use crate::reflect::types::ProtobufTypeDouble; +use crate::reflect::types::ProtobufTypeEnumOrUnknown; +use crate::reflect::types::ProtobufTypeFixed32; +use crate::reflect::types::ProtobufTypeFixed64; +use crate::reflect::types::ProtobufTypeFloat; +use crate::reflect::types::ProtobufTypeInt32; +use crate::reflect::types::ProtobufTypeInt64; +use crate::reflect::types::ProtobufTypeMessage; +use crate::reflect::types::ProtobufTypeSfixed32; +use crate::reflect::types::ProtobufTypeSfixed64; +use crate::reflect::types::ProtobufTypeSint32; +use crate::reflect::types::ProtobufTypeSint64; +use crate::reflect::types::ProtobufTypeString; +#[cfg(feature = "bytes")] +use crate::reflect::types::ProtobufTypeTokioBytes; +#[cfg(feature = "bytes")] +use crate::reflect::types::ProtobufTypeTokioChars; +use crate::reflect::types::ProtobufTypeTrait; +use crate::reflect::types::ProtobufTypeUint32; +use crate::reflect::types::ProtobufTypeUint64; +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::MessageRef; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectValueBox; +use crate::reflect::ReflectValueRef; +use crate::EnumFull; +use crate::UnknownValueRef; + +/// `RuntimeType` is not implemented by all protobuf types directly +/// because it's not possible to implement `RuntimeType` for all `Message` +/// implementations at once: each `Message` implementation has to reimplement +/// all the methods again. With current strategy there's only implementation +/// for all messages, which is `RuntimeTypeMessage`. +/// +/// The downside is that we have to explicitly specify type parameters +/// in a lot of places. +pub trait RuntimeTypeTrait: fmt::Debug + Send + Sync + Sized + 'static { + /// Actual value for this type. + type Value: ProtobufValue + Clone + Sized + fmt::Debug + Default; + + /// "Box" version of type type. + fn runtime_type_box() -> RuntimeType; + + /// Default value for this type. + fn default_value_ref() -> ReflectValueRef<'static>; + + /// Construct a value from given reflective value. + /// + /// # Panics + /// + /// If reflective value is of incompatible type. + fn from_value_box(value_box: ReflectValueBox) -> Result<Self::Value, ReflectValueBox>; + + /// Convert a value into a refletive box value. + fn into_value_box(value: Self::Value) -> ReflectValueBox; + + /// Convert a value into a ref value if possible. + /// + /// # Panics + /// + /// For message and enum. + // TODO: move the operation into a separate trait + fn into_static_value_ref(value: Self::Value) -> ReflectValueRef<'static> { + panic!("value {:?} cannot be converted to static ref", value) + } + + /// Pointer to a dynamic reference. + fn as_ref(value: &Self::Value) -> ReflectValueRef; + /// Mutable pointer to a dynamic mutable reference. + fn as_mut(value: &mut Self::Value) -> ReflectValueMut; + + /// Value is non-default? + fn is_non_zero(value: &Self::Value) -> bool; + + /// Write the value. + fn set_from_value_box(target: &mut Self::Value, value_box: ReflectValueBox) { + *target = Self::from_value_box(value_box).expect("wrong type"); + } + + /// Cast values to enum values. + /// + /// # Panics + /// + /// If self is not an enum. + fn cast_to_enum_values(values: &[Self::Value]) -> &[i32] { + let _ = values; + panic!("not enum") + } + + /// Parse the value from unknown fields. + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value>; +} + +/// Runtime type which can be dereferenced. +pub trait RuntimeTypeWithDeref: RuntimeTypeTrait { + /// Deref target. + type DerefTarget: ?Sized; + + /// Deref. + // TODO: rename to `deref` + fn deref_as_ref(value: &Self::DerefTarget) -> ReflectValueRef; +} + +/// Types which can be hashmap keys. +pub trait RuntimeTypeHashable: RuntimeTypeTrait { + /// Query hash map with a given key. + fn hash_map_get<'a, V>(map: &'a HashMap<Self::Value, V>, key: ReflectValueRef) + -> Option<&'a V>; +} + +/// Implementation for `f32` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeF32; +/// Implementation for `f64` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeF64; +/// Implementation for `i32` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeI32; +/// Implementation for `f32` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeI64; +/// Implementation for `u32` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeU32; +/// Implementation for `u64` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeU64; +/// Implementation for `bool` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeBool; +/// Implementation for `String` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeString; +/// Implementation for `Vec<u8>` +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeVecU8; + +/// Implementation for [`Bytes`]. +#[cfg(feature = "bytes")] +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeTokioBytes; +/// Implementation for [`Chars`]. +#[cfg(feature = "bytes")] +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeTokioChars; + +/// Implementation for enum. +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeEnumOrUnknown<E: EnumFull>(marker::PhantomData<E>); +/// Implementation for [`MessageFull`]. +#[derive(Debug, Copy, Clone)] +pub struct RuntimeTypeMessage<M: MessageFull>(marker::PhantomData<M>); + +impl RuntimeTypeTrait for RuntimeTypeF32 { + type Value = f32; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::F32 + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::F32(0.0) + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<f32, ReflectValueBox> { + match value_box { + ReflectValueBox::F32(v) => Ok(v), + b => Err(b), + } + } + fn into_value_box(value: f32) -> ReflectValueBox { + ReflectValueBox::F32(value) + } + + fn into_static_value_ref(value: f32) -> ReflectValueRef<'static> { + ReflectValueRef::F32(value) + } + fn as_ref(value: &f32) -> ReflectValueRef { + ReflectValueRef::F32(*value) + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn is_non_zero(value: &f32) -> bool { + *value != 0.0 + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_FLOAT); + ProtobufTypeFloat::get_from_unknown(unknown) + } +} + +impl RuntimeTypeTrait for RuntimeTypeF64 { + type Value = f64; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::F64(0.0) + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::F64 + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<f64, ReflectValueBox> { + match value_box { + ReflectValueBox::F64(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: f64) -> ReflectValueBox { + ReflectValueBox::F64(value) + } + + fn into_static_value_ref(value: f64) -> ReflectValueRef<'static> { + ReflectValueRef::F64(value) + } + + fn as_ref(value: &f64) -> ReflectValueRef { + ReflectValueRef::F64(*value) + } + + fn is_non_zero(value: &f64) -> bool { + *value != 0.0 + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_DOUBLE); + ProtobufTypeDouble::get_from_unknown(unknown) + } +} + +impl RuntimeTypeTrait for RuntimeTypeI32 { + type Value = i32; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::I32(0) + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::I32 + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<i32, ReflectValueBox> { + match value_box { + ReflectValueBox::I32(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: i32) -> ReflectValueBox { + ReflectValueBox::I32(value) + } + + fn into_static_value_ref(value: i32) -> ReflectValueRef<'static> { + ReflectValueRef::I32(value) + } + + fn as_ref(value: &i32) -> ReflectValueRef { + ReflectValueRef::I32(*value) + } + + fn is_non_zero(value: &i32) -> bool { + *value != 0 + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + match field_type { + Type::TYPE_INT32 => ProtobufTypeInt32::get_from_unknown(unknown), + Type::TYPE_SINT32 => ProtobufTypeSint32::get_from_unknown(unknown), + Type::TYPE_SFIXED32 => ProtobufTypeSfixed32::get_from_unknown(unknown), + _ => panic!("wrong type: {:?}", field_type), + } + } +} +impl RuntimeTypeHashable for RuntimeTypeI32 { + fn hash_map_get<'a, V>(map: &'a HashMap<i32, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::I32(i) => map.get(&i), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeI64 { + type Value = i64; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::I64(0) + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::I64 + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<i64, ReflectValueBox> { + match value_box { + ReflectValueBox::I64(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: i64) -> ReflectValueBox { + ReflectValueBox::I64(value) + } + + fn into_static_value_ref(value: i64) -> ReflectValueRef<'static> { + ReflectValueRef::I64(value) + } + + fn as_ref(value: &i64) -> ReflectValueRef { + ReflectValueRef::I64(*value) + } + + fn is_non_zero(value: &i64) -> bool { + *value != 0 + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + match field_type { + Type::TYPE_INT64 => ProtobufTypeInt64::get_from_unknown(unknown), + Type::TYPE_SINT64 => ProtobufTypeSint64::get_from_unknown(unknown), + Type::TYPE_SFIXED64 => ProtobufTypeSfixed64::get_from_unknown(unknown), + _ => panic!("wrong type: {:?}", field_type), + } + } +} +impl RuntimeTypeHashable for RuntimeTypeI64 { + fn hash_map_get<'a, V>(map: &'a HashMap<i64, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::I64(i) => map.get(&i), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeU32 { + type Value = u32; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::U32 + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::U32(0) + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<u32, ReflectValueBox> { + match value_box { + ReflectValueBox::U32(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: u32) -> ReflectValueBox { + ReflectValueBox::U32(value) + } + + fn into_static_value_ref(value: u32) -> ReflectValueRef<'static> { + ReflectValueRef::U32(value) + } + + fn as_ref(value: &u32) -> ReflectValueRef { + ReflectValueRef::U32(*value) + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn is_non_zero(value: &u32) -> bool { + *value != 0 + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + match field_type { + Type::TYPE_UINT32 => ProtobufTypeUint32::get_from_unknown(unknown), + Type::TYPE_FIXED32 => ProtobufTypeFixed32::get_from_unknown(unknown), + _ => panic!("wrong type: {:?}", field_type), + } + } +} +impl RuntimeTypeHashable for RuntimeTypeU32 { + fn hash_map_get<'a, V>(map: &'a HashMap<u32, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::U32(i) => map.get(&i), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeU64 { + type Value = u64; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::U64(0) + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::U64 + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<u64, ReflectValueBox> { + match value_box { + ReflectValueBox::U64(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: u64) -> ReflectValueBox { + ReflectValueBox::U64(value) + } + + fn into_static_value_ref(value: u64) -> ReflectValueRef<'static> { + ReflectValueRef::U64(value) + } + + fn as_ref(value: &u64) -> ReflectValueRef { + ReflectValueRef::U64(*value) + } + + fn is_non_zero(value: &u64) -> bool { + *value != 0 + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + match field_type { + Type::TYPE_UINT64 => ProtobufTypeUint64::get_from_unknown(unknown), + Type::TYPE_FIXED64 => ProtobufTypeFixed64::get_from_unknown(unknown), + _ => panic!("wrong type: {:?}", field_type), + } + } +} +impl RuntimeTypeHashable for RuntimeTypeU64 { + fn hash_map_get<'a, V>(map: &'a HashMap<u64, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::U64(i) => map.get(&i), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeBool { + type Value = bool; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::Bool(false) + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::Bool + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<bool, ReflectValueBox> { + match value_box { + ReflectValueBox::Bool(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: bool) -> ReflectValueBox { + ReflectValueBox::Bool(value) + } + + fn into_static_value_ref(value: bool) -> ReflectValueRef<'static> { + ReflectValueRef::Bool(value) + } + + fn as_ref(value: &bool) -> ReflectValueRef { + ReflectValueRef::Bool(*value) + } + + fn is_non_zero(value: &bool) -> bool { + *value + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_BOOL); + ProtobufTypeBool::get_from_unknown(unknown) + } +} +impl RuntimeTypeHashable for RuntimeTypeBool { + fn hash_map_get<'a, V>(map: &'a HashMap<bool, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::Bool(i) => map.get(&i), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeString { + type Value = String; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::String + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::String("") + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<String, ReflectValueBox> { + match value_box { + ReflectValueBox::String(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: String) -> ReflectValueBox { + ReflectValueBox::String(value) + } + + fn as_ref(value: &String) -> ReflectValueRef { + ReflectValueRef::String(&*value) + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn is_non_zero(value: &String) -> bool { + !value.is_empty() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_STRING); + ProtobufTypeString::get_from_unknown(unknown) + } +} +impl RuntimeTypeWithDeref for RuntimeTypeString { + type DerefTarget = str; + + fn deref_as_ref(value: &str) -> ReflectValueRef { + ReflectValueRef::String(value) + } +} +impl RuntimeTypeHashable for RuntimeTypeString { + fn hash_map_get<'a, V>(map: &'a HashMap<String, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::String(s) => map.get(*&s), + _ => None, + } + } +} + +impl RuntimeTypeTrait for RuntimeTypeVecU8 { + type Value = Vec<u8>; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::VecU8 + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::Bytes(b"") + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<Vec<u8>, ReflectValueBox> { + match value_box { + ReflectValueBox::Bytes(v) => Ok(v), + b => Err(b), + } + } + + fn into_value_box(value: Vec<u8>) -> ReflectValueBox { + ReflectValueBox::Bytes(value) + } + + fn as_ref(value: &Vec<u8>) -> ReflectValueRef { + ReflectValueRef::Bytes(value.as_slice()) + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn is_non_zero(value: &Vec<u8>) -> bool { + !value.is_empty() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_BYTES); + ProtobufTypeBytes::get_from_unknown(unknown) + } +} +impl RuntimeTypeWithDeref for RuntimeTypeVecU8 { + type DerefTarget = [u8]; + + fn deref_as_ref(value: &[u8]) -> ReflectValueRef { + ReflectValueRef::Bytes(value) + } +} + +#[cfg(feature = "bytes")] +impl RuntimeTypeTrait for RuntimeTypeTokioBytes { + type Value = Bytes; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::Bytes(b"") + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::VecU8 + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<Bytes, ReflectValueBox> { + match value_box { + ReflectValueBox::Bytes(v) => Ok(v.into()), + b => Err(b), + } + } + + fn into_value_box(value: Bytes) -> ReflectValueBox { + // TODO: copies here + ReflectValueBox::Bytes(value.as_ref().to_owned()) + } + + fn as_ref(value: &Bytes) -> ReflectValueRef { + ReflectValueRef::Bytes(value.as_ref()) + } + + fn is_non_zero(value: &Bytes) -> bool { + !value.is_empty() + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_BYTES); + ProtobufTypeTokioBytes::get_from_unknown(unknown) + } +} +#[cfg(feature = "bytes")] +impl RuntimeTypeWithDeref for RuntimeTypeTokioBytes { + type DerefTarget = [u8]; + + fn deref_as_ref(value: &[u8]) -> ReflectValueRef { + ReflectValueRef::Bytes(value) + } +} + +#[cfg(feature = "bytes")] +impl RuntimeTypeTrait for RuntimeTypeTokioChars { + type Value = Chars; + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::String("") + } + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::String + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<Chars, ReflectValueBox> { + match value_box { + ReflectValueBox::String(v) => Ok(v.into()), + b => Err(b), + } + } + + fn into_value_box(value: Chars) -> ReflectValueBox { + ReflectValueBox::String(value.into()) + } + + fn as_ref(value: &Chars) -> ReflectValueRef { + ReflectValueRef::String(value.as_ref()) + } + + fn is_non_zero(value: &Chars) -> bool { + !value.is_empty() + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_STRING); + ProtobufTypeTokioChars::get_from_unknown(unknown) + } +} +#[cfg(feature = "bytes")] +impl RuntimeTypeWithDeref for RuntimeTypeTokioChars { + type DerefTarget = str; + + fn deref_as_ref(value: &str) -> ReflectValueRef { + ReflectValueRef::String(value) + } +} +#[cfg(feature = "bytes")] +impl RuntimeTypeHashable for RuntimeTypeTokioChars { + fn hash_map_get<'a, V>(map: &'a HashMap<Chars, V>, key: ReflectValueRef) -> Option<&'a V> { + match key { + ReflectValueRef::String(s) => map.get(&*s), + _ => None, + } + } +} + +impl<E> RuntimeTypeTrait for RuntimeTypeEnumOrUnknown<E> +where + E: EnumFull + fmt::Debug, +{ + type Value = EnumOrUnknown<E>; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::Enum(E::enum_descriptor()) + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::from(E::enum_descriptor().default_value()) + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<EnumOrUnknown<E>, ReflectValueBox> { + match value_box { + ReflectValueBox::Enum(d, v) if d == E::enum_descriptor() => { + Ok(EnumOrUnknown::from_i32(v)) + } + b => Err(b), + } + } + + fn into_value_box(value: EnumOrUnknown<E>) -> ReflectValueBox { + ReflectValueBox::Enum(E::enum_descriptor(), value.value()) + } + + fn into_static_value_ref(value: EnumOrUnknown<E>) -> ReflectValueRef<'static> { + ReflectValueRef::Enum(E::enum_descriptor(), value.value()) + } + + fn as_ref(value: &EnumOrUnknown<E>) -> ReflectValueRef { + ReflectValueRef::Enum(E::enum_descriptor(), value.value()) + } + + fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { + unimplemented!() + } + + fn is_non_zero(value: &EnumOrUnknown<E>) -> bool { + value.value() != 0 + } + + fn cast_to_enum_values(values: &[EnumOrUnknown<E>]) -> &[i32] { + EnumOrUnknown::cast_to_values(values) + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_ENUM); + ProtobufTypeEnumOrUnknown::<E>::get_from_unknown(unknown) + } +} + +impl<M> RuntimeTypeTrait for RuntimeTypeMessage<M> +where + M: MessageFull + ProtobufValue + Clone + Default, +{ + type Value = M; + + fn runtime_type_box() -> RuntimeType + where + Self: Sized, + { + RuntimeType::Message(M::descriptor()) + } + + fn default_value_ref() -> ReflectValueRef<'static> { + ReflectValueRef::Message(MessageRef::new(M::default_instance())) + } + + fn from_value_box(value_box: ReflectValueBox) -> Result<M, ReflectValueBox> { + match value_box { + ReflectValueBox::Message(v) => v + .downcast_box() + .map(|v| *v) + .map_err(ReflectValueBox::Message), + b => Err(b), + } + } + + fn into_value_box(value: M) -> ReflectValueBox { + ReflectValueBox::Message(Box::new(value)) + } + fn as_ref(value: &M) -> ReflectValueRef { + ReflectValueRef::Message(MessageRef::new(value)) + } + + fn as_mut(value: &mut M) -> ReflectValueMut { + ReflectValueMut::Message(value) + } + + fn is_non_zero(_value: &M) -> bool { + true + } + + fn get_from_unknown(unknown: UnknownValueRef, field_type: Type) -> Option<Self::Value> { + assert_eq!(field_type, Type::TYPE_MESSAGE); + ProtobufTypeMessage::<M>::get_from_unknown(unknown) + } +} diff --git a/src/reflect/service/index.rs b/src/reflect/service/index.rs new file mode 100644 index 0000000..c002db2 --- /dev/null +++ b/src/reflect/service/index.rs @@ -0,0 +1,43 @@ +use crate::descriptor::MethodDescriptorProto; +use crate::descriptor::ServiceDescriptorProto; +use crate::reflect::field::index::ForwardProtobufTypeBox; +use crate::reflect::file::building::FileDescriptorBuilding; + +#[derive(Debug)] +pub(crate) struct ServiceIndex { + pub(crate) methods: Vec<MethodIndex>, +} + +impl ServiceIndex { + pub(crate) fn index( + proto: &ServiceDescriptorProto, + building: &FileDescriptorBuilding, + ) -> crate::Result<ServiceIndex> { + let methods = proto + .method + .iter() + .map(|method| MethodIndex::index(method, building)) + .collect::<crate::Result<Vec<_>>>()?; + Ok(ServiceIndex { methods }) + } +} + +#[derive(Debug)] +pub(crate) struct MethodIndex { + pub(crate) input_type: ForwardProtobufTypeBox, + pub(crate) output_type: ForwardProtobufTypeBox, +} + +impl MethodIndex { + pub(crate) fn index( + proto: &MethodDescriptorProto, + building: &FileDescriptorBuilding, + ) -> crate::Result<MethodIndex> { + let input_type = building.resolve_message(proto.input_type())?; + let output_type = building.resolve_message(proto.output_type())?; + Ok(MethodIndex { + input_type, + output_type, + }) + } +} diff --git a/src/reflect/service/mod.rs b/src/reflect/service/mod.rs new file mode 100644 index 0000000..9896aec --- /dev/null +++ b/src/reflect/service/mod.rs @@ -0,0 +1,78 @@ +use crate::descriptor::MethodDescriptorProto; +use crate::descriptor::ServiceDescriptorProto; +use crate::reflect::service::index::MethodIndex; +use crate::reflect::service::index::ServiceIndex; +use crate::reflect::FileDescriptor; +use crate::reflect::MessageDescriptor; + +pub(crate) mod index; + +/// Dynamic representation of service type. +/// +/// Rust-protobuf does not support services (it is not an RPC library), +/// but it support querying service description. Which might be useful +/// for example to generate source files for the services. +/// or to perform invocations dynamically. +#[derive(Clone, Eq, PartialEq)] +pub struct ServiceDescriptor { + file_descriptor: FileDescriptor, + index: usize, +} + +impl ServiceDescriptor { + pub(crate) fn new(file_descriptor: FileDescriptor, index: usize) -> ServiceDescriptor { + ServiceDescriptor { + file_descriptor, + index, + } + } + + fn index(&self) -> &ServiceIndex { + &self.file_descriptor.common().services[self.index] + } + + /// Proto snippet describing this service. + pub fn proto(&self) -> &ServiceDescriptorProto { + &self.file_descriptor.proto().service[self.index] + } + + /// Method descriptors of this service. + pub fn methods(&self) -> impl Iterator<Item = MethodDescriptor> + '_ { + let value_len = self.proto().method.len(); + (0..value_len).map(move |index| MethodDescriptor { + service_descriptor: self.clone(), + index, + }) + } +} + +/// Service method descriptor. +pub struct MethodDescriptor { + service_descriptor: ServiceDescriptor, + index: usize, +} + +impl MethodDescriptor { + fn index(&self) -> &MethodIndex { + &self.service_descriptor.index().methods[self.index] + } + + /// Proto snippet describing this method. + pub fn proto(&self) -> &MethodDescriptorProto { + &self.service_descriptor.proto().method[self.index] + } + + /// Method input type. + pub fn input_type(&self) -> MessageDescriptor { + self.index() + .input_type + .resolve_message(&self.service_descriptor.file_descriptor) + } + + /// Method output type. + pub fn output_type(&self) -> MessageDescriptor { + self.index() + .output_type + .resolve_message(&self.service_descriptor.file_descriptor) + } +} diff --git a/src/reflect/type_dynamic.rs b/src/reflect/type_dynamic.rs new file mode 100644 index 0000000..1c623f2 --- /dev/null +++ b/src/reflect/type_dynamic.rs @@ -0,0 +1,36 @@ +//! Reflection internals. + +use std::marker; + +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::types::ProtobufTypeTrait; +use crate::reflect::ProtobufValue; +use crate::reflect::RuntimeType; +use crate::wire_format::WireType; + +/// Dynamic version of [`ProtobufType`](crate::reflect::types::ProtobufType). +/// +/// This is used internally. +pub trait ProtobufTypeDynamic: Send + Sync + 'static { + /// Wire type for this type. + fn wire_type(&self) -> WireType; + + /// Get runtime type for this protobuf type. + fn runtime_type(&self) -> RuntimeType; +} + +pub(crate) struct ProtobufTypeDynamicImpl<T: ProtobufTypeTrait>(pub marker::PhantomData<T>); + +impl<T> ProtobufTypeDynamic for ProtobufTypeDynamicImpl<T> +where + T: ProtobufTypeTrait, + <T as ProtobufTypeTrait>::ProtobufValue: ProtobufValue, +{ + fn wire_type(&self) -> WireType { + T::WIRE_TYPE + } + + fn runtime_type(&self) -> RuntimeType { + <T::ProtobufValue as ProtobufValue>::RuntimeType::runtime_type_box() + } +} diff --git a/src/reflect/types.rs b/src/reflect/types.rs new file mode 100644 index 0000000..33ba68d --- /dev/null +++ b/src/reflect/types.rs @@ -0,0 +1,730 @@ +//! Implementations of `ProtobufType` for all types. + +#![doc(hidden)] + +use std::marker; + +#[cfg(feature = "bytes")] +use ::bytes::Bytes; + +#[cfg(feature = "bytes")] +use crate::chars::Chars; +use crate::coded_input_stream::CodedInputStream; +use crate::coded_output_stream::CodedOutputStream; +use crate::enums::Enum; +use crate::error::Result; +pub use crate::reflect::type_dynamic::ProtobufTypeDynamic; +use crate::reflect::type_dynamic::ProtobufTypeDynamicImpl; +use crate::reflect::ProtobufValue; +use crate::rt; +use crate::rt::singular::value_varint_zigzag_size_no_tag; +use crate::wire_format::WireType; +use crate::zigzag::decode_zig_zag_32; +use crate::zigzag::decode_zig_zag_64; +use crate::EnumOrUnknown; +use crate::Message; +use crate::UnknownValueRef; + +/// Encapsulate type-specific serialization and conversion logic +pub(crate) trait ProtobufTypeTrait: Send + Sync + Clone + Sized + 'static { + /// Rust type for this protobuf type. + type ProtobufValue: Default; + + /// Dynamic version of this + fn dynamic() -> &'static dyn ProtobufTypeDynamic + where + Self::ProtobufValue: ProtobufValue, + { + &ProtobufTypeDynamicImpl::<Self>(marker::PhantomData) + } + + /// Wire type for encoding objects of this type + const WIRE_TYPE: WireType; + + /// Read a value from `CodedInputStream` + fn read(is: &mut CodedInputStream) -> Result<Self::ProtobufValue>; + + /// Take a value from `UnknownValues` + fn get_from_unknown(_unknown: UnknownValueRef) -> Option<Self::ProtobufValue>; + + /// Compute serialized size of a value + fn compute_size(value: &Self::ProtobufValue) -> u64; + + /// Compute size adding length prefix if wire type is length delimited + /// (i. e. string, bytes, message) + fn compute_size_with_length_delimiter(value: &Self::ProtobufValue) -> u64 { + let size = Self::compute_size(value); + if Self::WIRE_TYPE == WireType::LengthDelimited { + rt::compute_raw_varint64_size(size) + size + } else { + size + } + } + + /// Get previously computed size + #[inline] + fn get_cached_size(value: &Self::ProtobufValue) -> u32 { + Self::compute_size(value) as u32 + } + + /// Get previously cached size with length prefix + #[inline] + fn get_cached_size_with_length_delimiter(value: &Self::ProtobufValue) -> u32 { + let size = Self::get_cached_size(value); + if Self::WIRE_TYPE == WireType::LengthDelimited { + rt::compute_raw_varint32_size(size) as u32 + size + } else { + size + } + } + + /// Write a value with previously cached size + fn write_with_cached_size( + field_number: u32, + value: &Self::ProtobufValue, + os: &mut CodedOutputStream, + ) -> Result<()>; +} + +/// All fixed size types +pub(crate) trait ProtobufTypeFixed: ProtobufTypeTrait { + /// Encoded size of value in bytes of this type. + /// + /// E. g. it is `4` for `fixed32` + const ENCODED_SIZE: u32; +} + +/// `float` +#[derive(Copy, Clone)] +pub struct ProtobufTypeFloat; +/// `double` +#[derive(Copy, Clone)] +pub struct ProtobufTypeDouble; +/// `int32` +#[derive(Copy, Clone)] +pub struct ProtobufTypeInt32; +/// `int64` +#[derive(Copy, Clone)] +pub struct ProtobufTypeInt64; +/// `uint32` +#[derive(Copy, Clone)] +pub struct ProtobufTypeUint32; +/// `uint64` +#[derive(Copy, Clone)] +pub struct ProtobufTypeUint64; +/// `sint32` +#[derive(Copy, Clone)] +pub struct ProtobufTypeSint32; +/// `sint64` +#[derive(Copy, Clone)] +pub struct ProtobufTypeSint64; +/// `fixed32` +#[derive(Copy, Clone)] +pub struct ProtobufTypeFixed32; +/// `fixed64` +#[derive(Copy, Clone)] +pub struct ProtobufTypeFixed64; +/// `sfixed32` +#[derive(Copy, Clone)] +pub struct ProtobufTypeSfixed32; +/// `sfixed64` +#[derive(Copy, Clone)] +pub struct ProtobufTypeSfixed64; +/// `bool` +#[derive(Copy, Clone)] +pub struct ProtobufTypeBool; +/// `string` +#[derive(Copy, Clone)] +pub struct ProtobufTypeString; +/// `bytes` +#[derive(Copy, Clone)] +pub struct ProtobufTypeBytes; + +/// `bytes` as [`Bytes`](bytes::Bytes) +#[cfg(feature = "bytes")] +#[derive(Copy, Clone)] +pub struct ProtobufTypeTokioBytes; +/// `string` as [`Chars`](crate::Chars) +#[cfg(feature = "bytes")] +#[derive(Copy, Clone)] +pub struct ProtobufTypeTokioChars; + +/// `enum` as `ProtobufEnumOrUnknown` +#[derive(Copy, Clone)] +pub struct ProtobufTypeEnumOrUnknown<E: Enum>(marker::PhantomData<E>); +/// `message` +#[derive(Copy, Clone)] +pub struct ProtobufTypeMessage<M: Message>(marker::PhantomData<M>); + +impl ProtobufTypeTrait for ProtobufTypeFloat { + type ProtobufValue = f32; + + const WIRE_TYPE: WireType = WireType::Fixed32; + + fn read(is: &mut CodedInputStream) -> Result<f32> { + is.read_float() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<f32> { + match unknown { + UnknownValueRef::Fixed32(v) => Some(f32::from_bits(v)), + _ => None, + } + } + + fn compute_size(_value: &f32) -> u64 { + Self::ENCODED_SIZE as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &f32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_float(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeFloat { + const ENCODED_SIZE: u32 = 4; +} + +impl ProtobufTypeTrait for ProtobufTypeDouble { + type ProtobufValue = f64; + + const WIRE_TYPE: WireType = WireType::Fixed64; + + fn read(is: &mut CodedInputStream) -> Result<f64> { + is.read_double() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<f64> { + match unknown { + UnknownValueRef::Fixed64(v) => Some(f64::from_bits(v)), + _ => None, + } + } + + fn compute_size(_value: &f64) -> u64 { + Self::ENCODED_SIZE as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &f64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_double(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeDouble { + const ENCODED_SIZE: u32 = 8; +} + +impl ProtobufTypeTrait for ProtobufTypeInt32 { + type ProtobufValue = i32; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<i32> { + is.read_int32() + } + + fn compute_size(value: &i32) -> u64 { + // See also: https://github.com/protocolbuffers/protobuf/blob/bd00671b924310c0353a730bf8fa77c44e0a9c72/src/google/protobuf/io/coded_stream.h#L1300-L1306 + if *value < 0 { + return 10; + } + rt::compute_raw_varint32_size(*value as u32) + } + + fn write_with_cached_size( + field_number: u32, + value: &i32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_int32(field_number, *value) + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i32> { + match unknown { + UnknownValueRef::Varint(v) => Some(v as i32), + _ => None, + } + } +} + +impl ProtobufTypeTrait for ProtobufTypeInt64 { + type ProtobufValue = i64; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<i64> { + is.read_int64() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i64> { + match unknown { + UnknownValueRef::Varint(v) => Some(v as i64), + _ => None, + } + } + + fn compute_size(value: &i64) -> u64 { + rt::compute_raw_varint64_size(*value as u64) + } + + fn write_with_cached_size( + field_number: u32, + value: &i64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_int64(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeUint32 { + type ProtobufValue = u32; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<u32> { + is.read_uint32() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<u32> { + match unknown { + UnknownValueRef::Varint(v) => Some(v as u32), + _ => None, + } + } + + fn compute_size(value: &u32) -> u64 { + rt::compute_raw_varint32_size(*value) + } + + fn write_with_cached_size( + field_number: u32, + value: &u32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_uint32(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeUint64 { + type ProtobufValue = u64; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<u64> { + is.read_uint64() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<u64> { + match unknown { + UnknownValueRef::Varint(v) => Some(v as u64), + _ => None, + } + } + + fn compute_size(value: &u64) -> u64 { + rt::compute_raw_varint64_size(*value) + } + + fn write_with_cached_size( + field_number: u32, + value: &u64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_uint64(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeSint32 { + type ProtobufValue = i32; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<i32> { + is.read_sint32() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i32> { + ProtobufTypeUint32::get_from_unknown(unknown).map(decode_zig_zag_32) + } + + fn compute_size(value: &i32) -> u64 { + value_varint_zigzag_size_no_tag(*value) + } + + fn write_with_cached_size( + field_number: u32, + value: &i32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_sint32(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeSint64 { + type ProtobufValue = i64; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<i64> { + is.read_sint64() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i64> { + ProtobufTypeUint64::get_from_unknown(unknown).map(decode_zig_zag_64) + } + + fn compute_size(value: &i64) -> u64 { + value_varint_zigzag_size_no_tag(*value) + } + + fn write_with_cached_size( + field_number: u32, + value: &i64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_sint64(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeFixed32 { + type ProtobufValue = u32; + + const WIRE_TYPE: WireType = WireType::Fixed32; + + fn read(is: &mut CodedInputStream) -> Result<u32> { + is.read_fixed32() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<u32> { + match unknown { + UnknownValueRef::Fixed32(v) => Some(v), + _ => None, + } + } + + fn compute_size(_value: &u32) -> u64 { + Self::ENCODED_SIZE as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &u32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_fixed32(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeFixed32 { + const ENCODED_SIZE: u32 = 4; +} + +impl ProtobufTypeTrait for ProtobufTypeFixed64 { + type ProtobufValue = u64; + + const WIRE_TYPE: WireType = WireType::Fixed64; + + fn read(is: &mut CodedInputStream) -> Result<u64> { + is.read_fixed64() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<u64> { + match unknown { + UnknownValueRef::Fixed64(v) => Some(v), + _ => None, + } + } + + fn compute_size(_value: &u64) -> u64 { + Self::ENCODED_SIZE as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &u64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_fixed64(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeFixed64 { + const ENCODED_SIZE: u32 = 8; +} + +impl ProtobufTypeTrait for ProtobufTypeSfixed32 { + type ProtobufValue = i32; + + const WIRE_TYPE: WireType = WireType::Fixed32; + + fn read(is: &mut CodedInputStream) -> Result<i32> { + is.read_sfixed32() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i32> { + match unknown { + UnknownValueRef::Fixed32(v) => Some(v as i32), + _ => None, + } + } + + fn compute_size(_value: &i32) -> u64 { + Self::ENCODED_SIZE as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &i32, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_sfixed32(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeSfixed32 { + const ENCODED_SIZE: u32 = 4; +} + +impl ProtobufTypeTrait for ProtobufTypeSfixed64 { + type ProtobufValue = i64; + + const WIRE_TYPE: WireType = WireType::Fixed64; + + fn read(is: &mut CodedInputStream) -> Result<i64> { + is.read_sfixed64() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<i64> { + match unknown { + UnknownValueRef::Fixed64(v) => Some(v as i64), + _ => None, + } + } + + fn compute_size(_value: &i64) -> u64 { + 8 + } + + fn write_with_cached_size( + field_number: u32, + value: &i64, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_sfixed64(field_number, *value) + } +} + +impl ProtobufTypeFixed for ProtobufTypeSfixed64 { + const ENCODED_SIZE: u32 = 8; +} + +impl ProtobufTypeTrait for ProtobufTypeBool { + type ProtobufValue = bool; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<bool> { + is.read_bool() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<bool> { + match unknown { + UnknownValueRef::Varint(b) => Some(b != 0), + _ => None, + } + } + + fn compute_size(_value: &bool) -> u64 { + 1 + } + + fn write_with_cached_size( + field_number: u32, + value: &bool, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_bool(field_number, *value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeString { + type ProtobufValue = String; + + const WIRE_TYPE: WireType = WireType::LengthDelimited; + + fn read(is: &mut CodedInputStream) -> Result<String> { + is.read_string() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<String> { + match unknown { + UnknownValueRef::LengthDelimited(v) => String::from_utf8(v.to_vec()).ok(), + _ => None, + } + } + + fn compute_size(value: &String) -> u64 { + value.len() as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &String, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_string(field_number, &value) + } +} + +impl ProtobufTypeTrait for ProtobufTypeBytes { + type ProtobufValue = Vec<u8>; + + const WIRE_TYPE: WireType = WireType::LengthDelimited; + + fn read(is: &mut CodedInputStream) -> Result<Vec<u8>> { + is.read_bytes() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<Vec<u8>> { + match unknown { + UnknownValueRef::LengthDelimited(v) => Some(v.to_vec()), + _ => None, + } + } + + fn compute_size(value: &Vec<u8>) -> u64 { + value.len() as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &Vec<u8>, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_bytes(field_number, &value) + } +} + +#[cfg(feature = "bytes")] +impl ProtobufTypeTrait for ProtobufTypeTokioBytes { + type ProtobufValue = bytes::Bytes; + + const WIRE_TYPE: WireType = ProtobufTypeBytes::WIRE_TYPE; + + fn read(is: &mut CodedInputStream) -> Result<Bytes> { + is.read_tokio_bytes() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<Bytes> { + ProtobufTypeBytes::get_from_unknown(unknown).map(Bytes::from) + } + + fn compute_size(value: &Bytes) -> u64 { + value.len() as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &Bytes, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_bytes(field_number, &value) + } +} + +#[cfg(feature = "bytes")] +impl ProtobufTypeTrait for ProtobufTypeTokioChars { + type ProtobufValue = Chars; + + const WIRE_TYPE: WireType = ProtobufTypeBytes::WIRE_TYPE; + + fn read(is: &mut CodedInputStream) -> Result<Chars> { + is.read_tokio_chars() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<Chars> { + ProtobufTypeString::get_from_unknown(unknown).map(Chars::from) + } + + fn compute_size(value: &Chars) -> u64 { + value.len() as u64 + } + + fn write_with_cached_size( + field_number: u32, + value: &Chars, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_string(field_number, &value) + } +} + +impl<E: Enum> ProtobufTypeTrait for ProtobufTypeEnumOrUnknown<E> { + type ProtobufValue = EnumOrUnknown<E>; + + const WIRE_TYPE: WireType = WireType::Varint; + + fn read(is: &mut CodedInputStream) -> Result<EnumOrUnknown<E>> { + is.read_enum_or_unknown() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<EnumOrUnknown<E>> { + ProtobufTypeInt32::get_from_unknown(unknown).map(|i| EnumOrUnknown::from_i32(i)) + } + + fn compute_size(value: &EnumOrUnknown<E>) -> u64 { + ProtobufTypeInt32::compute_size(&value.value()) + } + + fn write_with_cached_size( + field_number: u32, + value: &EnumOrUnknown<E>, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_enum_or_unknown(field_number, *value) + } +} + +impl<M: Message + Clone + Default> ProtobufTypeTrait for ProtobufTypeMessage<M> { + type ProtobufValue = M; + + const WIRE_TYPE: WireType = WireType::LengthDelimited; + + fn read(is: &mut CodedInputStream) -> Result<M> { + is.read_message() + } + + fn get_from_unknown(unknown: UnknownValueRef) -> Option<M> { + match unknown { + UnknownValueRef::LengthDelimited(v) => M::parse_from_bytes(&v).ok(), + _ => None, + } + } + + fn compute_size(value: &M) -> u64 { + value.compute_size() + } + + fn get_cached_size(value: &M) -> u32 { + value.cached_size() + } + + fn write_with_cached_size( + field_number: u32, + value: &Self::ProtobufValue, + os: &mut CodedOutputStream, + ) -> Result<()> { + os.write_tag(field_number, WireType::LengthDelimited)?; + os.write_raw_varint32(value.cached_size())?; + value.write_to_with_cached_sizes(os)?; + Ok(()) + } +} diff --git a/src/reflect/value.rs b/src/reflect/value.rs deleted file mode 100644 index 9598b9f..0000000 --- a/src/reflect/value.rs +++ /dev/null @@ -1,185 +0,0 @@ -use std::any::Any; - -#[cfg(feature = "bytes")] -use bytes::Bytes; - -use super::*; -#[cfg(feature = "bytes")] -use crate::chars::Chars; - -/// Type implemented by all protobuf elementary types -/// (ints, floats, bool, string, bytes, enums, messages). -pub trait ProtobufValue: Any + 'static { - /// As ref - fn as_ref(&self) -> ReflectValueRef; - - /// Convert to `Any` - fn as_any(&self) -> &dyn Any { - unimplemented!() - } - - /// Is value non-zero? - fn is_non_zero(&self) -> bool { - self.as_ref().is_non_zero() - } - - /// Return `ProtobufValueRef` if self is `Copy`. - /// - /// # Panics - /// - /// if `Self` is not `Copy`. - fn as_ref_copy(&self) -> ReflectValueRef<'static> -//where Self : Copy // TODO - { - match self.as_ref() { - ReflectValueRef::Bool(v) => ReflectValueRef::Bool(v), - ReflectValueRef::U32(v) => ReflectValueRef::U32(v), - ReflectValueRef::U64(v) => ReflectValueRef::U64(v), - ReflectValueRef::I32(v) => ReflectValueRef::I32(v), - ReflectValueRef::I64(v) => ReflectValueRef::I64(v), - ReflectValueRef::F32(v) => ReflectValueRef::F32(v), - ReflectValueRef::F64(v) => ReflectValueRef::F64(v), - ReflectValueRef::Enum(v) => ReflectValueRef::Enum(v), - ReflectValueRef::String(..) - | ReflectValueRef::Bytes(..) - | ReflectValueRef::Message(..) => unreachable!(), - } - } -} - -impl ProtobufValue for u32 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::U32(*self) - } -} - -impl ProtobufValue for u64 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::U64(*self) - } -} - -impl ProtobufValue for i32 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::I32(*self) - } -} - -impl ProtobufValue for i64 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::I64(*self) - } -} - -impl ProtobufValue for f32 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::F32(*self) - } -} - -impl ProtobufValue for f64 { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::F64(*self) - } -} - -impl ProtobufValue for bool { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::Bool(*self) - } -} - -impl ProtobufValue for String { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::String(*&self) - } -} - -impl ProtobufValue for str { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::String(self) - } -} - -impl ProtobufValue for Vec<u8> { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::Bytes(*&self) - } -} - -#[cfg(feature = "bytes")] -impl ProtobufValue for Bytes { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::Bytes(&*self) - } -} - -#[cfg(feature = "bytes")] -impl ProtobufValue for Chars { - fn as_ref(&self) -> ReflectValueRef { - ReflectValueRef::String(&*self) - } -} - -// conflicting implementations, so generated code is used instead -/* -impl<E : ProtobufEnum> ProtobufValue for E { - fn as_ref(&self) -> ProtobufValueRef { - ProtobufValueRef::Enum(self.descriptor()) - } -} - -impl<M : Message> ProtobufValue for M { - fn as_ref(&self) -> ProtobufValueRef { - ProtobufValueRef::Message(self) - } -} -*/ - -/// A reference to a value -#[derive(Debug)] -pub enum ReflectValueRef<'a> { - /// `u32` - U32(u32), - /// `u64` - U64(u64), - /// `i32` - I32(i32), - /// `i64` - I64(i64), - /// `f32` - F32(f32), - /// `f64` - F64(f64), - /// `bool` - Bool(bool), - /// `string` - String(&'a str), - /// `bytes` - Bytes(&'a [u8]), - /// `enum` - // TODO: change to (i32, EnumDescriptor) - Enum(&'static EnumValueDescriptor), - /// `message` - Message(&'a dyn Message), -} - -impl<'a> ReflectValueRef<'a> { - /// Value is "non-zero"? - #[doc(hidden)] - pub fn is_non_zero(&self) -> bool { - match *self { - ReflectValueRef::U32(v) => v != 0, - ReflectValueRef::U64(v) => v != 0, - ReflectValueRef::I32(v) => v != 0, - ReflectValueRef::I64(v) => v != 0, - ReflectValueRef::F32(v) => v != 0., - ReflectValueRef::F64(v) => v != 0., - ReflectValueRef::Bool(v) => v, - ReflectValueRef::String(v) => !v.is_empty(), - ReflectValueRef::Bytes(v) => !v.is_empty(), - ReflectValueRef::Enum(v) => v.value() != 0, - ReflectValueRef::Message(_) => true, - } - } -} diff --git a/src/reflect/value/mod.rs b/src/reflect/value/mod.rs new file mode 100644 index 0000000..3d04909 --- /dev/null +++ b/src/reflect/value/mod.rs @@ -0,0 +1,88 @@ +use std::fmt; + +#[cfg(feature = "bytes")] +use ::bytes::Bytes; + +#[cfg(feature = "bytes")] +use crate::chars::Chars; +use crate::reflect::runtime_types::RuntimeTypeBool; +use crate::reflect::runtime_types::RuntimeTypeF32; +use crate::reflect::runtime_types::RuntimeTypeF64; +use crate::reflect::runtime_types::RuntimeTypeI32; +use crate::reflect::runtime_types::RuntimeTypeI64; +use crate::reflect::runtime_types::RuntimeTypeString; +#[cfg(feature = "bytes")] +use crate::reflect::runtime_types::RuntimeTypeTokioBytes; +#[cfg(feature = "bytes")] +use crate::reflect::runtime_types::RuntimeTypeTokioChars; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::runtime_types::RuntimeTypeU32; +use crate::reflect::runtime_types::RuntimeTypeU64; +use crate::reflect::runtime_types::RuntimeTypeVecU8; + +pub(crate) mod value_box; +pub(crate) mod value_ref; + +/// Type implemented by all protobuf singular types +/// (primitives, string, messages, enums). +/// +/// Used in reflection. +pub trait ProtobufValue: Clone + Default + fmt::Debug + Send + Sync + Sized + 'static { + /// Actual implementation of type properties. + type RuntimeType: RuntimeTypeTrait<Value = Self>; +} + +impl ProtobufValue for u32 { + type RuntimeType = RuntimeTypeU32; +} + +impl ProtobufValue for u64 { + type RuntimeType = RuntimeTypeU64; +} + +impl ProtobufValue for i32 { + type RuntimeType = RuntimeTypeI32; +} + +impl ProtobufValue for i64 { + type RuntimeType = RuntimeTypeI64; +} + +impl ProtobufValue for f32 { + type RuntimeType = RuntimeTypeF32; +} + +impl ProtobufValue for f64 { + type RuntimeType = RuntimeTypeF64; +} + +impl ProtobufValue for bool { + type RuntimeType = RuntimeTypeBool; +} + +impl ProtobufValue for String { + type RuntimeType = RuntimeTypeString; +} + +impl ProtobufValue for Vec<u8> { + type RuntimeType = RuntimeTypeVecU8; +} + +#[cfg(feature = "bytes")] +impl ProtobufValue for Bytes { + type RuntimeType = RuntimeTypeTokioBytes; +} + +#[cfg(feature = "bytes")] +impl ProtobufValue for Chars { + type RuntimeType = RuntimeTypeTokioChars; +} + +// conflicting implementations, so generated code is used instead +/* +impl<E : ProtobufEnum> ProtobufValue for E { +} + +impl<M : Message> ProtobufValue for M { +} +*/ diff --git a/src/reflect/value/value_box.rs b/src/reflect/value/value_box.rs new file mode 100644 index 0000000..69fe338 --- /dev/null +++ b/src/reflect/value/value_box.rs @@ -0,0 +1,197 @@ +use crate::reflect::message::message_ref::MessageRef; +use crate::reflect::runtime_types::RuntimeTypeTrait; +use crate::reflect::value::value_ref::ReflectValueMut; +use crate::reflect::value::value_ref::ReflectValueRef; +use crate::reflect::EnumDescriptor; +use crate::reflect::EnumValueDescriptor; +use crate::reflect::ProtobufValue; +use crate::reflect::RuntimeType; +use crate::MessageDyn; + +/// Owner value of any elementary type +#[derive(Debug, Clone)] +pub enum ReflectValueBox { + /// `u32` + U32(u32), + /// `u64` + U64(u64), + /// `i32` + I32(i32), + /// `i64` + I64(i64), + /// `f32` + F32(f32), + /// `f64` + F64(f64), + /// `bool` + Bool(bool), + /// `string` + String(String), + /// `bytes` + Bytes(Vec<u8>), + /// `enum` + Enum(EnumDescriptor, i32), + /// `message` + Message(Box<dyn MessageDyn>), +} + +impl From<u32> for ReflectValueBox { + fn from(v: u32) -> Self { + ReflectValueBox::U32(v) + } +} + +impl From<u64> for ReflectValueBox { + fn from(v: u64) -> Self { + ReflectValueBox::U64(v) + } +} + +impl From<i32> for ReflectValueBox { + fn from(v: i32) -> Self { + ReflectValueBox::I32(v) + } +} + +impl From<i64> for ReflectValueBox { + fn from(v: i64) -> Self { + ReflectValueBox::I64(v) + } +} + +impl From<f32> for ReflectValueBox { + fn from(v: f32) -> Self { + ReflectValueBox::F32(v) + } +} + +impl From<f64> for ReflectValueBox { + fn from(v: f64) -> Self { + ReflectValueBox::F64(v) + } +} + +impl From<bool> for ReflectValueBox { + fn from(v: bool) -> Self { + ReflectValueBox::Bool(v) + } +} + +impl From<String> for ReflectValueBox { + fn from(v: String) -> Self { + ReflectValueBox::String(v) + } +} + +impl From<Vec<u8>> for ReflectValueBox { + fn from(v: Vec<u8>) -> Self { + ReflectValueBox::Bytes(v) + } +} + +impl<'a> From<&'a EnumValueDescriptor> for ReflectValueBox { + fn from(v: &'a EnumValueDescriptor) -> Self { + ReflectValueBox::from(v.clone()) + } +} + +impl From<EnumValueDescriptor> for ReflectValueBox { + fn from(v: EnumValueDescriptor) -> Self { + let number = v.value(); + ReflectValueBox::Enum(v.enum_descriptor, number) + } +} + +impl From<Box<dyn MessageDyn>> for ReflectValueBox { + fn from(v: Box<dyn MessageDyn>) -> Self { + ReflectValueBox::Message(v) + } +} + +fn _assert_value_box_send_sync() { + fn _assert_send_sync<T: Send + Sync>() {} + _assert_send_sync::<ReflectValueBox>(); +} + +impl ReflectValueBox { + /// Type of this value. + pub fn get_type(&self) -> RuntimeType { + self.as_value_ref().get_type() + } + + /// As ref + pub fn as_value_ref(&self) -> ReflectValueRef { + match self { + ReflectValueBox::U32(v) => ReflectValueRef::U32(*v), + ReflectValueBox::U64(v) => ReflectValueRef::U64(*v), + ReflectValueBox::I32(v) => ReflectValueRef::I32(*v), + ReflectValueBox::I64(v) => ReflectValueRef::I64(*v), + ReflectValueBox::F32(v) => ReflectValueRef::F32(*v), + ReflectValueBox::F64(v) => ReflectValueRef::F64(*v), + ReflectValueBox::Bool(v) => ReflectValueRef::Bool(*v), + ReflectValueBox::String(ref v) => ReflectValueRef::String(v.as_str()), + ReflectValueBox::Bytes(ref v) => ReflectValueRef::Bytes(v.as_slice()), + ReflectValueBox::Enum(d, v) => ReflectValueRef::Enum(d.clone(), *v), + ReflectValueBox::Message(v) => ReflectValueRef::Message(MessageRef::from(&**v)), + } + } + + pub(crate) fn as_value_mut(&mut self) -> ReflectValueMut { + match self { + ReflectValueBox::Message(m) => ReflectValueMut::Message(&mut **m), + _ => panic!( + "ReflectValueMut cannot be constructed from {:?}", + self.get_type() + ), + } + } + + /// Downcast to real typed value. + /// + /// For `enum` `V` can be either `V: ProtobufEnum` or `V: ProtobufEnumOrUnknown<E>`. + pub fn downcast<V: ProtobufValue>(self) -> Result<V, Self> { + V::RuntimeType::from_value_box(self) + } +} + +impl<'a> PartialEq for ReflectValueBox { + fn eq(&self, other: &Self) -> bool { + self.as_value_ref() == other.as_value_ref() + } +} + +impl<'a> PartialEq<ReflectValueBox> for ReflectValueRef<'a> { + fn eq(&self, other: &ReflectValueBox) -> bool { + *self == other.as_value_ref() + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn reflect_value_box_downcast_primitive() { + assert_eq!(Ok(10), ReflectValueBox::U32(10).downcast::<u32>()); + assert_eq!( + Err(ReflectValueBox::I32(10)), + ReflectValueBox::I32(10).downcast::<u32>() + ); + } + + #[test] + fn reflect_value_box_downcast_string() { + assert_eq!( + Ok("aa".to_owned()), + ReflectValueBox::String("aa".to_owned()).downcast::<String>() + ); + assert_eq!( + Err(ReflectValueBox::String("aa".to_owned())), + ReflectValueBox::String("aa".to_owned()).downcast::<u32>() + ); + assert_eq!( + Err(ReflectValueBox::Bool(false)), + ReflectValueBox::Bool(false).downcast::<String>() + ); + } +} diff --git a/src/reflect/value/value_ref.rs b/src/reflect/value/value_ref.rs new file mode 100644 index 0000000..18f8241 --- /dev/null +++ b/src/reflect/value/value_ref.rs @@ -0,0 +1,370 @@ +use std::fmt; +use std::hash::Hash; +use std::hash::Hasher; +use std::mem; + +use crate::reflect::value::value_box::ReflectValueBox; +use crate::reflect::EnumDescriptor; +use crate::reflect::EnumValueDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::MessageRef; +use crate::reflect::ProtobufValue; +use crate::reflect::ReflectEq; +use crate::reflect::ReflectEqMode; +use crate::reflect::RuntimeType; +use crate::MessageDyn; + +/// A reference to a value +#[derive(Debug, Clone)] +pub enum ReflectValueRef<'a> { + /// `u32` + U32(u32), + /// `u64` + U64(u64), + /// `i32` + I32(i32), + /// `i64` + I64(i64), + /// `f32` + F32(f32), + /// `f64` + F64(f64), + /// `bool` + Bool(bool), + /// `string` + String(&'a str), + /// `bytes` + Bytes(&'a [u8]), + /// `enum` + Enum( + EnumDescriptor, + /// Enum value. + /// + /// Note when `allow_alias` option is enabled, more than one enum variant + /// may have the same value. + i32, + ), + /// `message` + Message(MessageRef<'a>), +} + +impl<'a> fmt::Display for ReflectValueRef<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ReflectValueRef::U32(v) => write!(f, "{}", v), + ReflectValueRef::U64(v) => write!(f, "{}", v), + ReflectValueRef::I32(v) => write!(f, "{}", v), + ReflectValueRef::I64(v) => write!(f, "{}", v), + ReflectValueRef::F32(v) => write!(f, "{}", v), + ReflectValueRef::F64(v) => write!(f, "{}", v), + ReflectValueRef::Bool(v) => write!(f, "{}", v), + ReflectValueRef::String(v) => write!(f, "{}", v), + // TODO: better display + ReflectValueRef::Bytes(v) => write!(f, "{:?}", v), + ReflectValueRef::Enum(descriptor, value) => match descriptor.value_by_number(*value) { + Some(v) => write!(f, "{}", v.name()), + None => write!(f, "{}", value), + }, + ReflectValueRef::Message(msg) => write!(f, "{}", msg), + } + } +} + +impl<'a> ReflectValueRef<'a> { + /// Get type of this value. + pub fn get_type(&self) -> RuntimeType { + match self { + ReflectValueRef::U32(..) => RuntimeType::U32, + ReflectValueRef::U64(..) => RuntimeType::U64, + ReflectValueRef::I32(..) => RuntimeType::I32, + ReflectValueRef::I64(..) => RuntimeType::I64, + ReflectValueRef::F32(..) => RuntimeType::F32, + ReflectValueRef::F64(..) => RuntimeType::F64, + ReflectValueRef::Bool(..) => RuntimeType::Bool, + ReflectValueRef::String(..) => RuntimeType::String, + ReflectValueRef::Bytes(..) => RuntimeType::VecU8, + ReflectValueRef::Enum(d, ..) => RuntimeType::Enum(d.clone()), + ReflectValueRef::Message(m) => RuntimeType::Message(m.descriptor_dyn()), + } + } + + /// Value is "non-zero"? + pub(crate) fn is_non_zero(&self) -> bool { + match self { + ReflectValueRef::U32(v) => *v != 0, + ReflectValueRef::U64(v) => *v != 0, + ReflectValueRef::I32(v) => *v != 0, + ReflectValueRef::I64(v) => *v != 0, + ReflectValueRef::F32(v) => *v != 0., + ReflectValueRef::F64(v) => *v != 0., + ReflectValueRef::Bool(v) => *v, + ReflectValueRef::String(v) => !v.is_empty(), + ReflectValueRef::Bytes(v) => !v.is_empty(), + ReflectValueRef::Enum(_d, v) => *v != 0, + ReflectValueRef::Message(_) => true, + } + } + + pub(crate) fn is_initialized(&self) -> bool { + if let ReflectValueRef::Message(m) = self { + m.is_initialized_dyn() + } else { + true + } + } + + /// Take `i32` value. + pub fn to_i32(&self) -> Option<i32> { + match *self { + ReflectValueRef::I32(v) => Some(v), + _ => None, + } + } + + /// Take `i64` value. + pub fn to_i64(&self) -> Option<i64> { + match *self { + ReflectValueRef::I64(v) => Some(v), + _ => None, + } + } + + /// Take `u32` value. + pub fn to_u32(&self) -> Option<u32> { + match *self { + ReflectValueRef::U32(v) => Some(v), + _ => None, + } + } + + /// Take `u64` value. + pub fn to_u64(&self) -> Option<u64> { + match *self { + ReflectValueRef::U64(v) => Some(v), + _ => None, + } + } + + /// Take `f32` value. + pub fn to_f32(&self) -> Option<f32> { + match *self { + ReflectValueRef::F32(v) => Some(v), + _ => None, + } + } + + /// Take `f64` value. + pub fn to_f64(&self) -> Option<f64> { + match *self { + ReflectValueRef::F64(v) => Some(v), + _ => None, + } + } + + /// Take `bool` value. + pub fn to_bool(&self) -> Option<bool> { + match *self { + ReflectValueRef::Bool(v) => Some(v), + _ => None, + } + } + + /// Take `str` value. + pub fn to_str(&self) -> Option<&str> { + match *self { + ReflectValueRef::String(v) => Some(v), + _ => None, + } + } + + /// Take `[u8]` value. + pub fn to_bytes(&self) -> Option<&[u8]> { + match *self { + ReflectValueRef::Bytes(v) => Some(v), + _ => None, + } + } + + /// Take enum value. + pub fn to_enum_value(&self) -> Option<i32> { + match *self { + ReflectValueRef::Enum(_, v) => Some(v), + _ => None, + } + } + + /// Take message value. + pub fn to_message(&self) -> Option<MessageRef<'a>> { + match self { + ReflectValueRef::Message(m) => Some(m.clone()), + _ => None, + } + } + + /// Clone to a box + pub fn to_box(&self) -> ReflectValueBox { + match self { + ReflectValueRef::U32(v) => ReflectValueBox::U32(*v), + ReflectValueRef::U64(v) => ReflectValueBox::U64(*v), + ReflectValueRef::I32(v) => ReflectValueBox::I32(*v), + ReflectValueRef::I64(v) => ReflectValueBox::I64(*v), + ReflectValueRef::F32(v) => ReflectValueBox::F32(*v), + ReflectValueRef::F64(v) => ReflectValueBox::F64(*v), + ReflectValueRef::Bool(v) => ReflectValueBox::Bool(*v), + ReflectValueRef::String(v) => ReflectValueBox::String((*v).to_owned()), + ReflectValueRef::Bytes(v) => ReflectValueBox::Bytes((*v).to_owned()), + ReflectValueRef::Enum(d, v) => ReflectValueBox::Enum(d.clone(), *v), + ReflectValueRef::Message(v) => ReflectValueBox::Message(v.clone_box()), + } + } + + /// Convert a value to arbitrary value. + pub fn downcast_clone<V: ProtobufValue>(&self) -> Result<V, Self> { + self.to_box().downcast().map_err(|_| self.clone()) + } +} + +pub enum ReflectValueMut<'a> { + Message(&'a mut dyn MessageDyn), +} + +impl<'a> ReflectEq for ReflectValueRef<'a> { + fn reflect_eq(&self, that: &Self, mode: &ReflectEqMode) -> bool { + use crate::reflect::value::value_ref::ReflectValueRef::*; + match (self, that) { + (U32(a), U32(b)) => a == b, + (U64(a), U64(b)) => a == b, + (I32(a), I32(b)) => a == b, + (I64(a), I64(b)) => a == b, + (F32(a), F32(b)) => { + if a.is_nan() || b.is_nan() { + a.is_nan() == b.is_nan() && mode.nan_equal + } else { + a == b + } + } + (F64(a), F64(b)) => { + if a.is_nan() || b.is_nan() { + a.is_nan() == b.is_nan() && mode.nan_equal + } else { + a == b + } + } + (Bool(a), Bool(b)) => a == b, + (String(a), String(b)) => a == b, + (Bytes(a), Bytes(b)) => a == b, + (Enum(ad, a), Enum(bd, b)) => ad == bd && a == b, + (Message(a), Message(b)) => a.reflect_eq(b, mode), + _ => false, + } + } +} + +impl<'a> PartialEq for ReflectValueRef<'a> { + fn eq(&self, other: &ReflectValueRef) -> bool { + use self::ReflectValueRef::*; + match (self, other) { + (U32(a), U32(b)) => a == b, + (U64(a), U64(b)) => a == b, + (I32(a), I32(b)) => a == b, + (I64(a), I64(b)) => a == b, + // should probably NaN == NaN here + (F32(a), F32(b)) => a == b, + (F64(a), F64(b)) => a == b, + (Bool(a), Bool(b)) => a == b, + (String(a), String(b)) => a == b, + (Bytes(a), Bytes(b)) => a == b, + (Enum(da, a), Enum(db, b)) => da == db && a == b, + (Message(a), Message(b)) => { + MessageDescriptor::reflect_eq_maybe_unrelated(&**a, &**b, &ReflectEqMode::default()) + } + _ => false, + } + } +} + +impl<'a> PartialEq<ReflectValueRef<'a>> for ReflectValueBox { + fn eq(&self, other: &ReflectValueRef) -> bool { + self.as_value_ref() == *other + } +} + +// Panics if contained type is not hashable +impl<'a> Hash for ReflectValueRef<'a> { + fn hash<H: Hasher>(&self, state: &mut H) { + use self::ReflectValueRef::*; + Hash::hash(&mem::discriminant(self), state); + match self { + U32(v) => Hash::hash(&v, state), + U64(v) => Hash::hash(&v, state), + I32(v) => Hash::hash(&v, state), + I64(v) => Hash::hash(&v, state), + Bool(v) => Hash::hash(&v, state), + String(v) => Hash::hash(&v, state), + Bytes(v) => Hash::hash(&v, state), + Enum(_d, v) => Hash::hash(v, state), + F32(_) | F64(_) | Message(_) => panic!("not hashable: {:?}", self), + } + } +} + +impl<'a> From<EnumValueDescriptor> for ReflectValueRef<'a> { + fn from(v: EnumValueDescriptor) -> Self { + let number = v.value(); + ReflectValueRef::Enum(v.enum_descriptor, number) + } +} + +impl From<u32> for ReflectValueRef<'_> { + fn from(v: u32) -> Self { + ReflectValueRef::U32(v) + } +} + +impl From<i32> for ReflectValueRef<'_> { + fn from(v: i32) -> Self { + ReflectValueRef::I32(v) + } +} + +impl From<u64> for ReflectValueRef<'_> { + fn from(v: u64) -> Self { + ReflectValueRef::U64(v) + } +} + +impl From<i64> for ReflectValueRef<'_> { + fn from(v: i64) -> Self { + ReflectValueRef::I64(v) + } +} + +impl From<f32> for ReflectValueRef<'_> { + fn from(v: f32) -> Self { + ReflectValueRef::F32(v) + } +} + +impl From<f64> for ReflectValueRef<'_> { + fn from(v: f64) -> Self { + ReflectValueRef::F64(v) + } +} + +impl From<bool> for ReflectValueRef<'_> { + fn from(v: bool) -> Self { + ReflectValueRef::Bool(v) + } +} + +impl<'a> From<&'a str> for ReflectValueRef<'a> { + fn from(v: &'a str) -> Self { + ReflectValueRef::String(v) + } +} + +impl<'a> From<&'a [u8]> for ReflectValueRef<'a> { + fn from(v: &'a [u8]) -> Self { + ReflectValueRef::Bytes(v) + } +} diff --git a/src/repeated.rs b/src/repeated.rs deleted file mode 100644 index 0b749d9..0000000 --- a/src/repeated.rs +++ /dev/null @@ -1,563 +0,0 @@ -use std::borrow::Borrow; -use std::cmp::Ordering; -use std::default::Default; -use std::fmt; -use std::hash::Hash; -use std::hash::Hasher; -use std::iter::FromIterator; -use std::iter::IntoIterator; -use std::ops::Deref; -use std::ops::DerefMut; -use std::ops::Index; -use std::ops::IndexMut; -use std::slice; -use std::vec; - -#[cfg(feature = "with-serde")] -use serde; - -use crate::clear::Clear; - -/// Wrapper around vector to avoid deallocations on clear. -pub struct RepeatedField<T> { - vec: Vec<T>, - len: usize, -} - -impl<T> RepeatedField<T> { - /// Return number of elements in this container. - #[inline] - pub fn len(&self) -> usize { - self.len - } - - /// Clear. - #[inline] - pub fn clear(&mut self) { - self.len = 0; - } -} - -impl<T> Clear for RepeatedField<T> { - #[inline] - fn clear(&mut self) { - self.len = 0; - } -} - -impl<T> Default for RepeatedField<T> { - #[inline] - fn default() -> RepeatedField<T> { - RepeatedField { - vec: Vec::new(), - len: 0, - } - } -} - -impl<T> RepeatedField<T> { - /// Create new empty container. - #[inline] - pub fn new() -> RepeatedField<T> { - Default::default() - } - - /// Create a contained with data from given vec. - #[inline] - pub fn from_vec(vec: Vec<T>) -> RepeatedField<T> { - let len = vec.len(); - RepeatedField { vec: vec, len: len } - } - - /// Convert data into vec. - #[inline] - pub fn into_vec(self) -> Vec<T> { - let mut vec = self.vec; - vec.truncate(self.len); - vec - } - - /// Return current capacity. - #[inline] - pub fn capacity(&self) -> usize { - self.vec.capacity() - } - - /// View data as slice. - #[inline] - pub fn as_slice<'a>(&'a self) -> &'a [T] { - &self.vec[..self.len] - } - - /// View data as mutable slice. - #[inline] - pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] { - &mut self.vec[..self.len] - } - - /// Get subslice of this container. - #[inline] - pub fn slice(&self, start: usize, end: usize) -> &[T] { - &self.as_ref()[start..end] - } - - /// Get mutable subslice of this container. - #[inline] - pub fn slice_mut(&mut self, start: usize, end: usize) -> &mut [T] { - &mut self.as_mut_slice()[start..end] - } - - /// Get slice from given index. - #[inline] - pub fn slice_from(&self, start: usize) -> &[T] { - &self.as_ref()[start..] - } - - /// Get mutable slice from given index. - #[inline] - pub fn slice_from_mut(&mut self, start: usize) -> &mut [T] { - &mut self.as_mut_slice()[start..] - } - - /// Get slice to given index. - #[inline] - pub fn slice_to(&self, end: usize) -> &[T] { - &self.as_ref()[..end] - } - - /// Get mutable slice to given index. - #[inline] - pub fn slice_to_mut(&mut self, end: usize) -> &mut [T] { - &mut self.as_mut_slice()[..end] - } - - /// View this container as two slices split at given index. - #[inline] - pub fn split_at<'a>(&'a self, mid: usize) -> (&'a [T], &'a [T]) { - self.as_ref().split_at(mid) - } - - /// View this container as two mutable slices split at given index. - #[inline] - pub fn split_at_mut<'a>(&'a mut self, mid: usize) -> (&'a mut [T], &'a mut [T]) { - self.as_mut_slice().split_at_mut(mid) - } - - /// View all but first elements of this container. - #[inline] - pub fn tail(&self) -> &[T] { - &self.as_ref()[1..] - } - - /// Last element of this container. - #[inline] - pub fn last(&self) -> Option<&T> { - self.as_ref().last() - } - - /// Mutable last element of this container. - #[inline] - pub fn last_mut<'a>(&'a mut self) -> Option<&'a mut T> { - self.as_mut_slice().last_mut() - } - - /// View all but last elements of this container. - #[inline] - pub fn init<'a>(&'a self) -> &'a [T] { - let s = self.as_ref(); - &s[0..s.len() - 1] - } - - /// Push an element to the end. - #[inline] - pub fn push(&mut self, value: T) { - if self.len == self.vec.len() { - self.vec.push(value); - } else { - self.vec[self.len] = value; - } - self.len += 1; - } - - /// Pop last element. - #[inline] - pub fn pop(&mut self) -> Option<T> { - if self.len == 0 { - None - } else { - self.vec.truncate(self.len); - self.len -= 1; - self.vec.pop() - } - } - - /// Insert an element at specified position. - #[inline] - pub fn insert(&mut self, index: usize, value: T) { - assert!(index <= self.len); - self.vec.insert(index, value); - self.len += 1; - } - - /// Remove an element from specified position. - #[inline] - pub fn remove(&mut self, index: usize) -> T { - assert!(index < self.len); - self.len -= 1; - self.vec.remove(index) - } - - /// Retains only the elements specified by the predicate. - /// - /// In other words, remove all elements `e` such that `f(&e)` returns `false`. - /// This method operates in place, visiting each element exactly once in the - /// original order, and preserves the order of the retained elements. - /// - /// # Examples - /// - /// ``` - /// # use protobuf::RepeatedField; - /// - /// let mut vec = RepeatedField::from(vec![1, 2, 3, 4]); - /// vec.retain(|&x| x % 2 == 0); - /// assert_eq!(vec, RepeatedField::from(vec![2, 4])); - /// ``` - pub fn retain<F>(&mut self, f: F) - where - F: FnMut(&T) -> bool, - { - // suboptimal - self.vec.truncate(self.len); - self.vec.retain(f); - self.len = self.vec.len(); - } - - /// Truncate at specified length. - #[inline] - pub fn truncate(&mut self, len: usize) { - if self.len > len { - self.len = len; - } - } - - /// Reverse in place. - #[inline] - pub fn reverse(&mut self) { - self.as_mut_slice().reverse() - } - - /// Into owned iterator. - #[inline] - pub fn into_iter(mut self) -> vec::IntoIter<T> { - self.vec.truncate(self.len); - self.vec.into_iter() - } - - /// Immutable data iterator. - #[inline] - pub fn iter<'a>(&'a self) -> slice::Iter<'a, T> { - self.as_ref().iter() - } - - /// Mutable data iterator. - #[inline] - pub fn iter_mut<'a>(&'a mut self) -> slice::IterMut<'a, T> { - self.as_mut_slice().iter_mut() - } - - /// Sort elements with given comparator. - #[inline] - pub fn sort_by<F>(&mut self, compare: F) - where - F: Fn(&T, &T) -> Ordering, - { - self.as_mut_slice().sort_by(compare) - } - - /// Get data as raw pointer. - #[inline] - pub fn as_ptr(&self) -> *const T { - self.vec.as_ptr() - } - - /// Get data a mutable raw pointer. - #[inline] - pub fn as_mut_ptr(&mut self) -> *mut T { - self.vec.as_mut_ptr() - } -} - -impl<T: Default + Clear> RepeatedField<T> { - /// Push default value. - /// This operation could be faster than `rf.push(Default::default())`, - /// because it may reuse previously allocated and cleared element. - pub fn push_default<'a>(&'a mut self) -> &'a mut T { - if self.len == self.vec.len() { - self.vec.push(Default::default()); - } else { - self.vec[self.len].clear(); - } - self.len += 1; - self.last_mut().unwrap() - } -} - -impl<T> From<Vec<T>> for RepeatedField<T> { - #[inline] - fn from(values: Vec<T>) -> RepeatedField<T> { - RepeatedField::from_vec(values) - } -} - -impl<'a, T: Clone> From<&'a [T]> for RepeatedField<T> { - #[inline] - fn from(values: &'a [T]) -> RepeatedField<T> { - RepeatedField::from_slice(values) - } -} - -impl<T> Into<Vec<T>> for RepeatedField<T> { - #[inline] - fn into(self) -> Vec<T> { - self.into_vec() - } -} - -impl<T: Clone> RepeatedField<T> { - /// Copy slice data to `RepeatedField` - #[inline] - pub fn from_slice(values: &[T]) -> RepeatedField<T> { - RepeatedField::from_vec(values.to_vec()) - } - - /// Copy slice data to `RepeatedField` - #[inline] - pub fn from_ref<X: AsRef<[T]>>(values: X) -> RepeatedField<T> { - RepeatedField::from_slice(values.as_ref()) - } - - /// Copy this data into new vec. - #[inline] - pub fn to_vec(&self) -> Vec<T> { - self.as_ref().to_vec() - } -} - -impl<T: Clone> Clone for RepeatedField<T> { - #[inline] - fn clone(&self) -> RepeatedField<T> { - RepeatedField { - vec: self.to_vec(), - len: self.len(), - } - } -} - -impl<T> FromIterator<T> for RepeatedField<T> { - #[inline] - fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> RepeatedField<T> { - RepeatedField::from_vec(FromIterator::from_iter(iter)) - } -} - -impl<'a, T> IntoIterator for &'a RepeatedField<T> { - type Item = &'a T; - type IntoIter = slice::Iter<'a, T>; - - fn into_iter(self) -> slice::Iter<'a, T> { - self.iter() - } -} - -impl<'a, T> IntoIterator for &'a mut RepeatedField<T> { - type Item = &'a mut T; - type IntoIter = slice::IterMut<'a, T>; - - fn into_iter(self) -> slice::IterMut<'a, T> { - self.iter_mut() - } -} - -impl<'a, T> IntoIterator for RepeatedField<T> { - type Item = T; - type IntoIter = vec::IntoIter<T>; - - fn into_iter(self) -> vec::IntoIter<T> { - self.into_iter() - } -} - -impl<T: PartialEq> PartialEq for RepeatedField<T> { - #[inline] - fn eq(&self, other: &RepeatedField<T>) -> bool { - self.as_ref() == other.as_ref() - } -} - -impl<T: Eq> Eq for RepeatedField<T> {} - -impl<T: PartialEq> PartialEq<[T]> for RepeatedField<T> { - fn eq(&self, other: &[T]) -> bool { - self.as_slice() == other - } -} - -impl<T: PartialEq> PartialEq<RepeatedField<T>> for [T] { - fn eq(&self, other: &RepeatedField<T>) -> bool { - self == other.as_slice() - } -} - -impl<T: PartialEq> RepeatedField<T> { - /// True iff this container contains given element. - #[inline] - pub fn contains(&self, value: &T) -> bool { - self.as_ref().contains(value) - } -} - -impl<T: Hash> Hash for RepeatedField<T> { - fn hash<H: Hasher>(&self, state: &mut H) { - self.as_ref().hash(state); - } -} - -impl<T> AsRef<[T]> for RepeatedField<T> { - #[inline] - fn as_ref<'a>(&'a self) -> &'a [T] { - &self.vec[..self.len] - } -} - -impl<T> Borrow<[T]> for RepeatedField<T> { - #[inline] - fn borrow(&self) -> &[T] { - &self.vec[..self.len] - } -} - -impl<T> Deref for RepeatedField<T> { - type Target = [T]; - #[inline] - fn deref(&self) -> &[T] { - &self.vec[..self.len] - } -} - -impl<T> DerefMut for RepeatedField<T> { - #[inline] - fn deref_mut(&mut self) -> &mut [T] { - &mut self.vec[..self.len] - } -} - -impl<T> Index<usize> for RepeatedField<T> { - type Output = T; - - #[inline] - fn index<'a>(&'a self, index: usize) -> &'a T { - &self.as_ref()[index] - } -} - -impl<T> IndexMut<usize> for RepeatedField<T> { - #[inline] - fn index_mut<'a>(&'a mut self, index: usize) -> &'a mut T { - &mut self.as_mut_slice()[index] - } -} - -impl<T> Extend<T> for RepeatedField<T> { - fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) { - self.vec.truncate(self.len); - self.vec.extend(iter); - self.len = self.vec.len(); - } -} - -impl<'a, T: Copy + 'a> Extend<&'a T> for RepeatedField<T> { - fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) { - self.vec.truncate(self.len); - self.vec.extend(iter); - self.len = self.vec.len(); - } -} - -impl<T: fmt::Debug> fmt::Debug for RepeatedField<T> { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.as_ref().fmt(f) - } -} - -#[cfg(feature = "with-serde")] -impl<T: serde::Serialize> serde::Serialize for RepeatedField<T> { - fn serialize<S>( - &self, - serializer: S, - ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> - where - S: serde::Serializer, - { - self.as_ref().serialize(serializer) - } -} - -#[cfg(feature = "with-serde")] -impl<'de, T: serde::Deserialize<'de> + Default> serde::Deserialize<'de> for RepeatedField<T> { - fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> - where - D: serde::Deserializer<'de>, - { - Vec::deserialize(deserializer).map(RepeatedField::from) - } -} - -#[cfg(test)] -mod test { - use super::RepeatedField; - - #[test] - fn as_mut_slice() { - let mut v = RepeatedField::new(); - v.push(10); - v.push(20); - v.clear(); - assert_eq!(v.as_mut_slice(), &mut []); - v.push(30); - assert_eq!(v.as_mut_slice(), &mut [30]); - } - - #[test] - fn push_default() { - let mut v = RepeatedField::new(); - v.push("aa".to_string()); - v.push("bb".to_string()); - v.clear(); - assert_eq!("".to_string(), *v.push_default()); - } - - #[test] - fn extend_values() { - let mut r = RepeatedField::new(); - r.push(10); - r.push(20); - r.clear(); - // self-check - assert_eq!(2, r.vec.len()); - r.extend(vec![30, 40]); - assert_eq!(&[30, 40][..], &r); - } - - #[test] - fn extend_copy() { - let mut r = RepeatedField::new(); - r.push(10); - r.push(20); - r.clear(); - // self-check - assert_eq!(2, r.vec.len()); - r.extend(&[30, 40]); - assert_eq!(&[30, 40][..], &r); - } -} diff --git a/src/rt.rs b/src/rt.rs deleted file mode 100644 index fca1254..0000000 --- a/src/rt.rs +++ /dev/null @@ -1,929 +0,0 @@ -//! Functions used by generated protobuf code. -//! Should not be used by programs written by hands. - -use std::collections::HashMap; -use std::default::Default; -use std::hash::Hash; - -#[cfg(feature = "bytes")] -use bytes::Bytes; - -#[cfg(feature = "bytes")] -use crate::chars::Chars; -use crate::coded_input_stream::CodedInputStream; -use crate::coded_output_stream::CodedOutputStream; -use crate::enums::ProtobufEnum; -use crate::error::ProtobufError; -use crate::error::ProtobufResult; -use crate::error::WireError; -pub use crate::lazy_v2::LazyV2; -use crate::message::*; -use crate::repeated::RepeatedField; -use crate::singular::SingularField; -use crate::singular::SingularPtrField; -use crate::types::*; -use crate::unknown::UnknownFields; -use crate::wire_format; -use crate::wire_format::WireType; -use crate::zigzag::*; - -/// Given `u64` value compute varint encoded length. -pub fn compute_raw_varint64_size(value: u64) -> u32 { - if (value & (0xffffffffffffffffu64 << 7)) == 0 { - return 1; - } - if (value & (0xffffffffffffffffu64 << 14)) == 0 { - return 2; - } - if (value & (0xffffffffffffffffu64 << 21)) == 0 { - return 3; - } - if (value & (0xffffffffffffffffu64 << 28)) == 0 { - return 4; - } - if (value & (0xffffffffffffffffu64 << 35)) == 0 { - return 5; - } - if (value & (0xffffffffffffffffu64 << 42)) == 0 { - return 6; - } - if (value & (0xffffffffffffffffu64 << 49)) == 0 { - return 7; - } - if (value & (0xffffffffffffffffu64 << 56)) == 0 { - return 8; - } - if (value & (0xffffffffffffffffu64 << 63)) == 0 { - return 9; - } - 10 -} - -/// Given `u32` value compute varint encoded length. -pub fn compute_raw_varint32_size(value: u32) -> u32 { - compute_raw_varint64_size(value as u64) -} - -/// Helper trait implemented by integer types which could be encoded as varint. -pub trait ProtobufVarint { - /// Size of self when encoded as varint. - fn len_varint(&self) -> u32; -} - -/// Helper trait implemented by integer types which could be encoded as zigzag varint. -pub trait ProtobufVarintZigzag { - /// Size of self when encoded as zigzag varint. - fn len_varint_zigzag(&self) -> u32; -} - -impl ProtobufVarint for u64 { - fn len_varint(&self) -> u32 { - compute_raw_varint64_size(*self) - } -} - -impl ProtobufVarint for u32 { - fn len_varint(&self) -> u32 { - (*self as u64).len_varint() - } -} - -impl ProtobufVarint for i64 { - fn len_varint(&self) -> u32 { - // same as length of u64 - (*self as u64).len_varint() - } -} - -impl ProtobufVarintZigzag for i64 { - fn len_varint_zigzag(&self) -> u32 { - compute_raw_varint64_size(encode_zig_zag_64(*self)) - } -} - -impl ProtobufVarint for i32 { - fn len_varint(&self) -> u32 { - // sign-extend and then compute - (*self as i64).len_varint() - } -} - -impl ProtobufVarintZigzag for i32 { - fn len_varint_zigzag(&self) -> u32 { - compute_raw_varint32_size(encode_zig_zag_32(*self)) - } -} - -impl ProtobufVarint for bool { - fn len_varint(&self) -> u32 { - 1 - } -} - -/* Commented out due to https://github.com/mozilla/rust/issues/8075 -impl<E:ProtobufEnum> ProtobufVarint for E { - fn len_varint(&self) -> u32 { - self.value().len_varint() - } -} -*/ - -/// Size of serialized repeated packed field, excluding length and tag. -pub fn vec_packed_varint_data_size<T: ProtobufVarint>(vec: &[T]) -> u32 { - vec.iter().map(|v| v.len_varint()).fold(0, |a, i| a + i) -} - -/// Size of serialized repeated packed field, excluding length and tag. -pub fn vec_packed_varint_zigzag_data_size<T: ProtobufVarintZigzag>(vec: &[T]) -> u32 { - vec.iter() - .map(|v| v.len_varint_zigzag()) - .fold(0, |a, i| a + i) -} - -/// Size of serialized repeated packed enum field, excluding length and tag. -pub fn vec_packed_enum_data_size<E: ProtobufEnum>(vec: &[E]) -> u32 { - vec.iter() - .map(|e| compute_raw_varint32_size(e.value() as u32)) - .fold(0, |a, i| a + i) -} - -/// Size of serialized data with length prefix and tag -pub fn vec_packed_varint_size<T: ProtobufVarint>(field_number: u32, vec: &[T]) -> u32 { - if vec.is_empty() { - 0 - } else { - let data_size = vec_packed_varint_data_size(vec); - tag_size(field_number) + data_size.len_varint() + data_size - } -} - -/// Size of serialized data with length prefix and tag -pub fn vec_packed_varint_zigzag_size<T: ProtobufVarintZigzag>(field_number: u32, vec: &[T]) -> u32 { - if vec.is_empty() { - 0 - } else { - let data_size = vec_packed_varint_zigzag_data_size(vec); - tag_size(field_number) + data_size.len_varint() + data_size - } -} - -/// Size of serialized data with length prefix and tag -pub fn vec_packed_enum_size<E: ProtobufEnum>(field_number: u32, vec: &[E]) -> u32 { - if vec.is_empty() { - 0 - } else { - let data_size = vec_packed_enum_data_size(vec); - tag_size(field_number) + data_size.len_varint() + data_size - } -} - -/// Compute tag size. Size of tag does not depend on wire type. -pub fn tag_size(field_number: u32) -> u32 { - wire_format::Tag::make(field_number, WireType::WireTypeFixed64) - .value() - .len_varint() -} - -fn value_size_no_tag<T: ProtobufVarint>(value: T, wt: WireType) -> u32 { - match wt { - WireType::WireTypeFixed64 => 8, - WireType::WireTypeFixed32 => 4, - WireType::WireTypeVarint => value.len_varint(), - _ => panic!(), - } -} - -/// Integer value size when encoded as specified wire type. -pub fn value_size<T: ProtobufVarint>(field_number: u32, value: T, wt: WireType) -> u32 { - tag_size(field_number) + value_size_no_tag(value, wt) -} - -/// Integer value size when encoded as specified wire type. -pub fn value_varint_zigzag_size_no_tag<T: ProtobufVarintZigzag>(value: T) -> u32 { - value.len_varint_zigzag() -} - -/// Length of value when encoding with zigzag encoding with tag -pub fn value_varint_zigzag_size<T: ProtobufVarintZigzag>(field_number: u32, value: T) -> u32 { - tag_size(field_number) + value_varint_zigzag_size_no_tag(value) -} - -fn enum_size_no_tag<E: ProtobufEnum>(value: E) -> u32 { - value.value().len_varint() -} - -/// Size of encoded enum field value. -pub fn enum_size<E: ProtobufEnum>(field_number: u32, value: E) -> u32 { - tag_size(field_number) + enum_size_no_tag(value) -} - -fn bytes_size_no_tag(bytes: &[u8]) -> u32 { - compute_raw_varint64_size(bytes.len() as u64) + bytes.len() as u32 -} - -/// Size of encoded bytes field. -pub fn bytes_size(field_number: u32, bytes: &[u8]) -> u32 { - tag_size(field_number) + bytes_size_no_tag(bytes) -} - -fn string_size_no_tag(s: &str) -> u32 { - bytes_size_no_tag(s.as_bytes()) -} - -/// Size of encoded string field. -pub fn string_size(field_number: u32, s: &str) -> u32 { - tag_size(field_number) + string_size_no_tag(s) -} - -/// Size of encoded unknown fields size. -pub fn unknown_fields_size(unknown_fields: &UnknownFields) -> u32 { - let mut r = 0; - for (number, values) in unknown_fields { - r += (tag_size(number) + 4) * values.fixed32.len() as u32; - r += (tag_size(number) + 8) * values.fixed64.len() as u32; - - r += tag_size(number) * values.varint.len() as u32; - for varint in &values.varint { - r += varint.len_varint(); - } - - r += tag_size(number) * values.length_delimited.len() as u32; - for bytes in &values.length_delimited { - r += bytes_size_no_tag(&bytes); - } - } - r -} - -/// Read repeated `int32` field into given vec. -pub fn read_repeated_int32_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_int32_into(target), - WireType::WireTypeVarint => { - target.push(is.read_int32()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `int64` field into given vec. -pub fn read_repeated_int64_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_int64_into(target), - WireType::WireTypeVarint => { - target.push(is.read_int64()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `uint32` field into given vec. -pub fn read_repeated_uint32_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<u32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_uint32_into(target), - WireType::WireTypeVarint => { - target.push(is.read_uint32()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `uint64` field into given vec. -pub fn read_repeated_uint64_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<u64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_uint64_into(target), - WireType::WireTypeVarint => { - target.push(is.read_uint64()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `sint32` field into given vec. -pub fn read_repeated_sint32_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_sint32_into(target), - WireType::WireTypeVarint => { - target.push(is.read_sint32()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `sint64` field into given vec. -pub fn read_repeated_sint64_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_sint64_into(target), - WireType::WireTypeVarint => { - target.push(is.read_sint64()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `fixed32` field into given vec. -pub fn read_repeated_fixed32_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<u32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_fixed32_into(target), - WireType::WireTypeFixed32 => { - target.push(is.read_fixed32()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `fixed64` field into given vec. -pub fn read_repeated_fixed64_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<u64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_fixed64_into(target), - WireType::WireTypeFixed64 => { - target.push(is.read_fixed64()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `sfixed32` field into given vec. -pub fn read_repeated_sfixed32_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_sfixed32_into(target), - WireType::WireTypeFixed32 => { - target.push(is.read_sfixed32()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `sfixed64` field into given vec. -pub fn read_repeated_sfixed64_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<i64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_sfixed64_into(target), - WireType::WireTypeFixed64 => { - target.push(is.read_sfixed64()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `double` field into given vec. -pub fn read_repeated_double_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<f64>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_double_into(target), - WireType::WireTypeFixed64 => { - target.push(is.read_double()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `float` field into given vec. -pub fn read_repeated_float_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<f32>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_float_into(target), - WireType::WireTypeFixed32 => { - target.push(is.read_float()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `bool` field into given vec. -pub fn read_repeated_bool_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<bool>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_bool_into(target), - WireType::WireTypeVarint => { - target.push(is.read_bool()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `enum` field into given vec. -/// This function is no longer called from generated code, remove in 1.5. -pub fn read_repeated_enum_into<E: ProtobufEnum>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<E>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_repeated_packed_enum_into(target), - WireType::WireTypeVarint => { - target.push(is.read_enum()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Helper function to read single enum value. -#[inline] -fn read_enum_with_unknown_fields_into<E: ProtobufEnum, C>( - is: &mut CodedInputStream, - target: C, - field_number: u32, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> -where - C: FnOnce(E), -{ - let i = is.read_int32()?; - match ProtobufEnum::from_i32(i) { - Some(e) => target(e), - None => unknown_fields.add_varint(field_number, i as i64 as u64), - } - Ok(()) -} - -fn read_repeated_packed_enum_with_unknown_fields_into<E: ProtobufEnum>( - is: &mut CodedInputStream, - target: &mut Vec<E>, - field_number: u32, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> { - let len = is.read_raw_varint64()?; - let old_limit = is.push_limit(len)?; - while !is.eof()? { - read_enum_with_unknown_fields_into(is, |e| target.push(e), field_number, unknown_fields)?; - } - is.pop_limit(old_limit); - Ok(()) -} - -/// Read repeated `enum` field into given vec, -/// and when value is unknown store it in unknown fields -/// which matches proto2 spec. -/// -/// See explanation -/// [here](https://github.com/stepancheg/rust-protobuf/issues/233#issuecomment-375142710) -pub fn read_repeated_enum_with_unknown_fields_into<E: ProtobufEnum>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<E>, - field_number: u32, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => read_repeated_packed_enum_with_unknown_fields_into( - is, - target, - field_number, - unknown_fields, - ), - WireType::WireTypeVarint => { - read_enum_with_unknown_fields_into(is, |e| target.push(e), field_number, unknown_fields) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `enum` field into given vec, -/// and when value is unknown store it in unknown fields -/// which matches proto2 spec. -/// -/// See explanation -/// [here](https://github.com/stepancheg/rust-protobuf/issues/233#issuecomment-375142710) -pub fn read_proto3_enum_with_unknown_fields_into<E: ProtobufEnum>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut E, - field_number: u32, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> { - if wire_type != WireType::WireTypeVarint { - return Err(unexpected_wire_type(wire_type)); - } - - read_enum_with_unknown_fields_into(is, |e| *target = e, field_number, unknown_fields) -} - -/// Read repeated `enum` field into given vec, -/// and when value is unknown store it in unknown fields -/// which matches proto2 spec. -/// -/// See explanation -/// [here](https://github.com/stepancheg/rust-protobuf/issues/233#issuecomment-375142710) -pub fn read_proto2_enum_with_unknown_fields_into<E: ProtobufEnum>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Option<E>, - field_number: u32, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> { - if wire_type != WireType::WireTypeVarint { - return Err(unexpected_wire_type(wire_type)); - } - - read_enum_with_unknown_fields_into(is, |e| *target = Some(e), field_number, unknown_fields) -} - -/// Read repeated `string` field into given vec. -pub fn read_repeated_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut RepeatedField<String>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - let tmp = target.push_default(); - is.read_string_into(tmp) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `Chars` field into given vec. -#[cfg(feature = "bytes")] -pub fn read_repeated_carllerche_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<Chars>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - target.push(is.read_carllerche_chars()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `string` field. -pub fn read_singular_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut SingularField<String>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - let tmp = target.set_default(); - is.read_string_into(tmp) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `Chars` field. -#[cfg(feature = "bytes")] -pub fn read_singular_carllerche_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Option<Chars>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - *target = Some(is.read_carllerche_chars()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `string` field for proto3. -pub fn read_singular_proto3_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut String, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_string_into(target), - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `Chars` field for proto3. -#[cfg(feature = "bytes")] -pub fn read_singular_proto3_carllerche_string_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Chars, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - *target = is.read_carllerche_chars()?; - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `bytes` field into given vec. -pub fn read_repeated_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut RepeatedField<Vec<u8>>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - let tmp = target.push_default(); - is.read_bytes_into(tmp) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `Bytes` field into given vec. -#[cfg(feature = "bytes")] -pub fn read_repeated_carllerche_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<Bytes>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - target.push(is.read_carllerche_bytes()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `bytes` field. -pub fn read_singular_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut SingularField<Vec<u8>>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - let tmp = target.set_default(); - is.read_bytes_into(tmp) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `Bytes` field. -#[cfg(feature = "bytes")] -pub fn read_singular_carllerche_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Option<Bytes>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - *target = Some(is.read_carllerche_bytes()?); - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `bytes` field for proto3. -pub fn read_singular_proto3_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Vec<u8>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => is.read_bytes_into(target), - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `Bytes` field for proto3. -#[cfg(feature = "bytes")] -pub fn read_singular_proto3_carllerche_bytes_into( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut Bytes, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - *target = is.read_carllerche_bytes()?; - Ok(()) - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read repeated `message` field. -pub fn read_repeated_message_into<M: Message + Default>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut RepeatedField<M>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - is.incr_recursion()?; - let tmp = target.push_default(); - let res = is.merge_message(tmp); - is.decr_recursion(); - res - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -/// Read singular `message` field. -pub fn read_singular_message_into<M: Message + Default>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut SingularPtrField<M>, -) -> ProtobufResult<()> { - match wire_type { - WireType::WireTypeLengthDelimited => { - is.incr_recursion()?; - let tmp = target.set_default(); - let res = is.merge_message(tmp); - is.decr_recursion(); - res - } - _ => Err(unexpected_wire_type(wire_type)), - } -} - -fn skip_group(is: &mut CodedInputStream) -> ProtobufResult<()> { - loop { - let (_, wire_type) = is.read_tag_unpack()?; - if wire_type == wire_format::WireTypeEndGroup { - return Ok(()); - } - is.skip_field(wire_type)?; - } -} - -/// Handle unknown field in generated code. -/// Either store a value in unknown, or skip a group. -pub fn read_unknown_or_skip_group( - field_number: u32, - wire_type: WireType, - is: &mut CodedInputStream, - unknown_fields: &mut UnknownFields, -) -> ProtobufResult<()> { - match wire_type { - wire_format::WireTypeStartGroup => skip_group(is), - _ => { - let unknown = is.read_unknown(wire_type)?; - unknown_fields.add_value(field_number, unknown); - Ok(()) - } - } -} - -/// Create an error for unexpected wire type. -/// -/// Function is used in generated code, so error types can be changed, -/// but this function remains unchanged. -pub fn unexpected_wire_type(wire_type: WireType) -> ProtobufError { - ProtobufError::WireError(WireError::UnexpectedWireType(wire_type)) -} - -/// Compute serialized size of `map` field and cache nested field sizes. -pub fn compute_map_size<K, V>(field_number: u32, map: &HashMap<K::Value, V::Value>) -> u32 -where - K: ProtobufType, - V: ProtobufType, - K::Value: Eq + Hash, -{ - let mut sum = 0; - for (k, v) in map { - let key_tag_size = 1; - let value_tag_size = 1; - - let key_len = K::compute_size_with_length_delimiter(k); - let value_len = V::compute_size_with_length_delimiter(v); - - let entry_len = key_tag_size + key_len + value_tag_size + value_len; - sum += tag_size(field_number) + compute_raw_varint32_size(entry_len) + entry_len; - } - sum -} - -/// Write map, message sizes must be already known. -pub fn write_map_with_cached_sizes<K, V>( - field_number: u32, - map: &HashMap<K::Value, V::Value>, - os: &mut CodedOutputStream, -) -> ProtobufResult<()> -where - K: ProtobufType, - V: ProtobufType, - K::Value: Eq + Hash, -{ - for (k, v) in map { - let key_tag_size = 1; - let value_tag_size = 1; - - let key_len = K::get_cached_size_with_length_delimiter(k); - let value_len = V::get_cached_size_with_length_delimiter(v); - - let entry_len = key_tag_size + key_len + value_tag_size + value_len; - - os.write_tag(field_number, WireType::WireTypeLengthDelimited)?; - os.write_raw_varint32(entry_len)?; - K::write_with_cached_size(1, k, os)?; - V::write_with_cached_size(2, v, os)?; - } - Ok(()) -} - -/// Read `map` field. -pub fn read_map_into<K, V>( - wire_type: WireType, - is: &mut CodedInputStream, - target: &mut HashMap<K::Value, V::Value>, -) -> ProtobufResult<()> -where - K: ProtobufType, - V: ProtobufType, - K::Value: Eq + Hash + Default, - V::Value: Default, -{ - if wire_type != WireType::WireTypeLengthDelimited { - return Err(unexpected_wire_type(wire_type)); - } - - let mut key = Default::default(); - let mut value = Default::default(); - - let len = is.read_raw_varint32()?; - let old_limit = is.push_limit(len as u64)?; - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != K::wire_type() { - return Err(unexpected_wire_type(wire_type)); - } - key = K::read(is)?; - } - 2 => { - if wire_type != V::wire_type() { - return Err(unexpected_wire_type(wire_type)); - } - value = V::read(is)?; - } - _ => is.skip_field(wire_type)?, - } - } - is.pop_limit(old_limit); - - target.insert(key, value); - - Ok(()) -} diff --git a/src/rt/map.rs b/src/rt/map.rs new file mode 100644 index 0000000..0693a2b --- /dev/null +++ b/src/rt/map.rs @@ -0,0 +1,35 @@ +use crate::error::WireError; +use crate::wire_format::WireType; +use crate::CodedInputStream; + +pub(crate) fn read_map_template_new( + is: &mut CodedInputStream, + mut key: impl FnMut(WireType, &mut CodedInputStream) -> crate::Result<()>, + mut value: impl FnMut(WireType, &mut CodedInputStream) -> crate::Result<()>, +) -> crate::Result<()> { + let len = is.read_raw_varint32()?; + let old_limit = is.push_limit(len as u64)?; + while !is.eof()? { + let (field_number, wire_type) = is.read_tag_unpack()?; + match field_number { + 1 => key(wire_type, is)?, + 2 => value(wire_type, is)?, + _ => is.skip_field(wire_type)?, + } + } + is.pop_limit(old_limit); + Ok(()) +} + +pub(crate) fn read_map_template( + wire_type: WireType, + is: &mut CodedInputStream, + key: impl FnMut(WireType, &mut CodedInputStream) -> crate::Result<()>, + value: impl FnMut(WireType, &mut CodedInputStream) -> crate::Result<()>, +) -> crate::Result<()> { + if wire_type != WireType::LengthDelimited { + return Err(WireError::UnexpectedWireType(wire_type).into()); + } + + read_map_template_new(is, key, value) +} diff --git a/src/rt/message.rs b/src/rt/message.rs new file mode 100644 index 0000000..89434c0 --- /dev/null +++ b/src/rt/message.rs @@ -0,0 +1,33 @@ +use crate::wire_format::WireType; +use crate::CodedInputStream; +use crate::CodedOutputStream; +use crate::Message; +use crate::MessageField; + +/// Read singular `message` field. +pub fn read_singular_message_into_field<M>( + is: &mut CodedInputStream, + target: &mut MessageField<M>, +) -> crate::Result<()> +where + M: Message, +{ + let mut m = M::new(); + is.merge_message(&mut m)?; + *target = MessageField::some(m); + Ok(()) +} + +/// Write message with field number and length to the stream. +pub fn write_message_field_with_cached_size<M>( + field_number: u32, + message: &M, + os: &mut CodedOutputStream, +) -> crate::Result<()> +where + M: Message, +{ + os.write_tag(field_number, WireType::LengthDelimited)?; + os.write_raw_varint32(message.cached_size())?; + message.write_to_with_cached_sizes(os) +} diff --git a/src/rt/mod.rs b/src/rt/mod.rs new file mode 100644 index 0000000..90db0eb --- /dev/null +++ b/src/rt/mod.rs @@ -0,0 +1,62 @@ +//! # Functions and types used by generated protobuf code +//! +//! These are not considered to be public API of rust-protobuf, +//! so they can be changed any time (provided compatibility with +//! previously generated code is preserved). + +pub(crate) mod map; +mod message; +pub(crate) mod packed; +pub(crate) mod repeated; +pub(crate) mod singular; +pub(crate) mod unknown_or_group; + +pub use message::read_singular_message_into_field; +pub use message::write_message_field_with_cached_size; +pub use packed::vec_packed_bool_size; +pub use packed::vec_packed_double_size; +pub use packed::vec_packed_enum_or_unknown_size; +pub use packed::vec_packed_fixed32_size; +pub use packed::vec_packed_fixed64_size; +pub use packed::vec_packed_float_size; +pub use packed::vec_packed_int32_size; +pub use packed::vec_packed_int64_size; +pub use packed::vec_packed_sfixed32_size; +pub use packed::vec_packed_sfixed64_size; +pub use packed::vec_packed_sint32_size; +pub use packed::vec_packed_sint64_size; +pub use packed::vec_packed_uint32_size; +pub use packed::vec_packed_uint64_size; +pub use repeated::read_repeated_packed_enum_or_unknown_into; +pub use singular::bytes_size; +pub use singular::int32_size; +pub use singular::int64_size; +pub use singular::sint32_size; +pub use singular::sint64_size; +pub use singular::string_size; +pub use singular::uint32_size; +pub use singular::uint64_size; +pub use unknown_or_group::read_unknown_or_skip_group; +pub use unknown_or_group::skip_field_for_tag; +pub use unknown_or_group::unknown_fields_size; + +pub use crate::cached_size::CachedSize; +pub use crate::lazy::Lazy; +use crate::varint::encode::encoded_varint64_len; +pub use crate::wire_format::WireType; + +/// Given `u64` value compute varint encoded length. +pub fn compute_raw_varint64_size(value: u64) -> u64 { + encoded_varint64_len(value) as u64 +} + +/// Given `u32` value compute varint encoded length. +pub(crate) fn compute_raw_varint32_size(value: u32) -> u64 { + compute_raw_varint64_size(value as u64) +} + +/// Compute tag size. Size of tag does not depend on wire type. +#[inline] +pub fn tag_size(field_number: u32) -> u64 { + encoded_varint64_len((field_number as u64) << 3) as u64 +} diff --git a/src/rt/packed.rs b/src/rt/packed.rs new file mode 100644 index 0000000..d7132d4 --- /dev/null +++ b/src/rt/packed.rs @@ -0,0 +1,154 @@ +use crate::fixed::ProtobufFixed; +use crate::rt::compute_raw_varint32_size; +use crate::rt::tag_size; +use crate::varint::generic::ProtobufVarint; +use crate::zigzag::ProtobufVarintZigzag; +use crate::Enum; +use crate::EnumOrUnknown; + +/// Size of serialized repeated packed field, excluding length and tag. +pub(crate) fn vec_packed_varint_data_size<T: ProtobufVarint>(vec: &[T]) -> u64 { + vec.iter().map(|v| v.len_varint() as u64).sum() +} + +/// Size of serialized repeated packed field, excluding length and tag. +pub(crate) fn vec_packed_varint_zigzag_data_size<T: ProtobufVarintZigzag>(vec: &[T]) -> u64 { + vec.iter().map(|v| v.len_varint_zigzag()).sum() +} + +/// Size of serialized repeated packed enum field, excluding length and tag. +pub(crate) fn vec_packed_enum_or_unknown_data_size<E: Enum>(vec: &[EnumOrUnknown<E>]) -> u64 { + vec.iter() + .map(|e| compute_raw_varint32_size(e.value() as u32)) + .sum() +} + +/// Size of serialized data with length prefix and tag +#[inline] +fn vec_packed_varint_size<T: ProtobufVarint>(field_number: u32, vec: &[T]) -> u64 { + if vec.is_empty() { + 0 + } else { + let data_size = vec_packed_varint_data_size(vec); + tag_size(field_number) + data_size.len_varint() + data_size + } +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_int32_size(field_number: u32, vec: &[i32]) -> u64 { + vec_packed_varint_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_int64_size(field_number: u32, vec: &[i64]) -> u64 { + vec_packed_varint_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_uint32_size(field_number: u32, vec: &[u32]) -> u64 { + vec_packed_varint_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_uint64_size(field_number: u32, vec: &[u64]) -> u64 { + vec_packed_varint_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag +#[inline] +fn vec_packed_varint_zigzag_size<T: ProtobufVarintZigzag>(field_number: u32, vec: &[T]) -> u64 { + if vec.is_empty() { + 0 + } else { + let data_size = vec_packed_varint_zigzag_data_size(vec); + tag_size(field_number) + data_size.len_varint() + data_size + } +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_sint32_size(field_number: u32, vec: &[i32]) -> u64 { + vec_packed_varint_zigzag_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag. +#[inline] +pub fn vec_packed_sint64_size(field_number: u32, vec: &[i64]) -> u64 { + vec_packed_varint_zigzag_size(field_number, vec) +} + +/// Size of serialized data with length prefix and tag +#[inline] +pub fn vec_packed_enum_or_unknown_size<E: Enum>( + field_number: u32, + vec: &[EnumOrUnknown<E>], +) -> u64 { + if vec.is_empty() { + 0 + } else { + let data_size = vec_packed_enum_or_unknown_data_size(vec); + tag_size(field_number) + data_size.len_varint() + data_size + } +} + +/// Compute data size of fixed encoding of repeated field data. +pub(crate) fn vec_packed_fixed_data_size<V: ProtobufFixed>(vec: &[V]) -> u64 { + (vec.len() as u64) * (V::LEN as u64) +} + +/// Compute field size (data plus header) of fixed encoding of repeated field. +#[inline] +fn vec_packed_fixed_size<V: ProtobufFixed>(field_number: u32, vec: &[V]) -> u64 { + if vec.is_empty() { + 0 + } else { + let data_size = vec_packed_fixed_data_size::<V>(vec); + tag_size(field_number) + data_size.len_varint() + data_size + } +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_fixed32_size(field_number: u32, vec: &[u32]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_fixed64_size(field_number: u32, vec: &[u64]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_sfixed32_size(field_number: u32, vec: &[i32]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_sfixed64_size(field_number: u32, vec: &[i64]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_float_size(field_number: u32, vec: &[f32]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_double_size(field_number: u32, vec: &[f64]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} + +/// Compute data size of fixed encoding of repeated field data. +#[inline] +pub fn vec_packed_bool_size(field_number: u32, vec: &[bool]) -> u64 { + vec_packed_fixed_size(field_number, vec) +} diff --git a/src/rt/repeated.rs b/src/rt/repeated.rs new file mode 100644 index 0000000..1af9994 --- /dev/null +++ b/src/rt/repeated.rs @@ -0,0 +1,17 @@ +use crate::CodedInputStream; +use crate::Enum; +use crate::EnumOrUnknown; + +/// Read repeated enum field when the wire format is length-delimited. +pub fn read_repeated_packed_enum_or_unknown_into<E: Enum>( + is: &mut CodedInputStream, + target: &mut Vec<EnumOrUnknown<E>>, +) -> crate::Result<()> { + let len = is.read_raw_varint64()?; + let old_limit = is.push_limit(len)?; + while !is.eof()? { + target.push(is.read_enum_or_unknown()?); + } + is.pop_limit(old_limit); + Ok(()) +} diff --git a/src/rt/singular.rs b/src/rt/singular.rs new file mode 100644 index 0000000..e607046 --- /dev/null +++ b/src/rt/singular.rs @@ -0,0 +1,79 @@ +use crate::rt::compute_raw_varint64_size; +use crate::rt::tag_size; +use crate::varint::generic::ProtobufVarint; +use crate::zigzag::ProtobufVarintZigzag; + +/// Integer value size when encoded. +#[inline] +fn varint_size<T: ProtobufVarint>(field_number: u32, value: T) -> u64 { + tag_size(field_number) + value.len_varint() +} + +/// Encoded `int32` size. +#[inline] +pub fn int32_size(field_number: u32, value: i32) -> u64 { + varint_size(field_number, value) +} + +/// Encoded `int64` size. +#[inline] +pub fn int64_size(field_number: u32, value: i64) -> u64 { + varint_size(field_number, value) +} + +/// Encoded `uint32` size. +#[inline] +pub fn uint32_size(field_number: u32, value: u32) -> u64 { + varint_size(field_number, value) +} + +/// Encoded `uint64` size. +#[inline] +pub fn uint64_size(field_number: u32, value: u64) -> u64 { + varint_size(field_number, value) +} + +/// Integer value size when encoded as specified wire type. +pub(crate) fn value_varint_zigzag_size_no_tag<T: ProtobufVarintZigzag>(value: T) -> u64 { + value.len_varint_zigzag() +} + +/// Length of value when encoding with zigzag encoding with tag +#[inline] +fn value_varint_zigzag_size<T: ProtobufVarintZigzag>(field_number: u32, value: T) -> u64 { + tag_size(field_number) + value_varint_zigzag_size_no_tag(value) +} + +/// Size of serialized `sint32` field. +#[inline] +pub fn sint32_size(field_number: u32, value: i32) -> u64 { + value_varint_zigzag_size(field_number, value) +} + +/// Size of serialized `sint64` field. +#[inline] +pub fn sint64_size(field_number: u32, value: i64) -> u64 { + value_varint_zigzag_size(field_number, value) +} + +/// Size of encoded bytes field. +pub(crate) fn bytes_size_no_tag(bytes: &[u8]) -> u64 { + compute_raw_varint64_size(bytes.len() as u64) + bytes.len() as u64 +} + +/// Size of encoded bytes field. +#[inline] +pub fn bytes_size(field_number: u32, bytes: &[u8]) -> u64 { + tag_size(field_number) + bytes_size_no_tag(bytes) +} + +/// Size of encoded string field. +pub(crate) fn string_size_no_tag(s: &str) -> u64 { + bytes_size_no_tag(s.as_bytes()) +} + +/// Size of encoded string field. +#[inline] +pub fn string_size(field_number: u32, s: &str) -> u64 { + tag_size(field_number) + string_size_no_tag(s) +} diff --git a/src/rt/unknown_or_group.rs b/src/rt/unknown_or_group.rs new file mode 100644 index 0000000..33e6882 --- /dev/null +++ b/src/rt/unknown_or_group.rs @@ -0,0 +1,69 @@ +use crate::rt::compute_raw_varint64_size; +use crate::rt::singular::bytes_size_no_tag; +use crate::rt::tag_size; +use crate::wire_format::Tag; +use crate::wire_format::WireType; +use crate::CodedInputStream; +use crate::UnknownFields; +use crate::UnknownValueRef; + +fn skip_group(is: &mut CodedInputStream) -> crate::Result<()> { + loop { + let (_, wire_type) = is.read_tag_unpack()?; + if wire_type == WireType::EndGroup { + return Ok(()); + } + is.skip_field(wire_type)?; + } +} + +/// Size of encoded unknown fields size. +pub fn unknown_fields_size(unknown_fields: &UnknownFields) -> u64 { + let mut r = 0; + for (number, value) in unknown_fields { + r += tag_size(number); + r += match value { + UnknownValueRef::Fixed32(_) => 4, + UnknownValueRef::Fixed64(_) => 8, + UnknownValueRef::Varint(v) => compute_raw_varint64_size(v), + UnknownValueRef::LengthDelimited(v) => bytes_size_no_tag(v), + }; + } + r +} + +/// Handle unknown field in generated code. +/// Either store a value in unknown, or skip a group. +pub(crate) fn read_unknown_or_skip_group_with_tag_unpacked( + field_number: u32, + wire_type: WireType, + is: &mut CodedInputStream, + unknown_fields: &mut UnknownFields, +) -> crate::Result<()> { + match wire_type { + WireType::StartGroup => skip_group(is), + _ => { + let unknown = is.read_unknown(wire_type)?; + unknown_fields.add_value(field_number, unknown); + Ok(()) + } + } +} + +/// Handle unknown field in generated code. +/// Either store a value in unknown, or skip a group. +/// Return error if tag is incorrect. +pub fn read_unknown_or_skip_group( + tag: u32, + is: &mut CodedInputStream, + unknown_fields: &mut UnknownFields, +) -> crate::Result<()> { + let (field_humber, wire_type) = Tag::new(tag)?.unpack(); + read_unknown_or_skip_group_with_tag_unpacked(field_humber, wire_type, is, unknown_fields) +} + +/// Skip field. +pub fn skip_field_for_tag(tag: u32, is: &mut CodedInputStream) -> crate::Result<()> { + let (_field_humber, wire_type) = Tag::new(tag)?.unpack(); + is.skip_field(wire_type) +} diff --git a/src/rust.rs b/src/rust.rs deleted file mode 100644 index 9d4995b..0000000 --- a/src/rust.rs +++ /dev/null @@ -1,121 +0,0 @@ -#[cfg_attr(rustfmt, rustfmt_skip)] -static RUST_KEYWORDS: &'static [&'static str] = &[ - "as", - "async", - "await", - "break", - "crate", - "dyn", - "else", - "enum", - "extern", - "false", - "fn", - "for", - "if", - "impl", - "in", - "let", - "loop", - "match", - "mod", - "move", - "mut", - "pub", - "ref", - "return", - "static", - "self", - "Self", - "struct", - "super", - "true", - "trait", - "type", - "unsafe", - "use", - "while", - "continue", - "box", - "const", - "where", - "virtual", - "proc", - "alignof", - "become", - "offsetof", - "priv", - "pure", - "sizeof", - "typeof", - "unsized", - "yield", - "do", - "abstract", - "final", - "override", - "macro", -]; - -pub fn is_rust_keyword(ident: &str) -> bool { - RUST_KEYWORDS.contains(&ident) -} - -fn hex_digit(value: u32) -> char { - if value < 10 { - (b'0' + value as u8) as char - } else if value < 0x10 { - (b'a' + value as u8 - 10) as char - } else { - unreachable!() - } -} - -pub fn quote_escape_str(s: &str) -> String { - let mut buf = String::new(); - buf.push('"'); - buf.extend(s.chars().flat_map(|c| c.escape_default())); - buf.push('"'); - buf -} - -pub fn quote_escape_bytes(bytes: &[u8]) -> String { - let mut buf = String::new(); - buf.push('b'); - buf.push('"'); - for &b in bytes { - match b { - b'\n' => buf.push_str(r"\n"), - b'\r' => buf.push_str(r"\r"), - b'\t' => buf.push_str(r"\t"), - b'"' => buf.push_str("\\\""), - b'\\' => buf.push_str(r"\\"), - b'\x20'..=b'\x7e' => buf.push(b as char), - _ => { - buf.push_str(r"\x"); - buf.push(hex_digit((b as u32) >> 4)); - buf.push(hex_digit((b as u32) & 0x0f)); - } - } - } - buf.push('"'); - buf -} - -#[cfg(test)] -mod test { - - use super::*; - - #[test] - fn test_quote_escape_bytes() { - assert_eq!("b\"\"", quote_escape_bytes(b"")); - assert_eq!("b\"xyZW\"", quote_escape_bytes(b"xyZW")); - assert_eq!("b\"aa\\\"bb\"", quote_escape_bytes(b"aa\"bb")); - assert_eq!("b\"aa\\r\\n\\tbb\"", quote_escape_bytes(b"aa\r\n\tbb")); - assert_eq!( - "b\"\\x00\\x01\\x12\\xfe\\xff\"", - quote_escape_bytes(b"\x00\x01\x12\xfe\xff") - ); - } -} diff --git a/src/rustproto.rs b/src/rustproto.rs index 75df067..2c22af1 100644 --- a/src/rustproto.rs +++ b/src/rustproto.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,189 +16,155 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `rustproto.proto` /// Extension fields pub mod exts { - pub const expose_oneof_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17001, phantom: ::std::marker::PhantomData }; - - pub const expose_fields_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17003, phantom: ::std::marker::PhantomData }; - - pub const generate_accessors_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17004, phantom: ::std::marker::PhantomData }; - - pub const carllerche_bytes_for_bytes_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17011, phantom: ::std::marker::PhantomData }; - - pub const carllerche_bytes_for_string_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17012, phantom: ::std::marker::PhantomData }; - - pub const serde_derive_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17030, phantom: ::std::marker::PhantomData }; + pub const generate_accessors_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, bool> = crate::ext::ExtFieldOptional::new(17004, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const serde_derive_cfg_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeString> = crate::ext::ExtFieldOptional { field_number: 17031, phantom: ::std::marker::PhantomData }; + pub const generate_getter_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, bool> = crate::ext::ExtFieldOptional::new(17005, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const lite_runtime_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17035, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, bool> = crate::ext::ExtFieldOptional::new(17011, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const expose_oneof: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17001, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes_for_string_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, bool> = crate::ext::ExtFieldOptional::new(17012, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const expose_fields: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17003, phantom: ::std::marker::PhantomData }; + pub const lite_runtime_all: crate::ext::ExtFieldOptional<crate::descriptor::FileOptions, bool> = crate::ext::ExtFieldOptional::new(17035, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const generate_accessors: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17004, phantom: ::std::marker::PhantomData }; + pub const generate_accessors: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, bool> = crate::ext::ExtFieldOptional::new(17004, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const carllerche_bytes_for_bytes: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17011, phantom: ::std::marker::PhantomData }; + pub const generate_getter: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, bool> = crate::ext::ExtFieldOptional::new(17005, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const carllerche_bytes_for_string: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17012, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, bool> = crate::ext::ExtFieldOptional::new(17011, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const serde_derive: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17030, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes_for_string: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, bool> = crate::ext::ExtFieldOptional::new(17012, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const serde_derive_cfg: crate::ext::ExtFieldOptional<crate::descriptor::MessageOptions, crate::types::ProtobufTypeString> = crate::ext::ExtFieldOptional { field_number: 17031, phantom: ::std::marker::PhantomData }; + pub const generate_accessors_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, bool> = crate::ext::ExtFieldOptional::new(17004, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const expose_fields_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17003, phantom: ::std::marker::PhantomData }; + pub const generate_getter_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, bool> = crate::ext::ExtFieldOptional::new(17005, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const generate_accessors_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17004, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, bool> = crate::ext::ExtFieldOptional::new(17011, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); - pub const carllerche_bytes_for_bytes_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17011, phantom: ::std::marker::PhantomData }; - - pub const carllerche_bytes_for_string_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, crate::types::ProtobufTypeBool> = crate::ext::ExtFieldOptional { field_number: 17012, phantom: ::std::marker::PhantomData }; - - pub const serde_rename_all: crate::ext::ExtFieldOptional<crate::descriptor::EnumOptions, crate::types::ProtobufTypeString> = crate::ext::ExtFieldOptional { field_number: 17032, phantom: ::std::marker::PhantomData }; + pub const tokio_bytes_for_string_field: crate::ext::ExtFieldOptional<crate::descriptor::FieldOptions, bool> = crate::ext::ExtFieldOptional::new(17012, crate::descriptor::field_descriptor_proto::Type::TYPE_BOOL); } static file_descriptor_proto_data: &'static [u8] = b"\ \n\x0frustproto.proto\x12\trustproto\x1a\x20google/protobuf/descriptor.p\ - roto:H\n\x10expose_oneof_all\x18\xe9\x84\x01\x20\x01(\x08\x12\x1c.google\ - .protobuf.FileOptionsR\x0eexposeOneofAll:J\n\x11expose_fields_all\x18\ - \xeb\x84\x01\x20\x01(\x08\x12\x1c.google.protobuf.FileOptionsR\x0fexpose\ - FieldsAll:T\n\x16generate_accessors_all\x18\xec\x84\x01\x20\x01(\x08\x12\ - \x1c.google.protobuf.FileOptionsR\x14generateAccessorsAll:b\n\x1ecarller\ - che_bytes_for_bytes_all\x18\xf3\x84\x01\x20\x01(\x08\x12\x1c.google.prot\ - obuf.FileOptionsR\x1acarllercheBytesForBytesAll:d\n\x1fcarllerche_bytes_\ - for_string_all\x18\xf4\x84\x01\x20\x01(\x08\x12\x1c.google.protobuf.File\ - OptionsR\x1bcarllercheBytesForStringAll:H\n\x10serde_derive_all\x18\x86\ - \x85\x01\x20\x01(\x08\x12\x1c.google.protobuf.FileOptionsR\x0eserdeDeriv\ - eAll:O\n\x14serde_derive_cfg_all\x18\x87\x85\x01\x20\x01(\t\x12\x1c.goog\ - le.protobuf.FileOptionsR\x11serdeDeriveCfgAll:H\n\x10lite_runtime_all\ - \x18\x8b\x85\x01\x20\x01(\x08\x12\x1c.google.protobuf.FileOptionsR\x0eli\ - teRuntimeAll:D\n\x0cexpose_oneof\x18\xe9\x84\x01\x20\x01(\x08\x12\x1f.go\ - ogle.protobuf.MessageOptionsR\x0bexposeOneof:F\n\rexpose_fields\x18\xeb\ - \x84\x01\x20\x01(\x08\x12\x1f.google.protobuf.MessageOptionsR\x0cexposeF\ - ields:P\n\x12generate_accessors\x18\xec\x84\x01\x20\x01(\x08\x12\x1f.goo\ - gle.protobuf.MessageOptionsR\x11generateAccessors:^\n\x1acarllerche_byte\ - s_for_bytes\x18\xf3\x84\x01\x20\x01(\x08\x12\x1f.google.protobuf.Message\ - OptionsR\x17carllercheBytesForBytes:`\n\x1bcarllerche_bytes_for_string\ - \x18\xf4\x84\x01\x20\x01(\x08\x12\x1f.google.protobuf.MessageOptionsR\ - \x18carllercheBytesForString:D\n\x0cserde_derive\x18\x86\x85\x01\x20\x01\ - (\x08\x12\x1f.google.protobuf.MessageOptionsR\x0bserdeDerive:K\n\x10serd\ - e_derive_cfg\x18\x87\x85\x01\x20\x01(\t\x12\x1f.google.protobuf.MessageO\ - ptionsR\x0eserdeDeriveCfg:O\n\x13expose_fields_field\x18\xeb\x84\x01\x20\ - \x01(\x08\x12\x1d.google.protobuf.FieldOptionsR\x11exposeFieldsField:Y\n\ - \x18generate_accessors_field\x18\xec\x84\x01\x20\x01(\x08\x12\x1d.google\ - .protobuf.FieldOptionsR\x16generateAccessorsField:g\n\x20carllerche_byte\ - s_for_bytes_field\x18\xf3\x84\x01\x20\x01(\x08\x12\x1d.google.protobuf.F\ - ieldOptionsR\x1ccarllercheBytesForBytesField:i\n!carllerche_bytes_for_st\ - ring_field\x18\xf4\x84\x01\x20\x01(\x08\x12\x1d.google.protobuf.FieldOpt\ - ionsR\x1dcarllercheBytesForStringField:H\n\x10serde_rename_all\x18\x88\ - \x85\x01\x20\x01(\t\x12\x1c.google.protobuf.EnumOptionsR\x0eserdeRenameA\ - llJ\xea\x14\n\x06\x12\x04\0\0<\x01\n\x08\n\x01\x0c\x12\x03\0\0\x12\n\t\n\ - \x02\x03\0\x12\x03\x02\0*\nh\n\x01\x02\x12\x03\x07\0\x122^\x20see\x20htt\ - ps://github.com/gogo/protobuf/blob/master/gogoproto/gogo.proto\n\x20for\ - \x20the\x20original\x20idea\n\n\t\n\x01\x07\x12\x04\t\0\x1b\x01\n7\n\x02\ - \x07\0\x12\x03\x0b\x04+\x1a,\x20When\x20true,\x20oneof\x20field\x20is\ - \x20generated\x20public\n\n\n\n\x03\x07\0\x02\x12\x03\t\x07\"\n\n\n\x03\ - \x07\0\x04\x12\x03\x0b\x04\x0c\n\n\n\x03\x07\0\x05\x12\x03\x0b\r\x11\n\n\ - \n\x03\x07\0\x01\x12\x03\x0b\x12\"\n\n\n\x03\x07\0\x03\x12\x03\x0b%*\nI\ - \n\x02\x07\x01\x12\x03\r\x04,\x1a>\x20When\x20true\x20all\x20fields\x20a\ - re\x20public,\x20and\x20not\x20accessors\x20generated\n\n\n\n\x03\x07\ - \x01\x02\x12\x03\t\x07\"\n\n\n\x03\x07\x01\x04\x12\x03\r\x04\x0c\n\n\n\ - \x03\x07\x01\x05\x12\x03\r\r\x11\n\n\n\x03\x07\x01\x01\x12\x03\r\x12#\n\ - \n\n\x03\x07\x01\x03\x12\x03\r&+\nP\n\x02\x07\x02\x12\x03\x0f\x041\x1aE\ - \x20When\x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\x20accessors\ - \x20are\x20not\x20generated\n\n\n\n\x03\x07\x02\x02\x12\x03\t\x07\"\n\n\ - \n\x03\x07\x02\x04\x12\x03\x0f\x04\x0c\n\n\n\x03\x07\x02\x05\x12\x03\x0f\ - \r\x11\n\n\n\x03\x07\x02\x01\x12\x03\x0f\x12(\n\n\n\x03\x07\x02\x03\x12\ - \x03\x0f+0\n2\n\x02\x07\x03\x12\x03\x11\x049\x1a'\x20Use\x20`bytes::Byte\ - s`\x20for\x20`bytes`\x20fields\n\n\n\n\x03\x07\x03\x02\x12\x03\t\x07\"\n\ - \n\n\x03\x07\x03\x04\x12\x03\x11\x04\x0c\n\n\n\x03\x07\x03\x05\x12\x03\ - \x11\r\x11\n\n\n\x03\x07\x03\x01\x12\x03\x11\x120\n\n\n\x03\x07\x03\x03\ - \x12\x03\x1138\n3\n\x02\x07\x04\x12\x03\x13\x04:\x1a(\x20Use\x20`bytes::\ - Bytes`\x20for\x20`string`\x20fields\n\n\n\n\x03\x07\x04\x02\x12\x03\t\ - \x07\"\n\n\n\x03\x07\x04\x04\x12\x03\x13\x04\x0c\n\n\n\x03\x07\x04\x05\ - \x12\x03\x13\r\x11\n\n\n\x03\x07\x04\x01\x12\x03\x13\x121\n\n\n\x03\x07\ - \x04\x03\x12\x03\x1349\nJ\n\x02\x07\x05\x12\x03\x15\x04+\x1a?\x20Use\x20\ - `serde_derive`\x20to\x20implement\x20`Serialize`\x20and\x20`Deserialize`\ - \n\n\n\n\x03\x07\x05\x02\x12\x03\t\x07\"\n\n\n\x03\x07\x05\x04\x12\x03\ - \x15\x04\x0c\n\n\n\x03\x07\x05\x05\x12\x03\x15\r\x11\n\n\n\x03\x07\x05\ - \x01\x12\x03\x15\x12\"\n\n\n\x03\x07\x05\x03\x12\x03\x15%*\n3\n\x02\x07\ - \x06\x12\x03\x17\x041\x1a(\x20Guard\x20serde\x20annotations\x20with\x20c\ - fg\x20attr.\n\n\n\n\x03\x07\x06\x02\x12\x03\t\x07\"\n\n\n\x03\x07\x06\ - \x04\x12\x03\x17\x04\x0c\n\n\n\x03\x07\x06\x05\x12\x03\x17\r\x13\n\n\n\ - \x03\x07\x06\x01\x12\x03\x17\x14(\n\n\n\x03\x07\x06\x03\x12\x03\x17+0\nN\ - \n\x02\x07\x07\x12\x03\x1a\x04+\x1aC\x20When\x20true,\x20will\x20only\ - \x20generate\x20codes\x20that\x20works\x20with\x20lite\x20runtime.\n\n\n\ - \n\x03\x07\x07\x02\x12\x03\t\x07\"\n\n\n\x03\x07\x07\x04\x12\x03\x1a\x04\ - \x0c\n\n\n\x03\x07\x07\x05\x12\x03\x1a\r\x11\n\n\n\x03\x07\x07\x01\x12\ - \x03\x1a\x12\"\n\n\n\x03\x07\x07\x03\x12\x03\x1a%*\n\t\n\x01\x07\x12\x04\ - \x1d\0,\x01\n7\n\x02\x07\x08\x12\x03\x1f\x04'\x1a,\x20When\x20true,\x20o\ - neof\x20field\x20is\x20generated\x20public\n\n\n\n\x03\x07\x08\x02\x12\ - \x03\x1d\x07%\n\n\n\x03\x07\x08\x04\x12\x03\x1f\x04\x0c\n\n\n\x03\x07\ - \x08\x05\x12\x03\x1f\r\x11\n\n\n\x03\x07\x08\x01\x12\x03\x1f\x12\x1e\n\n\ - \n\x03\x07\x08\x03\x12\x03\x1f!&\nI\n\x02\x07\t\x12\x03!\x04(\x1a>\x20Wh\ - en\x20true\x20all\x20fields\x20are\x20public,\x20and\x20not\x20accessors\ - \x20generated\n\n\n\n\x03\x07\t\x02\x12\x03\x1d\x07%\n\n\n\x03\x07\t\x04\ - \x12\x03!\x04\x0c\n\n\n\x03\x07\t\x05\x12\x03!\r\x11\n\n\n\x03\x07\t\x01\ - \x12\x03!\x12\x1f\n\n\n\x03\x07\t\x03\x12\x03!\"'\nP\n\x02\x07\n\x12\x03\ - #\x04-\x1aE\x20When\x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\ - \x20accessors\x20are\x20not\x20generated\n\n\n\n\x03\x07\n\x02\x12\x03\ - \x1d\x07%\n\n\n\x03\x07\n\x04\x12\x03#\x04\x0c\n\n\n\x03\x07\n\x05\x12\ - \x03#\r\x11\n\n\n\x03\x07\n\x01\x12\x03#\x12$\n\n\n\x03\x07\n\x03\x12\ - \x03#',\n2\n\x02\x07\x0b\x12\x03%\x045\x1a'\x20Use\x20`bytes::Bytes`\x20\ - for\x20`bytes`\x20fields\n\n\n\n\x03\x07\x0b\x02\x12\x03\x1d\x07%\n\n\n\ - \x03\x07\x0b\x04\x12\x03%\x04\x0c\n\n\n\x03\x07\x0b\x05\x12\x03%\r\x11\n\ - \n\n\x03\x07\x0b\x01\x12\x03%\x12,\n\n\n\x03\x07\x0b\x03\x12\x03%/4\n3\n\ - \x02\x07\x0c\x12\x03'\x046\x1a(\x20Use\x20`bytes::Bytes`\x20for\x20`stri\ - ng`\x20fields\n\n\n\n\x03\x07\x0c\x02\x12\x03\x1d\x07%\n\n\n\x03\x07\x0c\ - \x04\x12\x03'\x04\x0c\n\n\n\x03\x07\x0c\x05\x12\x03'\r\x11\n\n\n\x03\x07\ - \x0c\x01\x12\x03'\x12-\n\n\n\x03\x07\x0c\x03\x12\x03'05\nJ\n\x02\x07\r\ - \x12\x03)\x04'\x1a?\x20Use\x20`serde_derive`\x20to\x20implement\x20`Seri\ - alize`\x20and\x20`Deserialize`\n\n\n\n\x03\x07\r\x02\x12\x03\x1d\x07%\n\ - \n\n\x03\x07\r\x04\x12\x03)\x04\x0c\n\n\n\x03\x07\r\x05\x12\x03)\r\x11\n\ - \n\n\x03\x07\r\x01\x12\x03)\x12\x1e\n\n\n\x03\x07\r\x03\x12\x03)!&\n3\n\ - \x02\x07\x0e\x12\x03+\x04-\x1a(\x20Guard\x20serde\x20annotations\x20with\ - \x20cfg\x20attr.\n\n\n\n\x03\x07\x0e\x02\x12\x03\x1d\x07%\n\n\n\x03\x07\ - \x0e\x04\x12\x03+\x04\x0c\n\n\n\x03\x07\x0e\x05\x12\x03+\r\x13\n\n\n\x03\ - \x07\x0e\x01\x12\x03+\x14$\n\n\n\x03\x07\x0e\x03\x12\x03+',\n\t\n\x01\ - \x07\x12\x04.\07\x01\nI\n\x02\x07\x0f\x12\x030\x04.\x1a>\x20When\x20true\ - \x20all\x20fields\x20are\x20public,\x20and\x20not\x20accessors\x20genera\ - ted\n\n\n\n\x03\x07\x0f\x02\x12\x03.\x07#\n\n\n\x03\x07\x0f\x04\x12\x030\ - \x04\x0c\n\n\n\x03\x07\x0f\x05\x12\x030\r\x11\n\n\n\x03\x07\x0f\x01\x12\ - \x030\x12%\n\n\n\x03\x07\x0f\x03\x12\x030(-\nP\n\x02\x07\x10\x12\x032\ - \x043\x1aE\x20When\x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\x20\ - accessors\x20are\x20not\x20generated\n\n\n\n\x03\x07\x10\x02\x12\x03.\ - \x07#\n\n\n\x03\x07\x10\x04\x12\x032\x04\x0c\n\n\n\x03\x07\x10\x05\x12\ - \x032\r\x11\n\n\n\x03\x07\x10\x01\x12\x032\x12*\n\n\n\x03\x07\x10\x03\ - \x12\x032-2\n2\n\x02\x07\x11\x12\x034\x04;\x1a'\x20Use\x20`bytes::Bytes`\ - \x20for\x20`bytes`\x20fields\n\n\n\n\x03\x07\x11\x02\x12\x03.\x07#\n\n\n\ - \x03\x07\x11\x04\x12\x034\x04\x0c\n\n\n\x03\x07\x11\x05\x12\x034\r\x11\n\ - \n\n\x03\x07\x11\x01\x12\x034\x122\n\n\n\x03\x07\x11\x03\x12\x0345:\n3\n\ - \x02\x07\x12\x12\x036\x04<\x1a(\x20Use\x20`bytes::Bytes`\x20for\x20`stri\ - ng`\x20fields\n\n\n\n\x03\x07\x12\x02\x12\x03.\x07#\n\n\n\x03\x07\x12\ - \x04\x12\x036\x04\x0c\n\n\n\x03\x07\x12\x05\x12\x036\r\x11\n\n\n\x03\x07\ - \x12\x01\x12\x036\x123\n\n\n\x03\x07\x12\x03\x12\x0366;\n\t\n\x01\x07\ - \x12\x049\0<\x01\n/\n\x02\x07\x13\x12\x03;\x04-\x1a$\x20use\x20rename_al\ - l\x20attribute\x20for\x20serde\n\n\n\n\x03\x07\x13\x02\x12\x039\x07\"\n\ - \n\n\x03\x07\x13\x04\x12\x03;\x04\x0c\n\n\n\x03\x07\x13\x05\x12\x03;\r\ - \x13\n\n\n\x03\x07\x13\x01\x12\x03;\x14$\n\n\n\x03\x07\x13\x03\x12\x03;'\ - ,\ + roto:T\n\x16generate_accessors_all\x18\xec\x84\x01\x20\x01(\x08\x12\x1c.\ + google.protobuf.FileOptionsR\x14generateAccessorsAll:N\n\x13generate_get\ + ter_all\x18\xed\x84\x01\x20\x01(\x08\x12\x1c.google.protobuf.FileOptions\ + R\x11generateGetterAll:F\n\x0ftokio_bytes_all\x18\xf3\x84\x01\x20\x01(\ + \x08\x12\x1c.google.protobuf.FileOptionsR\rtokioBytesAll:Z\n\x1atokio_by\ + tes_for_string_all\x18\xf4\x84\x01\x20\x01(\x08\x12\x1c.google.protobuf.\ + FileOptionsR\x16tokioBytesForStringAll:H\n\x10lite_runtime_all\x18\x8b\ + \x85\x01\x20\x01(\x08\x12\x1c.google.protobuf.FileOptionsR\x0eliteRuntim\ + eAll:P\n\x12generate_accessors\x18\xec\x84\x01\x20\x01(\x08\x12\x1f.goog\ + le.protobuf.MessageOptionsR\x11generateAccessors:J\n\x0fgenerate_getter\ + \x18\xed\x84\x01\x20\x01(\x08\x12\x1f.google.protobuf.MessageOptionsR\ + \x0egenerateGetter:B\n\x0btokio_bytes\x18\xf3\x84\x01\x20\x01(\x08\x12\ + \x1f.google.protobuf.MessageOptionsR\ntokioBytes:V\n\x16tokio_bytes_for_\ + string\x18\xf4\x84\x01\x20\x01(\x08\x12\x1f.google.protobuf.MessageOptio\ + nsR\x13tokioBytesForString:Y\n\x18generate_accessors_field\x18\xec\x84\ + \x01\x20\x01(\x08\x12\x1d.google.protobuf.FieldOptionsR\x16generateAcces\ + sorsField:S\n\x15generate_getter_field\x18\xed\x84\x01\x20\x01(\x08\x12\ + \x1d.google.protobuf.FieldOptionsR\x13generateGetterField:K\n\x11tokio_b\ + ytes_field\x18\xf3\x84\x01\x20\x01(\x08\x12\x1d.google.protobuf.FieldOpt\ + ionsR\x0ftokioBytesField:_\n\x1ctokio_bytes_for_string_field\x18\xf4\x84\ + \x01\x20\x01(\x08\x12\x1d.google.protobuf.FieldOptionsR\x18tokioBytesFor\ + StringFieldJ\x9d\x0f\n\x06\x12\x04\0\0.\x01\n\x08\n\x01\x0c\x12\x03\0\0\ + \x12\n\t\n\x02\x03\0\x12\x03\x02\0*\n\xe5\x01\n\x01\x02\x12\x03\n\0\x122\ + ^\x20see\x20https://github.com/gogo/protobuf/blob/master/gogoproto/gogo.\ + proto\n\x20for\x20the\x20original\x20idea\n2{\x20Generated\x20files\x20c\ + an\x20be\x20customized\x20using\x20this\x20proto\n\x20or\x20using\x20`Cu\ + stomize`\x20struct\x20when\x20codegen\x20is\x20invoked\x20programmatical\ + ly.\n\n\t\n\x01\x07\x12\x04\x0c\0\x18\x01\nP\n\x02\x07\0\x12\x03\x0e\x04\ + 1\x1aE\x20When\x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\x20acce\ + ssors\x20are\x20not\x20generated\n\n\n\n\x03\x07\0\x02\x12\x03\x0c\x07\"\ + \n\n\n\x03\x07\0\x04\x12\x03\x0e\x04\x0c\n\n\n\x03\x07\0\x05\x12\x03\x0e\ + \r\x11\n\n\n\x03\x07\0\x01\x12\x03\x0e\x12(\n\n\n\x03\x07\0\x03\x12\x03\ + \x0e+0\nL\n\x02\x07\x01\x12\x03\x10\x04.\x1aA\x20When\x20false,\x20`get_\ + `\x20is\x20not\x20generated\x20even\x20if\x20`syntax\x20=\x20\"proto2\"`\ + \n\n\n\n\x03\x07\x01\x02\x12\x03\x0c\x07\"\n\n\n\x03\x07\x01\x04\x12\x03\ + \x10\x04\x0c\n\n\n\x03\x07\x01\x05\x12\x03\x10\r\x11\n\n\n\x03\x07\x01\ + \x01\x12\x03\x10\x12%\n\n\n\x03\x07\x01\x03\x12\x03\x10(-\n2\n\x02\x07\ + \x02\x12\x03\x12\x04*\x1a'\x20Use\x20`bytes::Bytes`\x20for\x20`bytes`\ + \x20fields\n\n\n\n\x03\x07\x02\x02\x12\x03\x0c\x07\"\n\n\n\x03\x07\x02\ + \x04\x12\x03\x12\x04\x0c\n\n\n\x03\x07\x02\x05\x12\x03\x12\r\x11\n\n\n\ + \x03\x07\x02\x01\x12\x03\x12\x12!\n\n\n\x03\x07\x02\x03\x12\x03\x12$)\n3\ + \n\x02\x07\x03\x12\x03\x14\x045\x1a(\x20Use\x20`bytes::Bytes`\x20for\x20\ + `string`\x20fields\n\n\n\n\x03\x07\x03\x02\x12\x03\x0c\x07\"\n\n\n\x03\ + \x07\x03\x04\x12\x03\x14\x04\x0c\n\n\n\x03\x07\x03\x05\x12\x03\x14\r\x11\ + \n\n\n\x03\x07\x03\x01\x12\x03\x14\x12,\n\n\n\x03\x07\x03\x03\x12\x03\ + \x14/4\nN\n\x02\x07\x04\x12\x03\x17\x04+\x1aC\x20When\x20true,\x20will\ + \x20only\x20generate\x20codes\x20that\x20works\x20with\x20lite\x20runtim\ + e.\n\n\n\n\x03\x07\x04\x02\x12\x03\x0c\x07\"\n\n\n\x03\x07\x04\x04\x12\ + \x03\x17\x04\x0c\n\n\n\x03\x07\x04\x05\x12\x03\x17\r\x11\n\n\n\x03\x07\ + \x04\x01\x12\x03\x17\x12\"\n\n\n\x03\x07\x04\x03\x12\x03\x17%*\n\t\n\x01\ + \x07\x12\x04\x1a\0#\x01\nP\n\x02\x07\x05\x12\x03\x1c\x04-\x1aE\x20When\ + \x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\x20accessors\x20are\ + \x20not\x20generated\n\n\n\n\x03\x07\x05\x02\x12\x03\x1a\x07%\n\n\n\x03\ + \x07\x05\x04\x12\x03\x1c\x04\x0c\n\n\n\x03\x07\x05\x05\x12\x03\x1c\r\x11\ + \n\n\n\x03\x07\x05\x01\x12\x03\x1c\x12$\n\n\n\x03\x07\x05\x03\x12\x03\ + \x1c',\nL\n\x02\x07\x06\x12\x03\x1e\x04*\x1aA\x20When\x20false,\x20`get_\ + `\x20is\x20not\x20generated\x20even\x20if\x20`syntax\x20=\x20\"proto2\"`\ + \n\n\n\n\x03\x07\x06\x02\x12\x03\x1a\x07%\n\n\n\x03\x07\x06\x04\x12\x03\ + \x1e\x04\x0c\n\n\n\x03\x07\x06\x05\x12\x03\x1e\r\x11\n\n\n\x03\x07\x06\ + \x01\x12\x03\x1e\x12!\n\n\n\x03\x07\x06\x03\x12\x03\x1e$)\n2\n\x02\x07\ + \x07\x12\x03\x20\x04&\x1a'\x20Use\x20`bytes::Bytes`\x20for\x20`bytes`\ + \x20fields\n\n\n\n\x03\x07\x07\x02\x12\x03\x1a\x07%\n\n\n\x03\x07\x07\ + \x04\x12\x03\x20\x04\x0c\n\n\n\x03\x07\x07\x05\x12\x03\x20\r\x11\n\n\n\ + \x03\x07\x07\x01\x12\x03\x20\x12\x1d\n\n\n\x03\x07\x07\x03\x12\x03\x20\ + \x20%\n3\n\x02\x07\x08\x12\x03\"\x041\x1a(\x20Use\x20`bytes::Bytes`\x20f\ + or\x20`string`\x20fields\n\n\n\n\x03\x07\x08\x02\x12\x03\x1a\x07%\n\n\n\ + \x03\x07\x08\x04\x12\x03\"\x04\x0c\n\n\n\x03\x07\x08\x05\x12\x03\"\r\x11\ + \n\n\n\x03\x07\x08\x01\x12\x03\"\x12(\n\n\n\x03\x07\x08\x03\x12\x03\"+0\ + \n\t\n\x01\x07\x12\x04%\0.\x01\nP\n\x02\x07\t\x12\x03'\x043\x1aE\x20When\ + \x20false,\x20`get_`,\x20`set_`,\x20`mut_`\x20etc.\x20accessors\x20are\ + \x20not\x20generated\n\n\n\n\x03\x07\t\x02\x12\x03%\x07#\n\n\n\x03\x07\t\ + \x04\x12\x03'\x04\x0c\n\n\n\x03\x07\t\x05\x12\x03'\r\x11\n\n\n\x03\x07\t\ + \x01\x12\x03'\x12*\n\n\n\x03\x07\t\x03\x12\x03'-2\nL\n\x02\x07\n\x12\x03\ + )\x040\x1aA\x20When\x20false,\x20`get_`\x20is\x20not\x20generated\x20eve\ + n\x20if\x20`syntax\x20=\x20\"proto2\"`\n\n\n\n\x03\x07\n\x02\x12\x03%\ + \x07#\n\n\n\x03\x07\n\x04\x12\x03)\x04\x0c\n\n\n\x03\x07\n\x05\x12\x03)\ + \r\x11\n\n\n\x03\x07\n\x01\x12\x03)\x12'\n\n\n\x03\x07\n\x03\x12\x03)*/\ + \n2\n\x02\x07\x0b\x12\x03+\x04,\x1a'\x20Use\x20`bytes::Bytes`\x20for\x20\ + `bytes`\x20fields\n\n\n\n\x03\x07\x0b\x02\x12\x03%\x07#\n\n\n\x03\x07\ + \x0b\x04\x12\x03+\x04\x0c\n\n\n\x03\x07\x0b\x05\x12\x03+\r\x11\n\n\n\x03\ + \x07\x0b\x01\x12\x03+\x12#\n\n\n\x03\x07\x0b\x03\x12\x03+&+\n3\n\x02\x07\ + \x0c\x12\x03-\x047\x1a(\x20Use\x20`bytes::Bytes`\x20for\x20`string`\x20f\ + ields\n\n\n\n\x03\x07\x0c\x02\x12\x03%\x07#\n\n\n\x03\x07\x0c\x04\x12\ + \x03-\x04\x0c\n\n\n\x03\x07\x0c\x05\x12\x03-\r\x11\n\n\n\x03\x07\x0c\x01\ + \x12\x03-\x12.\n\n\n\x03\x07\x0c\x03\x12\x03-16\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(1); + deps.push(crate::descriptor::file_descriptor().clone()); + let mut messages = ::std::vec::Vec::with_capacity(0); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/singular.rs b/src/singular.rs deleted file mode 100644 index 1b7e28d..0000000 --- a/src/singular.rs +++ /dev/null @@ -1,594 +0,0 @@ -use std::default::Default; -use std::fmt; -use std::hash::Hash; -use std::hash::Hasher; -use std::mem; -use std::option; - -#[cfg(feature = "with-serde")] -use serde; - -use crate::clear::Clear; - -/// Like `Option<T>`, but keeps the actual element on `clear`. -pub struct SingularField<T> { - value: T, - set: bool, -} - -/// Like `Option<Box<T>>`, but keeps the actual element on `clear`. -pub struct SingularPtrField<T> { - value: Option<Box<T>>, - set: bool, -} - -impl<T> SingularField<T> { - /// Construct this object from given value. - #[inline] - pub fn some(value: T) -> SingularField<T> { - SingularField { - value: value, - set: true, - } - } - - /// True iff this object contains data. - #[inline] - pub fn is_some(&self) -> bool { - self.set - } - - /// True iff this object contains no data. - #[inline] - pub fn is_none(&self) -> bool { - !self.is_some() - } - - /// Convert this object into `Option`. - #[inline] - pub fn into_option(self) -> Option<T> { - if self.set { - Some(self.value) - } else { - None - } - } - - /// View data as `Option`. - #[inline] - pub fn as_ref<'a>(&'a self) -> Option<&'a T> { - if self.set { - Some(&self.value) - } else { - None - } - } - - /// View data as mutable `Option`. - #[inline] - pub fn as_mut<'a>(&'a mut self) -> Option<&'a mut T> { - if self.set { - Some(&mut self.value) - } else { - None - } - } - - /// Unwrap data as reference. - #[inline] - pub fn unwrap_ref<'a>(&'a self) -> &'a T { - self.as_ref().unwrap() - } - - /// Unwrap data as mutable reference. - #[inline] - pub fn unwrap_mut_ref<'a>(&'a mut self) -> &'a mut T { - self.as_mut().unwrap() - } - - /// Unwrap data, panic if not set. - #[inline] - pub fn unwrap(self) -> T { - if self.set { - self.value - } else { - panic!(); - } - } - - /// Unwrap data or return given default value. - #[inline] - pub fn unwrap_or(self, def: T) -> T { - if self.set { - self.value - } else { - def - } - } - - /// Unwrap data or return given default value. - #[inline] - pub fn unwrap_or_else<F>(self, f: F) -> T - where - F: FnOnce() -> T, - { - if self.set { - self.value - } else { - f() - } - } - - /// Apply a function to contained element and store result in new `SingularPtrField`. - #[inline] - pub fn map<U, F>(self, f: F) -> SingularPtrField<U> - where - F: FnOnce(T) -> U, - { - SingularPtrField::from_option(self.into_option().map(f)) - } - - /// View as iterator over references. - #[inline] - pub fn iter<'a>(&'a self) -> option::IntoIter<&'a T> { - self.as_ref().into_iter() - } - - /// View as iterator over mutable references. - #[inline] - pub fn mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T> { - self.as_mut().into_iter() - } - - /// Clear this object. - /// Note, contained object destructor is not called, so allocated memory could be reused. - #[inline] - pub fn clear(&mut self) { - self.set = false; - } -} - -impl<T: Default> SingularField<T> { - /// Construct a `SingularField` with no data. - #[inline] - pub fn none() -> SingularField<T> { - SingularField { - value: Default::default(), - set: false, - } - } - - /// Construct `SingularField` from `Option`. - #[inline] - pub fn from_option(option: Option<T>) -> SingularField<T> { - match option { - Some(x) => SingularField::some(x), - None => SingularField::none(), - } - } - - /// Return data as option, clear this object. - #[inline] - pub fn take(&mut self) -> Option<T> { - if self.set { - self.set = false; - Some(mem::replace(&mut self.value, Default::default())) - } else { - None - } - } -} - -impl<T> SingularPtrField<T> { - /// Construct `SingularPtrField` from given object. - #[inline] - pub fn some(value: T) -> SingularPtrField<T> { - SingularPtrField { - value: Some(Box::new(value)), - set: true, - } - } - - /// Construct an empty `SingularPtrField`. - #[inline] - pub fn none() -> SingularPtrField<T> { - SingularPtrField { - value: None, - set: false, - } - } - - /// Construct `SingularPtrField` from optional. - #[inline] - pub fn from_option(option: Option<T>) -> SingularPtrField<T> { - match option { - Some(x) => SingularPtrField::some(x), - None => SingularPtrField::none(), - } - } - - /// True iff this object contains data. - #[inline] - pub fn is_some(&self) -> bool { - self.set - } - - /// True iff this object contains no data. - #[inline] - pub fn is_none(&self) -> bool { - !self.is_some() - } - - /// Convert into `Option<T>`. - #[inline] - pub fn into_option(self) -> Option<T> { - if self.set { - Some(*self.value.unwrap()) - } else { - None - } - } - - /// View data as reference option. - #[inline] - pub fn as_ref<'a>(&'a self) -> Option<&'a T> { - if self.set { - Some(&**self.value.as_ref().unwrap()) - } else { - None - } - } - - /// View data as mutable reference option. - #[inline] - pub fn as_mut<'a>(&'a mut self) -> Option<&'a mut T> { - if self.set { - Some(&mut **self.value.as_mut().unwrap()) - } else { - None - } - } - - /// Get data as reference. - /// Panics if empty. - #[inline] - pub fn get_ref<'a>(&'a self) -> &'a T { - self.as_ref().unwrap() - } - - /// Get data as mutable reference. - /// Panics if empty. - #[inline] - pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T { - self.as_mut().unwrap() - } - - /// Take the data. - /// Panics if empty - #[inline] - pub fn unwrap(self) -> T { - if self.set { - *self.value.unwrap() - } else { - panic!(); - } - } - - /// Take the data or return supplied default element if empty. - #[inline] - pub fn unwrap_or(self, def: T) -> T { - if self.set { - *self.value.unwrap() - } else { - def - } - } - - /// Take the data or return supplied default element if empty. - #[inline] - pub fn unwrap_or_else<F>(self, f: F) -> T - where - F: FnOnce() -> T, - { - if self.set { - *self.value.unwrap() - } else { - f() - } - } - - /// Apply given function to contained data to construct another `SingularPtrField`. - /// Returns empty `SingularPtrField` if this object is empty. - #[inline] - pub fn map<U, F>(self, f: F) -> SingularPtrField<U> - where - F: FnOnce(T) -> U, - { - SingularPtrField::from_option(self.into_option().map(f)) - } - - /// View data as iterator. - #[inline] - pub fn iter<'a>(&'a self) -> option::IntoIter<&'a T> { - self.as_ref().into_iter() - } - - /// View data as mutable iterator. - #[inline] - pub fn mut_iter<'a>(&'a mut self) -> option::IntoIter<&'a mut T> { - self.as_mut().into_iter() - } - - /// Take data as option, leaving this object empty. - #[inline] - pub fn take(&mut self) -> Option<T> { - if self.set { - self.set = false; - Some(*self.value.take().unwrap()) - } else { - None - } - } - - /// Clear this object, but do not call destructor of underlying data. - #[inline] - pub fn clear(&mut self) { - self.set = false; - } -} - -impl<T: Default + Clear> SingularField<T> { - /// Get contained data, consume self. Return default value for type if this is empty. - #[inline] - pub fn unwrap_or_default(mut self) -> T { - if !self.set { - self.value.clear(); - } - self.value - } - - /// Initialize this object with default value. - /// This operation can be more efficient then construction of clear element, - /// because it may reuse previously contained object. - #[inline] - pub fn set_default<'a>(&'a mut self) -> &'a mut T { - self.set = true; - self.value.clear(); - &mut self.value - } -} - -impl<T: Default + Clear> SingularPtrField<T> { - /// Get contained data, consume self. Return default value for type if this is empty. - #[inline] - pub fn unwrap_or_default(mut self) -> T { - if self.set { - self.unwrap() - } else if self.value.is_some() { - self.value.clear(); - *self.value.unwrap() - } else { - Default::default() - } - } - - /// Initialize this object with default value. - /// This operation can be more efficient then construction of clear element, - /// because it may reuse previously contained object. - #[inline] - pub fn set_default<'a>(&'a mut self) -> &'a mut T { - self.set = true; - if self.value.is_some() { - self.value.as_mut().unwrap().clear(); - } else { - self.value = Some(Default::default()); - } - self.as_mut().unwrap() - } -} - -impl<T: Default> Default for SingularField<T> { - #[inline] - fn default() -> SingularField<T> { - SingularField::none() - } -} - -impl<T> Default for SingularPtrField<T> { - #[inline] - fn default() -> SingularPtrField<T> { - SingularPtrField::none() - } -} - -impl<T: Default> From<Option<T>> for SingularField<T> { - fn from(o: Option<T>) -> Self { - SingularField::from_option(o) - } -} - -impl<T> From<Option<T>> for SingularPtrField<T> { - fn from(o: Option<T>) -> Self { - SingularPtrField::from_option(o) - } -} - -impl<T: Clone + Default> Clone for SingularField<T> { - #[inline] - fn clone(&self) -> SingularField<T> { - if self.set { - SingularField::some(self.value.clone()) - } else { - SingularField::none() - } - } -} - -impl<T: Clone> Clone for SingularPtrField<T> { - #[inline] - fn clone(&self) -> SingularPtrField<T> { - if self.set { - SingularPtrField::some(self.as_ref().unwrap().clone()) - } else { - SingularPtrField::none() - } - } -} - -impl<T: fmt::Debug> fmt::Debug for SingularField<T> { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.is_some() { - write!(f, "Some({:?})", *self.as_ref().unwrap()) - } else { - write!(f, "None") - } - } -} - -impl<T: fmt::Debug> fmt::Debug for SingularPtrField<T> { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.is_some() { - write!(f, "Some({:?})", *self.as_ref().unwrap()) - } else { - write!(f, "None") - } - } -} - -impl<T: PartialEq> PartialEq for SingularField<T> { - #[inline] - fn eq(&self, other: &SingularField<T>) -> bool { - self.as_ref() == other.as_ref() - } -} - -impl<T: Eq> Eq for SingularField<T> {} - -impl<T: PartialEq> PartialEq for SingularPtrField<T> { - #[inline] - fn eq(&self, other: &SingularPtrField<T>) -> bool { - self.as_ref() == other.as_ref() - } -} - -impl<T: Eq> Eq for SingularPtrField<T> {} - -impl<T: Hash> Hash for SingularField<T> { - fn hash<H: Hasher>(&self, state: &mut H) { - self.as_ref().hash(state); - } -} - -impl<T: Hash> Hash for SingularPtrField<T> { - fn hash<H: Hasher>(&self, state: &mut H) { - self.as_ref().hash(state); - } -} - -impl<'a, T> IntoIterator for &'a SingularField<T> { - type Item = &'a T; - type IntoIter = option::IntoIter<&'a T>; - - fn into_iter(self) -> option::IntoIter<&'a T> { - self.iter() - } -} - -impl<'a, T> IntoIterator for &'a SingularPtrField<T> { - type Item = &'a T; - type IntoIter = option::IntoIter<&'a T>; - - fn into_iter(self) -> option::IntoIter<&'a T> { - self.iter() - } -} - -#[cfg(feature = "with-serde")] -impl<T: serde::Serialize> serde::Serialize for SingularPtrField<T> { - fn serialize<S>( - &self, - serializer: S, - ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> - where - S: serde::Serializer, - { - self.as_ref().serialize(serializer) - } -} - -#[cfg(feature = "with-serde")] -impl<T: serde::Serialize> serde::Serialize for SingularField<T> { - fn serialize<S>( - &self, - serializer: S, - ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error> - where - S: serde::Serializer, - { - self.as_ref().serialize(serializer) - } -} - -#[cfg(feature = "with-serde")] -impl<'de, T: serde::Deserialize<'de>> serde::Deserialize<'de> for SingularPtrField<T> { - fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> - where - D: serde::Deserializer<'de>, - { - Option::deserialize(deserializer).map(SingularPtrField::from_option) - } -} - -#[cfg(feature = "with-serde")] -impl<'de, T: serde::Deserialize<'de> + Default> serde::Deserialize<'de> for SingularField<T> { - fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error> - where - D: serde::Deserializer<'de>, - { - Option::deserialize(deserializer).map(SingularField::from_option) - } -} - -#[cfg(test)] -mod test { - use super::SingularField; - use crate::clear::Clear; - - #[test] - fn test_set_default_clears() { - #[derive(Default)] - struct Foo { - b: isize, - } - - impl Clear for Foo { - fn clear(&mut self) { - self.b = 0; - } - } - - let mut x = SingularField::some(Foo { b: 10 }); - x.clear(); - x.set_default(); - assert_eq!(0, x.as_ref().unwrap().b); - - x.as_mut().unwrap().b = 11; - // without clear - x.set_default(); - assert_eq!(0, x.as_ref().unwrap().b); - } - - #[test] - fn unwrap_or_default() { - assert_eq!( - "abc", - SingularField::some("abc".to_owned()).unwrap_or_default() - ); - assert_eq!("", SingularField::<String>::none().unwrap_or_default()); - let mut some = SingularField::some("abc".to_owned()); - some.clear(); - assert_eq!("", some.unwrap_or_default()); - } -} diff --git a/src/special.rs b/src/special.rs new file mode 100644 index 0000000..f559721 --- /dev/null +++ b/src/special.rs @@ -0,0 +1,40 @@ +use crate::cached_size::CachedSize; +use crate::UnknownFields; + +/// Special fields included in each generated message. +#[derive(Default, Eq, PartialEq, Clone, Debug, Hash)] +pub struct SpecialFields { + unknown_fields: UnknownFields, + cached_size: CachedSize, +} + +impl SpecialFields { + /// Defaults. + pub const fn new() -> SpecialFields { + SpecialFields { + unknown_fields: UnknownFields::new(), + cached_size: CachedSize::new(), + } + } + + /// Clear. + pub fn clear(&mut self) { + self.unknown_fields.clear(); + // No need to clear `cached_size`. + } + + /// Getter. + pub fn cached_size(&self) -> &CachedSize { + &self.cached_size + } + + /// Getter. + pub fn unknown_fields(&self) -> &UnknownFields { + &self.unknown_fields + } + + /// Setter. + pub fn mut_unknown_fields(&mut self) -> &mut UnknownFields { + &mut self.unknown_fields + } +} diff --git a/src/strx.rs b/src/strx.rs deleted file mode 100644 index af09de2..0000000 --- a/src/strx.rs +++ /dev/null @@ -1,34 +0,0 @@ -pub fn remove_to<'s>(s: &'s str, c: char) -> &'s str { - match s.rfind(c) { - Some(pos) => &s[(pos + 1)..], - None => s, - } -} - -pub fn remove_suffix<'s>(s: &'s str, suffix: &str) -> &'s str { - if !s.ends_with(suffix) { - s - } else { - &s[..(s.len() - suffix.len())] - } -} - -#[cfg(test)] -mod test { - - use super::remove_suffix; - use super::remove_to; - - #[test] - fn test_remove_to() { - assert_eq!("aaa", remove_to("aaa", '.')); - assert_eq!("bbb", remove_to("aaa.bbb", '.')); - assert_eq!("ccc", remove_to("aaa.bbb.ccc", '.')); - } - - #[test] - fn test_remove_suffix() { - assert_eq!("bbb", remove_suffix("bbbaaa", "aaa")); - assert_eq!("aaa", remove_suffix("aaa", "bbb")); - } -} diff --git a/src/text_format/lexer/float.rs b/src/text_format/lexer/float.rs deleted file mode 100644 index 0d69c09..0000000 --- a/src/text_format/lexer/float.rs +++ /dev/null @@ -1,58 +0,0 @@ -use std::f64; - -#[derive(Debug)] -pub enum ProtobufFloatParseError { - EmptyString, - CannotParseFloat, -} - -pub type ProtobufFloatParseResult<T> = Result<T, ProtobufFloatParseError>; - -pub const PROTOBUF_NAN: &str = "nan"; -pub const PROTOBUF_INF: &str = "inf"; - -/// Format float as in protobuf `.proto` files -pub fn format_protobuf_float(f: f64) -> String { - if f.is_nan() { - PROTOBUF_NAN.to_owned() - } else if f.is_infinite() { - if f > 0.0 { - format!("{}", PROTOBUF_INF) - } else { - format!("-{}", PROTOBUF_INF) - } - } else { - // TODO: make sure doesn't lose precision - format!("{}", f) - } -} - -/// Parse float from `.proto` format -pub fn parse_protobuf_float(s: &str) -> ProtobufFloatParseResult<f64> { - if s.is_empty() { - return Err(ProtobufFloatParseError::EmptyString); - } - if s == PROTOBUF_NAN { - return Ok(f64::NAN); - } - if s == PROTOBUF_INF || s == format!("+{}", PROTOBUF_INF) { - return Ok(f64::INFINITY); - } - if s == format!("-{}", PROTOBUF_INF) { - return Ok(f64::NEG_INFINITY); - } - match s.parse() { - Ok(f) => Ok(f), - Err(_) => Err(ProtobufFloatParseError::CannotParseFloat), - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_format_protobuf_float() { - assert_eq!("10", format_protobuf_float(10.0)); - } -} diff --git a/src/text_format/lexer/json_number_lit.rs b/src/text_format/lexer/json_number_lit.rs deleted file mode 100644 index 6394b0e..0000000 --- a/src/text_format/lexer/json_number_lit.rs +++ /dev/null @@ -1,10 +0,0 @@ -use std::fmt; - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct JsonNumberLit(pub(crate) String); - -impl fmt::Display for JsonNumberLit { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } -} diff --git a/src/text_format/lexer/lexer_impl.rs b/src/text_format/lexer/lexer_impl.rs deleted file mode 100644 index ae9035a..0000000 --- a/src/text_format/lexer/lexer_impl.rs +++ /dev/null @@ -1,726 +0,0 @@ -use std::char; -use std::convert::TryFrom; -use std::f64; -use std::fmt; -use std::num::ParseFloatError; -use std::num::ParseIntError; - -use super::float; -use super::loc::Loc; -use super::loc::FIRST_COL; -use super::str_lit::StrLit; -use super::str_lit::StrLitDecodeError; -use super::token::Token; -use super::token::TokenWithLocation; -use super::ParserLanguage; -use crate::text_format::lexer::JsonNumberLit; - -#[derive(Debug)] -pub enum LexerError { - IncorrectInput, // TODO: something better than this - UnexpectedEof, - ExpectChar(char), - ParseIntError, - ParseFloatError, - IncorrectFloatLit, // TODO: how it is different from ParseFloatError? - IncorrectJsonEscape, - IncorrectJsonNumber, - IncorrectUnicodeChar, - ExpectHexDigit, - ExpectOctDigit, - ExpectDecDigit, - StrLitDecodeError(StrLitDecodeError), - ExpectedIdent, -} - -impl fmt::Display for LexerError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - LexerError::IncorrectInput => write!(f, "Incorrect input"), - LexerError::UnexpectedEof => write!(f, "Unexpected EOF"), - LexerError::ExpectChar(c) => write!(f, "Expecting char: {}", c), - LexerError::ParseIntError => write!(f, "Parse int error"), - LexerError::ParseFloatError => write!(f, "Parse float error"), - LexerError::IncorrectFloatLit => write!(f, "Incorrect float literal"), - LexerError::IncorrectJsonEscape => write!(f, "Incorrect JSON escape"), - LexerError::IncorrectJsonNumber => write!(f, "Incorrect JSON number"), - LexerError::IncorrectUnicodeChar => write!(f, "Incorrect Unicode char"), - LexerError::ExpectHexDigit => write!(f, "Expecting hex digit"), - LexerError::ExpectOctDigit => write!(f, "Expecting oct digit"), - LexerError::ExpectDecDigit => write!(f, "Expecting dec digit"), - LexerError::StrLitDecodeError(e) => write!(f, "{}", e), - LexerError::ExpectedIdent => write!(f, "Expecting identifier"), - } - } -} - -impl std::error::Error for LexerError {} - -pub type LexerResult<T> = Result<T, LexerError>; - -impl From<StrLitDecodeError> for LexerError { - fn from(e: StrLitDecodeError) -> Self { - LexerError::StrLitDecodeError(e) - } -} - -impl From<ParseIntError> for LexerError { - fn from(_: ParseIntError) -> Self { - LexerError::ParseIntError - } -} - -impl From<ParseFloatError> for LexerError { - fn from(_: ParseFloatError) -> Self { - LexerError::ParseFloatError - } -} - -impl From<float::ProtobufFloatParseError> for LexerError { - fn from(_: float::ProtobufFloatParseError) -> Self { - LexerError::IncorrectFloatLit - } -} - -#[derive(Copy, Clone)] -pub struct Lexer<'a> { - language: ParserLanguage, - input: &'a str, - pos: usize, - pub loc: Loc, -} - -fn is_letter(c: char) -> bool { - c.is_alphabetic() || c == '_' -} - -impl<'a> Lexer<'a> { - pub fn new(input: &'a str, language: ParserLanguage) -> Lexer<'a> { - Lexer { - language, - input, - pos: 0, - loc: Loc::start(), - } - } - - /// No more chars - pub fn eof(&self) -> bool { - self.pos == self.input.len() - } - - /// Remaining chars - fn rem_chars(&self) -> &'a str { - &self.input[self.pos..] - } - - pub fn lookahead_char_is<P: FnOnce(char) -> bool>(&self, p: P) -> bool { - self.lookahead_char().map_or(false, p) - } - - fn lookahead_char_is_in(&self, alphabet: &str) -> bool { - self.lookahead_char_is(|c| alphabet.contains(c)) - } - - fn next_char_opt(&mut self) -> Option<char> { - let rem = self.rem_chars(); - if rem.is_empty() { - None - } else { - let mut char_indices = rem.char_indices(); - let (_, c) = char_indices.next().unwrap(); - let c_len = char_indices.next().map(|(len, _)| len).unwrap_or(rem.len()); - self.pos += c_len; - if c == '\n' { - self.loc.line += 1; - self.loc.col = FIRST_COL; - } else { - self.loc.col += 1; - } - Some(c) - } - } - - fn next_char(&mut self) -> LexerResult<char> { - self.next_char_opt().ok_or(LexerError::UnexpectedEof) - } - - /// Skip whitespaces - fn skip_whitespaces(&mut self) { - self.take_while(|c| c.is_whitespace()); - } - - fn skip_c_comment(&mut self) -> LexerResult<()> { - if self.skip_if_lookahead_is_str("/*") { - let end = "*/"; - match self.rem_chars().find(end) { - None => Err(LexerError::UnexpectedEof), - Some(len) => { - let new_pos = self.pos + len + end.len(); - self.skip_to_pos(new_pos); - Ok(()) - } - } - } else { - Ok(()) - } - } - - fn skip_cpp_comment(&mut self) { - if self.skip_if_lookahead_is_str("//") { - loop { - match self.next_char_opt() { - Some('\n') | None => break, - _ => {} - } - } - } - } - - fn skip_sh_comment(&mut self) { - if self.skip_if_lookahead_is_str("#") { - loop { - match self.next_char_opt() { - Some('\n') | None => break, - _ => {} - } - } - } - } - - fn skip_comment(&mut self) -> LexerResult<()> { - match self.language { - ParserLanguage::Proto => { - self.skip_c_comment()?; - self.skip_cpp_comment(); - } - ParserLanguage::TextFormat => { - self.skip_sh_comment(); - } - ParserLanguage::Json => {} - } - Ok(()) - } - - pub fn skip_ws(&mut self) -> LexerResult<()> { - loop { - let pos = self.pos; - self.skip_whitespaces(); - self.skip_comment()?; - if pos == self.pos { - // Did not advance - return Ok(()); - } - } - } - - pub fn take_while<F>(&mut self, f: F) -> &'a str - where - F: Fn(char) -> bool, - { - let start = self.pos; - while self.lookahead_char().map(&f) == Some(true) { - self.next_char_opt().unwrap(); - } - let end = self.pos; - &self.input[start..end] - } - - fn lookahead_char(&self) -> Option<char> { - self.clone().next_char_opt() - } - - fn lookahead_is_str(&self, s: &str) -> bool { - self.rem_chars().starts_with(s) - } - - fn skip_if_lookahead_is_str(&mut self, s: &str) -> bool { - if self.lookahead_is_str(s) { - let new_pos = self.pos + s.len(); - self.skip_to_pos(new_pos); - true - } else { - false - } - } - - fn next_char_if<P>(&mut self, p: P) -> Option<char> - where - P: FnOnce(char) -> bool, - { - let mut clone = self.clone(); - match clone.next_char_opt() { - Some(c) if p(c) => { - *self = clone; - Some(c) - } - _ => None, - } - } - - pub fn next_char_if_eq(&mut self, expect: char) -> bool { - self.next_char_if(|c| c == expect) != None - } - - fn next_char_if_in(&mut self, alphabet: &str) -> Option<char> { - for c in alphabet.chars() { - if self.next_char_if_eq(c) { - return Some(c); - } - } - None - } - - fn next_char_expect_eq(&mut self, expect: char) -> LexerResult<()> { - if self.next_char_if_eq(expect) { - Ok(()) - } else { - Err(LexerError::ExpectChar(expect)) - } - } - - fn next_char_expect<P>(&mut self, expect: P, err: LexerError) -> LexerResult<char> - where - P: FnOnce(char) -> bool, - { - self.next_char_if(expect).ok_or(err) - } - - // str functions - - /// properly update line and column - fn skip_to_pos(&mut self, new_pos: usize) -> &'a str { - assert!(new_pos >= self.pos); - assert!(new_pos <= self.input.len()); - let pos = self.pos; - while self.pos != new_pos { - self.next_char_opt().unwrap(); - } - &self.input[pos..new_pos] - } - - // Protobuf grammar - - // char functions - - // letter = "A" … "Z" | "a" … "z" - // https://github.com/google/protobuf/issues/4565 - fn next_letter_opt(&mut self) -> Option<char> { - self.next_char_if(is_letter) - } - - // capitalLetter = "A" … "Z" - fn _next_capital_letter_opt(&mut self) -> Option<char> { - self.next_char_if(|c| c >= 'A' && c <= 'Z') - } - - fn next_ident_part(&mut self) -> Option<char> { - self.next_char_if(|c| c.is_ascii_alphanumeric() || c == '_') - } - - // Identifiers - - // ident = letter { letter | decimalDigit | "_" } - fn next_ident_opt(&mut self) -> LexerResult<Option<String>> { - if let Some(c) = self.next_letter_opt() { - let mut ident = String::new(); - ident.push(c); - while let Some(c) = self.next_ident_part() { - ident.push(c); - } - Ok(Some(ident)) - } else { - Ok(None) - } - } - - // Integer literals - - // hexLit = "0" ( "x" | "X" ) hexDigit { hexDigit } - fn next_hex_lit_opt(&mut self) -> LexerResult<Option<u64>> { - Ok( - if self.skip_if_lookahead_is_str("0x") || self.skip_if_lookahead_is_str("0X") { - let s = self.take_while(|c| c.is_ascii_hexdigit()); - Some(u64::from_str_radix(s, 16)? as u64) - } else { - None - }, - ) - } - - // decimalLit = ( "1" … "9" ) { decimalDigit } - // octalLit = "0" { octalDigit } - fn next_decimal_octal_lit_opt(&mut self) -> LexerResult<Option<u64>> { - // do not advance on number parse error - let mut clone = self.clone(); - - let pos = clone.pos; - - Ok(if clone.next_char_if(|c| c.is_ascii_digit()) != None { - clone.take_while(|c| c.is_ascii_digit()); - let value = clone.input[pos..clone.pos].parse()?; - *self = clone; - Some(value) - } else { - None - }) - } - - // hexDigit = "0" … "9" | "A" … "F" | "a" … "f" - fn next_hex_digit(&mut self) -> LexerResult<u32> { - let mut clone = self.clone(); - let r = match clone.next_char()? { - c if c >= '0' && c <= '9' => c as u32 - b'0' as u32, - c if c >= 'A' && c <= 'F' => c as u32 - b'A' as u32 + 10, - c if c >= 'a' && c <= 'f' => c as u32 - b'a' as u32 + 10, - _ => return Err(LexerError::ExpectHexDigit), - }; - *self = clone; - Ok(r) - } - - // octalDigit = "0" … "7" - fn next_octal_digit(&mut self) -> LexerResult<u32> { - self.next_char_expect(|c| c >= '0' && c <= '9', LexerError::ExpectOctDigit) - .map(|c| c as u32 - '0' as u32) - } - - // decimalDigit = "0" … "9" - fn next_decimal_digit(&mut self) -> LexerResult<u32> { - self.next_char_expect(|c| c >= '0' && c <= '9', LexerError::ExpectDecDigit) - .map(|c| c as u32 - '0' as u32) - } - - // decimals = decimalDigit { decimalDigit } - fn next_decimal_digits(&mut self) -> LexerResult<()> { - self.next_decimal_digit()?; - self.take_while(|c| c >= '0' && c <= '9'); - Ok(()) - } - - // intLit = decimalLit | octalLit | hexLit - pub fn next_int_lit_opt(&mut self) -> LexerResult<Option<u64>> { - assert_ne!(ParserLanguage::Json, self.language); - - self.skip_ws()?; - if let Some(i) = self.next_hex_lit_opt()? { - return Ok(Some(i)); - } - if let Some(i) = self.next_decimal_octal_lit_opt()? { - return Ok(Some(i)); - } - Ok(None) - } - - // Floating-point literals - - // exponent = ( "e" | "E" ) [ "+" | "-" ] decimals - fn next_exponent_opt(&mut self) -> LexerResult<Option<()>> { - if self.next_char_if_in("eE") != None { - self.next_char_if_in("+-"); - self.next_decimal_digits()?; - Ok(Some(())) - } else { - Ok(None) - } - } - - // floatLit = ( decimals "." [ decimals ] [ exponent ] | decimals exponent | "."decimals [ exponent ] ) | "inf" | "nan" - fn next_float_lit(&mut self) -> LexerResult<()> { - assert_ne!(ParserLanguage::Json, self.language); - - // "inf" and "nan" are handled as part of ident - if self.next_char_if_eq('.') { - self.next_decimal_digits()?; - self.next_exponent_opt()?; - } else { - self.next_decimal_digits()?; - if self.next_char_if_eq('.') { - self.next_decimal_digits()?; - self.next_exponent_opt()?; - } else { - if self.next_exponent_opt()? == None { - return Err(LexerError::IncorrectFloatLit); - } - } - } - Ok(()) - } - - // String literals - - // charValue = hexEscape | octEscape | charEscape | /[^\0\n\\]/ - // hexEscape = '\' ( "x" | "X" ) hexDigit hexDigit - // https://github.com/google/protobuf/issues/4560 - // octEscape = '\' octalDigit octalDigit octalDigit - // charEscape = '\' ( "a" | "b" | "f" | "n" | "r" | "t" | "v" | '\' | "'" | '"' ) - // quote = "'" | '"' - pub fn next_byte_value(&mut self) -> LexerResult<u8> { - match self.next_char()? { - '\\' => { - match self.next_char()? { - '\'' => Ok(b'\''), - '"' => Ok(b'"'), - '\\' => Ok(b'\\'), - 'a' => Ok(b'\x07'), - 'b' => Ok(b'\x08'), - 'f' => Ok(b'\x0c'), - 'n' => Ok(b'\n'), - 'r' => Ok(b'\r'), - 't' => Ok(b'\t'), - 'v' => Ok(b'\x0b'), - 'x' => { - let d1 = self.next_hex_digit()? as u8; - let d2 = self.next_hex_digit()? as u8; - Ok(((d1 << 4) | d2) as u8) - } - d if d >= '0' && d <= '7' => { - let mut r = d as u8 - b'0'; - for _ in 0..2 { - match self.next_octal_digit() { - Err(_) => break, - Ok(d) => r = (r << 3) + d as u8, - } - } - Ok(r) - } - // https://github.com/google/protobuf/issues/4562 - // TODO: overflow - c => Ok(c as u8), - } - } - '\n' | '\0' => Err(LexerError::IncorrectInput), - // TODO: check overflow - c => Ok(c as u8), - } - } - - fn char_try_from(i: u32) -> LexerResult<char> { - char::try_from(i).map_err(|_| LexerError::IncorrectUnicodeChar) - } - - pub fn next_json_char_value(&mut self) -> LexerResult<char> { - match self.next_char()? { - '\\' => match self.next_char()? { - '"' => Ok('"'), - '\'' => Ok('\''), - '\\' => Ok('\\'), - '/' => Ok('/'), - 'b' => Ok('\x08'), - 'f' => Ok('\x0c'), - 'n' => Ok('\n'), - 'r' => Ok('\r'), - 't' => Ok('\t'), - 'u' => { - let mut v = 0; - for _ in 0..4 { - let digit = self.next_hex_digit()?; - v = v * 16 + digit; - } - Self::char_try_from(v) - } - _ => Err(LexerError::IncorrectJsonEscape), - }, - c => Ok(c), - } - } - - // https://github.com/google/protobuf/issues/4564 - // strLit = ( "'" { charValue } "'" ) | ( '"' { charValue } '"' ) - fn next_str_lit_raw(&mut self) -> LexerResult<String> { - let mut raw = String::new(); - - let mut first = true; - loop { - if !first { - self.skip_ws()?; - } - - let start = self.pos; - - let q = match self.next_char_if_in("'\"") { - Some(q) => q, - None if !first => break, - None => return Err(LexerError::IncorrectInput), - }; - first = false; - while self.lookahead_char() != Some(q) { - self.next_byte_value()?; - } - self.next_char_expect_eq(q)?; - - raw.push_str(&self.input[start + 1..self.pos - 1]); - } - Ok(raw) - } - - fn next_str_lit_raw_opt(&mut self) -> LexerResult<Option<String>> { - if self.lookahead_char_is_in("'\"") { - Ok(Some(self.next_str_lit_raw()?)) - } else { - Ok(None) - } - } - - /// Parse next token as JSON number - fn next_json_number_opt(&mut self) -> LexerResult<Option<JsonNumberLit>> { - assert_eq!(ParserLanguage::Json, self.language); - - fn is_digit(c: char) -> bool { - c >= '0' && c <= '9' - } - - fn is_digit_1_9(c: char) -> bool { - c >= '1' && c <= '9' - } - - if !self.lookahead_char_is_in("-0123456789") { - return Ok(None); - } - - let mut s = String::new(); - if self.next_char_if_eq('-') { - s.push('-'); - } - - if self.next_char_if_eq('0') { - s.push('0'); - } else { - s.push(self.next_char_expect(is_digit_1_9, LexerError::IncorrectJsonNumber)?); - while let Some(c) = self.next_char_if(is_digit) { - s.push(c); - } - } - - if self.next_char_if_eq('.') { - s.push('.'); - s.push(self.next_char_expect(is_digit, LexerError::IncorrectJsonNumber)?); - while let Some(c) = self.next_char_if(is_digit) { - s.push(c); - } - } - - if let Some(c) = self.next_char_if_in("eE") { - s.push(c); - if let Some(c) = self.next_char_if_in("+-") { - s.push(c); - } - s.push(self.next_char_expect(is_digit, LexerError::IncorrectJsonNumber)?); - while let Some(c) = self.next_char_if(is_digit) { - s.push(c); - } - } - - Ok(Some(JsonNumberLit(s))) - } - - fn next_token_inner(&mut self) -> LexerResult<Token> { - if self.language == ParserLanguage::Json { - if let Some(v) = self.next_json_number_opt()? { - return Ok(Token::JsonNumber(v)); - } - } - - if let Some(ident) = self.next_ident_opt()? { - let token = if self.language != ParserLanguage::Json && ident == float::PROTOBUF_NAN { - Token::FloatLit(f64::NAN) - } else if self.language != ParserLanguage::Json && ident == float::PROTOBUF_INF { - Token::FloatLit(f64::INFINITY) - } else { - Token::Ident(ident.to_owned()) - }; - return Ok(token); - } - - if self.language != ParserLanguage::Json { - let mut clone = self.clone(); - let pos = clone.pos; - if let Ok(_) = clone.next_float_lit() { - let f = float::parse_protobuf_float(&self.input[pos..clone.pos])?; - *self = clone; - return Ok(Token::FloatLit(f)); - } - - if let Some(lit) = self.next_int_lit_opt()? { - return Ok(Token::IntLit(lit)); - } - } - - if let Some(escaped) = self.next_str_lit_raw_opt()? { - return Ok(Token::StrLit(StrLit { escaped })); - } - - // This branch must be after str lit - if let Some(c) = self.next_char_if(|c| c.is_ascii_punctuation()) { - return Ok(Token::Symbol(c)); - } - - if let Some(ident) = self.next_ident_opt()? { - return Ok(Token::Ident(ident)); - } - - Err(LexerError::IncorrectInput) - } - - pub fn next_token(&mut self) -> LexerResult<Option<TokenWithLocation>> { - self.skip_ws()?; - let loc = self.loc; - - Ok(if self.eof() { - None - } else { - let token = self.next_token_inner()?; - // Skip whitespace here to update location - // to the beginning of the next token - self.skip_ws()?; - Some(TokenWithLocation { token, loc }) - }) - } -} - -#[cfg(test)] -mod test { - use super::*; - - fn lex<P, R>(input: &str, parse_what: P) -> R - where - P: FnOnce(&mut Lexer) -> LexerResult<R>, - { - let mut lexer = Lexer::new(input, ParserLanguage::Proto); - let r = parse_what(&mut lexer).expect(&format!("lexer failed at {}", lexer.loc)); - assert!(lexer.eof(), "check eof failed at {}", lexer.loc); - r - } - - fn lex_opt<P, R>(input: &str, parse_what: P) -> R - where - P: FnOnce(&mut Lexer) -> LexerResult<Option<R>>, - { - let mut lexer = Lexer::new(input, ParserLanguage::Proto); - let o = parse_what(&mut lexer).expect(&format!("lexer failed at {}", lexer.loc)); - let r = o.expect(&format!("lexer returned none at {}", lexer.loc)); - assert!(lexer.eof(), "check eof failed at {}", lexer.loc); - r - } - - #[test] - fn test_lexer_int_lit() { - let msg = r#"10"#; - let mess = lex_opt(msg, |p| p.next_int_lit_opt()); - assert_eq!(10, mess); - } - - #[test] - fn test_lexer_float_lit() { - let msg = r#"12.3"#; - let mess = lex(msg, |p| p.next_token_inner()); - assert_eq!(Token::FloatLit(12.3), mess); - } - - #[test] - fn test_lexer_float_lit_leading_zeros_in_exp() { - let msg = r#"1e00009"#; - let mess = lex(msg, |p| p.next_token_inner()); - assert_eq!(Token::FloatLit(1_000_000_000.0), mess); - } -} diff --git a/src/text_format/lexer/loc.rs b/src/text_format/lexer/loc.rs deleted file mode 100644 index ea3fc1a..0000000 --- a/src/text_format/lexer/loc.rs +++ /dev/null @@ -1,28 +0,0 @@ -use std::fmt; - -pub const FIRST_LINE: u32 = 1; -pub const FIRST_COL: u32 = 1; - -/// Location in file -#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd)] -pub struct Loc { - /// 1-based - pub line: u32, - /// 1-based - pub col: u32, -} - -impl fmt::Display for Loc { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}:{}", self.line, self.col) - } -} - -impl Loc { - pub fn start() -> Loc { - Loc { - line: FIRST_LINE, - col: FIRST_COL, - } - } -} diff --git a/src/text_format/lexer/mod.rs b/src/text_format/lexer/mod.rs deleted file mode 100644 index a7ed884..0000000 --- a/src/text_format/lexer/mod.rs +++ /dev/null @@ -1,21 +0,0 @@ -//! Implementation of lexer for both protobuf parser and for text format parser. - -pub mod float; -mod json_number_lit; -mod lexer_impl; -mod loc; -mod num_lit; -mod parser_language; -mod str_lit; -mod token; - -pub use self::json_number_lit::JsonNumberLit; -pub use self::lexer_impl::Lexer; -pub use self::lexer_impl::LexerError; -pub use self::loc::Loc; -pub use self::num_lit::NumLit; -pub use self::parser_language::ParserLanguage; -pub use self::str_lit::StrLit; -pub use self::str_lit::StrLitDecodeError; -pub use self::token::Token; -pub use self::token::TokenWithLocation; diff --git a/src/text_format/lexer/num_lit.rs b/src/text_format/lexer/num_lit.rs deleted file mode 100644 index cc64cc4..0000000 --- a/src/text_format/lexer/num_lit.rs +++ /dev/null @@ -1,5 +0,0 @@ -#[derive(Copy, Clone)] -pub enum NumLit { - U64(u64), - F64(f64), -} diff --git a/src/text_format/lexer/parser_language.rs b/src/text_format/lexer/parser_language.rs deleted file mode 100644 index e356571..0000000 --- a/src/text_format/lexer/parser_language.rs +++ /dev/null @@ -1,10 +0,0 @@ -/// We use the same lexer/tokenizer for all parsers for simplicity -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum ParserLanguage { - // `.proto` files - Proto, - // Protobuf text format - TextFormat, - // JSON - Json, -} diff --git a/src/text_format/lexer/str_lit.rs b/src/text_format/lexer/str_lit.rs deleted file mode 100644 index 15ffa5b..0000000 --- a/src/text_format/lexer/str_lit.rs +++ /dev/null @@ -1,86 +0,0 @@ -use std::fmt; -use std::string::FromUtf8Error; - -use super::lexer_impl::Lexer; -use super::lexer_impl::LexerError; -use crate::text_format::lexer::ParserLanguage; - -#[derive(Debug)] -pub enum StrLitDecodeError { - FromUtf8Error(FromUtf8Error), - // TODO: be more specific - OtherError, -} - -impl fmt::Display for StrLitDecodeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - StrLitDecodeError::FromUtf8Error(e) => write!(f, "{}", e), - StrLitDecodeError::OtherError => write!(f, "String literal decode error"), - } - } -} - -impl std::error::Error for StrLitDecodeError {} - -impl From<LexerError> for StrLitDecodeError { - fn from(_: LexerError) -> Self { - StrLitDecodeError::OtherError - } -} - -impl From<FromUtf8Error> for StrLitDecodeError { - fn from(e: FromUtf8Error) -> Self { - StrLitDecodeError::FromUtf8Error(e) - } -} - -pub type StrLitDecodeResult<T> = Result<T, StrLitDecodeError>; - -/// String literal, both `string` and `bytes`. -#[derive(Clone, Eq, PartialEq, Debug)] -pub struct StrLit { - pub escaped: String, -} - -impl StrLit { - /// May fail if not valid UTF8 - pub fn decode_utf8(&self) -> StrLitDecodeResult<String> { - let mut lexer = Lexer::new(&self.escaped, ParserLanguage::Json); - let mut r = Vec::new(); - while !lexer.eof() { - r.push(lexer.next_byte_value()?); - } - Ok(String::from_utf8(r)?) - } - - pub fn decode_bytes(&self) -> StrLitDecodeResult<Vec<u8>> { - let mut lexer = Lexer::new(&self.escaped, ParserLanguage::Json); - let mut r = Vec::new(); - while !lexer.eof() { - r.push(lexer.next_byte_value()?); - } - Ok(r) - } - - pub fn quoted(&self) -> String { - format!("\"{}\"", self.escaped) - } -} - -#[cfg(test)] -mod test { - use crate::text_format::lexer::StrLit; - - #[test] - fn decode_utf8() { - assert_eq!( - "\u{1234}".to_owned(), - StrLit { - escaped: "\\341\\210\\264".to_owned() - } - .decode_utf8() - .unwrap() - ) - } -} diff --git a/src/text_format/lexer/token.rs b/src/text_format/lexer/token.rs deleted file mode 100644 index 55d931a..0000000 --- a/src/text_format/lexer/token.rs +++ /dev/null @@ -1,47 +0,0 @@ -use super::lexer_impl::LexerError; -use super::lexer_impl::LexerResult; -use super::loc::Loc; -use super::num_lit::NumLit; -use super::str_lit::StrLit; -use crate::text_format::lexer::JsonNumberLit; - -#[derive(Clone, Debug, PartialEq)] -pub enum Token { - Ident(String), - Symbol(char), - // Protobuf tokenizer has separate tokens for int and float. - // Tokens do not include sign. - IntLit(u64), - FloatLit(f64), - JsonNumber(JsonNumberLit), - // including quotes - StrLit(StrLit), -} - -impl Token { - /// Back to original - pub fn format(&self) -> String { - match self { - &Token::Ident(ref s) => s.clone(), - &Token::Symbol(c) => c.to_string(), - &Token::IntLit(ref i) => i.to_string(), - &Token::StrLit(ref s) => s.quoted(), - &Token::FloatLit(ref f) => f.to_string(), - &Token::JsonNumber(ref f) => f.to_string(), - } - } - - pub fn to_num_lit(&self) -> LexerResult<NumLit> { - match self { - &Token::IntLit(i) => Ok(NumLit::U64(i)), - &Token::FloatLit(f) => Ok(NumLit::F64(f)), - _ => Err(LexerError::IncorrectInput), - } - } -} - -#[derive(Clone)] -pub struct TokenWithLocation { - pub token: Token, - pub loc: Loc, -} diff --git a/src/text_format/mod.rs b/src/text_format/mod.rs index 2fa9a16..4ae5372 100644 --- a/src/text_format/mod.rs +++ b/src/text_format/mod.rs @@ -1,4 +1,4 @@ -//! Protobuf "text format" implementation. +//! # Protobuf "text format" implementation. //! //! Text format message look like this: //! @@ -18,290 +18,20 @@ //! This format is not specified, but it is implemented by all official //! protobuf implementations, including `protoc` command which can decode //! and encode messages using text format. +//! +//! # JSON +//! +//! rust-protobuf also supports JSON printing and parsing. +//! It is implemented in +//! [`protobuf-json-mapping` crate](https://docs.rs/protobuf-json-mapping/%3E=3.0.0-alpha). -use std; -use std::fmt; -use std::fmt::Write; - -use crate::message::Message; -use crate::reflect::ReflectFieldRef; -use crate::reflect::ReflectValueRef; - +mod parse; mod print; -// Used by text format parser and by pure-rust codegen parsed -// this it is public but hidden module. -// https://github.com/rust-lang/rust/issues/44663 -#[doc(hidden)] -pub mod lexer; - -use self::print::print_str_to; -#[doc(hidden)] -pub use self::print::quote_bytes_to; -#[doc(hidden)] -pub use self::print::quote_escape_bytes; -use crate::text_format::print::quote_escape_bytes_to; - -#[doc(hidden)] -pub fn unescape_string(string: &str) -> Vec<u8> { - fn parse_if_digit(chars: &mut std::str::Chars) -> u8 { - let mut copy = chars.clone(); - let f = match copy.next() { - None => return 0, - Some(f) => f, - }; - let d = match f { - '0'..='9' => (f as u8 - b'0'), - _ => return 0, - }; - *chars = copy; - d - } - - fn parse_hex_digit(chars: &mut std::str::Chars) -> u8 { - match chars.next().unwrap() { - c @ '0'..='9' => (c as u8) - b'0', - c @ 'a'..='f' => (c as u8) - b'a' + 10, - c @ 'A'..='F' => (c as u8) - b'A' + 10, - _ => panic!("incorrect hex escape"), - } - } - - fn parse_escape_rem(chars: &mut std::str::Chars) -> u8 { - let n = chars.next().unwrap(); - match n { - 'a' => return b'\x07', - 'b' => return b'\x08', - 'f' => return b'\x0c', - 'n' => return b'\n', - 'r' => return b'\r', - 't' => return b'\t', - 'v' => return b'\x0b', - '"' => return b'"', - '\'' => return b'\'', - '0'..='9' => { - let d1 = n as u8 - b'0'; - let d2 = parse_if_digit(chars); - let d3 = parse_if_digit(chars); - return (d1 * 64 + d2 * 8 + d3) as u8; - } - 'x' => { - let d1 = parse_hex_digit(chars); - let d2 = parse_hex_digit(chars); - return d1 * 16 + d2; - } - c => return c as u8, // TODO: validate ASCII - }; - } - - let mut chars = string.chars(); - let mut r = Vec::new(); - - loop { - let f = match chars.next() { - None => return r, - Some(f) => f, - }; - - if f == '\\' { - r.push(parse_escape_rem(&mut chars)); - } else { - r.push(f as u8); // TODO: escape UTF-8 - } - } -} - -fn do_indent(buf: &mut String, pretty: bool, indent: usize) { - if pretty && indent > 0 { - for _ in 0..indent { - buf.push_str(" "); - } - } -} - -fn print_start_field( - buf: &mut String, - pretty: bool, - indent: usize, - first: &mut bool, - field_name: &str, -) { - if !*first && !pretty { - buf.push_str(" "); - } - do_indent(buf, pretty, indent); - *first = false; - buf.push_str(field_name); -} - -fn print_end_field(buf: &mut String, pretty: bool) { - if pretty { - buf.push_str("\n"); - } -} - -fn print_field( - buf: &mut String, - pretty: bool, - indent: usize, - first: &mut bool, - field_name: &str, - value: ReflectValueRef, -) { - print_start_field(buf, pretty, indent, first, field_name); - - match value { - ReflectValueRef::Message(m) => { - buf.push_str(" {"); - if pretty { - buf.push_str("\n"); - } - print_to_internal(m, buf, pretty, indent + 1); - do_indent(buf, pretty, indent); - buf.push_str("}"); - } - ReflectValueRef::Enum(e) => { - buf.push_str(": "); - buf.push_str(e.name()); - } - ReflectValueRef::String(s) => { - buf.push_str(": "); - print_str_to(s, buf); - } - ReflectValueRef::Bytes(b) => { - buf.push_str(": "); - quote_escape_bytes_to(b, buf); - } - ReflectValueRef::I32(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::I64(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::U32(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::U64(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::Bool(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::F32(v) => { - write!(buf, ": {}", v).unwrap(); - } - ReflectValueRef::F64(v) => { - write!(buf, ": {}", v).unwrap(); - } - } - - print_end_field(buf, pretty); -} - -fn print_to_internal(m: &dyn Message, buf: &mut String, pretty: bool, indent: usize) { - let d = m.descriptor(); - let mut first = true; - for f in d.fields() { - match f.get_reflect(m) { - ReflectFieldRef::Map(map) => { - for (k, v) in map { - print_start_field(buf, pretty, indent, &mut first, f.name()); - buf.push_str(" {"); - if pretty { - buf.push_str("\n"); - } - - let mut entry_first = true; - - print_field(buf, pretty, indent + 1, &mut entry_first, "key", k.as_ref()); - print_field( - buf, - pretty, - indent + 1, - &mut entry_first, - "value", - v.as_ref(), - ); - do_indent(buf, pretty, indent); - buf.push_str("}"); - print_end_field(buf, pretty); - } - } - ReflectFieldRef::Repeated(repeated) => { - // TODO: do not print zeros for v3 - for v in repeated { - print_field(buf, pretty, indent, &mut first, f.name(), v.as_ref()); - } - } - ReflectFieldRef::Optional(optional) => { - if let Some(v) = optional { - print_field(buf, pretty, indent, &mut first, f.name(), v); - } - } - } - } - - // TODO: unknown fields -} - -/// Text-format -pub fn print_to(m: &dyn Message, buf: &mut String) { - print_to_internal(m, buf, false, 0) -} - -fn print_to_string_internal(m: &dyn Message, pretty: bool) -> String { - let mut r = String::new(); - print_to_internal(m, &mut r, pretty, 0); - r.to_string() -} - -/// Text-format -pub fn print_to_string(m: &dyn Message) -> String { - print_to_string_internal(m, false) -} - -/// Text-format to `fmt::Formatter`. -pub fn fmt(m: &dyn Message, f: &mut fmt::Formatter) -> fmt::Result { - let pretty = f.alternate(); - f.write_str(&print_to_string_internal(m, pretty)) -} - -#[cfg(test)] -mod test { - - fn escape(data: &[u8]) -> String { - let mut s = String::with_capacity(data.len() * 4); - super::quote_bytes_to(data, &mut s); - s - } - - fn test_escape_unescape(text: &str, escaped: &str) { - assert_eq!(text.as_bytes(), &super::unescape_string(escaped)[..]); - assert_eq!(escaped, &escape(text.as_bytes())[..]); - } - - #[test] - fn test_print_to_bytes() { - assert_eq!("ab", escape(b"ab")); - assert_eq!("a\\\\023", escape(b"a\\023")); - assert_eq!("a\\r\\n\\t \\'\\\"\\\\", escape(b"a\r\n\t '\"\\")); - assert_eq!("\\344\\275\\240\\345\\245\\275", escape("ä½ å¥½".as_bytes())); - } - - #[test] - fn test_unescape_string() { - test_escape_unescape("", ""); - test_escape_unescape("aa", "aa"); - test_escape_unescape("\n", "\\n"); - test_escape_unescape("\r", "\\r"); - test_escape_unescape("\t", "\\t"); - test_escape_unescape("ä½ å¥½", "\\344\\275\\240\\345\\245\\275"); - // hex - assert_eq!(b"aaa\x01bbb", &super::unescape_string("aaa\\x01bbb")[..]); - assert_eq!(b"aaa\xcdbbb", &super::unescape_string("aaa\\xCDbbb")[..]); - assert_eq!(b"aaa\xcdbbb", &super::unescape_string("aaa\\xCDbbb")[..]); - // quotes - assert_eq!(b"aaa\"bbb", &super::unescape_string("aaa\\\"bbb")[..]); - assert_eq!(b"aaa\'bbb", &super::unescape_string("aaa\\\'bbb")[..]); - } -} +pub use self::parse::merge_from_str; +pub use self::parse::parse_from_str; +pub use self::parse::ParseError; +pub use self::print::fmt; +pub use self::print::print_to; +pub use self::print::print_to_string; +pub use self::print::print_to_string_pretty; diff --git a/src/text_format/parse.rs b/src/text_format/parse.rs new file mode 100644 index 0000000..905f641 --- /dev/null +++ b/src/text_format/parse.rs @@ -0,0 +1,321 @@ +use std::str; + +use protobuf_support::lexer::int; +use protobuf_support::lexer::loc::Loc; +use protobuf_support::lexer::parser_language::ParserLanguage; +use protobuf_support::lexer::str_lit::StrLitDecodeError; +use protobuf_support::lexer::tokenizer::Tokenizer; +use protobuf_support::lexer::tokenizer::TokenizerError; + +use crate::message_dyn::MessageDyn; +use crate::message_full::MessageFull; +use crate::reflect::EnumDescriptor; +use crate::reflect::EnumValueDescriptor; +use crate::reflect::MessageDescriptor; +use crate::reflect::ReflectValueBox; +use crate::reflect::RuntimeFieldType; +use crate::reflect::RuntimeType; + +#[derive(Debug, thiserror::Error)] +pub enum ParseErrorWithoutLoc { + #[error(transparent)] + TokenizerError(#[from] TokenizerError), + #[error(transparent)] + StrLitDecodeError(#[from] StrLitDecodeError), + #[error("Unknown field: `{}`", .0)] + UnknownField(String), + #[error("Unknown enum value: `{}`", .0)] + UnknownEnumValue(String), + #[error("Map field specified more than once: `{}`", .0)] + MapFieldIsSpecifiedMoreThanOnce(String), + #[error("Integer overflow")] + IntegerOverflow, + #[error("Expecting bool")] + ExpectingBool, + #[error("Message not initialized")] + MessageNotInitialized, +} + +impl From<int::Overflow> for ParseErrorWithoutLoc { + fn from(_: int::Overflow) -> Self { + ParseErrorWithoutLoc::IntegerOverflow + } +} + +/// Text format parse error. +#[derive(Debug, thiserror::Error)] +#[error("{}: {}", loc, error)] +pub struct ParseError { + error: ParseErrorWithoutLoc, + loc: Loc, +} + +pub type ParseResult<A> = Result<A, ParseErrorWithoutLoc>; +pub type ParseWithLocResult<A> = Result<A, ParseError>; + +#[derive(Clone)] +struct Parser<'a> { + tokenizer: Tokenizer<'a>, +} + +impl<'a> Parser<'a> { + // Text format + + fn next_field_name(&mut self) -> ParseResult<String> { + Ok(self.tokenizer.next_ident()?) + } + + fn read_colon(&mut self, desc: &'static str) -> ParseResult<()> { + Ok(self.tokenizer.next_symbol_expect_eq(':', desc)?) + } + + fn read_enum<'e>(&mut self, e: &'e EnumDescriptor) -> ParseResult<EnumValueDescriptor> { + self.read_colon("enum")?; + + // TODO: read integer? + let ident = self.tokenizer.next_ident()?; + let value = match e.value_by_name(&ident) { + Some(value) => value, + None => return Err(ParseErrorWithoutLoc::UnknownEnumValue(ident)), + }; + Ok(value) + } + + fn read_u64(&mut self) -> ParseResult<u64> { + self.read_colon("u64")?; + + Ok(self.tokenizer.next_int_lit()?) + } + + fn read_u32(&mut self) -> ParseResult<u32> { + self.read_colon("int value")?; + + let int_lit = self.tokenizer.next_int_lit()?; + let value_u32 = int_lit as u32; + if value_u32 as u64 != int_lit { + return Err(ParseErrorWithoutLoc::IntegerOverflow); + } + Ok(value_u32) + } + + fn read_i64(&mut self) -> ParseResult<i64> { + self.read_colon("int value")?; + + if self.tokenizer.next_symbol_if_eq('-')? { + let int_lit = self.tokenizer.next_int_lit()?; + Ok(int::neg(int_lit)?) + } else { + let int_lit = self.tokenizer.next_int_lit()?; + if int_lit > i64::MAX as u64 { + return Err(ParseErrorWithoutLoc::IntegerOverflow); + } + Ok(int_lit as i64) + } + } + + fn read_i32(&mut self) -> ParseResult<i32> { + let value = self.read_i64()?; + if value < i32::min_value() as i64 || value > i32::max_value() as i64 { + return Err(ParseErrorWithoutLoc::IntegerOverflow); + } + Ok(value as i32) + } + + fn read_f64(&mut self) -> ParseResult<f64> { + self.read_colon("float value")?; + + let minus = self.tokenizer.next_symbol_if_eq('-')?; + + let value = if let Ok(value) = self.tokenizer.next_int_lit() { + value as f64 + } else { + self.tokenizer.next_float_lit()? + }; + + Ok(if minus { -value } else { value }) + } + + fn read_f32(&mut self) -> ParseResult<f32> { + Ok(self.read_f64()? as f32) + } + + fn read_bool(&mut self) -> ParseResult<bool> { + self.read_colon("bool value")?; + + if self.tokenizer.next_ident_if_eq("true")? { + Ok(true) + } else if self.tokenizer.next_ident_if_eq("false")? { + Ok(false) + } else { + Err(ParseErrorWithoutLoc::ExpectingBool) + } + } + + fn read_string(&mut self) -> ParseResult<String> { + self.read_colon("string value")?; + + Ok(self + .tokenizer + .next_str_lit() + .and_then(|s| s.decode_utf8().map_err(From::from))?) + } + + fn read_bytes(&mut self) -> ParseResult<Vec<u8>> { + self.read_colon("bytes value")?; + + Ok(self + .tokenizer + .next_str_lit() + .and_then(|s| s.decode_bytes().map_err(From::from))?) + } + + fn read_message(&mut self, descriptor: &MessageDescriptor) -> ParseResult<Box<dyn MessageDyn>> { + let mut message = descriptor.new_instance(); + + let symbol = self.tokenizer.next_symbol_expect_eq_oneof(&['{', '<'])?; + let terminator = if symbol == '{' { '}' } else { '>' }; + while !self.tokenizer.lookahead_is_symbol(terminator)? { + self.merge_field(&mut *message, descriptor)?; + } + self.tokenizer + .next_symbol_expect_eq(terminator, "message")?; + Ok(message) + } + + fn read_map_entry( + &mut self, + k: &RuntimeType, + v: &RuntimeType, + ) -> ParseResult<(ReflectValueBox, ReflectValueBox)> { + let key_field_name: &str = "key"; + let value_field_name: &str = "value"; + + let mut key = None; + let mut value = None; + self.tokenizer.next_symbol_expect_eq('{', "map entry")?; + while !self.tokenizer.lookahead_is_symbol('}')? { + let ident = self.next_field_name()?; + let (field, field_type) = if ident == key_field_name { + (&mut key, k) + } else if ident == value_field_name { + (&mut value, v) + } else { + return Err(ParseErrorWithoutLoc::UnknownField(ident)); + }; + + if let Some(..) = *field { + return Err(ParseErrorWithoutLoc::MapFieldIsSpecifiedMoreThanOnce(ident)); + } + + let field_value = self.read_value_of_type(field_type)?; + + *field = Some(field_value); + } + self.tokenizer.next_symbol_expect_eq('}', "map entry")?; + let key = match key { + Some(key) => key, + None => k.default_value_ref().to_box(), + }; + let value = match value { + Some(value) => value, + None => v.default_value_ref().to_box(), + }; + Ok((key, value)) + } + + fn read_value_of_type(&mut self, t: &RuntimeType) -> ParseResult<ReflectValueBox> { + Ok(match t { + RuntimeType::Enum(d) => { + let value = self.read_enum(&d)?.value(); + ReflectValueBox::Enum(d.clone(), value) + } + RuntimeType::U32 => ReflectValueBox::U32(self.read_u32()?), + RuntimeType::U64 => ReflectValueBox::U64(self.read_u64()?), + RuntimeType::I32 => ReflectValueBox::I32(self.read_i32()?), + RuntimeType::I64 => ReflectValueBox::I64(self.read_i64()?), + RuntimeType::F32 => ReflectValueBox::F32(self.read_f32()?), + RuntimeType::F64 => ReflectValueBox::F64(self.read_f64()?), + RuntimeType::Bool => ReflectValueBox::Bool(self.read_bool()?), + RuntimeType::String => ReflectValueBox::String(self.read_string()?), + RuntimeType::VecU8 => ReflectValueBox::Bytes(self.read_bytes()?), + RuntimeType::Message(m) => ReflectValueBox::Message(self.read_message(&m)?), + }) + } + + fn merge_field( + &mut self, + message: &mut dyn MessageDyn, + descriptor: &MessageDescriptor, + ) -> ParseResult<()> { + let field_name = self.next_field_name()?; + + let field = match descriptor.field_by_name(&field_name) { + Some(field) => field, + None => { + // TODO: shouldn't unknown fields be quietly skipped? + return Err(ParseErrorWithoutLoc::UnknownField(field_name)); + } + }; + + match field.runtime_field_type() { + RuntimeFieldType::Singular(t) => { + let value = self.read_value_of_type(&t)?; + field.set_singular_field(message, value); + } + RuntimeFieldType::Repeated(t) => { + let value = self.read_value_of_type(&t)?; + field.mut_repeated(message).push(value); + } + RuntimeFieldType::Map(k, v) => { + let (k, v) = self.read_map_entry(&k, &v)?; + field.mut_map(message).insert(k, v); + } + }; + + Ok(()) + } + + fn merge_inner(&mut self, message: &mut dyn MessageDyn) -> ParseResult<()> { + loop { + if self.tokenizer.syntax_eof()? { + break; + } + let descriptor = message.descriptor_dyn(); + self.merge_field(message, &descriptor)?; + } + Ok(()) + } + + fn merge(&mut self, message: &mut dyn MessageDyn) -> ParseWithLocResult<()> { + match self.merge_inner(message) { + Ok(()) => Ok(()), + Err(error) => Err(ParseError { + error, + loc: self.tokenizer.loc(), + }), + } + } +} + +/// Parse text format message. +/// +/// This function does not check if message required fields are set. +pub fn merge_from_str(message: &mut dyn MessageDyn, input: &str) -> ParseWithLocResult<()> { + let mut parser = Parser { + tokenizer: Tokenizer::new(input, ParserLanguage::TextFormat), + }; + parser.merge(message) +} + +/// Parse text format message. +pub fn parse_from_str<M: MessageFull>(input: &str) -> ParseWithLocResult<M> { + let mut m = M::new(); + merge_from_str(&mut m, input)?; + if let Err(_) = m.check_initialized() { + return Err(ParseError { + error: ParseErrorWithoutLoc::MessageNotInitialized, + loc: Loc::start(), + }); + } + Ok(m) +} diff --git a/src/text_format/print.rs b/src/text_format/print.rs index 397e8cd..7fb4de5 100644 --- a/src/text_format/print.rs +++ b/src/text_format/print.rs @@ -1,38 +1,187 @@ -#[doc(hidden)] -pub fn quote_bytes_to(bytes: &[u8], buf: &mut String) { - for &c in bytes { - match c { - b'\n' => buf.push_str(r"\n"), - b'\r' => buf.push_str(r"\r"), - b'\t' => buf.push_str(r"\t"), - b'\'' => buf.push_str("\\\'"), - b'"' => buf.push_str("\\\""), - b'\\' => buf.push_str(r"\\"), - b'\x20'..=b'\x7e' => buf.push(c as char), - _ => { - buf.push('\\'); - buf.push((b'0' + (c >> 6)) as char); - buf.push((b'0' + ((c >> 3) & 7)) as char); - buf.push((b'0' + (c & 7)) as char); +use std::fmt; +use std::fmt::Write; + +use protobuf_support::text_format::quote_bytes_to; + +use crate::message_dyn::MessageDyn; +use crate::reflect::MessageRef; +use crate::reflect::ReflectFieldRef; +use crate::reflect::ReflectValueRef; +use crate::UnknownValueRef; + +fn print_str_to(s: &str, buf: &mut String) { + // TODO: keep printable Unicode + quote_bytes_to(s.as_bytes(), buf); +} + +fn do_indent(buf: &mut String, pretty: bool, indent: usize) { + if pretty && indent > 0 { + for _ in 0..indent { + buf.push_str(" "); + } + } +} + +trait FieldName: fmt::Display {} +impl<'a> FieldName for &'a str {} +impl FieldName for u32 {} + +fn print_start_field<F: FieldName>( + buf: &mut String, + pretty: bool, + indent: usize, + first: &mut bool, + field_name: F, +) { + if !*first && !pretty { + buf.push_str(" "); + } + do_indent(buf, pretty, indent); + *first = false; + write!(buf, "{}", field_name).unwrap(); +} + +fn print_end_field(buf: &mut String, pretty: bool) { + if pretty { + buf.push_str("\n"); + } +} + +fn print_field<F: FieldName>( + buf: &mut String, + pretty: bool, + indent: usize, + first: &mut bool, + field_name: F, + value: ReflectValueRef, +) { + print_start_field(buf, pretty, indent, first, field_name); + + match value { + ReflectValueRef::Message(m) => { + buf.push_str(" {"); + if pretty { + buf.push_str("\n"); + } + print_to_internal(&m, buf, pretty, indent + 1); + do_indent(buf, pretty, indent); + buf.push_str("}"); + } + ReflectValueRef::Enum(d, v) => { + buf.push_str(": "); + match d.value_by_number(v) { + Some(e) => buf.push_str(e.name()), + None => write!(buf, ": {}", v).unwrap(), + } + } + ReflectValueRef::String(s) => { + buf.push_str(": "); + print_str_to(s, buf); + } + ReflectValueRef::Bytes(b) => { + buf.push_str(": "); + quote_bytes_to(b, buf); + } + ReflectValueRef::I32(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::I64(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::U32(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::U64(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::Bool(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::F32(v) => { + write!(buf, ": {}", v).unwrap(); + } + ReflectValueRef::F64(v) => { + write!(buf, ": {}", v).unwrap(); + } + } + + print_end_field(buf, pretty); +} + +fn print_to_internal(m: &MessageRef, buf: &mut String, pretty: bool, indent: usize) { + let d = m.descriptor_dyn(); + let mut first = true; + for f in d.fields() { + match f.get_reflect(&**m) { + ReflectFieldRef::Map(map) => { + for (k, v) in &map { + print_start_field(buf, pretty, indent, &mut first, f.name()); + buf.push_str(" {"); + if pretty { + buf.push_str("\n"); + } + + let mut entry_first = true; + + print_field(buf, pretty, indent + 1, &mut entry_first, "key", k); + print_field(buf, pretty, indent + 1, &mut entry_first, "value", v); + do_indent(buf, pretty, indent); + buf.push_str("}"); + print_end_field(buf, pretty); + } + } + ReflectFieldRef::Repeated(repeated) => { + for v in repeated { + print_field(buf, pretty, indent, &mut first, f.name(), v); + } + } + ReflectFieldRef::Optional(optional) => { + if let Some(v) = optional.value() { + print_field(buf, pretty, indent, &mut first, f.name(), v); + } } } } + + let mut fields: Vec<(u32, UnknownValueRef)> = m.unknown_fields_dyn().iter().collect(); + // Sort for stable output + fields.sort_by_key(|(field_number, _)| *field_number); + for (field_number, value) in fields { + // TODO: try decode nested message for length-delimited + print_field( + buf, + pretty, + indent, + &mut first, + field_number, + value.to_reflect_value_ref(), + ); + } } -pub(crate) fn quote_escape_bytes_to(bytes: &[u8], buf: &mut String) { - buf.push('"'); - quote_bytes_to(bytes, buf); - buf.push('"'); +/// Text-format +pub fn print_to(m: &dyn MessageDyn, buf: &mut String) { + print_to_internal(&MessageRef::from(m), buf, false, 0) } -#[doc(hidden)] -pub fn quote_escape_bytes(bytes: &[u8]) -> String { +fn print_to_string_internal(m: &dyn MessageDyn, pretty: bool) -> String { let mut r = String::new(); - quote_escape_bytes_to(bytes, &mut r); - r + print_to_internal(&MessageRef::from(m), &mut r, pretty, 0); + r.to_string() } -pub(crate) fn print_str_to(s: &str, buf: &mut String) { - // TODO: keep printable Unicode - quote_escape_bytes_to(s.as_bytes(), buf); +/// Text-format +pub fn print_to_string(m: &dyn MessageDyn) -> String { + print_to_string_internal(m, false) +} + +/// Text-format +pub fn print_to_string_pretty(m: &dyn MessageDyn) -> String { + print_to_string_internal(m, true) +} + +/// Text-format to `fmt::Formatter`. +pub fn fmt(m: &dyn MessageDyn, f: &mut fmt::Formatter) -> fmt::Result { + let pretty = f.alternate(); + f.write_str(&print_to_string_internal(m, pretty)) } diff --git a/src/timestamp.rs b/src/timestamp.rs new file mode 100644 index 0000000..4383568 --- /dev/null +++ b/src/timestamp.rs @@ -0,0 +1,117 @@ +use crate::cached_size::CachedSize; +use crate::well_known_types::Timestamp; +use crate::UnknownFields; +use std::time::{Duration, SystemTime}; + +impl Timestamp { + /// Unix epoch value of timestamp. + pub const UNIX_EPOCH: Timestamp = Timestamp { + seconds: 0, + nanos: 0, + unknown_fields: UnknownFields::INIT, + cached_size: CachedSize::INIT, + }; + + /// Return current time as `Timestamp`. + pub fn now() -> Timestamp { + Timestamp::from(SystemTime::now()) + } +} + +/// Convert from [`Timestamp`]. +/// +/// # Panics +/// +/// This function panics if given `SystemTime` is outside of `Timestamp` range. +impl From<SystemTime> for Timestamp { + fn from(time: SystemTime) -> Self { + match time.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since_epoch) => Timestamp { + seconds: since_epoch.as_secs() as i64, + nanos: since_epoch.subsec_nanos() as i32, + ..Default::default() + }, + Err(e) => { + let before_epoch = e.duration(); + Timestamp { + seconds: -(before_epoch.as_secs() as i64) + - (before_epoch.subsec_nanos() != 0) as i64, + nanos: (1_000_000_000 - before_epoch.subsec_nanos() as i32) % 1_000_000_000, + ..Default::default() + } + } + } + } +} + +/// Convert into [`SystemTime`]. +/// +/// The conversion could be lossy if `SystemTime` precision is smaller than nanoseconds. +/// +/// # Panics +/// +/// This function panics: +/// * if given `Timestamp` is outside of `SystemTime` range +/// * if `Timestamp` is malformed +impl Into<SystemTime> for Timestamp { + fn into(self) -> SystemTime { + if self.seconds >= 0 { + let duration = + Duration::from_secs(self.seconds as u64) + Duration::from_nanos(self.nanos as u64); + SystemTime::UNIX_EPOCH + duration + } else { + let duration = + Duration::from_secs(-self.seconds as u64) - Duration::from_nanos(self.nanos as u64); + SystemTime::UNIX_EPOCH - duration + } + } +} + +#[cfg(test)] +mod test { + use crate::well_known_types::Timestamp; + use std::time::Duration; + use std::time::SystemTime; + + #[test] + fn from_system_time() { + fn to_from(timestamp: Timestamp, system_time: SystemTime) { + assert_eq!(timestamp, Timestamp::from(system_time)); + assert_eq!(system_time, Into::<SystemTime>::into(timestamp)); + } + + to_from(Timestamp::UNIX_EPOCH, SystemTime::UNIX_EPOCH); + to_from( + Timestamp { + seconds: 0, + nanos: 200_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH + Duration::from_millis(200), + ); + to_from( + Timestamp { + seconds: 3, + nanos: 200_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH + Duration::from_millis(3_200), + ); + to_from( + Timestamp { + seconds: -1, + nanos: 800_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH - Duration::from_millis(200), + ); + to_from( + Timestamp { + seconds: -4, + nanos: 800_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH - Duration::from_millis(3_200), + ); + } +} diff --git a/src/types.rs b/src/types.rs deleted file mode 100644 index 20244a1..0000000 --- a/src/types.rs +++ /dev/null @@ -1,684 +0,0 @@ -//! Implementations of `ProtobufType` for all types. - -use std::marker; -use std::mem; - -#[cfg(feature = "bytes")] -use bytes::Bytes; - -#[cfg(feature = "bytes")] -use crate::chars::Chars; -use crate::coded_input_stream::CodedInputStream; -use crate::coded_output_stream::CodedOutputStream; -use crate::enums::ProtobufEnum; -use crate::error::ProtobufResult; -use crate::message::Message; -use crate::reflect::ProtobufValue; -use crate::rt; -use crate::unknown::UnknownValues; -use crate::wire_format::WireType; -use crate::zigzag::decode_zig_zag_32; -use crate::zigzag::decode_zig_zag_64; - -/// Protobuf elementary type as generic trait -pub trait ProtobufType { - /// Rust type of value - type Value: ProtobufValue + Clone + 'static; - - /// Wire type when writing to stream - fn wire_type() -> WireType; - - /// Read value from `CodedInputStream` - fn read(is: &mut CodedInputStream) -> ProtobufResult<Self::Value>; - - /// Compute wire size - fn compute_size(value: &Self::Value) -> u32; - - /// Get value from `UnknownValues` - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<Self::Value>; - - /// Compute size adding length prefix if wire type is length delimited - /// (i. e. string, bytes, message) - fn compute_size_with_length_delimiter(value: &Self::Value) -> u32 { - let size = Self::compute_size(value); - if Self::wire_type() == WireType::WireTypeLengthDelimited { - rt::compute_raw_varint32_size(size) + size - } else { - size - } - } - - /// Get previously computed size - #[inline] - fn get_cached_size(value: &Self::Value) -> u32 { - Self::compute_size(value) - } - - /// Get previously cached size with length prefix - #[inline] - fn get_cached_size_with_length_delimiter(value: &Self::Value) -> u32 { - let size = Self::get_cached_size(value); - if Self::wire_type() == WireType::WireTypeLengthDelimited { - rt::compute_raw_varint32_size(size) + size - } else { - size - } - } - - /// Write a value with previously cached size - fn write_with_cached_size( - field_number: u32, - value: &Self::Value, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()>; -} - -/// `float` -pub struct ProtobufTypeFloat; -/// `double` -pub struct ProtobufTypeDouble; -/// `uint32` -pub struct ProtobufTypeInt32; -/// `int64` -pub struct ProtobufTypeInt64; -/// `uint32` -pub struct ProtobufTypeUint32; -/// `uint64` -pub struct ProtobufTypeUint64; -/// `sint32` -pub struct ProtobufTypeSint32; -/// `sint64` -pub struct ProtobufTypeSint64; -/// `fixed32` -pub struct ProtobufTypeFixed32; -/// `fixed64` -pub struct ProtobufTypeFixed64; -/// `sfixed32` -pub struct ProtobufTypeSfixed32; -/// `sfixed64` -pub struct ProtobufTypeSfixed64; -/// `bool` -pub struct ProtobufTypeBool; -/// `string` -pub struct ProtobufTypeString; -/// `bytes` -pub struct ProtobufTypeBytes; -/// Something which should be deleted -pub struct ProtobufTypeChars; - -/// `bytes` as [`Bytes`](bytes::Bytes) -#[cfg(feature = "bytes")] -pub struct ProtobufTypeCarllercheBytes; -/// `string` as [`Chars`](crate::Chars) -#[cfg(feature = "bytes")] -pub struct ProtobufTypeCarllercheChars; - -/// `enum` -pub struct ProtobufTypeEnum<E: ProtobufEnum>(marker::PhantomData<E>); -/// `message` -pub struct ProtobufTypeMessage<M: Message>(marker::PhantomData<M>); - -impl ProtobufType for ProtobufTypeFloat { - type Value = f32; - - fn wire_type() -> WireType { - WireType::WireTypeFixed32 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<f32> { - is.read_float() - } - - fn compute_size(_value: &f32) -> u32 { - 4 - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<f32> { - unknown_values - .fixed32 - .iter() - .rev() - .next() - .map(|&bits| unsafe { mem::transmute::<u32, f32>(bits) }) - } - - fn write_with_cached_size( - field_number: u32, - value: &f32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_float(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeDouble { - type Value = f64; - - fn wire_type() -> WireType { - WireType::WireTypeFixed64 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<f64> { - is.read_double() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<f64> { - unknown_values - .fixed64 - .iter() - .rev() - .next() - .map(|&bits| unsafe { mem::transmute::<u64, f64>(bits) }) - } - - fn compute_size(_value: &f64) -> u32 { - 8 - } - - fn write_with_cached_size( - field_number: u32, - value: &f64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_double(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeInt32 { - type Value = i32; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i32> { - is.read_int32() - } - - fn compute_size(value: &i32) -> u32 { - // See also: https://github.com/protocolbuffers/protobuf/blob/bd00671b924310c0353a730bf8fa77c44e0a9c72/src/google/protobuf/io/coded_stream.h#L1300-L1306 - if *value < 0 { - return 10; - } - rt::compute_raw_varint32_size(*value as u32) - } - - fn write_with_cached_size( - field_number: u32, - value: &i32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_int32(field_number, *value) - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i32> { - unknown_values.varint.iter().rev().next().map(|&v| v as i32) - } -} - -impl ProtobufType for ProtobufTypeInt64 { - type Value = i64; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i64> { - is.read_int64() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i64> { - unknown_values.varint.iter().rev().next().map(|&v| v as i64) - } - - fn compute_size(value: &i64) -> u32 { - rt::compute_raw_varint64_size(*value as u64) - } - - fn write_with_cached_size( - field_number: u32, - value: &i64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_int64(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeUint32 { - type Value = u32; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<u32> { - is.read_uint32() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<u32> { - unknown_values.varint.iter().rev().next().map(|&v| v as u32) - } - - fn compute_size(value: &u32) -> u32 { - rt::compute_raw_varint32_size(*value) - } - - fn write_with_cached_size( - field_number: u32, - value: &u32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_uint32(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeUint64 { - type Value = u64; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<u64> { - is.read_uint64() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<u64> { - unknown_values.varint.iter().cloned().rev().next() - } - - fn compute_size(value: &u64) -> u32 { - rt::compute_raw_varint64_size(*value) - } - - fn write_with_cached_size( - field_number: u32, - value: &u64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_uint64(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeSint32 { - type Value = i32; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i32> { - is.read_sint32() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i32> { - ProtobufTypeUint32::get_from_unknown(unknown_values).map(decode_zig_zag_32) - } - - fn compute_size(value: &i32) -> u32 { - rt::value_varint_zigzag_size_no_tag(*value) - } - - fn write_with_cached_size( - field_number: u32, - value: &i32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_sint32(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeSint64 { - type Value = i64; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i64> { - is.read_sint64() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i64> { - ProtobufTypeUint64::get_from_unknown(unknown_values).map(decode_zig_zag_64) - } - - fn compute_size(value: &i64) -> u32 { - rt::value_varint_zigzag_size_no_tag(*value) - } - - fn write_with_cached_size( - field_number: u32, - value: &i64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_sint64(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeFixed32 { - type Value = u32; - - fn wire_type() -> WireType { - WireType::WireTypeFixed32 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<u32> { - is.read_fixed32() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<u32> { - unknown_values.fixed32.iter().cloned().rev().next() - } - - fn compute_size(_value: &u32) -> u32 { - 4 - } - - fn write_with_cached_size( - field_number: u32, - value: &u32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_fixed32(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeFixed64 { - type Value = u64; - - fn wire_type() -> WireType { - WireType::WireTypeFixed64 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<u64> { - is.read_fixed64() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<u64> { - unknown_values.fixed64.iter().cloned().rev().next() - } - - fn compute_size(_value: &u64) -> u32 { - 8 - } - - fn write_with_cached_size( - field_number: u32, - value: &u64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_fixed64(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeSfixed32 { - type Value = i32; - - fn wire_type() -> WireType { - WireType::WireTypeFixed32 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i32> { - is.read_sfixed32() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i32> { - ProtobufTypeFixed32::get_from_unknown(unknown_values).map(|u| u as i32) - } - - fn compute_size(_value: &i32) -> u32 { - 4 - } - - fn write_with_cached_size( - field_number: u32, - value: &i32, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_sfixed32(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeSfixed64 { - type Value = i64; - - fn wire_type() -> WireType { - WireType::WireTypeFixed64 - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<i64> { - is.read_sfixed64() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<i64> { - ProtobufTypeFixed64::get_from_unknown(unknown_values).map(|u| u as i64) - } - - fn compute_size(_value: &i64) -> u32 { - 8 - } - - fn write_with_cached_size( - field_number: u32, - value: &i64, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_sfixed64(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeBool { - type Value = bool; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<bool> { - is.read_bool() - } - - fn get_from_unknown(unknown: &UnknownValues) -> Option<bool> { - unknown.varint.iter().rev().next().map(|&v| v != 0) - } - - fn compute_size(_value: &bool) -> u32 { - 1 - } - - fn write_with_cached_size( - field_number: u32, - value: &bool, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_bool(field_number, *value) - } -} - -impl ProtobufType for ProtobufTypeString { - type Value = String; - - fn wire_type() -> WireType { - WireType::WireTypeLengthDelimited - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<String> { - is.read_string() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<String> { - // TODO: should not panic - ProtobufTypeBytes::get_from_unknown(unknown_values) - .map(|b| String::from_utf8(b).expect("not a valid string")) - } - - fn compute_size(value: &String) -> u32 { - value.len() as u32 - } - - fn write_with_cached_size( - field_number: u32, - value: &String, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_string(field_number, &value) - } -} - -impl ProtobufType for ProtobufTypeBytes { - type Value = Vec<u8>; - - fn wire_type() -> WireType { - WireType::WireTypeLengthDelimited - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<Vec<u8>> { - is.read_bytes() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<Vec<u8>> { - unknown_values.length_delimited.iter().cloned().rev().next() - } - - fn compute_size(value: &Vec<u8>) -> u32 { - value.len() as u32 - } - - fn write_with_cached_size( - field_number: u32, - value: &Vec<u8>, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_bytes(field_number, &value) - } -} - -#[cfg(feature = "bytes")] -impl ProtobufType for ProtobufTypeCarllercheBytes { - type Value = Bytes; - - fn wire_type() -> WireType { - ProtobufTypeBytes::wire_type() - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<Self::Value> { - is.read_carllerche_bytes() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<Bytes> { - ProtobufTypeBytes::get_from_unknown(unknown_values).map(Bytes::from) - } - - fn compute_size(value: &Bytes) -> u32 { - value.len() as u32 - } - - fn write_with_cached_size( - field_number: u32, - value: &Bytes, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_bytes(field_number, &value) - } -} - -#[cfg(feature = "bytes")] -impl ProtobufType for ProtobufTypeCarllercheChars { - type Value = Chars; - - fn wire_type() -> WireType { - ProtobufTypeBytes::wire_type() - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<Self::Value> { - is.read_carllerche_chars() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<Chars> { - ProtobufTypeString::get_from_unknown(unknown_values).map(Chars::from) - } - - fn compute_size(value: &Chars) -> u32 { - value.len() as u32 - } - - fn write_with_cached_size( - field_number: u32, - value: &Chars, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_string(field_number, &value) - } -} - -impl<E: ProtobufEnum + ProtobufValue> ProtobufType for ProtobufTypeEnum<E> { - type Value = E; - - fn wire_type() -> WireType { - WireType::WireTypeVarint - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<E> { - is.read_enum() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<E> { - // TODO: do not panic - ProtobufTypeInt32::get_from_unknown(unknown_values) - .map(|i| E::from_i32(i).expect("not a valid enum value")) - } - - fn compute_size(value: &E) -> u32 { - rt::compute_raw_varint32_size(value.value() as u32) // TODO: wrap - } - - fn write_with_cached_size( - field_number: u32, - value: &E, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_enum_obj(field_number, *value) - } -} - -impl<M: Message + Clone + ProtobufValue> ProtobufType for ProtobufTypeMessage<M> { - type Value = M; - - fn wire_type() -> WireType { - WireType::WireTypeLengthDelimited - } - - fn read(is: &mut CodedInputStream) -> ProtobufResult<M> { - is.read_message() - } - - fn get_from_unknown(unknown_values: &UnknownValues) -> Option<M> { - // TODO: do not panic - unknown_values - .length_delimited - .iter() - .rev() - .next() - .map(|bytes| M::parse_from_bytes(bytes).expect("cannot parse message")) - } - - fn compute_size(value: &M) -> u32 { - value.compute_size() - } - - fn get_cached_size(value: &M) -> u32 { - value.get_cached_size() - } - - fn write_with_cached_size( - field_number: u32, - value: &Self::Value, - os: &mut CodedOutputStream, - ) -> ProtobufResult<()> { - os.write_tag(field_number, WireType::WireTypeLengthDelimited)?; - os.write_raw_varint32(value.get_cached_size())?; - value.write_to_with_cached_sizes(os)?; - Ok(()) - } -} diff --git a/src/unknown.rs b/src/unknown.rs index dd67033..c54b20c 100644 --- a/src/unknown.rs +++ b/src/unknown.rs @@ -7,10 +7,12 @@ use std::hash::Hash; use std::hash::Hasher; use std::slice; -use crate::clear::Clear; -use crate::wire_format; +use crate::reflect::ReflectValueRef; +use crate::rt; +use crate::wire_format::WireType; use crate::zigzag::encode_zig_zag_32; use crate::zigzag::encode_zig_zag_64; +use crate::CodedOutputStream; /// Unknown value. /// @@ -29,7 +31,7 @@ pub enum UnknownValue { impl UnknownValue { /// Wire type for this unknown - pub fn wire_type(&self) -> wire_format::WireType { + pub fn wire_type(&self) -> WireType { self.get_ref().wire_type() } @@ -43,6 +45,16 @@ impl UnknownValue { } } + /// Construct unknown value from `int64` value. + pub fn int32(i: i32) -> UnknownValue { + UnknownValue::int64(i as i64) + } + + /// Construct unknown value from `int64` value. + pub fn int64(i: i64) -> UnknownValue { + UnknownValue::Varint(i as u64) + } + /// Construct unknown value from `sint32` value. pub fn sint32(i: i32) -> UnknownValue { UnknownValue::Varint(encode_zig_zag_32(i) as u64) @@ -52,11 +64,32 @@ impl UnknownValue { pub fn sint64(i: i64) -> UnknownValue { UnknownValue::Varint(encode_zig_zag_64(i)) } + + /// Construct unknown value from `float` value. + pub fn float(f: f32) -> UnknownValue { + UnknownValue::Fixed32(f.to_bits()) + } + + /// Construct unknown value from `double` value. + pub fn double(f: f64) -> UnknownValue { + UnknownValue::Fixed64(f.to_bits()) + } + + /// Construct unknown value from `sfixed32` value. + pub fn sfixed32(i: i32) -> UnknownValue { + UnknownValue::Fixed32(i as u32) + } + + /// Construct unknown value from `sfixed64` value. + pub fn sfixed64(i: i64) -> UnknownValue { + UnknownValue::Fixed64(i as u64) + } } /// Reference to unknown value. /// /// See [`UnknownFields`](crate::UnknownFields) for explanations. +#[derive(Debug, PartialEq)] pub enum UnknownValueRef<'o> { /// 32-bit unknown Fixed32(u32), @@ -70,12 +103,21 @@ pub enum UnknownValueRef<'o> { impl<'o> UnknownValueRef<'o> { /// Wire-type to serialize this unknown - pub fn wire_type(&self) -> wire_format::WireType { + pub fn wire_type(&self) -> WireType { match *self { - UnknownValueRef::Fixed32(_) => wire_format::WireTypeFixed32, - UnknownValueRef::Fixed64(_) => wire_format::WireTypeFixed64, - UnknownValueRef::Varint(_) => wire_format::WireTypeVarint, - UnknownValueRef::LengthDelimited(_) => wire_format::WireTypeLengthDelimited, + UnknownValueRef::Fixed32(_) => WireType::Fixed32, + UnknownValueRef::Fixed64(_) => WireType::Fixed64, + UnknownValueRef::Varint(_) => WireType::Varint, + UnknownValueRef::LengthDelimited(_) => WireType::LengthDelimited, + } + } + + pub(crate) fn to_reflect_value_ref(&'o self) -> ReflectValueRef<'o> { + match self { + UnknownValueRef::Fixed32(v) => ReflectValueRef::U32(*v), + UnknownValueRef::Fixed64(v) => ReflectValueRef::U64(*v), + UnknownValueRef::Varint(v) => ReflectValueRef::U64(*v), + UnknownValueRef::LengthDelimited(v) => ReflectValueRef::Bytes(v), } } } @@ -84,15 +126,15 @@ impl<'o> UnknownValueRef<'o> { /// /// See [`UnknownFields`](crate::UnknownFields) for explanations. #[derive(Clone, PartialEq, Eq, Debug, Default, Hash)] -pub struct UnknownValues { +pub(crate) struct UnknownValues { /// 32-bit unknowns - pub fixed32: Vec<u32>, + pub(crate) fixed32: Vec<u32>, /// 64-bit unknowns - pub fixed64: Vec<u64>, + pub(crate) fixed64: Vec<u64>, /// Varint unknowns - pub varint: Vec<u64>, + pub(crate) varint: Vec<u64>, /// Length-delimited unknowns - pub length_delimited: Vec<Vec<u8>>, + pub(crate) length_delimited: Vec<Vec<u8>>, } impl UnknownValues { @@ -117,6 +159,20 @@ impl UnknownValues { length_delimited: self.length_delimited.iter(), } } + + pub(crate) fn any(&self) -> Option<UnknownValueRef> { + if let Some(last) = self.fixed32.last() { + Some(UnknownValueRef::Fixed32(*last)) + } else if let Some(last) = self.fixed64.last() { + Some(UnknownValueRef::Fixed64(*last)) + } else if let Some(last) = self.varint.last() { + Some(UnknownValueRef::Varint(*last)) + } else if let Some(last) = self.length_delimited.last() { + Some(UnknownValueRef::LengthDelimited(last)) + } else { + None + } + } } impl<'a> IntoIterator for &'a UnknownValues { @@ -129,7 +185,7 @@ impl<'a> IntoIterator for &'a UnknownValues { } /// Iterator over unknown values -pub struct UnknownValuesIter<'o> { +pub(crate) struct UnknownValuesIter<'o> { fixed32: slice::Iter<'o, u32>, fixed64: slice::Iter<'o, u64>, varint: slice::Iter<'o, u64>, @@ -140,21 +196,17 @@ impl<'o> Iterator for UnknownValuesIter<'o> { type Item = UnknownValueRef<'o>; fn next(&mut self) -> Option<UnknownValueRef<'o>> { - let fixed32 = self.fixed32.next(); - if fixed32.is_some() { - return Some(UnknownValueRef::Fixed32(*fixed32.unwrap())); + if let Some(fixed32) = self.fixed32.next() { + return Some(UnknownValueRef::Fixed32(*fixed32)); } - let fixed64 = self.fixed64.next(); - if fixed64.is_some() { - return Some(UnknownValueRef::Fixed64(*fixed64.unwrap())); + if let Some(fixed64) = self.fixed64.next() { + return Some(UnknownValueRef::Fixed64(*fixed64)); } - let varint = self.varint.next(); - if varint.is_some() { - return Some(UnknownValueRef::Varint(*varint.unwrap())); + if let Some(varint) = self.varint.next() { + return Some(UnknownValueRef::Varint(*varint)); } - let length_delimited = self.length_delimited.next(); - if length_delimited.is_some() { - return Some(UnknownValueRef::LengthDelimited(&length_delimited.unwrap())); + if let Some(length_delimited) = self.length_delimited.next() { + return Some(UnknownValueRef::LengthDelimited(&length_delimited)); } None } @@ -182,8 +234,7 @@ pub struct UnknownFields { // Note, Google Protobuf C++ simply uses linear map (which can exploitable the same way), // and Google Protobuf Java uses tree map to store unknown fields // (which is more expensive than hashmap). - // TODO: hide - pub fields: Option<Box<HashMap<u32, UnknownValues, BuildHasherDefault<DefaultHasher>>>>, + fields: Option<Box<HashMap<u32, UnknownValues, BuildHasherDefault<DefaultHasher>>>>, } /// Very simple hash implementation of `Hash` for `UnknownFields`. @@ -207,9 +258,16 @@ impl Hash for UnknownFields { } impl UnknownFields { - /// Empty unknown fields - pub fn new() -> UnknownFields { - Default::default() + /// Empty unknown fields. + pub const fn new() -> UnknownFields { + UnknownFields { fields: None } + } + + /// Clear all unknown fields. + pub fn clear(&mut self) { + if let Some(ref mut fields) = self.fields { + fields.clear(); + } } fn init_map(&mut self) { @@ -264,29 +322,35 @@ impl UnknownFields { /// Iterate over all unknowns pub fn iter<'s>(&'s self) -> UnknownFieldsIter<'s> { UnknownFieldsIter { - entries: self.fields.as_ref().map(|m| m.iter()), + entries: self.fields.as_ref().map(|m| UnknownFieldsNotEmptyIter { + fields: m.iter(), + current: None, + }), } } - /// Find unknown field by number - pub fn get(&self, field_number: u32) -> Option<&UnknownValues> { - match self.fields { - Some(ref map) => map.get(&field_number), + /// Get any value for unknown fields. + pub fn get(&self, field_number: u32) -> Option<UnknownValueRef> { + match &self.fields { + Some(map) => map.get(&field_number).and_then(|v| v.any()), None => None, } } -} -impl Clear for UnknownFields { - fn clear(&mut self) { - if let Some(ref mut fields) = self.fields { - fields.clear(); - } + #[doc(hidden)] + pub fn write_to_bytes(&self) -> Vec<u8> { + let mut r = Vec::with_capacity(rt::unknown_fields_size(self) as usize); + let mut stream = CodedOutputStream::vec(&mut r); + // Do we need it stable everywhere? + stream.write_unknown_fields_sorted(self).unwrap(); + stream.flush().unwrap(); + drop(stream); + r } } impl<'a> IntoIterator for &'a UnknownFields { - type Item = (u32, &'a UnknownValues); + type Item = (u32, UnknownValueRef<'a>); type IntoIter = UnknownFieldsIter<'a>; fn into_iter(self) -> UnknownFieldsIter<'a> { @@ -294,22 +358,40 @@ impl<'a> IntoIterator for &'a UnknownFields { } } +struct UnknownFieldsNotEmptyIter<'s> { + fields: hash_map::Iter<'s, u32, UnknownValues>, + current: Option<(u32, UnknownValuesIter<'s>)>, +} + /// Iterator over [`UnknownFields`](crate::UnknownFields) pub struct UnknownFieldsIter<'s> { - entries: Option<hash_map::Iter<'s, u32, UnknownValues>>, + entries: Option<UnknownFieldsNotEmptyIter<'s>>, } -impl<'s> Iterator for UnknownFieldsIter<'s> { - type Item = (u32, &'s UnknownValues); +impl<'s> Iterator for UnknownFieldsNotEmptyIter<'s> { + type Item = (u32, UnknownValueRef<'s>); - fn next(&mut self) -> Option<(u32, &'s UnknownValues)> { - match self.entries { - Some(ref mut entries) => entries.next().map(|(&number, values)| (number, values)), - None => None, + fn next(&mut self) -> Option<(u32, UnknownValueRef<'s>)> { + loop { + if let Some((field_number, values)) = &mut self.current { + if let Some(value) = values.next() { + return Some((*field_number, value)); + } + } + let (field_number, values) = self.fields.next()?; + self.current = Some((*field_number, values.iter())); } } } +impl<'s> Iterator for UnknownFieldsIter<'s> { + type Item = (u32, UnknownValueRef<'s>); + + fn next(&mut self) -> Option<(u32, UnknownValueRef<'s>)> { + self.entries.as_mut().and_then(|entries| entries.next()) + } +} + #[cfg(test)] mod test { use std::collections::hash_map::DefaultHasher; diff --git a/src/varint.rs b/src/varint.rs deleted file mode 100644 index 8e542bc..0000000 --- a/src/varint.rs +++ /dev/null @@ -1,39 +0,0 @@ -use std::mem::MaybeUninit; - -use crate::misc::maybe_uninit_write; - -/// Encode u64 as varint. -/// Panics if buffer length is less than 10. -#[inline] -pub fn encode_varint64(mut value: u64, buf: &mut [MaybeUninit<u8>]) -> usize { - assert!(buf.len() >= 10); - - unsafe { - let mut i = 0; - while (value & !0x7F) > 0 { - maybe_uninit_write(buf.get_unchecked_mut(i), ((value & 0x7F) | 0x80) as u8); - value >>= 7; - i += 1; - } - maybe_uninit_write(buf.get_unchecked_mut(i), value as u8); - i + 1 - } -} - -/// Encode u32 value as varint. -/// Panics if buffer length is less than 5. -#[inline] -pub fn encode_varint32(mut value: u32, buf: &mut [MaybeUninit<u8>]) -> usize { - assert!(buf.len() >= 5); - - unsafe { - let mut i = 0; - while (value & !0x7F) > 0 { - maybe_uninit_write(buf.get_unchecked_mut(i), ((value & 0x7F) | 0x80) as u8); - value >>= 7; - i += 1; - } - maybe_uninit_write(buf.get_unchecked_mut(i), value as u8); - i + 1 - } -} diff --git a/src/varint/decode.rs b/src/varint/decode.rs new file mode 100644 index 0000000..7145343 --- /dev/null +++ b/src/varint/decode.rs @@ -0,0 +1,113 @@ +//! Varint decode utilities. + +use crate::error::WireError; +use crate::varint::MAX_VARINT32_ENCODED_LEN; +use crate::varint::MAX_VARINT_ENCODED_LEN; + +trait DecodeVarint { + const MAX_ENCODED_LEN: usize; + const LAST_BYTE_MAX_VALUE: u8; + + fn from_u64(value: u64) -> Self; +} + +impl DecodeVarint for u64 { + const MAX_ENCODED_LEN: usize = MAX_VARINT_ENCODED_LEN; + const LAST_BYTE_MAX_VALUE: u8 = 0x01; + + fn from_u64(value: u64) -> Self { + value + } +} + +impl DecodeVarint for u32 { + const MAX_ENCODED_LEN: usize = MAX_VARINT32_ENCODED_LEN; + const LAST_BYTE_MAX_VALUE: u8 = 0x0f; + + fn from_u64(value: u64) -> Self { + value as u32 + } +} + +/// Decode a varint, and return decoded value and decoded byte count. +#[inline] +fn decode_varint_full<D: DecodeVarint>(rem: &[u8]) -> crate::Result<Option<(D, usize)>> { + let mut r: u64 = 0; + for (i, &b) in rem.iter().enumerate() { + if i == D::MAX_ENCODED_LEN - 1 { + if b > D::LAST_BYTE_MAX_VALUE { + return Err(WireError::IncorrectVarint.into()); + } + let r = r | ((b as u64) << (i as u64 * 7)); + return Ok(Some((D::from_u64(r), i + 1))); + } + + r = r | (((b & 0x7f) as u64) << (i as u64 * 7)); + if b < 0x80 { + return Ok(Some((D::from_u64(r), i + 1))); + } + } + Ok(None) +} + +#[inline] +fn decode_varint_impl<D: DecodeVarint>(buf: &[u8]) -> crate::Result<Option<(D, usize)>> { + if buf.len() >= 1 && buf[0] < 0x80 { + // The the most common case. + let ret = buf[0] as u64; + let consume = 1; + Ok(Some((D::from_u64(ret), consume))) + } else if buf.len() >= 2 && buf[1] < 0x80 { + // Handle the case of two bytes too. + let ret = (buf[0] & 0x7f) as u64 | (buf[1] as u64) << 7; + let consume = 2; + Ok(Some((D::from_u64(ret), consume))) + } else { + // Read from array when buf at at least 10 bytes, + // max len for varint. + decode_varint_full(buf) + } +} + +/// Try decode a varint. Return `None` if the buffer does not contain complete varint. +#[inline] +pub(crate) fn decode_varint64(buf: &[u8]) -> crate::Result<Option<(u64, usize)>> { + decode_varint_impl(buf) +} + +/// Try decode a varint. Return `None` if the buffer does not contain complete varint. +#[inline] +pub(crate) fn decode_varint32(buf: &[u8]) -> crate::Result<Option<(u32, usize)>> { + decode_varint_impl(buf) +} + +#[cfg(test)] +mod tests { + use crate::hex::decode_hex; + use crate::varint::decode::decode_varint32; + use crate::varint::decode::decode_varint64; + + #[test] + fn test_decode_varint64() { + assert_eq!((0, 1), decode_varint64(&decode_hex("00")).unwrap().unwrap()); + assert_eq!( + (u64::MAX, 10), + decode_varint64(&decode_hex("ff ff ff ff ff ff ff ff ff 01")) + .unwrap() + .unwrap() + ); + assert!(decode_varint64(&decode_hex("ff ff ff ff ff ff ff ff ff 02")).is_err()); + } + + #[test] + fn test_decode_varint32() { + assert_eq!((0, 1), decode_varint32(&decode_hex("00")).unwrap().unwrap()); + assert_eq!( + (u32::MAX, 5), + decode_varint32(&decode_hex("ff ff ff ff 0f")) + .unwrap() + .unwrap() + ); + assert!(decode_varint32(&decode_hex("ff ff ff ff 10")).is_err()); + } +} diff --git a/src/varint/encode.rs b/src/varint/encode.rs new file mode 100644 index 0000000..eb9fc2d --- /dev/null +++ b/src/varint/encode.rs @@ -0,0 +1,148 @@ +use std::mem::MaybeUninit; + +use crate::varint::MAX_VARINT_ENCODED_LEN; + +/// Encode u64 as varint. +/// Panics if buffer length is less than 10. +#[inline] +pub(crate) fn encode_varint64(mut value: u64, buf: &mut [MaybeUninit<u8>]) -> usize { + assert!(buf.len() >= MAX_VARINT_ENCODED_LEN); + + fn iter(value: &mut u64, byte: &mut MaybeUninit<u8>) -> bool { + if (*value & !0x7F) > 0 { + byte.write(((*value & 0x7F) | 0x80) as u8); + *value >>= 7; + true + } else { + byte.write(*value as u8); + false + } + } + + // Explicitly unroll loop to avoid either + // unsafe code or bound checking when writing to `buf` + + if !iter(&mut value, &mut buf[0]) { + return 1; + }; + if !iter(&mut value, &mut buf[1]) { + return 2; + }; + if !iter(&mut value, &mut buf[2]) { + return 3; + }; + if !iter(&mut value, &mut buf[3]) { + return 4; + }; + if !iter(&mut value, &mut buf[4]) { + return 5; + }; + if !iter(&mut value, &mut buf[5]) { + return 6; + }; + if !iter(&mut value, &mut buf[6]) { + return 7; + }; + if !iter(&mut value, &mut buf[7]) { + return 8; + }; + if !iter(&mut value, &mut buf[8]) { + return 9; + }; + buf[9].write(value as u8); + 10 +} + +/// Encode u32 value as varint. +/// Panics if buffer length is less than 5. +#[inline] +pub(crate) fn encode_varint32(mut value: u32, buf: &mut [MaybeUninit<u8>]) -> usize { + assert!(buf.len() >= 5); + + fn iter(value: &mut u32, byte: &mut MaybeUninit<u8>) -> bool { + if (*value & !0x7F) > 0 { + byte.write(((*value & 0x7F) | 0x80) as u8); + *value >>= 7; + true + } else { + byte.write(*value as u8); + false + } + } + + // Explicitly unroll loop to avoid either + // unsafe code or bound checking when writing to `buf` + + if !iter(&mut value, &mut buf[0]) { + return 1; + }; + if !iter(&mut value, &mut buf[1]) { + return 2; + }; + if !iter(&mut value, &mut buf[2]) { + return 3; + }; + if !iter(&mut value, &mut buf[3]) { + return 4; + }; + buf[4].write(value as u8); + 5 +} + +/// Encoded size of u64 value. +#[inline] +pub(crate) fn encoded_varint64_len(value: u64) -> usize { + if value == 0 { + 1 + } else { + let significant_bits = 64 - value.leading_zeros(); + (significant_bits + 6) as usize / 7 + } +} + +#[cfg(test)] +mod test { + use std::mem::MaybeUninit; + + use crate::varint::encode::encode_varint64; + use crate::varint::encode::encoded_varint64_len; + + #[test] + fn test_encoded_varint64_len() { + fn test(n: u64) { + let mut buf = [MaybeUninit::uninit(); 10]; + let expected = encode_varint64(n, &mut buf); + assert_eq!(expected, encoded_varint64_len(n), "n={}", n); + } + + for n in 0..1000 { + test(n); + } + + for p in 0.. { + match 2u64.checked_pow(p) { + Some(n) => test(n), + None => break, + } + } + + for p in 0.. { + match 3u64.checked_pow(p) { + Some(n) => test(n), + None => break, + } + } + + test(u64::MAX); + test(u64::MAX - 1); + test((i64::MAX as u64) + 1); + test(i64::MAX as u64); + test((i64::MAX as u64) - 1); + test((u32::MAX as u64) + 1); + test(u32::MAX as u64); + test((u32::MAX as u64) - 1); + test((i32::MAX as u64) + 1); + test(i32::MAX as u64); + test((i32::MAX as u64) - 1); + } +} diff --git a/src/varint/generic.rs b/src/varint/generic.rs new file mode 100644 index 0000000..4fc8ba2 --- /dev/null +++ b/src/varint/generic.rs @@ -0,0 +1,39 @@ +use crate::rt::compute_raw_varint64_size; + +/// Helper trait implemented by integer types which could be encoded as varint. +pub(crate) trait ProtobufVarint { + /// Size of self when encoded as varint. + fn len_varint(&self) -> u64; +} + +impl ProtobufVarint for u64 { + fn len_varint(&self) -> u64 { + compute_raw_varint64_size(*self) + } +} + +impl ProtobufVarint for u32 { + fn len_varint(&self) -> u64 { + (*self as u64).len_varint() + } +} + +impl ProtobufVarint for i64 { + fn len_varint(&self) -> u64 { + // same as length of u64 + (*self as u64).len_varint() + } +} + +impl ProtobufVarint for i32 { + fn len_varint(&self) -> u64 { + // sign-extend and then compute + (*self as i64).len_varint() + } +} + +impl ProtobufVarint for bool { + fn len_varint(&self) -> u64 { + 1 + } +} diff --git a/src/varint/mod.rs b/src/varint/mod.rs new file mode 100644 index 0000000..d693975 --- /dev/null +++ b/src/varint/mod.rs @@ -0,0 +1,7 @@ +pub(crate) mod decode; +pub(crate) mod encode; +pub(crate) mod generic; + +/// Encoded varint message is not longer than 10 bytes. +pub(crate) const MAX_VARINT_ENCODED_LEN: usize = 10; +pub(crate) const MAX_VARINT32_ENCODED_LEN: usize = 5; diff --git a/src/well_known_types/any.rs b/src/well_known_types/any.rs index e46065f..6b8d343 100644 --- a/src/well_known_types/any.rs +++ b/src/well_known_types/any.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,21 +16,51 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/any.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Any) pub struct Any { // message fields + /// 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. + /// + /// Schemes other than `http`, `https` (or the empty scheme) might be + /// used with implementation specific semantics. + /// + // @@protoc_insertion_point(field:google.protobuf.Any.type_url) pub type_url: ::std::string::String, + /// Must be a valid serialized protocol buffer of the above specified type. + // @@protoc_insertion_point(field:google.protobuf.Any.value) pub value: ::std::vec::Vec<u8>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Any.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Any { @@ -43,76 +74,45 @@ impl Any { ::std::default::Default::default() } - // string type_url = 1; - - - pub fn get_type_url(&self) -> &str { - &self.type_url - } - pub fn clear_type_url(&mut self) { - self.type_url.clear(); - } - - // Param is passed by value, moved - pub fn set_type_url(&mut self, v: ::std::string::String) { - self.type_url = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_type_url(&mut self) -> &mut ::std::string::String { - &mut self.type_url - } - - // Take field - pub fn take_type_url(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.type_url, ::std::string::String::new()) - } - - // bytes value = 2; - - - pub fn get_value(&self) -> &[u8] { - &self.value - } - pub fn clear_value(&mut self) { - self.value.clear(); - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: ::std::vec::Vec<u8>) { - self.value = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_value(&mut self) -> &mut ::std::vec::Vec<u8> { - &mut self.value - } - - // Take field - pub fn take_value(&mut self) -> ::std::vec::Vec<u8> { - ::std::mem::replace(&mut self.value, ::std::vec::Vec::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "type_url", + |m: &Any| { &m.type_url }, + |m: &mut Any| { &mut m.type_url }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &Any| { &m.value }, + |m: &mut Any| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Any>( + "Any", + fields, + oneofs, + ) } } impl crate::Message for Any { + const NAME: &'static str = "Any"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.type_url)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.type_url = is.read_string()?; }, - 2 => { - crate::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.value)?; + 18 => { + self.value = is.read_bytes()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -121,7 +121,7 @@ impl crate::Message for Any { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.type_url.is_empty() { my_size += crate::rt::string_size(1, &self.type_url); @@ -129,98 +129,65 @@ impl crate::Message for Any { if !self.value.is_empty() { my_size += crate::rt::bytes_size(2, &self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.type_url.is_empty() { os.write_string(1, &self.type_url)?; } if !self.value.is_empty() { os.write_bytes(2, &self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Any { Any::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "type_url", - |m: &Any| { &m.type_url }, - |m: &mut Any| { &mut m.type_url }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBytes>( - "value", - |m: &Any| { &m.value }, - |m: &mut Any| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Any>( - "Any", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.type_url.clear(); + self.value.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static Any { - static instance: crate::rt::LazyV2<Any> = crate::rt::LazyV2::INIT; - instance.get(Any::new) + static instance: Any = Any { + type_url: ::std::string::String::new(), + value: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Any { - fn clear(&mut self) { - self.type_url.clear(); - self.value.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for Any { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Any").unwrap()).clone() } } -impl ::std::fmt::Debug for Any { +impl ::std::fmt::Display for Any { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Any { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -361,14 +328,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x05\x04\0\x02\x01\x03\x12\x04\x9c\x01\x10\x11b\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(Any::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/api.rs b/src/well_known_types/api.rs index ef97015..afd19d3 100644 --- a/src/well_known_types/api.rs +++ b/src/well_known_types/api.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,26 +16,70 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/api.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// 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. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Api) pub struct Api { // message fields + /// The fully qualified name of this interface, including package name + /// followed by the interface's simple name. + // @@protoc_insertion_point(field:google.protobuf.Api.name) pub name: ::std::string::String, - pub methods: crate::RepeatedField<Method>, - pub options: crate::RepeatedField<crate::well_known_types::Option>, + /// The methods of this interface, in unspecified order. + // @@protoc_insertion_point(field:google.protobuf.Api.methods) + pub methods: ::std::vec::Vec<Method>, + /// Any metadata attached to the interface. + // @@protoc_insertion_point(field:google.protobuf.Api.options) + pub options: ::std::vec::Vec<crate::well_known_types::type_::Option>, + /// 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<major-version>`, 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. + /// + /// + // @@protoc_insertion_point(field:google.protobuf.Api.version) pub version: ::std::string::String, - pub source_context: crate::SingularPtrField<crate::well_known_types::SourceContext>, - pub mixins: crate::RepeatedField<Mixin>, - pub syntax: crate::well_known_types::Syntax, + /// Source context for the protocol buffer service represented by this + /// message. + // @@protoc_insertion_point(field:google.protobuf.Api.source_context) + pub source_context: crate::MessageField<crate::well_known_types::source_context::SourceContext>, + /// Included interfaces. See [Mixin][]. + // @@protoc_insertion_point(field:google.protobuf.Api.mixins) + pub mixins: ::std::vec::Vec<Mixin>, + /// The source syntax of the service. + // @@protoc_insertion_point(field:google.protobuf.Api.syntax) + pub syntax: crate::EnumOrUnknown<crate::well_known_types::type_::Syntax>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Api.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Api { @@ -48,234 +93,85 @@ impl Api { ::std::default::Default::default() } - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // repeated .google.protobuf.Method methods = 2; - - - pub fn get_methods(&self) -> &[Method] { - &self.methods - } - pub fn clear_methods(&mut self) { - self.methods.clear(); - } - - // Param is passed by value, moved - pub fn set_methods(&mut self, v: crate::RepeatedField<Method>) { - self.methods = v; - } - - // Mutable pointer to the field. - pub fn mut_methods(&mut self) -> &mut crate::RepeatedField<Method> { - &mut self.methods - } - - // Take field - pub fn take_methods(&mut self) -> crate::RepeatedField<Method> { - ::std::mem::replace(&mut self.methods, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.Option options = 3; - - - pub fn get_options(&self) -> &[crate::well_known_types::Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<crate::well_known_types::Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<crate::well_known_types::Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<crate::well_known_types::Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } - - // string version = 4; - - - pub fn get_version(&self) -> &str { - &self.version - } - pub fn clear_version(&mut self) { - self.version.clear(); - } - - // Param is passed by value, moved - pub fn set_version(&mut self, v: ::std::string::String) { - self.version = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_version(&mut self) -> &mut ::std::string::String { - &mut self.version - } - - // Take field - pub fn take_version(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.version, ::std::string::String::new()) - } - - // .google.protobuf.SourceContext source_context = 5; - - - pub fn get_source_context(&self) -> &crate::well_known_types::SourceContext { - self.source_context.as_ref().unwrap_or_else(|| <crate::well_known_types::SourceContext as crate::Message>::default_instance()) - } - pub fn clear_source_context(&mut self) { - self.source_context.clear(); - } - - pub fn has_source_context(&self) -> bool { - self.source_context.is_some() - } - - // Param is passed by value, moved - pub fn set_source_context(&mut self, v: crate::well_known_types::SourceContext) { - self.source_context = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_source_context(&mut self) -> &mut crate::well_known_types::SourceContext { - if self.source_context.is_none() { - self.source_context.set_default(); - } - self.source_context.as_mut().unwrap() - } - - // Take field - pub fn take_source_context(&mut self) -> crate::well_known_types::SourceContext { - self.source_context.take().unwrap_or_else(|| crate::well_known_types::SourceContext::new()) - } - - // repeated .google.protobuf.Mixin mixins = 6; - - - pub fn get_mixins(&self) -> &[Mixin] { - &self.mixins - } - pub fn clear_mixins(&mut self) { - self.mixins.clear(); - } - - // Param is passed by value, moved - pub fn set_mixins(&mut self, v: crate::RepeatedField<Mixin>) { - self.mixins = v; - } - - // Mutable pointer to the field. - pub fn mut_mixins(&mut self) -> &mut crate::RepeatedField<Mixin> { - &mut self.mixins - } - - // Take field - pub fn take_mixins(&mut self) -> crate::RepeatedField<Mixin> { - ::std::mem::replace(&mut self.mixins, crate::RepeatedField::new()) - } - - // .google.protobuf.Syntax syntax = 7; - - - pub fn get_syntax(&self) -> crate::well_known_types::Syntax { - self.syntax - } - pub fn clear_syntax(&mut self) { - self.syntax = crate::well_known_types::Syntax::SYNTAX_PROTO2; - } - - // Param is passed by value, moved - pub fn set_syntax(&mut self, v: crate::well_known_types::Syntax) { - self.syntax = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(7); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Api| { &m.name }, + |m: &mut Api| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "methods", + |m: &Api| { &m.methods }, + |m: &mut Api| { &mut m.methods }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &Api| { &m.options }, + |m: &mut Api| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "version", + |m: &Api| { &m.version }, + |m: &mut Api| { &mut m.version }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, crate::well_known_types::source_context::SourceContext>( + "source_context", + |m: &Api| { &m.source_context }, + |m: &mut Api| { &mut m.source_context }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "mixins", + |m: &Api| { &m.mixins }, + |m: &mut Api| { &mut m.mixins }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "syntax", + |m: &Api| { &m.syntax }, + |m: &mut Api| { &mut m.syntax }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Api>( + "Api", + fields, + oneofs, + ) } } impl crate::Message for Api { + const NAME: &'static str = "Api"; + fn is_initialized(&self) -> bool { - for v in &self.methods { - if !v.is_initialized() { - return false; - } - }; - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - for v in &self.source_context { - if !v.is_initialized() { - return false; - } - }; - for v in &self.mixins { - if !v.is_initialized() { - return false; - } - }; true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.methods)?; + 18 => { + self.methods.push(is.read_message()?); }, - 3 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; + 26 => { + self.options.push(is.read_message()?); }, - 4 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.version)?; + 34 => { + self.version = is.read_string()?; }, - 5 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.source_context)?; + 42 => { + crate::rt::read_singular_message_into_field(is, &mut self.source_context)?; }, - 6 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.mixins)?; + 50 => { + self.mixins.push(is.read_message()?); }, - 7 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.syntax, 7, &mut self.unknown_fields)? + 56 => { + self.syntax = is.read_enum_or_unknown()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -284,156 +180,76 @@ impl crate::Message for Api { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.name.is_empty() { my_size += crate::rt::string_size(1, &self.name); } for value in &self.methods { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; for value in &self.options { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; if !self.version.is_empty() { my_size += crate::rt::string_size(4, &self.version); } - if let Some(ref v) = self.source_context.as_ref() { + if let Some(v) = self.source_context.as_ref() { let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; } for value in &self.mixins { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if self.syntax != crate::well_known_types::Syntax::SYNTAX_PROTO2 { - my_size += crate::rt::enum_size(7, self.syntax); + if self.syntax != crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2) { + my_size += crate::rt::int32_size(7, self.syntax.value()); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.name.is_empty() { os.write_string(1, &self.name)?; } for v in &self.methods { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; }; for v in &self.options { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(3, v, os)?; }; if !self.version.is_empty() { os.write_string(4, &self.version)?; } - if let Some(ref v) = self.source_context.as_ref() { - os.write_tag(5, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + if let Some(v) = self.source_context.as_ref() { + crate::rt::write_message_field_with_cached_size(5, v, os)?; } for v in &self.mixins { - os.write_tag(6, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(6, v, os)?; }; - if self.syntax != crate::well_known_types::Syntax::SYNTAX_PROTO2 { - os.write_enum(7, crate::ProtobufEnum::value(&self.syntax))?; + if self.syntax != crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2) { + os.write_enum(7, crate::EnumOrUnknown::value(&self.syntax))?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Api { Api::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Api| { &m.name }, - |m: &mut Api| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Method>>( - "methods", - |m: &Api| { &m.methods }, - |m: &mut Api| { &mut m.methods }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::Option>>( - "options", - |m: &Api| { &m.options }, - |m: &mut Api| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "version", - |m: &Api| { &m.version }, - |m: &mut Api| { &mut m.version }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::SourceContext>>( - "source_context", - |m: &Api| { &m.source_context }, - |m: &mut Api| { &mut m.source_context }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Mixin>>( - "mixins", - |m: &Api| { &m.mixins }, - |m: &mut Api| { &mut m.mixins }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<crate::well_known_types::Syntax>>( - "syntax", - |m: &Api| { &m.syntax }, - |m: &mut Api| { &mut m.syntax }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Api>( - "Api", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Api { - static instance: crate::rt::LazyV2<Api> = crate::rt::LazyV2::INIT; - instance.get(Api::new) - } -} - -impl crate::Clear for Api { fn clear(&mut self) { self.name.clear(); self.methods.clear(); @@ -441,39 +257,71 @@ impl crate::Clear for Api { self.version.clear(); self.source_context.clear(); self.mixins.clear(); - self.syntax = crate::well_known_types::Syntax::SYNTAX_PROTO2; - self.unknown_fields.clear(); + self.syntax = crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Api { + static instance: Api = Api { + name: ::std::string::String::new(), + methods: ::std::vec::Vec::new(), + options: ::std::vec::Vec::new(), + version: ::std::string::String::new(), + source_context: crate::MessageField::none(), + mixins: ::std::vec::Vec::new(), + syntax: crate::EnumOrUnknown::from_i32(0), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Api { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Api").unwrap()).clone() } } -impl ::std::fmt::Debug for Api { +impl ::std::fmt::Display for Api { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Api { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Method represents a method of an API interface. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Method) pub struct Method { // message fields + /// The simple name of this method. + // @@protoc_insertion_point(field:google.protobuf.Method.name) pub name: ::std::string::String, + /// A URL of the input message type. + // @@protoc_insertion_point(field:google.protobuf.Method.request_type_url) pub request_type_url: ::std::string::String, + /// If true, the request is streamed. + // @@protoc_insertion_point(field:google.protobuf.Method.request_streaming) pub request_streaming: bool, + /// The URL of the output message type. + // @@protoc_insertion_point(field:google.protobuf.Method.response_type_url) pub response_type_url: ::std::string::String, + /// If true, the response is streamed. + // @@protoc_insertion_point(field:google.protobuf.Method.response_streaming) pub response_streaming: bool, - pub options: crate::RepeatedField<crate::well_known_types::Option>, - pub syntax: crate::well_known_types::Syntax, + /// Any metadata attached to the method. + // @@protoc_insertion_point(field:google.protobuf.Method.options) + pub options: ::std::vec::Vec<crate::well_known_types::type_::Option>, + /// The source syntax of this method. + // @@protoc_insertion_point(field:google.protobuf.Method.syntax) + pub syntax: crate::EnumOrUnknown<crate::well_known_types::type_::Syntax>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Method.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Method { @@ -487,200 +335,85 @@ impl Method { ::std::default::Default::default() } - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // string request_type_url = 2; - - - pub fn get_request_type_url(&self) -> &str { - &self.request_type_url - } - pub fn clear_request_type_url(&mut self) { - self.request_type_url.clear(); - } - - // Param is passed by value, moved - pub fn set_request_type_url(&mut self, v: ::std::string::String) { - self.request_type_url = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_request_type_url(&mut self) -> &mut ::std::string::String { - &mut self.request_type_url - } - - // Take field - pub fn take_request_type_url(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.request_type_url, ::std::string::String::new()) - } - - // bool request_streaming = 3; - - - pub fn get_request_streaming(&self) -> bool { - self.request_streaming - } - pub fn clear_request_streaming(&mut self) { - self.request_streaming = false; - } - - // Param is passed by value, moved - pub fn set_request_streaming(&mut self, v: bool) { - self.request_streaming = v; - } - - // string response_type_url = 4; - - - pub fn get_response_type_url(&self) -> &str { - &self.response_type_url - } - pub fn clear_response_type_url(&mut self) { - self.response_type_url.clear(); - } - - // Param is passed by value, moved - pub fn set_response_type_url(&mut self, v: ::std::string::String) { - self.response_type_url = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_response_type_url(&mut self) -> &mut ::std::string::String { - &mut self.response_type_url - } - - // Take field - pub fn take_response_type_url(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.response_type_url, ::std::string::String::new()) - } - - // bool response_streaming = 5; - - - pub fn get_response_streaming(&self) -> bool { - self.response_streaming - } - pub fn clear_response_streaming(&mut self) { - self.response_streaming = false; - } - - // Param is passed by value, moved - pub fn set_response_streaming(&mut self, v: bool) { - self.response_streaming = v; - } - - // repeated .google.protobuf.Option options = 6; - - - pub fn get_options(&self) -> &[crate::well_known_types::Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<crate::well_known_types::Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<crate::well_known_types::Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<crate::well_known_types::Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } - - // .google.protobuf.Syntax syntax = 7; - - - pub fn get_syntax(&self) -> crate::well_known_types::Syntax { - self.syntax - } - pub fn clear_syntax(&mut self) { - self.syntax = crate::well_known_types::Syntax::SYNTAX_PROTO2; - } - - // Param is passed by value, moved - pub fn set_syntax(&mut self, v: crate::well_known_types::Syntax) { - self.syntax = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(7); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Method| { &m.name }, + |m: &mut Method| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "request_type_url", + |m: &Method| { &m.request_type_url }, + |m: &mut Method| { &mut m.request_type_url }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "request_streaming", + |m: &Method| { &m.request_streaming }, + |m: &mut Method| { &mut m.request_streaming }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "response_type_url", + |m: &Method| { &m.response_type_url }, + |m: &mut Method| { &mut m.response_type_url }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "response_streaming", + |m: &Method| { &m.response_streaming }, + |m: &mut Method| { &mut m.response_streaming }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &Method| { &m.options }, + |m: &mut Method| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "syntax", + |m: &Method| { &m.syntax }, + |m: &mut Method| { &mut m.syntax }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Method>( + "Method", + fields, + oneofs, + ) } } impl crate::Message for Method { + const NAME: &'static str = "Method"; + fn is_initialized(&self) -> bool { - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; }, - 2 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.request_type_url)?; + 18 => { + self.request_type_url = is.read_string()?; }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.request_streaming = tmp; + 24 => { + self.request_streaming = is.read_bool()?; }, - 4 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.response_type_url)?; + 34 => { + self.response_type_url = is.read_string()?; }, - 5 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.response_streaming = tmp; + 40 => { + self.response_streaming = is.read_bool()?; }, - 6 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; + 50 => { + self.options.push(is.read_message()?); }, - 7 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.syntax, 7, &mut self.unknown_fields)? + 56 => { + self.syntax = is.read_enum_or_unknown()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -689,7 +422,7 @@ impl crate::Message for Method { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.name.is_empty() { my_size += crate::rt::string_size(1, &self.name); @@ -698,27 +431,27 @@ impl crate::Message for Method { my_size += crate::rt::string_size(2, &self.request_type_url); } if self.request_streaming != false { - my_size += 2; + my_size += 1 + 1; } if !self.response_type_url.is_empty() { my_size += crate::rt::string_size(4, &self.response_type_url); } if self.response_streaming != false { - my_size += 2; + my_size += 1 + 1; } for value in &self.options { let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; }; - if self.syntax != crate::well_known_types::Syntax::SYNTAX_PROTO2 { - my_size += crate::rt::enum_size(7, self.syntax); + if self.syntax != crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2) { + my_size += crate::rt::int32_size(7, self.syntax.value()); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.name.is_empty() { os.write_string(1, &self.name)?; } @@ -735,101 +468,27 @@ impl crate::Message for Method { os.write_bool(5, self.response_streaming)?; } for v in &self.options { - os.write_tag(6, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; + crate::rt::write_message_field_with_cached_size(6, v, os)?; }; - if self.syntax != crate::well_known_types::Syntax::SYNTAX_PROTO2 { - os.write_enum(7, crate::ProtobufEnum::value(&self.syntax))?; + if self.syntax != crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2) { + os.write_enum(7, crate::EnumOrUnknown::value(&self.syntax))?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Method { Method::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Method| { &m.name }, - |m: &mut Method| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "request_type_url", - |m: &Method| { &m.request_type_url }, - |m: &mut Method| { &mut m.request_type_url }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBool>( - "request_streaming", - |m: &Method| { &m.request_streaming }, - |m: &mut Method| { &mut m.request_streaming }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "response_type_url", - |m: &Method| { &m.response_type_url }, - |m: &mut Method| { &mut m.response_type_url }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBool>( - "response_streaming", - |m: &Method| { &m.response_streaming }, - |m: &mut Method| { &mut m.response_streaming }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::Option>>( - "options", - |m: &Method| { &m.options }, - |m: &mut Method| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<crate::well_known_types::Syntax>>( - "syntax", - |m: &Method| { &m.syntax }, - |m: &mut Method| { &mut m.syntax }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Method>( - "Method", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Method { - static instance: crate::rt::LazyV2<Method> = crate::rt::LazyV2::INIT; - instance.get(Method::new) - } -} - -impl crate::Clear for Method { fn clear(&mut self) { self.name.clear(); self.request_type_url.clear(); @@ -837,34 +496,56 @@ impl crate::Clear for Method { self.response_type_url.clear(); self.response_streaming = false; self.options.clear(); - self.syntax = crate::well_known_types::Syntax::SYNTAX_PROTO2; - self.unknown_fields.clear(); + self.syntax = crate::EnumOrUnknown::new(crate::well_known_types::type_::Syntax::SYNTAX_PROTO2); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Method { + static instance: Method = Method { + name: ::std::string::String::new(), + request_type_url: ::std::string::String::new(), + request_streaming: false, + response_type_url: ::std::string::String::new(), + response_streaming: false, + options: ::std::vec::Vec::new(), + syntax: crate::EnumOrUnknown::from_i32(0), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Method { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Method").unwrap()).clone() } } -impl ::std::fmt::Debug for Method { +impl ::std::fmt::Display for Method { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Method { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Mixin) pub struct Mixin { // message fields + /// The fully qualified name of the interface which is included. + // @@protoc_insertion_point(field:google.protobuf.Mixin.name) pub name: ::std::string::String, + /// If non-empty specifies a path under which inherited HTTP paths + /// are rooted. + // @@protoc_insertion_point(field:google.protobuf.Mixin.root) pub root: ::std::string::String, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Mixin.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Mixin { @@ -878,76 +559,45 @@ impl Mixin { ::std::default::Default::default() } - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // string root = 2; - - - pub fn get_root(&self) -> &str { - &self.root - } - pub fn clear_root(&mut self) { - self.root.clear(); - } - - // Param is passed by value, moved - pub fn set_root(&mut self, v: ::std::string::String) { - self.root = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_root(&mut self) -> &mut ::std::string::String { - &mut self.root - } - - // Take field - pub fn take_root(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.root, ::std::string::String::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Mixin| { &m.name }, + |m: &mut Mixin| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "root", + |m: &Mixin| { &m.root }, + |m: &mut Mixin| { &mut m.root }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Mixin>( + "Mixin", + fields, + oneofs, + ) } } impl crate::Message for Mixin { + const NAME: &'static str = "Mixin"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; }, - 2 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.root)?; + 18 => { + self.root = is.read_string()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -956,7 +606,7 @@ impl crate::Message for Mixin { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.name.is_empty() { my_size += crate::rt::string_size(1, &self.name); @@ -964,98 +614,65 @@ impl crate::Message for Mixin { if !self.root.is_empty() { my_size += crate::rt::string_size(2, &self.root); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.name.is_empty() { os.write_string(1, &self.name)?; } if !self.root.is_empty() { os.write_string(2, &self.root)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Mixin { Mixin::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Mixin| { &m.name }, - |m: &mut Mixin| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "root", - |m: &Mixin| { &m.root }, - |m: &mut Mixin| { &mut m.root }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Mixin>( - "Mixin", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.name.clear(); + self.root.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static Mixin { - static instance: crate::rt::LazyV2<Mixin> = crate::rt::LazyV2::INIT; - instance.get(Mixin::new) + static instance: Mixin = Mixin { + name: ::std::string::String::new(), + root: ::std::string::String::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Mixin { - fn clear(&mut self) { - self.name.clear(); - self.root.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for Mixin { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Mixin").unwrap()).clone() } } -impl ::std::fmt::Debug for Mixin { +impl ::std::fmt::Display for Mixin { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Mixin { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -1279,14 +896,35 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \xce\x01\x10\x11b\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(2); + deps.push(crate::well_known_types::source_context::file_descriptor().clone()); + deps.push(crate::well_known_types::type_::file_descriptor().clone()); + let mut messages = ::std::vec::Vec::with_capacity(3); + messages.push(Api::generated_message_descriptor_data()); + messages.push(Method::generated_message_descriptor_data()); + messages.push(Mixin::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/duration.rs b/src/well_known_types/duration.rs index 822061a..1162a59 100644 --- a/src/well_known_types/duration.rs +++ b/src/well_known_types/duration.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,21 +16,31 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/duration.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Duration) pub struct Duration { // message fields + /// 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 + // @@protoc_insertion_point(field:google.protobuf.Duration.seconds) pub seconds: i64, + /// 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. + // @@protoc_insertion_point(field:google.protobuf.Duration.nanos) pub nanos: i32, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Duration.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Duration { @@ -43,62 +54,45 @@ impl Duration { ::std::default::Default::default() } - // int64 seconds = 1; - - - pub fn get_seconds(&self) -> i64 { - self.seconds - } - pub fn clear_seconds(&mut self) { - self.seconds = 0; - } - - // Param is passed by value, moved - pub fn set_seconds(&mut self, v: i64) { - self.seconds = v; - } - - // int32 nanos = 2; - - - pub fn get_nanos(&self) -> i32 { - self.nanos - } - pub fn clear_nanos(&mut self) { - self.nanos = 0; - } - - // Param is passed by value, moved - pub fn set_nanos(&mut self, v: i32) { - self.nanos = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "seconds", + |m: &Duration| { &m.seconds }, + |m: &mut Duration| { &mut m.seconds }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "nanos", + |m: &Duration| { &m.nanos }, + |m: &mut Duration| { &mut m.nanos }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Duration>( + "Duration", + fields, + oneofs, + ) } } impl crate::Message for Duration { + const NAME: &'static str = "Duration"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int64()?; - self.seconds = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.seconds = is.read_int64()?; }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.nanos = tmp; + 16 => { + self.nanos = is.read_int32()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -107,106 +101,73 @@ impl crate::Message for Duration { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.seconds != 0 { - my_size += crate::rt::value_size(1, self.seconds, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int64_size(1, self.seconds); } if self.nanos != 0 { - my_size += crate::rt::value_size(2, self.nanos, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(2, self.nanos); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.seconds != 0 { os.write_int64(1, self.seconds)?; } if self.nanos != 0 { os.write_int32(2, self.nanos)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Duration { Duration::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt64>( - "seconds", - |m: &Duration| { &m.seconds }, - |m: &mut Duration| { &mut m.seconds }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "nanos", - |m: &Duration| { &m.nanos }, - |m: &mut Duration| { &mut m.nanos }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Duration>( - "Duration", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.seconds = 0; + self.nanos = 0; + self.special_fields.clear(); } fn default_instance() -> &'static Duration { - static instance: crate::rt::LazyV2<Duration> = crate::rt::LazyV2::INIT; - instance.get(Duration::new) + static instance: Duration = Duration { + seconds: 0, + nanos: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Duration { - fn clear(&mut self) { - self.seconds = 0; - self.nanos = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for Duration { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Duration").unwrap()).clone() } } -impl ::std::fmt::Debug for Duration { +impl ::std::fmt::Display for Duration { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Duration { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -325,14 +286,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ 3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(Duration::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/empty.rs b/src/well_known_types/empty.rs index d55e517..acb4d00 100644 --- a/src/well_known_types/empty.rs +++ b/src/well_known_types/empty.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,18 +16,17 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/empty.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Empty) pub struct Empty { // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Empty.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Empty { @@ -39,19 +39,30 @@ impl Empty { pub fn new() -> Empty { ::std::default::Default::default() } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(0); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Empty>( + "Empty", + fields, + oneofs, + ) + } } impl crate::Message for Empty { + const NAME: &'static str = "Empty"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -60,82 +71,57 @@ impl crate::Message for Empty { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - os.write_unknown_fields(self.get_unknown_fields())?; + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Empty { Empty::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let fields = ::std::vec::Vec::new(); - crate::reflect::MessageDescriptor::new_pb_name::<Empty>( - "Empty", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.special_fields.clear(); } fn default_instance() -> &'static Empty { - static instance: crate::rt::LazyV2<Empty> = crate::rt::LazyV2::INIT; - instance.get(Empty::new) + static instance: Empty = Empty { + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Empty { - fn clear(&mut self) { - self.unknown_fields.clear(); +impl crate::MessageFull for Empty { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Empty").unwrap()).clone() } } -impl ::std::fmt::Debug for Empty { +impl ::std::fmt::Display for Empty { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Empty { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -195,14 +181,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x12\x033\x08\rb\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(Empty::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/field_mask.rs b/src/well_known_types/field_mask.rs index e98eb53..9a31c0a 100644 --- a/src/well_known_types/field_mask.rs +++ b/src/well_known_types/field_mask.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,20 +16,21 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/field_mask.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FieldMask) pub struct FieldMask { // message fields - pub paths: crate::RepeatedField<::std::string::String>, + /// The set of field mask paths. + // @@protoc_insertion_point(field:google.protobuf.FieldMask.paths) + pub paths: ::std::vec::Vec<::std::string::String>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FieldMask.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FieldMask { @@ -42,46 +44,37 @@ impl FieldMask { ::std::default::Default::default() } - // repeated string paths = 1; - - - pub fn get_paths(&self) -> &[::std::string::String] { - &self.paths - } - pub fn clear_paths(&mut self) { - self.paths.clear(); - } - - // Param is passed by value, moved - pub fn set_paths(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.paths = v; - } - - // Mutable pointer to the field. - pub fn mut_paths(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.paths - } - - // Take field - pub fn take_paths(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.paths, crate::RepeatedField::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "paths", + |m: &FieldMask| { &m.paths }, + |m: &mut FieldMask| { &mut m.paths }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FieldMask>( + "FieldMask", + fields, + oneofs, + ) } } impl crate::Message for FieldMask { + const NAME: &'static str = "FieldMask"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.paths)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.paths.push(is.read_string()?); }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -90,94 +83,65 @@ impl crate::Message for FieldMask { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; for value in &self.paths { my_size += crate::rt::string_size(1, &value); }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { for v in &self.paths { os.write_string(1, &v)?; }; - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FieldMask { FieldMask::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "paths", - |m: &FieldMask| { &m.paths }, - |m: &mut FieldMask| { &mut m.paths }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FieldMask>( - "FieldMask", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.paths.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static FieldMask { - static instance: crate::rt::LazyV2<FieldMask> = crate::rt::LazyV2::INIT; - instance.get(FieldMask::new) + static instance: FieldMask = FieldMask { + paths: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for FieldMask { - fn clear(&mut self) { - self.paths.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for FieldMask { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FieldMask").unwrap()).clone() } } -impl ::std::fmt::Debug for FieldMask { +impl ::std::fmt::Display for FieldMask { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for FieldMask { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -372,14 +336,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ 3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(FieldMask::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/mod.rs b/src/well_known_types/mod.rs index 9ecf8fb..d2e1659 100644 --- a/src/well_known_types/mod.rs +++ b/src/well_known_types/mod.rs @@ -1,26 +1,19 @@ // This file is generated. Do not edit +// @generated //! Generated code for "well known types" //! //! [This document](https://developers.google.com/protocol-buffers/docs/reference/google.protobuf) describes these types. -mod any; -mod api; -mod duration; -mod empty; -mod field_mask; -mod source_context; -mod struct_pb; -mod timestamp; -mod type_pb; -mod wrappers; +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] -pub use self::any::*; -pub use self::api::*; -pub use self::duration::*; -pub use self::empty::*; -pub use self::field_mask::*; -pub use self::source_context::*; -pub use self::struct_pb::*; -pub use self::timestamp::*; -pub use self::type_pb::*; -pub use self::wrappers::*; +pub mod any; +pub mod api; +pub mod duration; +pub mod empty; +pub mod field_mask; +pub mod source_context; +pub mod struct_; +pub mod timestamp; +pub mod type_; +pub mod wrappers; diff --git a/src/well_known_types/source_context.rs b/src/well_known_types/source_context.rs index 646e87d..7edcecc 100644 --- a/src/well_known_types/source_context.rs +++ b/src/well_known_types/source_context.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,20 +16,24 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/source_context.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// `SourceContext` represents information about the source of a +/// protobuf element, like the file in which it is defined. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.SourceContext) pub struct SourceContext { // message fields + /// The path-qualified name of the .proto file that contained the associated + /// protobuf element. For example: `"google/protobuf/source_context.proto"`. + // @@protoc_insertion_point(field:google.protobuf.SourceContext.file_name) pub file_name: ::std::string::String, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.SourceContext.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a SourceContext { @@ -42,47 +47,37 @@ impl SourceContext { ::std::default::Default::default() } - // string file_name = 1; - - - pub fn get_file_name(&self) -> &str { - &self.file_name - } - pub fn clear_file_name(&mut self) { - self.file_name.clear(); - } - - // Param is passed by value, moved - pub fn set_file_name(&mut self, v: ::std::string::String) { - self.file_name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_file_name(&mut self) -> &mut ::std::string::String { - &mut self.file_name - } - - // Take field - pub fn take_file_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.file_name, ::std::string::String::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "file_name", + |m: &SourceContext| { &m.file_name }, + |m: &mut SourceContext| { &mut m.file_name }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<SourceContext>( + "SourceContext", + fields, + oneofs, + ) } } impl crate::Message for SourceContext { + const NAME: &'static str = "SourceContext"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.file_name)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.file_name = is.read_string()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -91,94 +86,65 @@ impl crate::Message for SourceContext { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.file_name.is_empty() { my_size += crate::rt::string_size(1, &self.file_name); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.file_name.is_empty() { os.write_string(1, &self.file_name)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> SourceContext { SourceContext::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "file_name", - |m: &SourceContext| { &m.file_name }, - |m: &mut SourceContext| { &mut m.file_name }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<SourceContext>( - "SourceContext", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.file_name.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static SourceContext { - static instance: crate::rt::LazyV2<SourceContext> = crate::rt::LazyV2::INIT; - instance.get(SourceContext::new) + static instance: SourceContext = SourceContext { + file_name: ::std::string::String::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for SourceContext { - fn clear(&mut self) { - self.file_name.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for SourceContext { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("SourceContext").unwrap()).clone() } } -impl ::std::fmt::Debug for SourceContext { +impl ::std::fmt::Display for SourceContext { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for SourceContext { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -238,14 +204,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x16b\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(SourceContext::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/struct_.rs b/src/well_known_types/struct_.rs new file mode 100644 index 0000000..d565c81 --- /dev/null +++ b/src/well_known_types/struct_.rs @@ -0,0 +1,990 @@ +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_results)] +#![allow(unused_mut)] + +//! Generated file from `google/protobuf/struct.proto` + +/// `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. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Struct) +pub struct Struct { + // message fields + /// Unordered map of dynamically typed values. + // @@protoc_insertion_point(field:google.protobuf.Struct.fields) + pub fields: ::std::collections::HashMap<::std::string::String, Value>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Struct.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Struct { + fn default() -> &'a Struct { + <Struct as crate::Message>::default_instance() + } +} + +impl Struct { + pub fn new() -> Struct { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_map_simpler_accessor::<_, _, _>( + "fields", + |m: &Struct| { &m.fields }, + |m: &mut Struct| { &mut m.fields }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Struct>( + "Struct", + fields, + oneofs, + ) + } +} + +impl crate::Message for Struct { + const NAME: &'static str = "Struct"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + let len = is.read_raw_varint32()?; + let old_limit = is.push_limit(len as u64)?; + let mut key = ::std::default::Default::default(); + let mut value = ::std::default::Default::default(); + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => key = is.read_string()?, + 18 => value = is.read_message()?, + _ => crate::rt::skip_field_for_tag(tag, is)?, + }; + } + is.pop_limit(old_limit); + self.fields.insert(key, value); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + for (k, v) in &self.fields { + let mut entry_size = 0; + entry_size += crate::rt::string_size(1, &k); + let len = v.compute_size(); + entry_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + my_size += 1 + crate::rt::compute_raw_varint64_size(entry_size) + entry_size + }; + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + for (k, v) in &self.fields { + let mut entry_size = 0; + entry_size += crate::rt::string_size(1, &k); + let len = v.cached_size() as u64; + entry_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + os.write_raw_varint32(10)?; // Tag. + os.write_raw_varint32(entry_size as u32)?; + os.write_string(1, &k)?; + crate::rt::write_message_field_with_cached_size(2, v, os)?; + }; + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Struct { + Struct::new() + } + + fn clear(&mut self) { + self.fields.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Struct { + static instance: crate::rt::Lazy<Struct> = crate::rt::Lazy::new(); + instance.get(Struct::new) + } +} + +impl crate::MessageFull for Struct { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Struct").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Struct { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Struct { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// `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. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Value) +pub struct Value { + // message oneof groups + pub kind: ::std::option::Option<value::Kind>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Value.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Value { + fn default() -> &'a Value { + <Value as crate::Message>::default_instance() + } +} + +impl Value { + pub fn new() -> Value { + ::std::default::Default::default() + } + + // .google.protobuf.NullValue null_value = 1; + + pub fn null_value(&self) -> NullValue { + match self.kind { + ::std::option::Option::Some(value::Kind::NullValue(v)) => crate::EnumOrUnknown::enum_value_or_default(&v), + _ => NullValue::NULL_VALUE, + } + } + + pub fn clear_null_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_null_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::NullValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_null_value(&mut self, v: NullValue) { + self.kind = ::std::option::Option::Some(value::Kind::NullValue(crate::EnumOrUnknown::new(v))) + } + + // double number_value = 2; + + pub fn number_value(&self) -> f64 { + match self.kind { + ::std::option::Option::Some(value::Kind::NumberValue(v)) => v, + _ => 0., + } + } + + pub fn clear_number_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_number_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::NumberValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_number_value(&mut self, v: f64) { + self.kind = ::std::option::Option::Some(value::Kind::NumberValue(v)) + } + + // string string_value = 3; + + pub fn string_value(&self) -> &str { + match self.kind { + ::std::option::Option::Some(value::Kind::StringValue(ref v)) => v, + _ => "", + } + } + + pub fn clear_string_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_string_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::StringValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_string_value(&mut self, v: ::std::string::String) { + self.kind = ::std::option::Option::Some(value::Kind::StringValue(v)) + } + + // Mutable pointer to the field. + pub fn mut_string_value(&mut self) -> &mut ::std::string::String { + if let ::std::option::Option::Some(value::Kind::StringValue(_)) = self.kind { + } else { + self.kind = ::std::option::Option::Some(value::Kind::StringValue(::std::string::String::new())); + } + match self.kind { + ::std::option::Option::Some(value::Kind::StringValue(ref mut v)) => v, + _ => panic!(), + } + } + + // Take field + pub fn take_string_value(&mut self) -> ::std::string::String { + if self.has_string_value() { + match self.kind.take() { + ::std::option::Option::Some(value::Kind::StringValue(v)) => v, + _ => panic!(), + } + } else { + ::std::string::String::new() + } + } + + // bool bool_value = 4; + + pub fn bool_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::BoolValue(v)) => v, + _ => false, + } + } + + pub fn clear_bool_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_bool_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::BoolValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_bool_value(&mut self, v: bool) { + self.kind = ::std::option::Option::Some(value::Kind::BoolValue(v)) + } + + // .google.protobuf.Struct struct_value = 5; + + pub fn struct_value(&self) -> &Struct { + match self.kind { + ::std::option::Option::Some(value::Kind::StructValue(ref v)) => v, + _ => <Struct as crate::Message>::default_instance(), + } + } + + pub fn clear_struct_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_struct_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::StructValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_struct_value(&mut self, v: Struct) { + self.kind = ::std::option::Option::Some(value::Kind::StructValue(v)) + } + + // Mutable pointer to the field. + pub fn mut_struct_value(&mut self) -> &mut Struct { + if let ::std::option::Option::Some(value::Kind::StructValue(_)) = self.kind { + } else { + self.kind = ::std::option::Option::Some(value::Kind::StructValue(Struct::new())); + } + match self.kind { + ::std::option::Option::Some(value::Kind::StructValue(ref mut v)) => v, + _ => panic!(), + } + } + + // Take field + pub fn take_struct_value(&mut self) -> Struct { + if self.has_struct_value() { + match self.kind.take() { + ::std::option::Option::Some(value::Kind::StructValue(v)) => v, + _ => panic!(), + } + } else { + Struct::new() + } + } + + // .google.protobuf.ListValue list_value = 6; + + pub fn list_value(&self) -> &ListValue { + match self.kind { + ::std::option::Option::Some(value::Kind::ListValue(ref v)) => v, + _ => <ListValue as crate::Message>::default_instance(), + } + } + + pub fn clear_list_value(&mut self) { + self.kind = ::std::option::Option::None; + } + + pub fn has_list_value(&self) -> bool { + match self.kind { + ::std::option::Option::Some(value::Kind::ListValue(..)) => true, + _ => false, + } + } + + // Param is passed by value, moved + pub fn set_list_value(&mut self, v: ListValue) { + self.kind = ::std::option::Option::Some(value::Kind::ListValue(v)) + } + + // Mutable pointer to the field. + pub fn mut_list_value(&mut self) -> &mut ListValue { + if let ::std::option::Option::Some(value::Kind::ListValue(_)) = self.kind { + } else { + self.kind = ::std::option::Option::Some(value::Kind::ListValue(ListValue::new())); + } + match self.kind { + ::std::option::Option::Some(value::Kind::ListValue(ref mut v)) => v, + _ => panic!(), + } + } + + // Take field + pub fn take_list_value(&mut self) -> ListValue { + if self.has_list_value() { + match self.kind.take() { + ::std::option::Option::Some(value::Kind::ListValue(v)) => v, + _ => panic!(), + } + } else { + ListValue::new() + } + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(6); + let mut oneofs = ::std::vec::Vec::with_capacity(1); + fields.push(crate::reflect::rt::v2::make_oneof_enum_accessors::<_, _>( + "null_value", + |message: &Value| match &message.kind { + ::std::option::Option::Some(value::Kind::NullValue(e)) => ::std::option::Option::Some(*e), + _ => ::std::option::Option::None, + }, + |message: &mut Value, e: crate::EnumOrUnknown<NullValue>| { + message.kind = ::std::option::Option::Some(value::Kind::NullValue(e)); + }, + NullValue::NULL_VALUE, + )); + fields.push(crate::reflect::rt::v2::make_oneof_copy_has_get_set_simpler_accessors::<_, _>( + "number_value", + Value::has_number_value, + Value::number_value, + Value::set_number_value, + )); + fields.push(crate::reflect::rt::v2::make_oneof_deref_has_get_set_simpler_accessor::<_, _>( + "string_value", + Value::has_string_value, + Value::string_value, + Value::set_string_value, + )); + fields.push(crate::reflect::rt::v2::make_oneof_copy_has_get_set_simpler_accessors::<_, _>( + "bool_value", + Value::has_bool_value, + Value::bool_value, + Value::set_bool_value, + )); + fields.push(crate::reflect::rt::v2::make_oneof_message_has_get_mut_set_accessor::<_, Struct>( + "struct_value", + Value::has_struct_value, + Value::struct_value, + Value::mut_struct_value, + Value::set_struct_value, + )); + fields.push(crate::reflect::rt::v2::make_oneof_message_has_get_mut_set_accessor::<_, ListValue>( + "list_value", + Value::has_list_value, + Value::list_value, + Value::mut_list_value, + Value::set_list_value, + )); + oneofs.push(value::Kind::generated_oneof_descriptor_data()); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Value>( + "Value", + fields, + oneofs, + ) + } +} + +impl crate::Message for Value { + const NAME: &'static str = "Value"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.kind = ::std::option::Option::Some(value::Kind::NullValue(is.read_enum_or_unknown()?)); + }, + 17 => { + self.kind = ::std::option::Option::Some(value::Kind::NumberValue(is.read_double()?)); + }, + 26 => { + self.kind = ::std::option::Option::Some(value::Kind::StringValue(is.read_string()?)); + }, + 32 => { + self.kind = ::std::option::Option::Some(value::Kind::BoolValue(is.read_bool()?)); + }, + 42 => { + self.kind = ::std::option::Option::Some(value::Kind::StructValue(is.read_message()?)); + }, + 50 => { + self.kind = ::std::option::Option::Some(value::Kind::ListValue(is.read_message()?)); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if let ::std::option::Option::Some(ref v) = self.kind { + match v { + &value::Kind::NullValue(v) => { + my_size += crate::rt::int32_size(1, v.value()); + }, + &value::Kind::NumberValue(v) => { + my_size += 1 + 8; + }, + &value::Kind::StringValue(ref v) => { + my_size += crate::rt::string_size(3, &v); + }, + &value::Kind::BoolValue(v) => { + my_size += 1 + 1; + }, + &value::Kind::StructValue(ref v) => { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }, + &value::Kind::ListValue(ref v) => { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }, + }; + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if let ::std::option::Option::Some(ref v) = self.kind { + match v { + &value::Kind::NullValue(v) => { + os.write_enum(1, crate::EnumOrUnknown::value(&v))?; + }, + &value::Kind::NumberValue(v) => { + os.write_double(2, v)?; + }, + &value::Kind::StringValue(ref v) => { + os.write_string(3, v)?; + }, + &value::Kind::BoolValue(v) => { + os.write_bool(4, v)?; + }, + &value::Kind::StructValue(ref v) => { + crate::rt::write_message_field_with_cached_size(5, v, os)?; + }, + &value::Kind::ListValue(ref v) => { + crate::rt::write_message_field_with_cached_size(6, v, os)?; + }, + }; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Value { + Value::new() + } + + fn clear(&mut self) { + self.kind = ::std::option::Option::None; + self.kind = ::std::option::Option::None; + self.kind = ::std::option::Option::None; + self.kind = ::std::option::Option::None; + self.kind = ::std::option::Option::None; + self.kind = ::std::option::Option::None; + self.special_fields.clear(); + } + + fn default_instance() -> &'static Value { + static instance: Value = Value { + kind: ::std::option::Option::None, + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Value { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Value").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Value { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Value { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `Value` +pub mod value { + + #[derive(Clone,PartialEq,Debug)] + #[non_exhaustive] + // @@protoc_insertion_point(oneof:google.protobuf.Value.kind) + pub enum Kind { + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.null_value) + NullValue(crate::EnumOrUnknown<super::NullValue>), + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.number_value) + NumberValue(f64), + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.string_value) + StringValue(::std::string::String), + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.bool_value) + BoolValue(bool), + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.struct_value) + StructValue(super::Struct), + // @@protoc_insertion_point(oneof_field:google.protobuf.Value.list_value) + ListValue(super::ListValue), + } + + impl crate::Oneof for Kind { + } + + impl crate::OneofFull for Kind { + fn descriptor() -> crate::reflect::OneofDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::OneofDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| <super::Value as crate::MessageFull>::descriptor().oneof_by_name("kind").unwrap()).clone() + } + } + + impl Kind { + pub(in super) fn generated_oneof_descriptor_data() -> crate::reflect::GeneratedOneofDescriptorData { + crate::reflect::GeneratedOneofDescriptorData::new::<Kind>("kind") + } + } +} + +/// `ListValue` is a wrapper around a repeated field of values. +/// +/// The JSON representation for `ListValue` is JSON array. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.ListValue) +pub struct ListValue { + // message fields + /// Repeated field of dynamically typed values. + // @@protoc_insertion_point(field:google.protobuf.ListValue.values) + pub values: ::std::vec::Vec<Value>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.ListValue.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a ListValue { + fn default() -> &'a ListValue { + <ListValue as crate::Message>::default_instance() + } +} + +impl ListValue { + pub fn new() -> ListValue { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "values", + |m: &ListValue| { &m.values }, + |m: &mut ListValue| { &mut m.values }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<ListValue>( + "ListValue", + fields, + oneofs, + ) + } +} + +impl crate::Message for ListValue { + const NAME: &'static str = "ListValue"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.values.push(is.read_message()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + for value in &self.values { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + for v in &self.values { + crate::rt::write_message_field_with_cached_size(1, v, os)?; + }; + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> ListValue { + ListValue::new() + } + + fn clear(&mut self) { + self.values.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static ListValue { + static instance: ListValue = ListValue { + values: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for ListValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("ListValue").unwrap()).clone() + } +} + +impl ::std::fmt::Display for ListValue { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for ListValue { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// `NullValue` is a singleton enumeration to represent the null value for the +/// `Value` type union. +/// +/// The JSON representation for `NullValue` is JSON `null`. +#[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] +// @@protoc_insertion_point(enum:google.protobuf.NullValue) +pub enum NullValue { + // @@protoc_insertion_point(enum_value:google.protobuf.NullValue.NULL_VALUE) + NULL_VALUE = 0, +} + +impl crate::Enum for NullValue { + const NAME: &'static str = "NullValue"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<NullValue> { + match value { + 0 => ::std::option::Option::Some(NullValue::NULL_VALUE), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [NullValue] = &[ + NullValue::NULL_VALUE, + ]; +} + +impl crate::EnumFull for NullValue { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().enum_by_package_relative_name("NullValue").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } +} + +impl ::std::default::Default for NullValue { + fn default() -> Self { + NullValue::NULL_VALUE + } +} + +impl NullValue { + fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<NullValue>("NullValue") + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x1cgoogle/protobuf/struct.proto\x12\x0fgoogle.protobuf\"\x98\x01\n\ + \x06Struct\x12;\n\x06fields\x18\x01\x20\x03(\x0b2#.google.protobuf.Struc\ + t.FieldsEntryR\x06fields\x1aQ\n\x0bFieldsEntry\x12\x10\n\x03key\x18\x01\ + \x20\x01(\tR\x03key\x12,\n\x05value\x18\x02\x20\x01(\x0b2\x16.google.pro\ + tobuf.ValueR\x05value:\x028\x01\"\xb2\x02\n\x05Value\x12;\n\nnull_value\ + \x18\x01\x20\x01(\x0e2\x1a.google.protobuf.NullValueH\0R\tnullValue\x12#\ + \n\x0cnumber_value\x18\x02\x20\x01(\x01H\0R\x0bnumberValue\x12#\n\x0cstr\ + ing_value\x18\x03\x20\x01(\tH\0R\x0bstringValue\x12\x1f\n\nbool_value\ + \x18\x04\x20\x01(\x08H\0R\tboolValue\x12<\n\x0cstruct_value\x18\x05\x20\ + \x01(\x0b2\x17.google.protobuf.StructH\0R\x0bstructValue\x12;\n\nlist_va\ + lue\x18\x06\x20\x01(\x0b2\x1a.google.protobuf.ListValueH\0R\tlistValueB\ + \x06\n\x04kind\";\n\tListValue\x12.\n\x06values\x18\x01\x20\x03(\x0b2\ + \x16.google.protobuf.ValueR\x06values*\x1b\n\tNullValue\x12\x0e\n\nNULL_\ + VALUE\x10\0B\x7f\n\x13com.google.protobufB\x0bStructProtoP\x01Z/google.g\ + olang.org/protobuf/types/known/structpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\ + \x02\x1eGoogle.Protobuf.WellKnownTypesJ\x9a\x1d\n\x06\x12\x04\x1e\0^\x01\ + \n\xcc\x0c\n\x01\x0c\x12\x03\x1e\0\x122\xc1\x0c\x20Protocol\x20Buffers\ + \x20-\x20Google's\x20data\x20interchange\x20format\n\x20Copyright\x20200\ + 8\x20Google\x20Inc.\x20\x20All\x20rights\x20reserved.\n\x20https://devel\ + opers.google.com/protocol-buffers/\n\n\x20Redistribution\x20and\x20use\ + \x20in\x20source\x20and\x20binary\x20forms,\x20with\x20or\x20without\n\ + \x20modification,\x20are\x20permitted\x20provided\x20that\x20the\x20foll\ + owing\x20conditions\x20are\n\x20met:\n\n\x20\x20\x20\x20\x20*\x20Redistr\ + ibutions\x20of\x20source\x20code\x20must\x20retain\x20the\x20above\x20co\ + pyright\n\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\ + \x20following\x20disclaimer.\n\x20\x20\x20\x20\x20*\x20Redistributions\ + \x20in\x20binary\x20form\x20must\x20reproduce\x20the\x20above\n\x20copyr\ + ight\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\x20fol\ + lowing\x20disclaimer\n\x20in\x20the\x20documentation\x20and/or\x20other\ + \x20materials\x20provided\x20with\x20the\n\x20distribution.\n\x20\x20\ + \x20\x20\x20*\x20Neither\x20the\x20name\x20of\x20Google\x20Inc.\x20nor\ + \x20the\x20names\x20of\x20its\n\x20contributors\x20may\x20be\x20used\x20\ + to\x20endorse\x20or\x20promote\x20products\x20derived\x20from\n\x20this\ + \x20software\x20without\x20specific\x20prior\x20written\x20permission.\n\ + \n\x20THIS\x20SOFTWARE\x20IS\x20PROVIDED\x20BY\x20THE\x20COPYRIGHT\x20HO\ + LDERS\x20AND\x20CONTRIBUTORS\n\x20\"AS\x20IS\"\x20AND\x20ANY\x20EXPRESS\ + \x20OR\x20IMPLIED\x20WARRANTIES,\x20INCLUDING,\x20BUT\x20NOT\n\x20LIMITE\ + D\x20TO,\x20THE\x20IMPLIED\x20WARRANTIES\x20OF\x20MERCHANTABILITY\x20AND\ + \x20FITNESS\x20FOR\n\x20A\x20PARTICULAR\x20PURPOSE\x20ARE\x20DISCLAIMED.\ + \x20IN\x20NO\x20EVENT\x20SHALL\x20THE\x20COPYRIGHT\n\x20OWNER\x20OR\x20C\ + ONTRIBUTORS\x20BE\x20LIABLE\x20FOR\x20ANY\x20DIRECT,\x20INDIRECT,\x20INC\ + IDENTAL,\n\x20SPECIAL,\x20EXEMPLARY,\x20OR\x20CONSEQUENTIAL\x20DAMAGES\ + \x20(INCLUDING,\x20BUT\x20NOT\n\x20LIMITED\x20TO,\x20PROCUREMENT\x20OF\ + \x20SUBSTITUTE\x20GOODS\x20OR\x20SERVICES;\x20LOSS\x20OF\x20USE,\n\x20DA\ + TA,\x20OR\x20PROFITS;\x20OR\x20BUSINESS\x20INTERRUPTION)\x20HOWEVER\x20C\ + AUSED\x20AND\x20ON\x20ANY\n\x20THEORY\x20OF\x20LIABILITY,\x20WHETHER\x20\ + IN\x20CONTRACT,\x20STRICT\x20LIABILITY,\x20OR\x20TORT\n\x20(INCLUDING\ + \x20NEGLIGENCE\x20OR\x20OTHERWISE)\x20ARISING\x20IN\x20ANY\x20WAY\x20OUT\ + \x20OF\x20THE\x20USE\n\x20OF\x20THIS\x20SOFTWARE,\x20EVEN\x20IF\x20ADVIS\ + ED\x20OF\x20THE\x20POSSIBILITY\x20OF\x20SUCH\x20DAMAGE.\n\n\x08\n\x01\ + \x02\x12\x03\x20\0\x18\n\x08\n\x01\x08\x12\x03\"\0;\n\t\n\x02\x08%\x12\ + \x03\"\0;\n\x08\n\x01\x08\x12\x03#\0\x1f\n\t\n\x02\x08\x1f\x12\x03#\0\ + \x1f\n\x08\n\x01\x08\x12\x03$\0F\n\t\n\x02\x08\x0b\x12\x03$\0F\n\x08\n\ + \x01\x08\x12\x03%\0,\n\t\n\x02\x08\x01\x12\x03%\0,\n\x08\n\x01\x08\x12\ + \x03&\0,\n\t\n\x02\x08\x08\x12\x03&\0,\n\x08\n\x01\x08\x12\x03'\0\"\n\t\ + \n\x02\x08\n\x12\x03'\0\"\n\x08\n\x01\x08\x12\x03(\0!\n\t\n\x02\x08$\x12\ + \x03(\0!\n\xb3\x03\n\x02\x04\0\x12\x042\05\x01\x1a\xa6\x03\x20`Struct`\ + \x20represents\x20a\x20structured\x20data\x20value,\x20consisting\x20of\ + \x20fields\n\x20which\x20map\x20to\x20dynamically\x20typed\x20values.\ + \x20In\x20some\x20languages,\x20`Struct`\n\x20might\x20be\x20supported\ + \x20by\x20a\x20native\x20representation.\x20For\x20example,\x20in\n\x20s\ + cripting\x20languages\x20like\x20JS\x20a\x20struct\x20is\x20represented\ + \x20as\x20an\n\x20object.\x20The\x20details\x20of\x20that\x20representat\ + ion\x20are\x20described\x20together\n\x20with\x20the\x20proto\x20support\ + \x20for\x20the\x20language.\n\n\x20The\x20JSON\x20representation\x20for\ + \x20`Struct`\x20is\x20JSON\x20object.\n\n\n\n\x03\x04\0\x01\x12\x032\x08\ + \x0e\n9\n\x04\x04\0\x02\0\x12\x034\x02\x20\x1a,\x20Unordered\x20map\x20o\ + f\x20dynamically\x20typed\x20values.\n\n\x0c\n\x05\x04\0\x02\0\x06\x12\ + \x034\x02\x14\n\x0c\n\x05\x04\0\x02\0\x01\x12\x034\x15\x1b\n\x0c\n\x05\ + \x04\0\x02\0\x03\x12\x034\x1e\x1f\n\xc4\x02\n\x02\x04\x01\x12\x04=\0M\ + \x01\x1a\xb7\x02\x20`Value`\x20represents\x20a\x20dynamically\x20typed\ + \x20value\x20which\x20can\x20be\x20either\n\x20null,\x20a\x20number,\x20\ + a\x20string,\x20a\x20boolean,\x20a\x20recursive\x20struct\x20value,\x20o\ + r\x20a\n\x20list\x20of\x20values.\x20A\x20producer\x20of\x20value\x20is\ + \x20expected\x20to\x20set\x20one\x20of\x20these\n\x20variants.\x20Absenc\ + e\x20of\x20any\x20variant\x20indicates\x20an\x20error.\n\n\x20The\x20JSO\ + N\x20representation\x20for\x20`Value`\x20is\x20JSON\x20value.\n\n\n\n\ + \x03\x04\x01\x01\x12\x03=\x08\r\n\"\n\x04\x04\x01\x08\0\x12\x04?\x02L\ + \x03\x1a\x14\x20The\x20kind\x20of\x20value.\n\n\x0c\n\x05\x04\x01\x08\0\ + \x01\x12\x03?\x08\x0c\n'\n\x04\x04\x01\x02\0\x12\x03A\x04\x1d\x1a\x1a\ + \x20Represents\x20a\x20null\x20value.\n\n\x0c\n\x05\x04\x01\x02\0\x06\ + \x12\x03A\x04\r\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03A\x0e\x18\n\x0c\n\ + \x05\x04\x01\x02\0\x03\x12\x03A\x1b\x1c\n)\n\x04\x04\x01\x02\x01\x12\x03\ + C\x04\x1c\x1a\x1c\x20Represents\x20a\x20double\x20value.\n\n\x0c\n\x05\ + \x04\x01\x02\x01\x05\x12\x03C\x04\n\n\x0c\n\x05\x04\x01\x02\x01\x01\x12\ + \x03C\x0b\x17\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03C\x1a\x1b\n)\n\x04\ + \x04\x01\x02\x02\x12\x03E\x04\x1c\x1a\x1c\x20Represents\x20a\x20string\ + \x20value.\n\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03E\x04\n\n\x0c\n\x05\ + \x04\x01\x02\x02\x01\x12\x03E\x0b\x17\n\x0c\n\x05\x04\x01\x02\x02\x03\ + \x12\x03E\x1a\x1b\n*\n\x04\x04\x01\x02\x03\x12\x03G\x04\x18\x1a\x1d\x20R\ + epresents\x20a\x20boolean\x20value.\n\n\x0c\n\x05\x04\x01\x02\x03\x05\ + \x12\x03G\x04\x08\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03G\t\x13\n\x0c\n\ + \x05\x04\x01\x02\x03\x03\x12\x03G\x16\x17\n-\n\x04\x04\x01\x02\x04\x12\ + \x03I\x04\x1c\x1a\x20\x20Represents\x20a\x20structured\x20value.\n\n\x0c\ + \n\x05\x04\x01\x02\x04\x06\x12\x03I\x04\n\n\x0c\n\x05\x04\x01\x02\x04\ + \x01\x12\x03I\x0b\x17\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03I\x1a\x1b\n\ + -\n\x04\x04\x01\x02\x05\x12\x03K\x04\x1d\x1a\x20\x20Represents\x20a\x20r\ + epeated\x20`Value`.\n\n\x0c\n\x05\x04\x01\x02\x05\x06\x12\x03K\x04\r\n\ + \x0c\n\x05\x04\x01\x02\x05\x01\x12\x03K\x0e\x18\n\x0c\n\x05\x04\x01\x02\ + \x05\x03\x12\x03K\x1b\x1c\n\xa9\x01\n\x02\x05\0\x12\x04S\0V\x01\x1a\x9c\ + \x01\x20`NullValue`\x20is\x20a\x20singleton\x20enumeration\x20to\x20repr\ + esent\x20the\x20null\x20value\x20for\x20the\n\x20`Value`\x20type\x20unio\ + n.\n\n\x20\x20The\x20JSON\x20representation\x20for\x20`NullValue`\x20is\ + \x20JSON\x20`null`.\n\n\n\n\x03\x05\0\x01\x12\x03S\x05\x0e\n\x1a\n\x04\ + \x05\0\x02\0\x12\x03U\x02\x11\x1a\r\x20Null\x20value.\n\n\x0c\n\x05\x05\ + \0\x02\0\x01\x12\x03U\x02\x0c\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03U\x0f\ + \x10\n\x82\x01\n\x02\x04\x02\x12\x04[\0^\x01\x1av\x20`ListValue`\x20is\ + \x20a\x20wrapper\x20around\x20a\x20repeated\x20field\x20of\x20values.\n\ + \n\x20The\x20JSON\x20representation\x20for\x20`ListValue`\x20is\x20JSON\ + \x20array.\n\n\n\n\x03\x04\x02\x01\x12\x03[\x08\x11\n:\n\x04\x04\x02\x02\ + \0\x12\x03]\x02\x1c\x1a-\x20Repeated\x20field\x20of\x20dynamically\x20ty\ + ped\x20values.\n\n\x0c\n\x05\x04\x02\x02\0\x04\x12\x03]\x02\n\n\x0c\n\ + \x05\x04\x02\x02\0\x06\x12\x03]\x0b\x10\n\x0c\n\x05\x04\x02\x02\0\x01\ + \x12\x03]\x11\x17\n\x0c\n\x05\x04\x02\x02\0\x03\x12\x03]\x1a\x1bb\x06pro\ + to3\ +"; + +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) +} + +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(3); + messages.push(Struct::generated_message_descriptor_data()); + messages.push(Value::generated_message_descriptor_data()); + messages.push(ListValue::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(1); + enums.push(NullValue::generated_enum_descriptor_data()); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) + }) +} diff --git a/src/well_known_types/struct_pb.rs b/src/well_known_types/struct_pb.rs deleted file mode 100644 index 5f18a42..0000000 --- a/src/well_known_types/struct_pb.rs +++ /dev/null @@ -1,1009 +0,0 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit -// @generated - -// https://github.com/rust-lang/rust-clippy/issues/702 -#![allow(unknown_lints)] -#![allow(clippy::all)] - -#![allow(unused_attributes)] -#![cfg_attr(rustfmt, rustfmt::skip)] - -#![allow(box_pointers)] -#![allow(dead_code)] -#![allow(missing_docs)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] -#![allow(non_upper_case_globals)] -#![allow(trivial_casts)] -#![allow(unused_imports)] -#![allow(unused_results)] -//! Generated file from `google/protobuf/struct.proto` - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Struct { - // message fields - pub fields: ::std::collections::HashMap<::std::string::String, Value>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Struct { - fn default() -> &'a Struct { - <Struct as crate::Message>::default_instance() - } -} - -impl Struct { - pub fn new() -> Struct { - ::std::default::Default::default() - } - - // repeated .google.protobuf.Struct.FieldsEntry fields = 1; - - - pub fn get_fields(&self) -> &::std::collections::HashMap<::std::string::String, Value> { - &self.fields - } - pub fn clear_fields(&mut self) { - self.fields.clear(); - } - - // Param is passed by value, moved - pub fn set_fields(&mut self, v: ::std::collections::HashMap<::std::string::String, Value>) { - self.fields = v; - } - - // Mutable pointer to the field. - pub fn mut_fields(&mut self) -> &mut ::std::collections::HashMap<::std::string::String, Value> { - &mut self.fields - } - - // Take field - pub fn take_fields(&mut self) -> ::std::collections::HashMap<::std::string::String, Value> { - ::std::mem::replace(&mut self.fields, ::std::collections::HashMap::new()) - } -} - -impl crate::Message for Struct { - fn is_initialized(&self) -> bool { - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_map_into::<crate::types::ProtobufTypeString, crate::types::ProtobufTypeMessage<Value>>(wire_type, is, &mut self.fields)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - my_size += crate::rt::compute_map_size::<crate::types::ProtobufTypeString, crate::types::ProtobufTypeMessage<Value>>(1, &self.fields); - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - crate::rt::write_map_with_cached_sizes::<crate::types::ProtobufTypeString, crate::types::ProtobufTypeMessage<Value>>(1, &self.fields, os)?; - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Struct { - Struct::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_map_accessor::<_, crate::types::ProtobufTypeString, crate::types::ProtobufTypeMessage<Value>>( - "fields", - |m: &Struct| { &m.fields }, - |m: &mut Struct| { &mut m.fields }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Struct>( - "Struct", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Struct { - static instance: crate::rt::LazyV2<Struct> = crate::rt::LazyV2::INIT; - instance.get(Struct::new) - } -} - -impl crate::Clear for Struct { - fn clear(&mut self) { - self.fields.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Struct { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Struct { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Value { - // message oneof groups - pub kind: ::std::option::Option<Value_oneof_kind>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Value { - fn default() -> &'a Value { - <Value as crate::Message>::default_instance() - } -} - -#[derive(Clone,PartialEq,Debug)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum Value_oneof_kind { - null_value(NullValue), - number_value(f64), - string_value(::std::string::String), - bool_value(bool), - struct_value(Struct), - list_value(ListValue), -} - -impl Value { - pub fn new() -> Value { - ::std::default::Default::default() - } - - // .google.protobuf.NullValue null_value = 1; - - - pub fn get_null_value(&self) -> NullValue { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::null_value(v)) => v, - _ => NullValue::NULL_VALUE, - } - } - pub fn clear_null_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_null_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::null_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_null_value(&mut self, v: NullValue) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::null_value(v)) - } - - // double number_value = 2; - - - pub fn get_number_value(&self) -> f64 { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::number_value(v)) => v, - _ => 0., - } - } - pub fn clear_number_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_number_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::number_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_number_value(&mut self, v: f64) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::number_value(v)) - } - - // string string_value = 3; - - - pub fn get_string_value(&self) -> &str { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::string_value(ref v)) => v, - _ => "", - } - } - pub fn clear_string_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_string_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::string_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_string_value(&mut self, v: ::std::string::String) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::string_value(v)) - } - - // Mutable pointer to the field. - pub fn mut_string_value(&mut self) -> &mut ::std::string::String { - if let ::std::option::Option::Some(Value_oneof_kind::string_value(_)) = self.kind { - } else { - self.kind = ::std::option::Option::Some(Value_oneof_kind::string_value(::std::string::String::new())); - } - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::string_value(ref mut v)) => v, - _ => panic!(), - } - } - - // Take field - pub fn take_string_value(&mut self) -> ::std::string::String { - if self.has_string_value() { - match self.kind.take() { - ::std::option::Option::Some(Value_oneof_kind::string_value(v)) => v, - _ => panic!(), - } - } else { - ::std::string::String::new() - } - } - - // bool bool_value = 4; - - - pub fn get_bool_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::bool_value(v)) => v, - _ => false, - } - } - pub fn clear_bool_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_bool_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::bool_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_bool_value(&mut self, v: bool) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::bool_value(v)) - } - - // .google.protobuf.Struct struct_value = 5; - - - pub fn get_struct_value(&self) -> &Struct { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::struct_value(ref v)) => v, - _ => <Struct as crate::Message>::default_instance(), - } - } - pub fn clear_struct_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_struct_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::struct_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_struct_value(&mut self, v: Struct) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::struct_value(v)) - } - - // Mutable pointer to the field. - pub fn mut_struct_value(&mut self) -> &mut Struct { - if let ::std::option::Option::Some(Value_oneof_kind::struct_value(_)) = self.kind { - } else { - self.kind = ::std::option::Option::Some(Value_oneof_kind::struct_value(Struct::new())); - } - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::struct_value(ref mut v)) => v, - _ => panic!(), - } - } - - // Take field - pub fn take_struct_value(&mut self) -> Struct { - if self.has_struct_value() { - match self.kind.take() { - ::std::option::Option::Some(Value_oneof_kind::struct_value(v)) => v, - _ => panic!(), - } - } else { - Struct::new() - } - } - - // .google.protobuf.ListValue list_value = 6; - - - pub fn get_list_value(&self) -> &ListValue { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::list_value(ref v)) => v, - _ => <ListValue as crate::Message>::default_instance(), - } - } - pub fn clear_list_value(&mut self) { - self.kind = ::std::option::Option::None; - } - - pub fn has_list_value(&self) -> bool { - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::list_value(..)) => true, - _ => false, - } - } - - // Param is passed by value, moved - pub fn set_list_value(&mut self, v: ListValue) { - self.kind = ::std::option::Option::Some(Value_oneof_kind::list_value(v)) - } - - // Mutable pointer to the field. - pub fn mut_list_value(&mut self) -> &mut ListValue { - if let ::std::option::Option::Some(Value_oneof_kind::list_value(_)) = self.kind { - } else { - self.kind = ::std::option::Option::Some(Value_oneof_kind::list_value(ListValue::new())); - } - match self.kind { - ::std::option::Option::Some(Value_oneof_kind::list_value(ref mut v)) => v, - _ => panic!(), - } - } - - // Take field - pub fn take_list_value(&mut self) -> ListValue { - if self.has_list_value() { - match self.kind.take() { - ::std::option::Option::Some(Value_oneof_kind::list_value(v)) => v, - _ => panic!(), - } - } else { - ListValue::new() - } - } -} - -impl crate::Message for Value { - fn is_initialized(&self) -> bool { - if let Some(Value_oneof_kind::struct_value(ref v)) = self.kind { - if !v.is_initialized() { - return false; - } - } - if let Some(Value_oneof_kind::list_value(ref v)) = self.kind { - if !v.is_initialized() { - return false; - } - } - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::null_value(is.read_enum()?)); - }, - 2 => { - if wire_type != crate::wire_format::WireTypeFixed64 { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::number_value(is.read_double()?)); - }, - 3 => { - if wire_type != crate::wire_format::WireTypeLengthDelimited { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::string_value(is.read_string()?)); - }, - 4 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::bool_value(is.read_bool()?)); - }, - 5 => { - if wire_type != crate::wire_format::WireTypeLengthDelimited { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::struct_value(is.read_message()?)); - }, - 6 => { - if wire_type != crate::wire_format::WireTypeLengthDelimited { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - self.kind = ::std::option::Option::Some(Value_oneof_kind::list_value(is.read_message()?)); - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if let ::std::option::Option::Some(ref v) = self.kind { - match v { - &Value_oneof_kind::null_value(v) => { - my_size += crate::rt::enum_size(1, v); - }, - &Value_oneof_kind::number_value(v) => { - my_size += 9; - }, - &Value_oneof_kind::string_value(ref v) => { - my_size += crate::rt::string_size(3, &v); - }, - &Value_oneof_kind::bool_value(v) => { - my_size += 2; - }, - &Value_oneof_kind::struct_value(ref v) => { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }, - &Value_oneof_kind::list_value(ref v) => { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }, - }; - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if let ::std::option::Option::Some(ref v) = self.kind { - match v { - &Value_oneof_kind::null_value(v) => { - os.write_enum(1, crate::ProtobufEnum::value(&v))?; - }, - &Value_oneof_kind::number_value(v) => { - os.write_double(2, v)?; - }, - &Value_oneof_kind::string_value(ref v) => { - os.write_string(3, v)?; - }, - &Value_oneof_kind::bool_value(v) => { - os.write_bool(4, v)?; - }, - &Value_oneof_kind::struct_value(ref v) => { - os.write_tag(5, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }, - &Value_oneof_kind::list_value(ref v) => { - os.write_tag(6, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }, - }; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Value { - Value::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_singular_enum_accessor::<_, NullValue>( - "null_value", - Value::has_null_value, - Value::get_null_value, - )); - fields.push(crate::reflect::accessor::make_singular_f64_accessor::<_>( - "number_value", - Value::has_number_value, - Value::get_number_value, - )); - fields.push(crate::reflect::accessor::make_singular_string_accessor::<_>( - "string_value", - Value::has_string_value, - Value::get_string_value, - )); - fields.push(crate::reflect::accessor::make_singular_bool_accessor::<_>( - "bool_value", - Value::has_bool_value, - Value::get_bool_value, - )); - fields.push(crate::reflect::accessor::make_singular_message_accessor::<_, Struct>( - "struct_value", - Value::has_struct_value, - Value::get_struct_value, - )); - fields.push(crate::reflect::accessor::make_singular_message_accessor::<_, ListValue>( - "list_value", - Value::has_list_value, - Value::get_list_value, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Value>( - "Value", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Value { - static instance: crate::rt::LazyV2<Value> = crate::rt::LazyV2::INIT; - instance.get(Value::new) - } -} - -impl crate::Clear for Value { - fn clear(&mut self) { - self.kind = ::std::option::Option::None; - self.kind = ::std::option::Option::None; - self.kind = ::std::option::Option::None; - self.kind = ::std::option::Option::None; - self.kind = ::std::option::Option::None; - self.kind = ::std::option::Option::None; - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Value { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Value { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct ListValue { - // message fields - pub values: crate::RepeatedField<Value>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a ListValue { - fn default() -> &'a ListValue { - <ListValue as crate::Message>::default_instance() - } -} - -impl ListValue { - pub fn new() -> ListValue { - ::std::default::Default::default() - } - - // repeated .google.protobuf.Value values = 1; - - - pub fn get_values(&self) -> &[Value] { - &self.values - } - pub fn clear_values(&mut self) { - self.values.clear(); - } - - // Param is passed by value, moved - pub fn set_values(&mut self, v: crate::RepeatedField<Value>) { - self.values = v; - } - - // Mutable pointer to the field. - pub fn mut_values(&mut self) -> &mut crate::RepeatedField<Value> { - &mut self.values - } - - // Take field - pub fn take_values(&mut self) -> crate::RepeatedField<Value> { - ::std::mem::replace(&mut self.values, crate::RepeatedField::new()) - } -} - -impl crate::Message for ListValue { - fn is_initialized(&self) -> bool { - for v in &self.values { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.values)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - for value in &self.values { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - for v in &self.values { - os.write_tag(1, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> ListValue { - ListValue::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Value>>( - "values", - |m: &ListValue| { &m.values }, - |m: &mut ListValue| { &mut m.values }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<ListValue>( - "ListValue", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static ListValue { - static instance: crate::rt::LazyV2<ListValue> = crate::rt::LazyV2::INIT; - instance.get(ListValue::new) - } -} - -impl crate::Clear for ListValue { - fn clear(&mut self) { - self.values.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for ListValue { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for ListValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum NullValue { - NULL_VALUE = 0, -} - -impl crate::ProtobufEnum for NullValue { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<NullValue> { - match value { - 0 => ::std::option::Option::Some(NullValue::NULL_VALUE), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [NullValue] = &[ - NullValue::NULL_VALUE, - ]; - values - } - - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<NullValue>("NullValue", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for NullValue { -} - -impl ::std::default::Default for NullValue { - fn default() -> Self { - NullValue::NULL_VALUE - } -} - -impl crate::reflect::ProtobufValue for NullValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) - } -} - -static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x1cgoogle/protobuf/struct.proto\x12\x0fgoogle.protobuf\"\x98\x01\n\ - \x06Struct\x12;\n\x06fields\x18\x01\x20\x03(\x0b2#.google.protobuf.Struc\ - t.FieldsEntryR\x06fields\x1aQ\n\x0bFieldsEntry\x12\x10\n\x03key\x18\x01\ - \x20\x01(\tR\x03key\x12,\n\x05value\x18\x02\x20\x01(\x0b2\x16.google.pro\ - tobuf.ValueR\x05value:\x028\x01\"\xb2\x02\n\x05Value\x12;\n\nnull_value\ - \x18\x01\x20\x01(\x0e2\x1a.google.protobuf.NullValueH\0R\tnullValue\x12#\ - \n\x0cnumber_value\x18\x02\x20\x01(\x01H\0R\x0bnumberValue\x12#\n\x0cstr\ - ing_value\x18\x03\x20\x01(\tH\0R\x0bstringValue\x12\x1f\n\nbool_value\ - \x18\x04\x20\x01(\x08H\0R\tboolValue\x12<\n\x0cstruct_value\x18\x05\x20\ - \x01(\x0b2\x17.google.protobuf.StructH\0R\x0bstructValue\x12;\n\nlist_va\ - lue\x18\x06\x20\x01(\x0b2\x1a.google.protobuf.ListValueH\0R\tlistValueB\ - \x06\n\x04kind\";\n\tListValue\x12.\n\x06values\x18\x01\x20\x03(\x0b2\ - \x16.google.protobuf.ValueR\x06values*\x1b\n\tNullValue\x12\x0e\n\nNULL_\ - VALUE\x10\0B\x7f\n\x13com.google.protobufB\x0bStructProtoP\x01Z/google.g\ - olang.org/protobuf/types/known/structpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\ - \x02\x1eGoogle.Protobuf.WellKnownTypesJ\x99\x1d\n\x06\x12\x04\x1e\0^\x01\ - \n\xcc\x0c\n\x01\x0c\x12\x03\x1e\0\x122\xc1\x0c\x20Protocol\x20Buffers\ - \x20-\x20Google's\x20data\x20interchange\x20format\n\x20Copyright\x20200\ - 8\x20Google\x20Inc.\x20\x20All\x20rights\x20reserved.\n\x20https://devel\ - opers.google.com/protocol-buffers/\n\n\x20Redistribution\x20and\x20use\ - \x20in\x20source\x20and\x20binary\x20forms,\x20with\x20or\x20without\n\ - \x20modification,\x20are\x20permitted\x20provided\x20that\x20the\x20foll\ - owing\x20conditions\x20are\n\x20met:\n\n\x20\x20\x20\x20\x20*\x20Redistr\ - ibutions\x20of\x20source\x20code\x20must\x20retain\x20the\x20above\x20co\ - pyright\n\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\ - \x20following\x20disclaimer.\n\x20\x20\x20\x20\x20*\x20Redistributions\ - \x20in\x20binary\x20form\x20must\x20reproduce\x20the\x20above\n\x20copyr\ - ight\x20notice,\x20this\x20list\x20of\x20conditions\x20and\x20the\x20fol\ - lowing\x20disclaimer\n\x20in\x20the\x20documentation\x20and/or\x20other\ - \x20materials\x20provided\x20with\x20the\n\x20distribution.\n\x20\x20\ - \x20\x20\x20*\x20Neither\x20the\x20name\x20of\x20Google\x20Inc.\x20nor\ - \x20the\x20names\x20of\x20its\n\x20contributors\x20may\x20be\x20used\x20\ - to\x20endorse\x20or\x20promote\x20products\x20derived\x20from\n\x20this\ - \x20software\x20without\x20specific\x20prior\x20written\x20permission.\n\ - \n\x20THIS\x20SOFTWARE\x20IS\x20PROVIDED\x20BY\x20THE\x20COPYRIGHT\x20HO\ - LDERS\x20AND\x20CONTRIBUTORS\n\x20\"AS\x20IS\"\x20AND\x20ANY\x20EXPRESS\ - \x20OR\x20IMPLIED\x20WARRANTIES,\x20INCLUDING,\x20BUT\x20NOT\n\x20LIMITE\ - D\x20TO,\x20THE\x20IMPLIED\x20WARRANTIES\x20OF\x20MERCHANTABILITY\x20AND\ - \x20FITNESS\x20FOR\n\x20A\x20PARTICULAR\x20PURPOSE\x20ARE\x20DISCLAIMED.\ - \x20IN\x20NO\x20EVENT\x20SHALL\x20THE\x20COPYRIGHT\n\x20OWNER\x20OR\x20C\ - ONTRIBUTORS\x20BE\x20LIABLE\x20FOR\x20ANY\x20DIRECT,\x20INDIRECT,\x20INC\ - IDENTAL,\n\x20SPECIAL,\x20EXEMPLARY,\x20OR\x20CONSEQUENTIAL\x20DAMAGES\ - \x20(INCLUDING,\x20BUT\x20NOT\n\x20LIMITED\x20TO,\x20PROCUREMENT\x20OF\ - \x20SUBSTITUTE\x20GOODS\x20OR\x20SERVICES;\x20LOSS\x20OF\x20USE,\n\x20DA\ - TA,\x20OR\x20PROFITS;\x20OR\x20BUSINESS\x20INTERRUPTION)\x20HOWEVER\x20C\ - AUSED\x20AND\x20ON\x20ANY\n\x20THEORY\x20OF\x20LIABILITY,\x20WHETHER\x20\ - IN\x20CONTRACT,\x20STRICT\x20LIABILITY,\x20OR\x20TORT\n\x20(INCLUDING\ - \x20NEGLIGENCE\x20OR\x20OTHERWISE)\x20ARISING\x20IN\x20ANY\x20WAY\x20OUT\ - \x20OF\x20THE\x20USE\n\x20OF\x20THIS\x20SOFTWARE,\x20EVEN\x20IF\x20ADVIS\ - ED\x20OF\x20THE\x20POSSIBILITY\x20OF\x20SUCH\x20DAMAGE.\n\n\x08\n\x01\ - \x02\x12\x03\x20\0\x18\n\x08\n\x01\x08\x12\x03\"\0;\n\t\n\x02\x08%\x12\ - \x03\"\0;\n\x08\n\x01\x08\x12\x03#\0\x1f\n\t\n\x02\x08\x1f\x12\x03#\0\ - \x1f\n\x08\n\x01\x08\x12\x03$\0F\n\t\n\x02\x08\x0b\x12\x03$\0F\n\x08\n\ - \x01\x08\x12\x03%\0,\n\t\n\x02\x08\x01\x12\x03%\0,\n\x08\n\x01\x08\x12\ - \x03&\0,\n\t\n\x02\x08\x08\x12\x03&\0,\n\x08\n\x01\x08\x12\x03'\0\"\n\t\ - \n\x02\x08\n\x12\x03'\0\"\n\x08\n\x01\x08\x12\x03(\0!\n\t\n\x02\x08$\x12\ - \x03(\0!\n\xb3\x03\n\x02\x04\0\x12\x042\05\x01\x1a\xa6\x03\x20`Struct`\ - \x20represents\x20a\x20structured\x20data\x20value,\x20consisting\x20of\ - \x20fields\n\x20which\x20map\x20to\x20dynamically\x20typed\x20values.\ - \x20In\x20some\x20languages,\x20`Struct`\n\x20might\x20be\x20supported\ - \x20by\x20a\x20native\x20representation.\x20For\x20example,\x20in\n\x20s\ - cripting\x20languages\x20like\x20JS\x20a\x20struct\x20is\x20represented\ - \x20as\x20an\n\x20object.\x20The\x20details\x20of\x20that\x20representat\ - ion\x20are\x20described\x20together\n\x20with\x20the\x20proto\x20support\ - \x20for\x20the\x20language.\n\n\x20The\x20JSON\x20representation\x20for\ - \x20`Struct`\x20is\x20JSON\x20object.\n\n\n\n\x03\x04\0\x01\x12\x032\x08\ - \x0e\n9\n\x04\x04\0\x02\0\x12\x034\x02\x20\x1a,\x20Unordered\x20map\x20o\ - f\x20dynamically\x20typed\x20values.\n\n\x0c\n\x05\x04\0\x02\0\x06\x12\ - \x034\x02\x14\n\x0c\n\x05\x04\0\x02\0\x01\x12\x034\x15\x1b\n\x0c\n\x05\ - \x04\0\x02\0\x03\x12\x034\x1e\x1f\n\xc3\x02\n\x02\x04\x01\x12\x04=\0M\ - \x01\x1a\xb6\x02\x20`Value`\x20represents\x20a\x20dynamically\x20typed\ - \x20value\x20which\x20can\x20be\x20either\n\x20null,\x20a\x20number,\x20\ - a\x20string,\x20a\x20boolean,\x20a\x20recursive\x20struct\x20value,\x20o\ - r\x20a\n\x20list\x20of\x20values.\x20A\x20producer\x20of\x20value\x20is\ - \x20expected\x20to\x20set\x20one\x20of\x20that\n\x20variants,\x20absence\ - \x20of\x20any\x20variant\x20indicates\x20an\x20error.\n\n\x20The\x20JSON\ - \x20representation\x20for\x20`Value`\x20is\x20JSON\x20value.\n\n\n\n\x03\ - \x04\x01\x01\x12\x03=\x08\r\n\"\n\x04\x04\x01\x08\0\x12\x04?\x02L\x03\ - \x1a\x14\x20The\x20kind\x20of\x20value.\n\n\x0c\n\x05\x04\x01\x08\0\x01\ - \x12\x03?\x08\x0c\n'\n\x04\x04\x01\x02\0\x12\x03A\x04\x1d\x1a\x1a\x20Rep\ - resents\x20a\x20null\x20value.\n\n\x0c\n\x05\x04\x01\x02\0\x06\x12\x03A\ - \x04\r\n\x0c\n\x05\x04\x01\x02\0\x01\x12\x03A\x0e\x18\n\x0c\n\x05\x04\ - \x01\x02\0\x03\x12\x03A\x1b\x1c\n)\n\x04\x04\x01\x02\x01\x12\x03C\x04\ - \x1c\x1a\x1c\x20Represents\x20a\x20double\x20value.\n\n\x0c\n\x05\x04\ - \x01\x02\x01\x05\x12\x03C\x04\n\n\x0c\n\x05\x04\x01\x02\x01\x01\x12\x03C\ - \x0b\x17\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03C\x1a\x1b\n)\n\x04\x04\ - \x01\x02\x02\x12\x03E\x04\x1c\x1a\x1c\x20Represents\x20a\x20string\x20va\ - lue.\n\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03E\x04\n\n\x0c\n\x05\x04\ - \x01\x02\x02\x01\x12\x03E\x0b\x17\n\x0c\n\x05\x04\x01\x02\x02\x03\x12\ - \x03E\x1a\x1b\n*\n\x04\x04\x01\x02\x03\x12\x03G\x04\x18\x1a\x1d\x20Repre\ - sents\x20a\x20boolean\x20value.\n\n\x0c\n\x05\x04\x01\x02\x03\x05\x12\ - \x03G\x04\x08\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03G\t\x13\n\x0c\n\x05\ - \x04\x01\x02\x03\x03\x12\x03G\x16\x17\n-\n\x04\x04\x01\x02\x04\x12\x03I\ - \x04\x1c\x1a\x20\x20Represents\x20a\x20structured\x20value.\n\n\x0c\n\ - \x05\x04\x01\x02\x04\x06\x12\x03I\x04\n\n\x0c\n\x05\x04\x01\x02\x04\x01\ - \x12\x03I\x0b\x17\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03I\x1a\x1b\n-\n\ - \x04\x04\x01\x02\x05\x12\x03K\x04\x1d\x1a\x20\x20Represents\x20a\x20repe\ - ated\x20`Value`.\n\n\x0c\n\x05\x04\x01\x02\x05\x06\x12\x03K\x04\r\n\x0c\ - \n\x05\x04\x01\x02\x05\x01\x12\x03K\x0e\x18\n\x0c\n\x05\x04\x01\x02\x05\ - \x03\x12\x03K\x1b\x1c\n\xa9\x01\n\x02\x05\0\x12\x04S\0V\x01\x1a\x9c\x01\ - \x20`NullValue`\x20is\x20a\x20singleton\x20enumeration\x20to\x20represen\ - t\x20the\x20null\x20value\x20for\x20the\n\x20`Value`\x20type\x20union.\n\ - \n\x20\x20The\x20JSON\x20representation\x20for\x20`NullValue`\x20is\x20J\ - SON\x20`null`.\n\n\n\n\x03\x05\0\x01\x12\x03S\x05\x0e\n\x1a\n\x04\x05\0\ - \x02\0\x12\x03U\x02\x11\x1a\r\x20Null\x20value.\n\n\x0c\n\x05\x05\0\x02\ - \0\x01\x12\x03U\x02\x0c\n\x0c\n\x05\x05\0\x02\0\x02\x12\x03U\x0f\x10\n\ - \x82\x01\n\x02\x04\x02\x12\x04[\0^\x01\x1av\x20`ListValue`\x20is\x20a\ - \x20wrapper\x20around\x20a\x20repeated\x20field\x20of\x20values.\n\n\x20\ - The\x20JSON\x20representation\x20for\x20`ListValue`\x20is\x20JSON\x20arr\ - ay.\n\n\n\n\x03\x04\x02\x01\x12\x03[\x08\x11\n:\n\x04\x04\x02\x02\0\x12\ - \x03]\x02\x1c\x1a-\x20Repeated\x20field\x20of\x20dynamically\x20typed\ - \x20values.\n\n\x0c\n\x05\x04\x02\x02\0\x04\x12\x03]\x02\n\n\x0c\n\x05\ - \x04\x02\x02\0\x06\x12\x03]\x0b\x10\n\x0c\n\x05\x04\x02\x02\0\x01\x12\ - \x03]\x11\x17\n\x0c\n\x05\x04\x02\x02\0\x03\x12\x03]\x1a\x1bb\x06proto3\ -"; - -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() -} - -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() - }) -} diff --git a/src/well_known_types/timestamp.rs b/src/well_known_types/timestamp.rs index 25e7acf..8692696 100644 --- a/src/well_known_types/timestamp.rs +++ b/src/well_known_types/timestamp.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,21 +16,29 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/timestamp.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Timestamp) pub struct Timestamp { // message fields + /// Represents seconds of UTC time since Unix epoch + /// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + /// 9999-12-31T23:59:59Z inclusive. + // @@protoc_insertion_point(field:google.protobuf.Timestamp.seconds) pub seconds: i64, + /// Non-negative fractions of a second at nanosecond resolution. Negative + /// second values with fractions must still have non-negative nanos values + /// that count forward in time. Must be from 0 to 999,999,999 + /// inclusive. + // @@protoc_insertion_point(field:google.protobuf.Timestamp.nanos) pub nanos: i32, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Timestamp.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Timestamp { @@ -43,62 +52,45 @@ impl Timestamp { ::std::default::Default::default() } - // int64 seconds = 1; - - - pub fn get_seconds(&self) -> i64 { - self.seconds - } - pub fn clear_seconds(&mut self) { - self.seconds = 0; - } - - // Param is passed by value, moved - pub fn set_seconds(&mut self, v: i64) { - self.seconds = v; - } - - // int32 nanos = 2; - - - pub fn get_nanos(&self) -> i32 { - self.nanos - } - pub fn clear_nanos(&mut self) { - self.nanos = 0; - } - - // Param is passed by value, moved - pub fn set_nanos(&mut self, v: i32) { - self.nanos = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "seconds", + |m: &Timestamp| { &m.seconds }, + |m: &mut Timestamp| { &mut m.seconds }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "nanos", + |m: &Timestamp| { &m.nanos }, + |m: &mut Timestamp| { &mut m.nanos }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Timestamp>( + "Timestamp", + fields, + oneofs, + ) } } impl crate::Message for Timestamp { + const NAME: &'static str = "Timestamp"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int64()?; - self.seconds = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.seconds = is.read_int64()?; }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.nanos = tmp; + 16 => { + self.nanos = is.read_int32()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -107,106 +99,73 @@ impl crate::Message for Timestamp { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.seconds != 0 { - my_size += crate::rt::value_size(1, self.seconds, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int64_size(1, self.seconds); } if self.nanos != 0 { - my_size += crate::rt::value_size(2, self.nanos, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(2, self.nanos); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.seconds != 0 { os.write_int64(1, self.seconds)?; } if self.nanos != 0 { os.write_int32(2, self.nanos)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Timestamp { Timestamp::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt64>( - "seconds", - |m: &Timestamp| { &m.seconds }, - |m: &mut Timestamp| { &mut m.seconds }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "nanos", - |m: &Timestamp| { &m.nanos }, - |m: &mut Timestamp| { &mut m.nanos }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Timestamp>( - "Timestamp", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.seconds = 0; + self.nanos = 0; + self.special_fields.clear(); } fn default_instance() -> &'static Timestamp { - static instance: crate::rt::LazyV2<Timestamp> = crate::rt::LazyV2::INIT; - instance.get(Timestamp::new) + static instance: Timestamp = Timestamp { + seconds: 0, + nanos: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Timestamp { - fn clear(&mut self) { - self.seconds = 0; - self.nanos = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for Timestamp { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Timestamp").unwrap()).clone() } } -impl ::std::fmt::Debug for Timestamp { +impl ::std::fmt::Display for Timestamp { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Timestamp { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -350,14 +309,31 @@ static file_descriptor_proto_data: &'static [u8] = b"\ \x03\x12\x04\x91\x01\x10\x11b\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(1); + messages.push(Timestamp::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types/type_.rs b/src/well_known_types/type_.rs new file mode 100644 index 0000000..a342830 --- /dev/null +++ b/src/well_known_types/type_.rs @@ -0,0 +1,1626 @@ +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... +// @generated + +// https://github.com/rust-lang/rust-clippy/issues/702 +#![allow(unknown_lints)] +#![allow(clippy::all)] + +#![allow(unused_attributes)] +#![cfg_attr(rustfmt, rustfmt::skip)] + +#![allow(box_pointers)] +#![allow(dead_code)] +#![allow(missing_docs)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(trivial_casts)] +#![allow(unused_results)] +#![allow(unused_mut)] + +//! Generated file from `google/protobuf/type.proto` + +/// A protocol buffer message type. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Type) +pub struct Type { + // message fields + /// The fully qualified message name. + // @@protoc_insertion_point(field:google.protobuf.Type.name) + pub name: ::std::string::String, + /// The list of fields. + // @@protoc_insertion_point(field:google.protobuf.Type.fields) + pub fields: ::std::vec::Vec<Field>, + /// The list of types appearing in `oneof` definitions in this type. + // @@protoc_insertion_point(field:google.protobuf.Type.oneofs) + pub oneofs: ::std::vec::Vec<::std::string::String>, + /// The protocol buffer options. + // @@protoc_insertion_point(field:google.protobuf.Type.options) + pub options: ::std::vec::Vec<Option>, + /// The source context. + // @@protoc_insertion_point(field:google.protobuf.Type.source_context) + pub source_context: crate::MessageField<crate::well_known_types::source_context::SourceContext>, + /// The source syntax. + // @@protoc_insertion_point(field:google.protobuf.Type.syntax) + pub syntax: crate::EnumOrUnknown<Syntax>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Type.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Type { + fn default() -> &'a Type { + <Type as crate::Message>::default_instance() + } +} + +impl Type { + pub fn new() -> Type { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(6); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Type| { &m.name }, + |m: &mut Type| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "fields", + |m: &Type| { &m.fields }, + |m: &mut Type| { &mut m.fields }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "oneofs", + |m: &Type| { &m.oneofs }, + |m: &mut Type| { &mut m.oneofs }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &Type| { &m.options }, + |m: &mut Type| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, crate::well_known_types::source_context::SourceContext>( + "source_context", + |m: &Type| { &m.source_context }, + |m: &mut Type| { &mut m.source_context }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "syntax", + |m: &Type| { &m.syntax }, + |m: &mut Type| { &mut m.syntax }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Type>( + "Type", + fields, + oneofs, + ) + } +} + +impl crate::Message for Type { + const NAME: &'static str = "Type"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; + }, + 18 => { + self.fields.push(is.read_message()?); + }, + 26 => { + self.oneofs.push(is.read_string()?); + }, + 34 => { + self.options.push(is.read_message()?); + }, + 42 => { + crate::rt::read_singular_message_into_field(is, &mut self.source_context)?; + }, + 48 => { + self.syntax = is.read_enum_or_unknown()?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if !self.name.is_empty() { + my_size += crate::rt::string_size(1, &self.name); + } + for value in &self.fields { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + for value in &self.oneofs { + my_size += crate::rt::string_size(3, &value); + }; + for value in &self.options { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + if let Some(v) = self.source_context.as_ref() { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + } + if self.syntax != crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2) { + my_size += crate::rt::int32_size(6, self.syntax.value()); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if !self.name.is_empty() { + os.write_string(1, &self.name)?; + } + for v in &self.fields { + crate::rt::write_message_field_with_cached_size(2, v, os)?; + }; + for v in &self.oneofs { + os.write_string(3, &v)?; + }; + for v in &self.options { + crate::rt::write_message_field_with_cached_size(4, v, os)?; + }; + if let Some(v) = self.source_context.as_ref() { + crate::rt::write_message_field_with_cached_size(5, v, os)?; + } + if self.syntax != crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2) { + os.write_enum(6, crate::EnumOrUnknown::value(&self.syntax))?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Type { + Type::new() + } + + fn clear(&mut self) { + self.name.clear(); + self.fields.clear(); + self.oneofs.clear(); + self.options.clear(); + self.source_context.clear(); + self.syntax = crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Type { + static instance: Type = Type { + name: ::std::string::String::new(), + fields: ::std::vec::Vec::new(), + oneofs: ::std::vec::Vec::new(), + options: ::std::vec::Vec::new(), + source_context: crate::MessageField::none(), + syntax: crate::EnumOrUnknown::from_i32(0), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Type { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Type").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Type { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Type { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// A single field of a message type. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Field) +pub struct Field { + // message fields + /// The field type. + // @@protoc_insertion_point(field:google.protobuf.Field.kind) + pub kind: crate::EnumOrUnknown<field::Kind>, + /// The field cardinality. + // @@protoc_insertion_point(field:google.protobuf.Field.cardinality) + pub cardinality: crate::EnumOrUnknown<field::Cardinality>, + /// The field number. + // @@protoc_insertion_point(field:google.protobuf.Field.number) + pub number: i32, + /// The field name. + // @@protoc_insertion_point(field:google.protobuf.Field.name) + pub name: ::std::string::String, + /// The field type URL, without the scheme, for message or enumeration + /// types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. + // @@protoc_insertion_point(field:google.protobuf.Field.type_url) + pub type_url: ::std::string::String, + /// 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. + // @@protoc_insertion_point(field:google.protobuf.Field.oneof_index) + pub oneof_index: i32, + /// Whether to use alternative packed wire representation. + // @@protoc_insertion_point(field:google.protobuf.Field.packed) + pub packed: bool, + /// The protocol buffer options. + // @@protoc_insertion_point(field:google.protobuf.Field.options) + pub options: ::std::vec::Vec<Option>, + /// The field JSON name. + // @@protoc_insertion_point(field:google.protobuf.Field.json_name) + pub json_name: ::std::string::String, + /// The string value of the default value of this field. Proto2 syntax only. + // @@protoc_insertion_point(field:google.protobuf.Field.default_value) + pub default_value: ::std::string::String, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Field.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Field { + fn default() -> &'a Field { + <Field as crate::Message>::default_instance() + } +} + +impl Field { + pub fn new() -> Field { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(10); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "kind", + |m: &Field| { &m.kind }, + |m: &mut Field| { &mut m.kind }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "cardinality", + |m: &Field| { &m.cardinality }, + |m: &mut Field| { &mut m.cardinality }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "number", + |m: &Field| { &m.number }, + |m: &mut Field| { &mut m.number }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Field| { &m.name }, + |m: &mut Field| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "type_url", + |m: &Field| { &m.type_url }, + |m: &mut Field| { &mut m.type_url }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "oneof_index", + |m: &Field| { &m.oneof_index }, + |m: &mut Field| { &mut m.oneof_index }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "packed", + |m: &Field| { &m.packed }, + |m: &mut Field| { &mut m.packed }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &Field| { &m.options }, + |m: &mut Field| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "json_name", + |m: &Field| { &m.json_name }, + |m: &mut Field| { &mut m.json_name }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "default_value", + |m: &Field| { &m.default_value }, + |m: &mut Field| { &mut m.default_value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Field>( + "Field", + fields, + oneofs, + ) + } +} + +impl crate::Message for Field { + const NAME: &'static str = "Field"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.kind = is.read_enum_or_unknown()?; + }, + 16 => { + self.cardinality = is.read_enum_or_unknown()?; + }, + 24 => { + self.number = is.read_int32()?; + }, + 34 => { + self.name = is.read_string()?; + }, + 50 => { + self.type_url = is.read_string()?; + }, + 56 => { + self.oneof_index = is.read_int32()?; + }, + 64 => { + self.packed = is.read_bool()?; + }, + 74 => { + self.options.push(is.read_message()?); + }, + 82 => { + self.json_name = is.read_string()?; + }, + 90 => { + self.default_value = is.read_string()?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if self.kind != crate::EnumOrUnknown::new(field::Kind::TYPE_UNKNOWN) { + my_size += crate::rt::int32_size(1, self.kind.value()); + } + if self.cardinality != crate::EnumOrUnknown::new(field::Cardinality::CARDINALITY_UNKNOWN) { + my_size += crate::rt::int32_size(2, self.cardinality.value()); + } + if self.number != 0 { + my_size += crate::rt::int32_size(3, self.number); + } + if !self.name.is_empty() { + my_size += crate::rt::string_size(4, &self.name); + } + if !self.type_url.is_empty() { + my_size += crate::rt::string_size(6, &self.type_url); + } + if self.oneof_index != 0 { + my_size += crate::rt::int32_size(7, self.oneof_index); + } + if self.packed != false { + my_size += 1 + 1; + } + for value in &self.options { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + if !self.json_name.is_empty() { + my_size += crate::rt::string_size(10, &self.json_name); + } + if !self.default_value.is_empty() { + my_size += crate::rt::string_size(11, &self.default_value); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if self.kind != crate::EnumOrUnknown::new(field::Kind::TYPE_UNKNOWN) { + os.write_enum(1, crate::EnumOrUnknown::value(&self.kind))?; + } + if self.cardinality != crate::EnumOrUnknown::new(field::Cardinality::CARDINALITY_UNKNOWN) { + os.write_enum(2, crate::EnumOrUnknown::value(&self.cardinality))?; + } + if self.number != 0 { + os.write_int32(3, self.number)?; + } + if !self.name.is_empty() { + os.write_string(4, &self.name)?; + } + if !self.type_url.is_empty() { + os.write_string(6, &self.type_url)?; + } + if self.oneof_index != 0 { + os.write_int32(7, self.oneof_index)?; + } + if self.packed != false { + os.write_bool(8, self.packed)?; + } + for v in &self.options { + crate::rt::write_message_field_with_cached_size(9, v, os)?; + }; + if !self.json_name.is_empty() { + os.write_string(10, &self.json_name)?; + } + if !self.default_value.is_empty() { + os.write_string(11, &self.default_value)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Field { + Field::new() + } + + fn clear(&mut self) { + self.kind = crate::EnumOrUnknown::new(field::Kind::TYPE_UNKNOWN); + self.cardinality = crate::EnumOrUnknown::new(field::Cardinality::CARDINALITY_UNKNOWN); + self.number = 0; + self.name.clear(); + self.type_url.clear(); + self.oneof_index = 0; + self.packed = false; + self.options.clear(); + self.json_name.clear(); + self.default_value.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Field { + static instance: Field = Field { + kind: crate::EnumOrUnknown::from_i32(0), + cardinality: crate::EnumOrUnknown::from_i32(0), + number: 0, + name: ::std::string::String::new(), + type_url: ::std::string::String::new(), + oneof_index: 0, + packed: false, + options: ::std::vec::Vec::new(), + json_name: ::std::string::String::new(), + default_value: ::std::string::String::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Field { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Field").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Field { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Field { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Nested message and enums of message `Field` +pub mod field { + /// Basic field types. + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.Field.Kind) + pub enum Kind { + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_UNKNOWN) + TYPE_UNKNOWN = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_DOUBLE) + TYPE_DOUBLE = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_FLOAT) + TYPE_FLOAT = 2, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_INT64) + TYPE_INT64 = 3, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_UINT64) + TYPE_UINT64 = 4, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_INT32) + TYPE_INT32 = 5, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_FIXED64) + TYPE_FIXED64 = 6, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_FIXED32) + TYPE_FIXED32 = 7, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_BOOL) + TYPE_BOOL = 8, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_STRING) + TYPE_STRING = 9, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_GROUP) + TYPE_GROUP = 10, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_MESSAGE) + TYPE_MESSAGE = 11, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_BYTES) + TYPE_BYTES = 12, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_UINT32) + TYPE_UINT32 = 13, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_ENUM) + TYPE_ENUM = 14, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_SFIXED32) + TYPE_SFIXED32 = 15, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_SFIXED64) + TYPE_SFIXED64 = 16, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_SINT32) + TYPE_SINT32 = 17, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Kind.TYPE_SINT64) + TYPE_SINT64 = 18, + } + + impl crate::Enum for Kind { + const NAME: &'static str = "Kind"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<Kind> { + match value { + 0 => ::std::option::Option::Some(Kind::TYPE_UNKNOWN), + 1 => ::std::option::Option::Some(Kind::TYPE_DOUBLE), + 2 => ::std::option::Option::Some(Kind::TYPE_FLOAT), + 3 => ::std::option::Option::Some(Kind::TYPE_INT64), + 4 => ::std::option::Option::Some(Kind::TYPE_UINT64), + 5 => ::std::option::Option::Some(Kind::TYPE_INT32), + 6 => ::std::option::Option::Some(Kind::TYPE_FIXED64), + 7 => ::std::option::Option::Some(Kind::TYPE_FIXED32), + 8 => ::std::option::Option::Some(Kind::TYPE_BOOL), + 9 => ::std::option::Option::Some(Kind::TYPE_STRING), + 10 => ::std::option::Option::Some(Kind::TYPE_GROUP), + 11 => ::std::option::Option::Some(Kind::TYPE_MESSAGE), + 12 => ::std::option::Option::Some(Kind::TYPE_BYTES), + 13 => ::std::option::Option::Some(Kind::TYPE_UINT32), + 14 => ::std::option::Option::Some(Kind::TYPE_ENUM), + 15 => ::std::option::Option::Some(Kind::TYPE_SFIXED32), + 16 => ::std::option::Option::Some(Kind::TYPE_SFIXED64), + 17 => ::std::option::Option::Some(Kind::TYPE_SINT32), + 18 => ::std::option::Option::Some(Kind::TYPE_SINT64), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [Kind] = &[ + Kind::TYPE_UNKNOWN, + Kind::TYPE_DOUBLE, + Kind::TYPE_FLOAT, + Kind::TYPE_INT64, + Kind::TYPE_UINT64, + Kind::TYPE_INT32, + Kind::TYPE_FIXED64, + Kind::TYPE_FIXED32, + Kind::TYPE_BOOL, + Kind::TYPE_STRING, + Kind::TYPE_GROUP, + Kind::TYPE_MESSAGE, + Kind::TYPE_BYTES, + Kind::TYPE_UINT32, + Kind::TYPE_ENUM, + Kind::TYPE_SFIXED32, + Kind::TYPE_SFIXED64, + Kind::TYPE_SINT32, + Kind::TYPE_SINT64, + ]; + } + + impl crate::EnumFull for Kind { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("Field.Kind").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } + } + + impl ::std::default::Default for Kind { + fn default() -> Self { + Kind::TYPE_UNKNOWN + } + } + + impl Kind { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Kind>("Field.Kind") + } + } + + /// Whether a field is optional, required, or repeated. + #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] + // @@protoc_insertion_point(enum:google.protobuf.Field.Cardinality) + pub enum Cardinality { + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Cardinality.CARDINALITY_UNKNOWN) + CARDINALITY_UNKNOWN = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Cardinality.CARDINALITY_OPTIONAL) + CARDINALITY_OPTIONAL = 1, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Cardinality.CARDINALITY_REQUIRED) + CARDINALITY_REQUIRED = 2, + // @@protoc_insertion_point(enum_value:google.protobuf.Field.Cardinality.CARDINALITY_REPEATED) + CARDINALITY_REPEATED = 3, + } + + impl crate::Enum for Cardinality { + const NAME: &'static str = "Cardinality"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<Cardinality> { + match value { + 0 => ::std::option::Option::Some(Cardinality::CARDINALITY_UNKNOWN), + 1 => ::std::option::Option::Some(Cardinality::CARDINALITY_OPTIONAL), + 2 => ::std::option::Option::Some(Cardinality::CARDINALITY_REQUIRED), + 3 => ::std::option::Option::Some(Cardinality::CARDINALITY_REPEATED), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [Cardinality] = &[ + Cardinality::CARDINALITY_UNKNOWN, + Cardinality::CARDINALITY_OPTIONAL, + Cardinality::CARDINALITY_REQUIRED, + Cardinality::CARDINALITY_REPEATED, + ]; + } + + impl crate::EnumFull for Cardinality { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| super::file_descriptor().enum_by_package_relative_name("Field.Cardinality").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } + } + + impl ::std::default::Default for Cardinality { + fn default() -> Self { + Cardinality::CARDINALITY_UNKNOWN + } + } + + impl Cardinality { + pub(in super) fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Cardinality>("Field.Cardinality") + } + } +} + +/// Enum type definition. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Enum) +pub struct Enum { + // message fields + /// Enum type name. + // @@protoc_insertion_point(field:google.protobuf.Enum.name) + pub name: ::std::string::String, + /// Enum value definitions. + // @@protoc_insertion_point(field:google.protobuf.Enum.enumvalue) + pub enumvalue: ::std::vec::Vec<EnumValue>, + /// Protocol buffer options. + // @@protoc_insertion_point(field:google.protobuf.Enum.options) + pub options: ::std::vec::Vec<Option>, + /// The source context. + // @@protoc_insertion_point(field:google.protobuf.Enum.source_context) + pub source_context: crate::MessageField<crate::well_known_types::source_context::SourceContext>, + /// The source syntax. + // @@protoc_insertion_point(field:google.protobuf.Enum.syntax) + pub syntax: crate::EnumOrUnknown<Syntax>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Enum.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Enum { + fn default() -> &'a Enum { + <Enum as crate::Message>::default_instance() + } +} + +impl Enum { + pub fn new() -> Enum { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(5); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Enum| { &m.name }, + |m: &mut Enum| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "enumvalue", + |m: &Enum| { &m.enumvalue }, + |m: &mut Enum| { &mut m.enumvalue }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &Enum| { &m.options }, + |m: &mut Enum| { &mut m.options }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, crate::well_known_types::source_context::SourceContext>( + "source_context", + |m: &Enum| { &m.source_context }, + |m: &mut Enum| { &mut m.source_context }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "syntax", + |m: &Enum| { &m.syntax }, + |m: &mut Enum| { &mut m.syntax }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Enum>( + "Enum", + fields, + oneofs, + ) + } +} + +impl crate::Message for Enum { + const NAME: &'static str = "Enum"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; + }, + 18 => { + self.enumvalue.push(is.read_message()?); + }, + 26 => { + self.options.push(is.read_message()?); + }, + 34 => { + crate::rt::read_singular_message_into_field(is, &mut self.source_context)?; + }, + 40 => { + self.syntax = is.read_enum_or_unknown()?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if !self.name.is_empty() { + my_size += crate::rt::string_size(1, &self.name); + } + for value in &self.enumvalue { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + for value in &self.options { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + if let Some(v) = self.source_context.as_ref() { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + } + if self.syntax != crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2) { + my_size += crate::rt::int32_size(5, self.syntax.value()); + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if !self.name.is_empty() { + os.write_string(1, &self.name)?; + } + for v in &self.enumvalue { + crate::rt::write_message_field_with_cached_size(2, v, os)?; + }; + for v in &self.options { + crate::rt::write_message_field_with_cached_size(3, v, os)?; + }; + if let Some(v) = self.source_context.as_ref() { + crate::rt::write_message_field_with_cached_size(4, v, os)?; + } + if self.syntax != crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2) { + os.write_enum(5, crate::EnumOrUnknown::value(&self.syntax))?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Enum { + Enum::new() + } + + fn clear(&mut self) { + self.name.clear(); + self.enumvalue.clear(); + self.options.clear(); + self.source_context.clear(); + self.syntax = crate::EnumOrUnknown::new(Syntax::SYNTAX_PROTO2); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Enum { + static instance: Enum = Enum { + name: ::std::string::String::new(), + enumvalue: ::std::vec::Vec::new(), + options: ::std::vec::Vec::new(), + source_context: crate::MessageField::none(), + syntax: crate::EnumOrUnknown::from_i32(0), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Enum { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Enum").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Enum { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Enum { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// Enum value definition. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.EnumValue) +pub struct EnumValue { + // message fields + /// Enum value name. + // @@protoc_insertion_point(field:google.protobuf.EnumValue.name) + pub name: ::std::string::String, + /// Enum value number. + // @@protoc_insertion_point(field:google.protobuf.EnumValue.number) + pub number: i32, + /// Protocol buffer options. + // @@protoc_insertion_point(field:google.protobuf.EnumValue.options) + pub options: ::std::vec::Vec<Option>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.EnumValue.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a EnumValue { + fn default() -> &'a EnumValue { + <EnumValue as crate::Message>::default_instance() + } +} + +impl EnumValue { + pub fn new() -> EnumValue { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(3); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &EnumValue| { &m.name }, + |m: &mut EnumValue| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "number", + |m: &EnumValue| { &m.number }, + |m: &mut EnumValue| { &mut m.number }, + )); + fields.push(crate::reflect::rt::v2::make_vec_simpler_accessor::<_, _>( + "options", + |m: &EnumValue| { &m.options }, + |m: &mut EnumValue| { &mut m.options }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<EnumValue>( + "EnumValue", + fields, + oneofs, + ) + } +} + +impl crate::Message for EnumValue { + const NAME: &'static str = "EnumValue"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; + }, + 16 => { + self.number = is.read_int32()?; + }, + 26 => { + self.options.push(is.read_message()?); + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if !self.name.is_empty() { + my_size += crate::rt::string_size(1, &self.name); + } + if self.number != 0 { + my_size += crate::rt::int32_size(2, self.number); + } + for value in &self.options { + let len = value.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + }; + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if !self.name.is_empty() { + os.write_string(1, &self.name)?; + } + if self.number != 0 { + os.write_int32(2, self.number)?; + } + for v in &self.options { + crate::rt::write_message_field_with_cached_size(3, v, os)?; + }; + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> EnumValue { + EnumValue::new() + } + + fn clear(&mut self) { + self.name.clear(); + self.number = 0; + self.options.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static EnumValue { + static instance: EnumValue = EnumValue { + name: ::std::string::String::new(), + number: 0, + options: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for EnumValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("EnumValue").unwrap()).clone() + } +} + +impl ::std::fmt::Display for EnumValue { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for EnumValue { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// A protocol buffer option, which can be attached to a message, field, +/// enumeration, etc. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Option) +pub struct Option { + // message fields + /// 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"`. + // @@protoc_insertion_point(field:google.protobuf.Option.name) + pub name: ::std::string::String, + /// 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. + // @@protoc_insertion_point(field:google.protobuf.Option.value) + pub value: crate::MessageField<crate::well_known_types::any::Any>, + // special fields + // @@protoc_insertion_point(special_field:google.protobuf.Option.special_fields) + pub special_fields: crate::SpecialFields, +} + +impl<'a> ::std::default::Default for &'a Option { + fn default() -> &'a Option { + <Option as crate::Message>::default_instance() + } +} + +impl Option { + pub fn new() -> Option { + ::std::default::Default::default() + } + + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(2); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "name", + |m: &Option| { &m.name }, + |m: &mut Option| { &mut m.name }, + )); + fields.push(crate::reflect::rt::v2::make_message_field_accessor::<_, crate::well_known_types::any::Any>( + "value", + |m: &Option| { &m.value }, + |m: &mut Option| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Option>( + "Option", + fields, + oneofs, + ) + } +} + +impl crate::Message for Option { + const NAME: &'static str = "Option"; + + fn is_initialized(&self) -> bool { + true + } + + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.name = is.read_string()?; + }, + 18 => { + crate::rt::read_singular_message_into_field(is, &mut self.value)?; + }, + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; + }, + }; + } + ::std::result::Result::Ok(()) + } + + // Compute sizes of nested messages + #[allow(unused_variables)] + fn compute_size(&self) -> u64 { + let mut my_size = 0; + if !self.name.is_empty() { + my_size += crate::rt::string_size(1, &self.name); + } + if let Some(v) = self.value.as_ref() { + let len = v.compute_size(); + my_size += 1 + crate::rt::compute_raw_varint64_size(len) + len; + } + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); + my_size + } + + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { + if !self.name.is_empty() { + os.write_string(1, &self.name)?; + } + if let Some(v) = self.value.as_ref() { + crate::rt::write_message_field_with_cached_size(2, v, os)?; + } + os.write_unknown_fields(self.special_fields.unknown_fields())?; + ::std::result::Result::Ok(()) + } + + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields + } + + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields + } + + fn new() -> Option { + Option::new() + } + + fn clear(&mut self) { + self.name.clear(); + self.value.clear(); + self.special_fields.clear(); + } + + fn default_instance() -> &'static Option { + static instance: Option = Option { + name: ::std::string::String::new(), + value: crate::MessageField::none(), + special_fields: crate::SpecialFields::new(), + }; + &instance + } +} + +impl crate::MessageFull for Option { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Option").unwrap()).clone() + } +} + +impl ::std::fmt::Display for Option { + fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + crate::text_format::fmt(self, f) + } +} + +impl crate::reflect::ProtobufValue for Option { + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; +} + +/// The syntax in which a protocol buffer element is defined. +#[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] +// @@protoc_insertion_point(enum:google.protobuf.Syntax) +pub enum Syntax { + // @@protoc_insertion_point(enum_value:google.protobuf.Syntax.SYNTAX_PROTO2) + SYNTAX_PROTO2 = 0, + // @@protoc_insertion_point(enum_value:google.protobuf.Syntax.SYNTAX_PROTO3) + SYNTAX_PROTO3 = 1, +} + +impl crate::Enum for Syntax { + const NAME: &'static str = "Syntax"; + + fn value(&self) -> i32 { + *self as i32 + } + + fn from_i32(value: i32) -> ::std::option::Option<Syntax> { + match value { + 0 => ::std::option::Option::Some(Syntax::SYNTAX_PROTO2), + 1 => ::std::option::Option::Some(Syntax::SYNTAX_PROTO3), + _ => ::std::option::Option::None + } + } + + const VALUES: &'static [Syntax] = &[ + Syntax::SYNTAX_PROTO2, + Syntax::SYNTAX_PROTO3, + ]; +} + +impl crate::EnumFull for Syntax { + fn enum_descriptor() -> crate::reflect::EnumDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::EnumDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().enum_by_package_relative_name("Syntax").unwrap()).clone() + } + + fn descriptor(&self) -> crate::reflect::EnumValueDescriptor { + let index = *self as usize; + Self::enum_descriptor().value_by_index(index) + } +} + +impl ::std::default::Default for Syntax { + fn default() -> Self { + Syntax::SYNTAX_PROTO2 + } +} + +impl Syntax { + fn generated_enum_descriptor_data() -> crate::reflect::GeneratedEnumDescriptorData { + crate::reflect::GeneratedEnumDescriptorData::new::<Syntax>("Syntax") + } +} + +static file_descriptor_proto_data: &'static [u8] = b"\ + \n\x1agoogle/protobuf/type.proto\x12\x0fgoogle.protobuf\x1a\x19google/pr\ + otobuf/any.proto\x1a$google/protobuf/source_context.proto\"\x8d\x02\n\ + \x04Type\x12\x12\n\x04name\x18\x01\x20\x01(\tR\x04name\x12.\n\x06fields\ + \x18\x02\x20\x03(\x0b2\x16.google.protobuf.FieldR\x06fields\x12\x16\n\ + \x06oneofs\x18\x03\x20\x03(\tR\x06oneofs\x121\n\x07options\x18\x04\x20\ + \x03(\x0b2\x17.google.protobuf.OptionR\x07options\x12E\n\x0esource_conte\ + xt\x18\x05\x20\x01(\x0b2\x1e.google.protobuf.SourceContextR\rsourceConte\ + xt\x12/\n\x06syntax\x18\x06\x20\x01(\x0e2\x17.google.protobuf.SyntaxR\ + \x06syntax\"\xb4\x06\n\x05Field\x12/\n\x04kind\x18\x01\x20\x01(\x0e2\x1b\ + .google.protobuf.Field.KindR\x04kind\x12D\n\x0bcardinality\x18\x02\x20\ + \x01(\x0e2\".google.protobuf.Field.CardinalityR\x0bcardinality\x12\x16\n\ + \x06number\x18\x03\x20\x01(\x05R\x06number\x12\x12\n\x04name\x18\x04\x20\ + \x01(\tR\x04name\x12\x19\n\x08type_url\x18\x06\x20\x01(\tR\x07typeUrl\ + \x12\x1f\n\x0boneof_index\x18\x07\x20\x01(\x05R\noneofIndex\x12\x16\n\ + \x06packed\x18\x08\x20\x01(\x08R\x06packed\x121\n\x07options\x18\t\x20\ + \x03(\x0b2\x17.google.protobuf.OptionR\x07options\x12\x1b\n\tjson_name\ + \x18\n\x20\x01(\tR\x08jsonName\x12#\n\rdefault_value\x18\x0b\x20\x01(\tR\ + \x0cdefaultValue\"\xc8\x02\n\x04Kind\x12\x10\n\x0cTYPE_UNKNOWN\x10\0\x12\ + \x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nT\ + YPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\ + \x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\ + \x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\ + \nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYT\ + ES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\ + \x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\ + \x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"t\n\x0bCardina\ + lity\x12\x17\n\x13CARDINALITY_UNKNOWN\x10\0\x12\x18\n\x14CARDINALITY_OPT\ + IONAL\x10\x01\x12\x18\n\x14CARDINALITY_REQUIRED\x10\x02\x12\x18\n\x14CAR\ + DINALITY_REPEATED\x10\x03\"\xff\x01\n\x04Enum\x12\x12\n\x04name\x18\x01\ + \x20\x01(\tR\x04name\x128\n\tenumvalue\x18\x02\x20\x03(\x0b2\x1a.google.\ + protobuf.EnumValueR\tenumvalue\x121\n\x07options\x18\x03\x20\x03(\x0b2\ + \x17.google.protobuf.OptionR\x07options\x12E\n\x0esource_context\x18\x04\ + \x20\x01(\x0b2\x1e.google.protobuf.SourceContextR\rsourceContext\x12/\n\ + \x06syntax\x18\x05\x20\x01(\x0e2\x17.google.protobuf.SyntaxR\x06syntax\"\ + j\n\tEnumValue\x12\x12\n\x04name\x18\x01\x20\x01(\tR\x04name\x12\x16\n\ + \x06number\x18\x02\x20\x01(\x05R\x06number\x121\n\x07options\x18\x03\x20\ + \x03(\x0b2\x17.google.protobuf.OptionR\x07options\"H\n\x06Option\x12\x12\ + \n\x04name\x18\x01\x20\x01(\tR\x04name\x12*\n\x05value\x18\x02\x20\x01(\ + \x0b2\x14.google.protobuf.AnyR\x05value*.\n\x06Syntax\x12\x11\n\rSYNTAX_\ + PROTO2\x10\0\x12\x11\n\rSYNTAX_PROTO3\x10\x01B{\n\x13com.google.protobuf\ + B\tTypeProtoP\x01Z-google.golang.org/protobuf/types/known/typepb\xf8\x01\ + \x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesJ\xc38\n\ + \x07\x12\x05\x1e\0\xba\x01\x01\n\xcc\x0c\n\x01\x0c\x12\x03\x1e\0\x122\ + \xc1\x0c\x20Protocol\x20Buffers\x20-\x20Google's\x20data\x20interchange\ + \x20format\n\x20Copyright\x202008\x20Google\x20Inc.\x20\x20All\x20rights\ + \x20reserved.\n\x20https://developers.google.com/protocol-buffers/\n\n\ + \x20Redistribution\x20and\x20use\x20in\x20source\x20and\x20binary\x20for\ + ms,\x20with\x20or\x20without\n\x20modification,\x20are\x20permitted\x20p\ + rovided\x20that\x20the\x20following\x20conditions\x20are\n\x20met:\n\n\ + \x20\x20\x20\x20\x20*\x20Redistributions\x20of\x20source\x20code\x20must\ + \x20retain\x20the\x20above\x20copyright\n\x20notice,\x20this\x20list\x20\ + of\x20conditions\x20and\x20the\x20following\x20disclaimer.\n\x20\x20\x20\ + \x20\x20*\x20Redistributions\x20in\x20binary\x20form\x20must\x20reproduc\ + e\x20the\x20above\n\x20copyright\x20notice,\x20this\x20list\x20of\x20con\ + ditions\x20and\x20the\x20following\x20disclaimer\n\x20in\x20the\x20docum\ + entation\x20and/or\x20other\x20materials\x20provided\x20with\x20the\n\ + \x20distribution.\n\x20\x20\x20\x20\x20*\x20Neither\x20the\x20name\x20of\ + \x20Google\x20Inc.\x20nor\x20the\x20names\x20of\x20its\n\x20contributors\ + \x20may\x20be\x20used\x20to\x20endorse\x20or\x20promote\x20products\x20d\ + erived\x20from\n\x20this\x20software\x20without\x20specific\x20prior\x20\ + written\x20permission.\n\n\x20THIS\x20SOFTWARE\x20IS\x20PROVIDED\x20BY\ + \x20THE\x20COPYRIGHT\x20HOLDERS\x20AND\x20CONTRIBUTORS\n\x20\"AS\x20IS\"\ + \x20AND\x20ANY\x20EXPRESS\x20OR\x20IMPLIED\x20WARRANTIES,\x20INCLUDING,\ + \x20BUT\x20NOT\n\x20LIMITED\x20TO,\x20THE\x20IMPLIED\x20WARRANTIES\x20OF\ + \x20MERCHANTABILITY\x20AND\x20FITNESS\x20FOR\n\x20A\x20PARTICULAR\x20PUR\ + POSE\x20ARE\x20DISCLAIMED.\x20IN\x20NO\x20EVENT\x20SHALL\x20THE\x20COPYR\ + IGHT\n\x20OWNER\x20OR\x20CONTRIBUTORS\x20BE\x20LIABLE\x20FOR\x20ANY\x20D\ + IRECT,\x20INDIRECT,\x20INCIDENTAL,\n\x20SPECIAL,\x20EXEMPLARY,\x20OR\x20\ + CONSEQUENTIAL\x20DAMAGES\x20(INCLUDING,\x20BUT\x20NOT\n\x20LIMITED\x20TO\ + ,\x20PROCUREMENT\x20OF\x20SUBSTITUTE\x20GOODS\x20OR\x20SERVICES;\x20LOSS\ + \x20OF\x20USE,\n\x20DATA,\x20OR\x20PROFITS;\x20OR\x20BUSINESS\x20INTERRU\ + PTION)\x20HOWEVER\x20CAUSED\x20AND\x20ON\x20ANY\n\x20THEORY\x20OF\x20LIA\ + BILITY,\x20WHETHER\x20IN\x20CONTRACT,\x20STRICT\x20LIABILITY,\x20OR\x20T\ + ORT\n\x20(INCLUDING\x20NEGLIGENCE\x20OR\x20OTHERWISE)\x20ARISING\x20IN\ + \x20ANY\x20WAY\x20OUT\x20OF\x20THE\x20USE\n\x20OF\x20THIS\x20SOFTWARE,\ + \x20EVEN\x20IF\x20ADVISED\x20OF\x20THE\x20POSSIBILITY\x20OF\x20SUCH\x20D\ + AMAGE.\n\n\x08\n\x01\x02\x12\x03\x20\0\x18\n\t\n\x02\x03\0\x12\x03\"\0#\ + \n\t\n\x02\x03\x01\x12\x03#\0.\n\x08\n\x01\x08\x12\x03%\0;\n\t\n\x02\x08\ + %\x12\x03%\0;\n\x08\n\x01\x08\x12\x03&\0\x1f\n\t\n\x02\x08\x1f\x12\x03&\ + \0\x1f\n\x08\n\x01\x08\x12\x03'\0,\n\t\n\x02\x08\x01\x12\x03'\0,\n\x08\n\ + \x01\x08\x12\x03(\0*\n\t\n\x02\x08\x08\x12\x03(\0*\n\x08\n\x01\x08\x12\ + \x03)\0\"\n\t\n\x02\x08\n\x12\x03)\0\"\n\x08\n\x01\x08\x12\x03*\0!\n\t\n\ + \x02\x08$\x12\x03*\0!\n\x08\n\x01\x08\x12\x03+\0D\n\t\n\x02\x08\x0b\x12\ + \x03+\0D\n-\n\x02\x04\0\x12\x04.\0;\x01\x1a!\x20A\x20protocol\x20buffer\ + \x20message\x20type.\n\n\n\n\x03\x04\0\x01\x12\x03.\x08\x0c\n0\n\x04\x04\ + \0\x02\0\x12\x030\x02\x12\x1a#\x20The\x20fully\x20qualified\x20message\ + \x20name.\n\n\x0c\n\x05\x04\0\x02\0\x05\x12\x030\x02\x08\n\x0c\n\x05\x04\ + \0\x02\0\x01\x12\x030\t\r\n\x0c\n\x05\x04\0\x02\0\x03\x12\x030\x10\x11\n\ + \"\n\x04\x04\0\x02\x01\x12\x032\x02\x1c\x1a\x15\x20The\x20list\x20of\x20\ + fields.\n\n\x0c\n\x05\x04\0\x02\x01\x04\x12\x032\x02\n\n\x0c\n\x05\x04\0\ + \x02\x01\x06\x12\x032\x0b\x10\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x032\x11\ + \x17\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x032\x1a\x1b\nO\n\x04\x04\0\x02\ + \x02\x12\x034\x02\x1d\x1aB\x20The\x20list\x20of\x20types\x20appearing\ + \x20in\x20`oneof`\x20definitions\x20in\x20this\x20type.\n\n\x0c\n\x05\ + \x04\0\x02\x02\x04\x12\x034\x02\n\n\x0c\n\x05\x04\0\x02\x02\x05\x12\x034\ + \x0b\x11\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x034\x12\x18\n\x0c\n\x05\x04\ + \0\x02\x02\x03\x12\x034\x1b\x1c\n+\n\x04\x04\0\x02\x03\x12\x036\x02\x1e\ + \x1a\x1e\x20The\x20protocol\x20buffer\x20options.\n\n\x0c\n\x05\x04\0\ + \x02\x03\x04\x12\x036\x02\n\n\x0c\n\x05\x04\0\x02\x03\x06\x12\x036\x0b\ + \x11\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x036\x12\x19\n\x0c\n\x05\x04\0\ + \x02\x03\x03\x12\x036\x1c\x1d\n\"\n\x04\x04\0\x02\x04\x12\x038\x02#\x1a\ + \x15\x20The\x20source\x20context.\n\n\x0c\n\x05\x04\0\x02\x04\x06\x12\ + \x038\x02\x0f\n\x0c\n\x05\x04\0\x02\x04\x01\x12\x038\x10\x1e\n\x0c\n\x05\ + \x04\0\x02\x04\x03\x12\x038!\"\n!\n\x04\x04\0\x02\x05\x12\x03:\x02\x14\ + \x1a\x14\x20The\x20source\x20syntax.\n\n\x0c\n\x05\x04\0\x02\x05\x06\x12\ + \x03:\x02\x08\n\x0c\n\x05\x04\0\x02\x05\x01\x12\x03:\t\x0f\n\x0c\n\x05\ + \x04\0\x02\x05\x03\x12\x03:\x12\x13\n0\n\x02\x04\x01\x12\x05>\0\x8b\x01\ + \x01\x1a#\x20A\x20single\x20field\x20of\x20a\x20message\x20type.\n\n\n\n\ + \x03\x04\x01\x01\x12\x03>\x08\r\n\"\n\x04\x04\x01\x04\0\x12\x04@\x02g\ + \x03\x1a\x14\x20Basic\x20field\x20types.\n\n\x0c\n\x05\x04\x01\x04\0\x01\ + \x12\x03@\x07\x0b\n$\n\x06\x04\x01\x04\0\x02\0\x12\x03B\x04\x15\x1a\x15\ + \x20Field\x20type\x20unknown.\n\n\x0e\n\x07\x04\x01\x04\0\x02\0\x01\x12\ + \x03B\x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\0\x02\x12\x03B\x13\x14\n#\n\ + \x06\x04\x01\x04\0\x02\x01\x12\x03D\x04\x14\x1a\x14\x20Field\x20type\x20\ + double.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x01\x01\x12\x03D\x04\x0f\n\x0e\n\ + \x07\x04\x01\x04\0\x02\x01\x02\x12\x03D\x12\x13\n\"\n\x06\x04\x01\x04\0\ + \x02\x02\x12\x03F\x04\x13\x1a\x13\x20Field\x20type\x20float.\n\n\x0e\n\ + \x07\x04\x01\x04\0\x02\x02\x01\x12\x03F\x04\x0e\n\x0e\n\x07\x04\x01\x04\ + \0\x02\x02\x02\x12\x03F\x11\x12\n\"\n\x06\x04\x01\x04\0\x02\x03\x12\x03H\ + \x04\x13\x1a\x13\x20Field\x20type\x20int64.\n\n\x0e\n\x07\x04\x01\x04\0\ + \x02\x03\x01\x12\x03H\x04\x0e\n\x0e\n\x07\x04\x01\x04\0\x02\x03\x02\x12\ + \x03H\x11\x12\n#\n\x06\x04\x01\x04\0\x02\x04\x12\x03J\x04\x14\x1a\x14\ + \x20Field\x20type\x20uint64.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x04\x01\x12\ + \x03J\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\x04\x02\x12\x03J\x12\x13\n\"\ + \n\x06\x04\x01\x04\0\x02\x05\x12\x03L\x04\x13\x1a\x13\x20Field\x20type\ + \x20int32.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x05\x01\x12\x03L\x04\x0e\n\ + \x0e\n\x07\x04\x01\x04\0\x02\x05\x02\x12\x03L\x11\x12\n$\n\x06\x04\x01\ + \x04\0\x02\x06\x12\x03N\x04\x15\x1a\x15\x20Field\x20type\x20fixed64.\n\n\ + \x0e\n\x07\x04\x01\x04\0\x02\x06\x01\x12\x03N\x04\x10\n\x0e\n\x07\x04\ + \x01\x04\0\x02\x06\x02\x12\x03N\x13\x14\n$\n\x06\x04\x01\x04\0\x02\x07\ + \x12\x03P\x04\x15\x1a\x15\x20Field\x20type\x20fixed32.\n\n\x0e\n\x07\x04\ + \x01\x04\0\x02\x07\x01\x12\x03P\x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\ + \x07\x02\x12\x03P\x13\x14\n!\n\x06\x04\x01\x04\0\x02\x08\x12\x03R\x04\ + \x12\x1a\x12\x20Field\x20type\x20bool.\n\n\x0e\n\x07\x04\x01\x04\0\x02\ + \x08\x01\x12\x03R\x04\r\n\x0e\n\x07\x04\x01\x04\0\x02\x08\x02\x12\x03R\ + \x10\x11\n#\n\x06\x04\x01\x04\0\x02\t\x12\x03T\x04\x14\x1a\x14\x20Field\ + \x20type\x20string.\n\n\x0e\n\x07\x04\x01\x04\0\x02\t\x01\x12\x03T\x04\ + \x0f\n\x0e\n\x07\x04\x01\x04\0\x02\t\x02\x12\x03T\x12\x13\nF\n\x06\x04\ + \x01\x04\0\x02\n\x12\x03V\x04\x14\x1a7\x20Field\x20type\x20group.\x20Pro\ + to2\x20syntax\x20only,\x20and\x20deprecated.\n\n\x0e\n\x07\x04\x01\x04\0\ + \x02\n\x01\x12\x03V\x04\x0e\n\x0e\n\x07\x04\x01\x04\0\x02\n\x02\x12\x03V\ + \x11\x13\n$\n\x06\x04\x01\x04\0\x02\x0b\x12\x03X\x04\x16\x1a\x15\x20Fiel\ + d\x20type\x20message.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0b\x01\x12\x03X\ + \x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\x0b\x02\x12\x03X\x13\x15\n\"\n\ + \x06\x04\x01\x04\0\x02\x0c\x12\x03Z\x04\x14\x1a\x13\x20Field\x20type\x20\ + bytes.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0c\x01\x12\x03Z\x04\x0e\n\x0e\n\ + \x07\x04\x01\x04\0\x02\x0c\x02\x12\x03Z\x11\x13\n#\n\x06\x04\x01\x04\0\ + \x02\r\x12\x03\\\x04\x15\x1a\x14\x20Field\x20type\x20uint32.\n\n\x0e\n\ + \x07\x04\x01\x04\0\x02\r\x01\x12\x03\\\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\ + \x02\r\x02\x12\x03\\\x12\x14\n!\n\x06\x04\x01\x04\0\x02\x0e\x12\x03^\x04\ + \x13\x1a\x12\x20Field\x20type\x20enum.\n\n\x0e\n\x07\x04\x01\x04\0\x02\ + \x0e\x01\x12\x03^\x04\r\n\x0e\n\x07\x04\x01\x04\0\x02\x0e\x02\x12\x03^\ + \x10\x12\n%\n\x06\x04\x01\x04\0\x02\x0f\x12\x03`\x04\x17\x1a\x16\x20Fiel\ + d\x20type\x20sfixed32.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0f\x01\x12\x03`\ + \x04\x11\n\x0e\n\x07\x04\x01\x04\0\x02\x0f\x02\x12\x03`\x14\x16\n%\n\x06\ + \x04\x01\x04\0\x02\x10\x12\x03b\x04\x17\x1a\x16\x20Field\x20type\x20sfix\ + ed64.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x10\x01\x12\x03b\x04\x11\n\x0e\n\ + \x07\x04\x01\x04\0\x02\x10\x02\x12\x03b\x14\x16\n#\n\x06\x04\x01\x04\0\ + \x02\x11\x12\x03d\x04\x15\x1a\x14\x20Field\x20type\x20sint32.\n\n\x0e\n\ + \x07\x04\x01\x04\0\x02\x11\x01\x12\x03d\x04\x0f\n\x0e\n\x07\x04\x01\x04\ + \0\x02\x11\x02\x12\x03d\x12\x14\n#\n\x06\x04\x01\x04\0\x02\x12\x12\x03f\ + \x04\x15\x1a\x14\x20Field\x20type\x20sint64.\n\n\x0e\n\x07\x04\x01\x04\0\ + \x02\x12\x01\x12\x03f\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\x12\x02\x12\ + \x03f\x12\x14\nC\n\x04\x04\x01\x04\x01\x12\x04j\x02s\x03\x1a5\x20Whether\ + \x20a\x20field\x20is\x20optional,\x20required,\x20or\x20repeated.\n\n\ + \x0c\n\x05\x04\x01\x04\x01\x01\x12\x03j\x07\x12\n5\n\x06\x04\x01\x04\x01\ + \x02\0\x12\x03l\x04\x1c\x1a&\x20For\x20fields\x20with\x20unknown\x20card\ + inality.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\0\x01\x12\x03l\x04\x17\n\x0e\ + \n\x07\x04\x01\x04\x01\x02\0\x02\x12\x03l\x1a\x1b\n%\n\x06\x04\x01\x04\ + \x01\x02\x01\x12\x03n\x04\x1d\x1a\x16\x20For\x20optional\x20fields.\n\n\ + \x0e\n\x07\x04\x01\x04\x01\x02\x01\x01\x12\x03n\x04\x18\n\x0e\n\x07\x04\ + \x01\x04\x01\x02\x01\x02\x12\x03n\x1b\x1c\n9\n\x06\x04\x01\x04\x01\x02\ + \x02\x12\x03p\x04\x1d\x1a*\x20For\x20required\x20fields.\x20Proto2\x20sy\ + ntax\x20only.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\x02\x01\x12\x03p\x04\x18\ + \n\x0e\n\x07\x04\x01\x04\x01\x02\x02\x02\x12\x03p\x1b\x1c\n%\n\x06\x04\ + \x01\x04\x01\x02\x03\x12\x03r\x04\x1d\x1a\x16\x20For\x20repeated\x20fiel\ + ds.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\x03\x01\x12\x03r\x04\x18\n\x0e\n\ + \x07\x04\x01\x04\x01\x02\x03\x02\x12\x03r\x1b\x1c\n\x1e\n\x04\x04\x01\ + \x02\0\x12\x03v\x02\x10\x1a\x11\x20The\x20field\x20type.\n\n\x0c\n\x05\ + \x04\x01\x02\0\x06\x12\x03v\x02\x06\n\x0c\n\x05\x04\x01\x02\0\x01\x12\ + \x03v\x07\x0b\n\x0c\n\x05\x04\x01\x02\0\x03\x12\x03v\x0e\x0f\n%\n\x04\ + \x04\x01\x02\x01\x12\x03x\x02\x1e\x1a\x18\x20The\x20field\x20cardinality\ + .\n\n\x0c\n\x05\x04\x01\x02\x01\x06\x12\x03x\x02\r\n\x0c\n\x05\x04\x01\ + \x02\x01\x01\x12\x03x\x0e\x19\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03x\ + \x1c\x1d\n\x20\n\x04\x04\x01\x02\x02\x12\x03z\x02\x13\x1a\x13\x20The\x20\ + field\x20number.\n\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03z\x02\x07\n\ + \x0c\n\x05\x04\x01\x02\x02\x01\x12\x03z\x08\x0e\n\x0c\n\x05\x04\x01\x02\ + \x02\x03\x12\x03z\x11\x12\n\x1e\n\x04\x04\x01\x02\x03\x12\x03|\x02\x12\ + \x1a\x11\x20The\x20field\x20name.\n\n\x0c\n\x05\x04\x01\x02\x03\x05\x12\ + \x03|\x02\x08\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03|\t\r\n\x0c\n\x05\ + \x04\x01\x02\x03\x03\x12\x03|\x10\x11\n\x96\x01\n\x04\x04\x01\x02\x04\ + \x12\x03\x7f\x02\x16\x1a\x88\x01\x20The\x20field\x20type\x20URL,\x20with\ + out\x20the\x20scheme,\x20for\x20message\x20or\x20enumeration\n\x20types.\ + \x20Example:\x20`\"type.googleapis.com/google.protobuf.Timestamp\"`.\n\n\ + \x0c\n\x05\x04\x01\x02\x04\x05\x12\x03\x7f\x02\x08\n\x0c\n\x05\x04\x01\ + \x02\x04\x01\x12\x03\x7f\t\x11\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03\ + \x7f\x14\x15\n\xa5\x01\n\x04\x04\x01\x02\x05\x12\x04\x82\x01\x02\x18\x1a\ + \x96\x01\x20The\x20index\x20of\x20the\x20field\x20type\x20in\x20`Type.on\ + eofs`,\x20for\x20message\x20or\x20enumeration\n\x20types.\x20The\x20firs\ + t\x20type\x20has\x20index\x201;\x20zero\x20means\x20the\x20type\x20is\ + \x20not\x20in\x20the\x20list.\n\n\r\n\x05\x04\x01\x02\x05\x05\x12\x04\ + \x82\x01\x02\x07\n\r\n\x05\x04\x01\x02\x05\x01\x12\x04\x82\x01\x08\x13\n\ + \r\n\x05\x04\x01\x02\x05\x03\x12\x04\x82\x01\x16\x17\nF\n\x04\x04\x01\ + \x02\x06\x12\x04\x84\x01\x02\x12\x1a8\x20Whether\x20to\x20use\x20alterna\ + tive\x20packed\x20wire\x20representation.\n\n\r\n\x05\x04\x01\x02\x06\ + \x05\x12\x04\x84\x01\x02\x06\n\r\n\x05\x04\x01\x02\x06\x01\x12\x04\x84\ + \x01\x07\r\n\r\n\x05\x04\x01\x02\x06\x03\x12\x04\x84\x01\x10\x11\n,\n\ + \x04\x04\x01\x02\x07\x12\x04\x86\x01\x02\x1e\x1a\x1e\x20The\x20protocol\ + \x20buffer\x20options.\n\n\r\n\x05\x04\x01\x02\x07\x04\x12\x04\x86\x01\ + \x02\n\n\r\n\x05\x04\x01\x02\x07\x06\x12\x04\x86\x01\x0b\x11\n\r\n\x05\ + \x04\x01\x02\x07\x01\x12\x04\x86\x01\x12\x19\n\r\n\x05\x04\x01\x02\x07\ + \x03\x12\x04\x86\x01\x1c\x1d\n$\n\x04\x04\x01\x02\x08\x12\x04\x88\x01\ + \x02\x18\x1a\x16\x20The\x20field\x20JSON\x20name.\n\n\r\n\x05\x04\x01\ + \x02\x08\x05\x12\x04\x88\x01\x02\x08\n\r\n\x05\x04\x01\x02\x08\x01\x12\ + \x04\x88\x01\t\x12\n\r\n\x05\x04\x01\x02\x08\x03\x12\x04\x88\x01\x15\x17\ + \nX\n\x04\x04\x01\x02\t\x12\x04\x8a\x01\x02\x1c\x1aJ\x20The\x20string\ + \x20value\x20of\x20the\x20default\x20value\x20of\x20this\x20field.\x20Pr\ + oto2\x20syntax\x20only.\n\n\r\n\x05\x04\x01\x02\t\x05\x12\x04\x8a\x01\ + \x02\x08\n\r\n\x05\x04\x01\x02\t\x01\x12\x04\x8a\x01\t\x16\n\r\n\x05\x04\ + \x01\x02\t\x03\x12\x04\x8a\x01\x19\x1b\n%\n\x02\x04\x02\x12\x06\x8e\x01\ + \0\x99\x01\x01\x1a\x17\x20Enum\x20type\x20definition.\n\n\x0b\n\x03\x04\ + \x02\x01\x12\x04\x8e\x01\x08\x0c\n\x1f\n\x04\x04\x02\x02\0\x12\x04\x90\ + \x01\x02\x12\x1a\x11\x20Enum\x20type\x20name.\n\n\r\n\x05\x04\x02\x02\0\ + \x05\x12\x04\x90\x01\x02\x08\n\r\n\x05\x04\x02\x02\0\x01\x12\x04\x90\x01\ + \t\r\n\r\n\x05\x04\x02\x02\0\x03\x12\x04\x90\x01\x10\x11\n'\n\x04\x04\ + \x02\x02\x01\x12\x04\x92\x01\x02#\x1a\x19\x20Enum\x20value\x20definition\ + s.\n\n\r\n\x05\x04\x02\x02\x01\x04\x12\x04\x92\x01\x02\n\n\r\n\x05\x04\ + \x02\x02\x01\x06\x12\x04\x92\x01\x0b\x14\n\r\n\x05\x04\x02\x02\x01\x01\ + \x12\x04\x92\x01\x15\x1e\n\r\n\x05\x04\x02\x02\x01\x03\x12\x04\x92\x01!\ + \"\n(\n\x04\x04\x02\x02\x02\x12\x04\x94\x01\x02\x1e\x1a\x1a\x20Protocol\ + \x20buffer\x20options.\n\n\r\n\x05\x04\x02\x02\x02\x04\x12\x04\x94\x01\ + \x02\n\n\r\n\x05\x04\x02\x02\x02\x06\x12\x04\x94\x01\x0b\x11\n\r\n\x05\ + \x04\x02\x02\x02\x01\x12\x04\x94\x01\x12\x19\n\r\n\x05\x04\x02\x02\x02\ + \x03\x12\x04\x94\x01\x1c\x1d\n#\n\x04\x04\x02\x02\x03\x12\x04\x96\x01\ + \x02#\x1a\x15\x20The\x20source\x20context.\n\n\r\n\x05\x04\x02\x02\x03\ + \x06\x12\x04\x96\x01\x02\x0f\n\r\n\x05\x04\x02\x02\x03\x01\x12\x04\x96\ + \x01\x10\x1e\n\r\n\x05\x04\x02\x02\x03\x03\x12\x04\x96\x01!\"\n\"\n\x04\ + \x04\x02\x02\x04\x12\x04\x98\x01\x02\x14\x1a\x14\x20The\x20source\x20syn\ + tax.\n\n\r\n\x05\x04\x02\x02\x04\x06\x12\x04\x98\x01\x02\x08\n\r\n\x05\ + \x04\x02\x02\x04\x01\x12\x04\x98\x01\t\x0f\n\r\n\x05\x04\x02\x02\x04\x03\ + \x12\x04\x98\x01\x12\x13\n&\n\x02\x04\x03\x12\x06\x9c\x01\0\xa3\x01\x01\ + \x1a\x18\x20Enum\x20value\x20definition.\n\n\x0b\n\x03\x04\x03\x01\x12\ + \x04\x9c\x01\x08\x11\n\x20\n\x04\x04\x03\x02\0\x12\x04\x9e\x01\x02\x12\ + \x1a\x12\x20Enum\x20value\x20name.\n\n\r\n\x05\x04\x03\x02\0\x05\x12\x04\ + \x9e\x01\x02\x08\n\r\n\x05\x04\x03\x02\0\x01\x12\x04\x9e\x01\t\r\n\r\n\ + \x05\x04\x03\x02\0\x03\x12\x04\x9e\x01\x10\x11\n\"\n\x04\x04\x03\x02\x01\ + \x12\x04\xa0\x01\x02\x13\x1a\x14\x20Enum\x20value\x20number.\n\n\r\n\x05\ + \x04\x03\x02\x01\x05\x12\x04\xa0\x01\x02\x07\n\r\n\x05\x04\x03\x02\x01\ + \x01\x12\x04\xa0\x01\x08\x0e\n\r\n\x05\x04\x03\x02\x01\x03\x12\x04\xa0\ + \x01\x11\x12\n(\n\x04\x04\x03\x02\x02\x12\x04\xa2\x01\x02\x1e\x1a\x1a\ + \x20Protocol\x20buffer\x20options.\n\n\r\n\x05\x04\x03\x02\x02\x04\x12\ + \x04\xa2\x01\x02\n\n\r\n\x05\x04\x03\x02\x02\x06\x12\x04\xa2\x01\x0b\x11\ + \n\r\n\x05\x04\x03\x02\x02\x01\x12\x04\xa2\x01\x12\x19\n\r\n\x05\x04\x03\ + \x02\x02\x03\x12\x04\xa2\x01\x1c\x1d\ng\n\x02\x04\x04\x12\x06\xa7\x01\0\ + \xb2\x01\x01\x1aY\x20A\x20protocol\x20buffer\x20option,\x20which\x20can\ + \x20be\x20attached\x20to\x20a\x20message,\x20field,\n\x20enumeration,\ + \x20etc.\n\n\x0b\n\x03\x04\x04\x01\x12\x04\xa7\x01\x08\x0e\n\xfc\x01\n\ + \x04\x04\x04\x02\0\x12\x04\xac\x01\x02\x12\x1a\xed\x01\x20The\x20option'\ + s\x20name.\x20For\x20protobuf\x20built-in\x20options\x20(options\x20defi\ + ned\x20in\n\x20descriptor.proto),\x20this\x20is\x20the\x20short\x20name.\ + \x20For\x20example,\x20`\"map_entry\"`.\n\x20For\x20custom\x20options,\ + \x20it\x20should\x20be\x20the\x20fully-qualified\x20name.\x20For\x20exam\ + ple,\n\x20`\"google.api.http\"`.\n\n\r\n\x05\x04\x04\x02\0\x05\x12\x04\ + \xac\x01\x02\x08\n\r\n\x05\x04\x04\x02\0\x01\x12\x04\xac\x01\t\r\n\r\n\ + \x05\x04\x04\x02\0\x03\x12\x04\xac\x01\x10\x11\n\xa0\x02\n\x04\x04\x04\ + \x02\x01\x12\x04\xb1\x01\x02\x10\x1a\x91\x02\x20The\x20option's\x20value\ + \x20packed\x20in\x20an\x20Any\x20message.\x20If\x20the\x20value\x20is\ + \x20a\x20primitive,\n\x20the\x20corresponding\x20wrapper\x20type\x20defi\ + ned\x20in\x20google/protobuf/wrappers.proto\n\x20should\x20be\x20used.\ + \x20If\x20the\x20value\x20is\x20an\x20enum,\x20it\x20should\x20be\x20sto\ + red\x20as\x20an\x20int32\n\x20value\x20using\x20the\x20google.protobuf.I\ + nt32Value\x20type.\n\n\r\n\x05\x04\x04\x02\x01\x06\x12\x04\xb1\x01\x02\ + \x05\n\r\n\x05\x04\x04\x02\x01\x01\x12\x04\xb1\x01\x06\x0b\n\r\n\x05\x04\ + \x04\x02\x01\x03\x12\x04\xb1\x01\x0e\x0f\nI\n\x02\x05\0\x12\x06\xb5\x01\ + \0\xba\x01\x01\x1a;\x20The\x20syntax\x20in\x20which\x20a\x20protocol\x20\ + buffer\x20element\x20is\x20defined.\n\n\x0b\n\x03\x05\0\x01\x12\x04\xb5\ + \x01\x05\x0b\n\x20\n\x04\x05\0\x02\0\x12\x04\xb7\x01\x02\x14\x1a\x12\x20\ + Syntax\x20`proto2`.\n\n\r\n\x05\x05\0\x02\0\x01\x12\x04\xb7\x01\x02\x0f\ + \n\r\n\x05\x05\0\x02\0\x02\x12\x04\xb7\x01\x12\x13\n\x20\n\x04\x05\0\x02\ + \x01\x12\x04\xb9\x01\x02\x14\x1a\x12\x20Syntax\x20`proto3`.\n\n\r\n\x05\ + \x05\0\x02\x01\x01\x12\x04\xb9\x01\x02\x0f\n\r\n\x05\x05\0\x02\x01\x02\ + \x12\x04\xb9\x01\x12\x13b\x06proto3\ +"; + +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) +} + +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(2); + deps.push(crate::well_known_types::any::file_descriptor().clone()); + deps.push(crate::well_known_types::source_context::file_descriptor().clone()); + let mut messages = ::std::vec::Vec::with_capacity(5); + messages.push(Type::generated_message_descriptor_data()); + messages.push(Field::generated_message_descriptor_data()); + messages.push(Enum::generated_message_descriptor_data()); + messages.push(EnumValue::generated_message_descriptor_data()); + messages.push(Option::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(3); + enums.push(Syntax::generated_enum_descriptor_data()); + enums.push(field::Kind::generated_enum_descriptor_data()); + enums.push(field::Cardinality::generated_enum_descriptor_data()); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) + }) +} diff --git a/src/well_known_types/type_pb.rs b/src/well_known_types/type_pb.rs deleted file mode 100644 index 14bfdb2..0000000 --- a/src/well_known_types/type_pb.rs +++ /dev/null @@ -1,2233 +0,0 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit -// @generated - -// https://github.com/rust-lang/rust-clippy/issues/702 -#![allow(unknown_lints)] -#![allow(clippy::all)] - -#![allow(unused_attributes)] -#![cfg_attr(rustfmt, rustfmt::skip)] - -#![allow(box_pointers)] -#![allow(dead_code)] -#![allow(missing_docs)] -#![allow(non_camel_case_types)] -#![allow(non_snake_case)] -#![allow(non_upper_case_globals)] -#![allow(trivial_casts)] -#![allow(unused_imports)] -#![allow(unused_results)] -//! Generated file from `google/protobuf/type.proto` - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Type { - // message fields - pub name: ::std::string::String, - pub fields: crate::RepeatedField<Field>, - pub oneofs: crate::RepeatedField<::std::string::String>, - pub options: crate::RepeatedField<Option>, - pub source_context: crate::SingularPtrField<crate::well_known_types::SourceContext>, - pub syntax: Syntax, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Type { - fn default() -> &'a Type { - <Type as crate::Message>::default_instance() - } -} - -impl Type { - pub fn new() -> Type { - ::std::default::Default::default() - } - - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // repeated .google.protobuf.Field fields = 2; - - - pub fn get_fields(&self) -> &[Field] { - &self.fields - } - pub fn clear_fields(&mut self) { - self.fields.clear(); - } - - // Param is passed by value, moved - pub fn set_fields(&mut self, v: crate::RepeatedField<Field>) { - self.fields = v; - } - - // Mutable pointer to the field. - pub fn mut_fields(&mut self) -> &mut crate::RepeatedField<Field> { - &mut self.fields - } - - // Take field - pub fn take_fields(&mut self) -> crate::RepeatedField<Field> { - ::std::mem::replace(&mut self.fields, crate::RepeatedField::new()) - } - - // repeated string oneofs = 3; - - - pub fn get_oneofs(&self) -> &[::std::string::String] { - &self.oneofs - } - pub fn clear_oneofs(&mut self) { - self.oneofs.clear(); - } - - // Param is passed by value, moved - pub fn set_oneofs(&mut self, v: crate::RepeatedField<::std::string::String>) { - self.oneofs = v; - } - - // Mutable pointer to the field. - pub fn mut_oneofs(&mut self) -> &mut crate::RepeatedField<::std::string::String> { - &mut self.oneofs - } - - // Take field - pub fn take_oneofs(&mut self) -> crate::RepeatedField<::std::string::String> { - ::std::mem::replace(&mut self.oneofs, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.Option options = 4; - - - pub fn get_options(&self) -> &[Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } - - // .google.protobuf.SourceContext source_context = 5; - - - pub fn get_source_context(&self) -> &crate::well_known_types::SourceContext { - self.source_context.as_ref().unwrap_or_else(|| <crate::well_known_types::SourceContext as crate::Message>::default_instance()) - } - pub fn clear_source_context(&mut self) { - self.source_context.clear(); - } - - pub fn has_source_context(&self) -> bool { - self.source_context.is_some() - } - - // Param is passed by value, moved - pub fn set_source_context(&mut self, v: crate::well_known_types::SourceContext) { - self.source_context = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_source_context(&mut self) -> &mut crate::well_known_types::SourceContext { - if self.source_context.is_none() { - self.source_context.set_default(); - } - self.source_context.as_mut().unwrap() - } - - // Take field - pub fn take_source_context(&mut self) -> crate::well_known_types::SourceContext { - self.source_context.take().unwrap_or_else(|| crate::well_known_types::SourceContext::new()) - } - - // .google.protobuf.Syntax syntax = 6; - - - pub fn get_syntax(&self) -> Syntax { - self.syntax - } - pub fn clear_syntax(&mut self) { - self.syntax = Syntax::SYNTAX_PROTO2; - } - - // Param is passed by value, moved - pub fn set_syntax(&mut self, v: Syntax) { - self.syntax = v; - } -} - -impl crate::Message for Type { - fn is_initialized(&self) -> bool { - for v in &self.fields { - if !v.is_initialized() { - return false; - } - }; - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - for v in &self.source_context { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; - }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.fields)?; - }, - 3 => { - crate::rt::read_repeated_string_into(wire_type, is, &mut self.oneofs)?; - }, - 4 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; - }, - 5 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.source_context)?; - }, - 6 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.syntax, 6, &mut self.unknown_fields)? - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.name.is_empty() { - my_size += crate::rt::string_size(1, &self.name); - } - for value in &self.fields { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - for value in &self.oneofs { - my_size += crate::rt::string_size(3, &value); - }; - for value in &self.options { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - if let Some(ref v) = self.source_context.as_ref() { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - } - if self.syntax != Syntax::SYNTAX_PROTO2 { - my_size += crate::rt::enum_size(6, self.syntax); - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.name.is_empty() { - os.write_string(1, &self.name)?; - } - for v in &self.fields { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - for v in &self.oneofs { - os.write_string(3, &v)?; - }; - for v in &self.options { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - if let Some(ref v) = self.source_context.as_ref() { - os.write_tag(5, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - } - if self.syntax != Syntax::SYNTAX_PROTO2 { - os.write_enum(6, crate::ProtobufEnum::value(&self.syntax))?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Type { - Type::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Type| { &m.name }, - |m: &mut Type| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Field>>( - "fields", - |m: &Type| { &m.fields }, - |m: &mut Type| { &mut m.fields }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeString>( - "oneofs", - |m: &Type| { &m.oneofs }, - |m: &mut Type| { &mut m.oneofs }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Option>>( - "options", - |m: &Type| { &m.options }, - |m: &mut Type| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::SourceContext>>( - "source_context", - |m: &Type| { &m.source_context }, - |m: &mut Type| { &mut m.source_context }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<Syntax>>( - "syntax", - |m: &Type| { &m.syntax }, - |m: &mut Type| { &mut m.syntax }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Type>( - "Type", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Type { - static instance: crate::rt::LazyV2<Type> = crate::rt::LazyV2::INIT; - instance.get(Type::new) - } -} - -impl crate::Clear for Type { - fn clear(&mut self) { - self.name.clear(); - self.fields.clear(); - self.oneofs.clear(); - self.options.clear(); - self.source_context.clear(); - self.syntax = Syntax::SYNTAX_PROTO2; - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Type { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Type { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Field { - // message fields - pub kind: Field_Kind, - pub cardinality: Field_Cardinality, - pub number: i32, - pub name: ::std::string::String, - pub type_url: ::std::string::String, - pub oneof_index: i32, - pub packed: bool, - pub options: crate::RepeatedField<Option>, - pub json_name: ::std::string::String, - pub default_value: ::std::string::String, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Field { - fn default() -> &'a Field { - <Field as crate::Message>::default_instance() - } -} - -impl Field { - pub fn new() -> Field { - ::std::default::Default::default() - } - - // .google.protobuf.Field.Kind kind = 1; - - - pub fn get_kind(&self) -> Field_Kind { - self.kind - } - pub fn clear_kind(&mut self) { - self.kind = Field_Kind::TYPE_UNKNOWN; - } - - // Param is passed by value, moved - pub fn set_kind(&mut self, v: Field_Kind) { - self.kind = v; - } - - // .google.protobuf.Field.Cardinality cardinality = 2; - - - pub fn get_cardinality(&self) -> Field_Cardinality { - self.cardinality - } - pub fn clear_cardinality(&mut self) { - self.cardinality = Field_Cardinality::CARDINALITY_UNKNOWN; - } - - // Param is passed by value, moved - pub fn set_cardinality(&mut self, v: Field_Cardinality) { - self.cardinality = v; - } - - // int32 number = 3; - - - pub fn get_number(&self) -> i32 { - self.number - } - pub fn clear_number(&mut self) { - self.number = 0; - } - - // Param is passed by value, moved - pub fn set_number(&mut self, v: i32) { - self.number = v; - } - - // string name = 4; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // string type_url = 6; - - - pub fn get_type_url(&self) -> &str { - &self.type_url - } - pub fn clear_type_url(&mut self) { - self.type_url.clear(); - } - - // Param is passed by value, moved - pub fn set_type_url(&mut self, v: ::std::string::String) { - self.type_url = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_type_url(&mut self) -> &mut ::std::string::String { - &mut self.type_url - } - - // Take field - pub fn take_type_url(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.type_url, ::std::string::String::new()) - } - - // int32 oneof_index = 7; - - - pub fn get_oneof_index(&self) -> i32 { - self.oneof_index - } - pub fn clear_oneof_index(&mut self) { - self.oneof_index = 0; - } - - // Param is passed by value, moved - pub fn set_oneof_index(&mut self, v: i32) { - self.oneof_index = v; - } - - // bool packed = 8; - - - pub fn get_packed(&self) -> bool { - self.packed - } - pub fn clear_packed(&mut self) { - self.packed = false; - } - - // Param is passed by value, moved - pub fn set_packed(&mut self, v: bool) { - self.packed = v; - } - - // repeated .google.protobuf.Option options = 9; - - - pub fn get_options(&self) -> &[Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } - - // string json_name = 10; - - - pub fn get_json_name(&self) -> &str { - &self.json_name - } - pub fn clear_json_name(&mut self) { - self.json_name.clear(); - } - - // Param is passed by value, moved - pub fn set_json_name(&mut self, v: ::std::string::String) { - self.json_name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_json_name(&mut self) -> &mut ::std::string::String { - &mut self.json_name - } - - // Take field - pub fn take_json_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.json_name, ::std::string::String::new()) - } - - // string default_value = 11; - - - pub fn get_default_value(&self) -> &str { - &self.default_value - } - pub fn clear_default_value(&mut self) { - self.default_value.clear(); - } - - // Param is passed by value, moved - pub fn set_default_value(&mut self, v: ::std::string::String) { - self.default_value = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_default_value(&mut self) -> &mut ::std::string::String { - &mut self.default_value - } - - // Take field - pub fn take_default_value(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.default_value, ::std::string::String::new()) - } -} - -impl crate::Message for Field { - fn is_initialized(&self) -> bool { - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.kind, 1, &mut self.unknown_fields)? - }, - 2 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.cardinality, 2, &mut self.unknown_fields)? - }, - 3 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.number = tmp; - }, - 4 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; - }, - 6 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.type_url)?; - }, - 7 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.oneof_index = tmp; - }, - 8 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.packed = tmp; - }, - 9 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; - }, - 10 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.json_name)?; - }, - 11 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.default_value)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if self.kind != Field_Kind::TYPE_UNKNOWN { - my_size += crate::rt::enum_size(1, self.kind); - } - if self.cardinality != Field_Cardinality::CARDINALITY_UNKNOWN { - my_size += crate::rt::enum_size(2, self.cardinality); - } - if self.number != 0 { - my_size += crate::rt::value_size(3, self.number, crate::wire_format::WireTypeVarint); - } - if !self.name.is_empty() { - my_size += crate::rt::string_size(4, &self.name); - } - if !self.type_url.is_empty() { - my_size += crate::rt::string_size(6, &self.type_url); - } - if self.oneof_index != 0 { - my_size += crate::rt::value_size(7, self.oneof_index, crate::wire_format::WireTypeVarint); - } - if self.packed != false { - my_size += 2; - } - for value in &self.options { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - if !self.json_name.is_empty() { - my_size += crate::rt::string_size(10, &self.json_name); - } - if !self.default_value.is_empty() { - my_size += crate::rt::string_size(11, &self.default_value); - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if self.kind != Field_Kind::TYPE_UNKNOWN { - os.write_enum(1, crate::ProtobufEnum::value(&self.kind))?; - } - if self.cardinality != Field_Cardinality::CARDINALITY_UNKNOWN { - os.write_enum(2, crate::ProtobufEnum::value(&self.cardinality))?; - } - if self.number != 0 { - os.write_int32(3, self.number)?; - } - if !self.name.is_empty() { - os.write_string(4, &self.name)?; - } - if !self.type_url.is_empty() { - os.write_string(6, &self.type_url)?; - } - if self.oneof_index != 0 { - os.write_int32(7, self.oneof_index)?; - } - if self.packed != false { - os.write_bool(8, self.packed)?; - } - for v in &self.options { - os.write_tag(9, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - if !self.json_name.is_empty() { - os.write_string(10, &self.json_name)?; - } - if !self.default_value.is_empty() { - os.write_string(11, &self.default_value)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Field { - Field::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<Field_Kind>>( - "kind", - |m: &Field| { &m.kind }, - |m: &mut Field| { &mut m.kind }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<Field_Cardinality>>( - "cardinality", - |m: &Field| { &m.cardinality }, - |m: &mut Field| { &mut m.cardinality }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "number", - |m: &Field| { &m.number }, - |m: &mut Field| { &mut m.number }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Field| { &m.name }, - |m: &mut Field| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "type_url", - |m: &Field| { &m.type_url }, - |m: &mut Field| { &mut m.type_url }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "oneof_index", - |m: &Field| { &m.oneof_index }, - |m: &mut Field| { &mut m.oneof_index }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBool>( - "packed", - |m: &Field| { &m.packed }, - |m: &mut Field| { &mut m.packed }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Option>>( - "options", - |m: &Field| { &m.options }, - |m: &mut Field| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "json_name", - |m: &Field| { &m.json_name }, - |m: &mut Field| { &mut m.json_name }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "default_value", - |m: &Field| { &m.default_value }, - |m: &mut Field| { &mut m.default_value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Field>( - "Field", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Field { - static instance: crate::rt::LazyV2<Field> = crate::rt::LazyV2::INIT; - instance.get(Field::new) - } -} - -impl crate::Clear for Field { - fn clear(&mut self) { - self.kind = Field_Kind::TYPE_UNKNOWN; - self.cardinality = Field_Cardinality::CARDINALITY_UNKNOWN; - self.number = 0; - self.name.clear(); - self.type_url.clear(); - self.oneof_index = 0; - self.packed = false; - self.options.clear(); - self.json_name.clear(); - self.default_value.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Field { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Field { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum Field_Kind { - TYPE_UNKNOWN = 0, - TYPE_DOUBLE = 1, - TYPE_FLOAT = 2, - TYPE_INT64 = 3, - TYPE_UINT64 = 4, - TYPE_INT32 = 5, - TYPE_FIXED64 = 6, - TYPE_FIXED32 = 7, - TYPE_BOOL = 8, - TYPE_STRING = 9, - TYPE_GROUP = 10, - TYPE_MESSAGE = 11, - TYPE_BYTES = 12, - TYPE_UINT32 = 13, - TYPE_ENUM = 14, - TYPE_SFIXED32 = 15, - TYPE_SFIXED64 = 16, - TYPE_SINT32 = 17, - TYPE_SINT64 = 18, -} - -impl crate::ProtobufEnum for Field_Kind { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<Field_Kind> { - match value { - 0 => ::std::option::Option::Some(Field_Kind::TYPE_UNKNOWN), - 1 => ::std::option::Option::Some(Field_Kind::TYPE_DOUBLE), - 2 => ::std::option::Option::Some(Field_Kind::TYPE_FLOAT), - 3 => ::std::option::Option::Some(Field_Kind::TYPE_INT64), - 4 => ::std::option::Option::Some(Field_Kind::TYPE_UINT64), - 5 => ::std::option::Option::Some(Field_Kind::TYPE_INT32), - 6 => ::std::option::Option::Some(Field_Kind::TYPE_FIXED64), - 7 => ::std::option::Option::Some(Field_Kind::TYPE_FIXED32), - 8 => ::std::option::Option::Some(Field_Kind::TYPE_BOOL), - 9 => ::std::option::Option::Some(Field_Kind::TYPE_STRING), - 10 => ::std::option::Option::Some(Field_Kind::TYPE_GROUP), - 11 => ::std::option::Option::Some(Field_Kind::TYPE_MESSAGE), - 12 => ::std::option::Option::Some(Field_Kind::TYPE_BYTES), - 13 => ::std::option::Option::Some(Field_Kind::TYPE_UINT32), - 14 => ::std::option::Option::Some(Field_Kind::TYPE_ENUM), - 15 => ::std::option::Option::Some(Field_Kind::TYPE_SFIXED32), - 16 => ::std::option::Option::Some(Field_Kind::TYPE_SFIXED64), - 17 => ::std::option::Option::Some(Field_Kind::TYPE_SINT32), - 18 => ::std::option::Option::Some(Field_Kind::TYPE_SINT64), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [Field_Kind] = &[ - Field_Kind::TYPE_UNKNOWN, - Field_Kind::TYPE_DOUBLE, - Field_Kind::TYPE_FLOAT, - Field_Kind::TYPE_INT64, - Field_Kind::TYPE_UINT64, - Field_Kind::TYPE_INT32, - Field_Kind::TYPE_FIXED64, - Field_Kind::TYPE_FIXED32, - Field_Kind::TYPE_BOOL, - Field_Kind::TYPE_STRING, - Field_Kind::TYPE_GROUP, - Field_Kind::TYPE_MESSAGE, - Field_Kind::TYPE_BYTES, - Field_Kind::TYPE_UINT32, - Field_Kind::TYPE_ENUM, - Field_Kind::TYPE_SFIXED32, - Field_Kind::TYPE_SFIXED64, - Field_Kind::TYPE_SINT32, - Field_Kind::TYPE_SINT64, - ]; - values - } - - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<Field_Kind>("Field.Kind", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for Field_Kind { -} - -impl ::std::default::Default for Field_Kind { - fn default() -> Self { - Field_Kind::TYPE_UNKNOWN - } -} - -impl crate::reflect::ProtobufValue for Field_Kind { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum Field_Cardinality { - CARDINALITY_UNKNOWN = 0, - CARDINALITY_OPTIONAL = 1, - CARDINALITY_REQUIRED = 2, - CARDINALITY_REPEATED = 3, -} - -impl crate::ProtobufEnum for Field_Cardinality { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<Field_Cardinality> { - match value { - 0 => ::std::option::Option::Some(Field_Cardinality::CARDINALITY_UNKNOWN), - 1 => ::std::option::Option::Some(Field_Cardinality::CARDINALITY_OPTIONAL), - 2 => ::std::option::Option::Some(Field_Cardinality::CARDINALITY_REQUIRED), - 3 => ::std::option::Option::Some(Field_Cardinality::CARDINALITY_REPEATED), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [Field_Cardinality] = &[ - Field_Cardinality::CARDINALITY_UNKNOWN, - Field_Cardinality::CARDINALITY_OPTIONAL, - Field_Cardinality::CARDINALITY_REQUIRED, - Field_Cardinality::CARDINALITY_REPEATED, - ]; - values - } - - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<Field_Cardinality>("Field.Cardinality", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for Field_Cardinality { -} - -impl ::std::default::Default for Field_Cardinality { - fn default() -> Self { - Field_Cardinality::CARDINALITY_UNKNOWN - } -} - -impl crate::reflect::ProtobufValue for Field_Cardinality { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Enum { - // message fields - pub name: ::std::string::String, - pub enumvalue: crate::RepeatedField<EnumValue>, - pub options: crate::RepeatedField<Option>, - pub source_context: crate::SingularPtrField<crate::well_known_types::SourceContext>, - pub syntax: Syntax, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Enum { - fn default() -> &'a Enum { - <Enum as crate::Message>::default_instance() - } -} - -impl Enum { - pub fn new() -> Enum { - ::std::default::Default::default() - } - - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // repeated .google.protobuf.EnumValue enumvalue = 2; - - - pub fn get_enumvalue(&self) -> &[EnumValue] { - &self.enumvalue - } - pub fn clear_enumvalue(&mut self) { - self.enumvalue.clear(); - } - - // Param is passed by value, moved - pub fn set_enumvalue(&mut self, v: crate::RepeatedField<EnumValue>) { - self.enumvalue = v; - } - - // Mutable pointer to the field. - pub fn mut_enumvalue(&mut self) -> &mut crate::RepeatedField<EnumValue> { - &mut self.enumvalue - } - - // Take field - pub fn take_enumvalue(&mut self) -> crate::RepeatedField<EnumValue> { - ::std::mem::replace(&mut self.enumvalue, crate::RepeatedField::new()) - } - - // repeated .google.protobuf.Option options = 3; - - - pub fn get_options(&self) -> &[Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } - - // .google.protobuf.SourceContext source_context = 4; - - - pub fn get_source_context(&self) -> &crate::well_known_types::SourceContext { - self.source_context.as_ref().unwrap_or_else(|| <crate::well_known_types::SourceContext as crate::Message>::default_instance()) - } - pub fn clear_source_context(&mut self) { - self.source_context.clear(); - } - - pub fn has_source_context(&self) -> bool { - self.source_context.is_some() - } - - // Param is passed by value, moved - pub fn set_source_context(&mut self, v: crate::well_known_types::SourceContext) { - self.source_context = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_source_context(&mut self) -> &mut crate::well_known_types::SourceContext { - if self.source_context.is_none() { - self.source_context.set_default(); - } - self.source_context.as_mut().unwrap() - } - - // Take field - pub fn take_source_context(&mut self) -> crate::well_known_types::SourceContext { - self.source_context.take().unwrap_or_else(|| crate::well_known_types::SourceContext::new()) - } - - // .google.protobuf.Syntax syntax = 5; - - - pub fn get_syntax(&self) -> Syntax { - self.syntax - } - pub fn clear_syntax(&mut self) { - self.syntax = Syntax::SYNTAX_PROTO2; - } - - // Param is passed by value, moved - pub fn set_syntax(&mut self, v: Syntax) { - self.syntax = v; - } -} - -impl crate::Message for Enum { - fn is_initialized(&self) -> bool { - for v in &self.enumvalue { - if !v.is_initialized() { - return false; - } - }; - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - for v in &self.source_context { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; - }, - 2 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.enumvalue)?; - }, - 3 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; - }, - 4 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.source_context)?; - }, - 5 => { - crate::rt::read_proto3_enum_with_unknown_fields_into(wire_type, is, &mut self.syntax, 5, &mut self.unknown_fields)? - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.name.is_empty() { - my_size += crate::rt::string_size(1, &self.name); - } - for value in &self.enumvalue { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - for value in &self.options { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - if let Some(ref v) = self.source_context.as_ref() { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - } - if self.syntax != Syntax::SYNTAX_PROTO2 { - my_size += crate::rt::enum_size(5, self.syntax); - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.name.is_empty() { - os.write_string(1, &self.name)?; - } - for v in &self.enumvalue { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - for v in &self.options { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - if let Some(ref v) = self.source_context.as_ref() { - os.write_tag(4, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - } - if self.syntax != Syntax::SYNTAX_PROTO2 { - os.write_enum(5, crate::ProtobufEnum::value(&self.syntax))?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Enum { - Enum::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Enum| { &m.name }, - |m: &mut Enum| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<EnumValue>>( - "enumvalue", - |m: &Enum| { &m.enumvalue }, - |m: &mut Enum| { &mut m.enumvalue }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Option>>( - "options", - |m: &Enum| { &m.options }, - |m: &mut Enum| { &mut m.options }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::SourceContext>>( - "source_context", - |m: &Enum| { &m.source_context }, - |m: &mut Enum| { &mut m.source_context }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeEnum<Syntax>>( - "syntax", - |m: &Enum| { &m.syntax }, - |m: &mut Enum| { &mut m.syntax }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Enum>( - "Enum", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Enum { - static instance: crate::rt::LazyV2<Enum> = crate::rt::LazyV2::INIT; - instance.get(Enum::new) - } -} - -impl crate::Clear for Enum { - fn clear(&mut self) { - self.name.clear(); - self.enumvalue.clear(); - self.options.clear(); - self.source_context.clear(); - self.syntax = Syntax::SYNTAX_PROTO2; - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Enum { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Enum { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct EnumValue { - // message fields - pub name: ::std::string::String, - pub number: i32, - pub options: crate::RepeatedField<Option>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a EnumValue { - fn default() -> &'a EnumValue { - <EnumValue as crate::Message>::default_instance() - } -} - -impl EnumValue { - pub fn new() -> EnumValue { - ::std::default::Default::default() - } - - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // int32 number = 2; - - - pub fn get_number(&self) -> i32 { - self.number - } - pub fn clear_number(&mut self) { - self.number = 0; - } - - // Param is passed by value, moved - pub fn set_number(&mut self, v: i32) { - self.number = v; - } - - // repeated .google.protobuf.Option options = 3; - - - pub fn get_options(&self) -> &[Option] { - &self.options - } - pub fn clear_options(&mut self) { - self.options.clear(); - } - - // Param is passed by value, moved - pub fn set_options(&mut self, v: crate::RepeatedField<Option>) { - self.options = v; - } - - // Mutable pointer to the field. - pub fn mut_options(&mut self) -> &mut crate::RepeatedField<Option> { - &mut self.options - } - - // Take field - pub fn take_options(&mut self) -> crate::RepeatedField<Option> { - ::std::mem::replace(&mut self.options, crate::RepeatedField::new()) - } -} - -impl crate::Message for EnumValue { - fn is_initialized(&self) -> bool { - for v in &self.options { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; - }, - 2 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.number = tmp; - }, - 3 => { - crate::rt::read_repeated_message_into(wire_type, is, &mut self.options)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.name.is_empty() { - my_size += crate::rt::string_size(1, &self.name); - } - if self.number != 0 { - my_size += crate::rt::value_size(2, self.number, crate::wire_format::WireTypeVarint); - } - for value in &self.options { - let len = value.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - }; - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.name.is_empty() { - os.write_string(1, &self.name)?; - } - if self.number != 0 { - os.write_int32(2, self.number)?; - } - for v in &self.options { - os.write_tag(3, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - }; - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> EnumValue { - EnumValue::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &EnumValue| { &m.name }, - |m: &mut EnumValue| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "number", - |m: &EnumValue| { &m.number }, - |m: &mut EnumValue| { &mut m.number }, - )); - fields.push(crate::reflect::accessor::make_repeated_field_accessor::<_, crate::types::ProtobufTypeMessage<Option>>( - "options", - |m: &EnumValue| { &m.options }, - |m: &mut EnumValue| { &mut m.options }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<EnumValue>( - "EnumValue", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static EnumValue { - static instance: crate::rt::LazyV2<EnumValue> = crate::rt::LazyV2::INIT; - instance.get(EnumValue::new) - } -} - -impl crate::Clear for EnumValue { - fn clear(&mut self) { - self.name.clear(); - self.number = 0; - self.options.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for EnumValue { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for EnumValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub struct Option { - // message fields - pub name: ::std::string::String, - pub value: crate::SingularPtrField<crate::well_known_types::Any>, - // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, -} - -impl<'a> ::std::default::Default for &'a Option { - fn default() -> &'a Option { - <Option as crate::Message>::default_instance() - } -} - -impl Option { - pub fn new() -> Option { - ::std::default::Default::default() - } - - // string name = 1; - - - pub fn get_name(&self) -> &str { - &self.name - } - pub fn clear_name(&mut self) { - self.name.clear(); - } - - // Param is passed by value, moved - pub fn set_name(&mut self, v: ::std::string::String) { - self.name = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_name(&mut self) -> &mut ::std::string::String { - &mut self.name - } - - // Take field - pub fn take_name(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.name, ::std::string::String::new()) - } - - // .google.protobuf.Any value = 2; - - - pub fn get_value(&self) -> &crate::well_known_types::Any { - self.value.as_ref().unwrap_or_else(|| <crate::well_known_types::Any as crate::Message>::default_instance()) - } - pub fn clear_value(&mut self) { - self.value.clear(); - } - - pub fn has_value(&self) -> bool { - self.value.is_some() - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: crate::well_known_types::Any) { - self.value = crate::SingularPtrField::some(v); - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_value(&mut self) -> &mut crate::well_known_types::Any { - if self.value.is_none() { - self.value.set_default(); - } - self.value.as_mut().unwrap() - } - - // Take field - pub fn take_value(&mut self) -> crate::well_known_types::Any { - self.value.take().unwrap_or_else(|| crate::well_known_types::Any::new()) - } -} - -impl crate::Message for Option { - fn is_initialized(&self) -> bool { - for v in &self.value { - if !v.is_initialized() { - return false; - } - }; - true - } - - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.name)?; - }, - 2 => { - crate::rt::read_singular_message_into(wire_type, is, &mut self.value)?; - }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; - }, - }; - } - ::std::result::Result::Ok(()) - } - - // Compute sizes of nested messages - #[allow(unused_variables)] - fn compute_size(&self) -> u32 { - let mut my_size = 0; - if !self.name.is_empty() { - my_size += crate::rt::string_size(1, &self.name); - } - if let Some(ref v) = self.value.as_ref() { - let len = v.compute_size(); - my_size += 1 + crate::rt::compute_raw_varint32_size(len) + len; - } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); - my_size - } - - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { - if !self.name.is_empty() { - os.write_string(1, &self.name)?; - } - if let Some(ref v) = self.value.as_ref() { - os.write_tag(2, crate::wire_format::WireTypeLengthDelimited)?; - os.write_raw_varint32(v.get_cached_size())?; - v.write_to_with_cached_sizes(os)?; - } - os.write_unknown_fields(self.get_unknown_fields())?; - ::std::result::Result::Ok(()) - } - - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() - } - - fn new() -> Option { - Option::new() - } - - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "name", - |m: &Option| { &m.name }, - |m: &mut Option| { &mut m.name }, - )); - fields.push(crate::reflect::accessor::make_singular_ptr_field_accessor::<_, crate::types::ProtobufTypeMessage<crate::well_known_types::Any>>( - "value", - |m: &Option| { &m.value }, - |m: &mut Option| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Option>( - "Option", - fields, - file_descriptor_proto() - ) - }) - } - - fn default_instance() -> &'static Option { - static instance: crate::rt::LazyV2<Option> = crate::rt::LazyV2::INIT; - instance.get(Option::new) - } -} - -impl crate::Clear for Option { - fn clear(&mut self) { - self.name.clear(); - self.value.clear(); - self.unknown_fields.clear(); - } -} - -impl ::std::fmt::Debug for Option { - fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - crate::text_format::fmt(self, f) - } -} - -impl crate::reflect::ProtobufValue for Option { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } -} - -#[derive(Clone,PartialEq,Eq,Debug,Hash)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] -pub enum Syntax { - SYNTAX_PROTO2 = 0, - SYNTAX_PROTO3 = 1, -} - -impl crate::ProtobufEnum for Syntax { - fn value(&self) -> i32 { - *self as i32 - } - - fn from_i32(value: i32) -> ::std::option::Option<Syntax> { - match value { - 0 => ::std::option::Option::Some(Syntax::SYNTAX_PROTO2), - 1 => ::std::option::Option::Some(Syntax::SYNTAX_PROTO3), - _ => ::std::option::Option::None - } - } - - fn values() -> &'static [Self] { - static values: &'static [Syntax] = &[ - Syntax::SYNTAX_PROTO2, - Syntax::SYNTAX_PROTO3, - ]; - values - } - - fn enum_descriptor_static() -> &'static crate::reflect::EnumDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::EnumDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - crate::reflect::EnumDescriptor::new_pb_name::<Syntax>("Syntax", file_descriptor_proto()) - }) - } -} - -impl ::std::marker::Copy for Syntax { -} - -impl ::std::default::Default for Syntax { - fn default() -> Self { - Syntax::SYNTAX_PROTO2 - } -} - -impl crate::reflect::ProtobufValue for Syntax { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Enum(crate::ProtobufEnum::descriptor(self)) - } -} - -static file_descriptor_proto_data: &'static [u8] = b"\ - \n\x1agoogle/protobuf/type.proto\x12\x0fgoogle.protobuf\x1a\x19google/pr\ - otobuf/any.proto\x1a$google/protobuf/source_context.proto\"\x8d\x02\n\ - \x04Type\x12\x12\n\x04name\x18\x01\x20\x01(\tR\x04name\x12.\n\x06fields\ - \x18\x02\x20\x03(\x0b2\x16.google.protobuf.FieldR\x06fields\x12\x16\n\ - \x06oneofs\x18\x03\x20\x03(\tR\x06oneofs\x121\n\x07options\x18\x04\x20\ - \x03(\x0b2\x17.google.protobuf.OptionR\x07options\x12E\n\x0esource_conte\ - xt\x18\x05\x20\x01(\x0b2\x1e.google.protobuf.SourceContextR\rsourceConte\ - xt\x12/\n\x06syntax\x18\x06\x20\x01(\x0e2\x17.google.protobuf.SyntaxR\ - \x06syntax\"\xb4\x06\n\x05Field\x12/\n\x04kind\x18\x01\x20\x01(\x0e2\x1b\ - .google.protobuf.Field.KindR\x04kind\x12D\n\x0bcardinality\x18\x02\x20\ - \x01(\x0e2\".google.protobuf.Field.CardinalityR\x0bcardinality\x12\x16\n\ - \x06number\x18\x03\x20\x01(\x05R\x06number\x12\x12\n\x04name\x18\x04\x20\ - \x01(\tR\x04name\x12\x19\n\x08type_url\x18\x06\x20\x01(\tR\x07typeUrl\ - \x12\x1f\n\x0boneof_index\x18\x07\x20\x01(\x05R\noneofIndex\x12\x16\n\ - \x06packed\x18\x08\x20\x01(\x08R\x06packed\x121\n\x07options\x18\t\x20\ - \x03(\x0b2\x17.google.protobuf.OptionR\x07options\x12\x1b\n\tjson_name\ - \x18\n\x20\x01(\tR\x08jsonName\x12#\n\rdefault_value\x18\x0b\x20\x01(\tR\ - \x0cdefaultValue\"\xc8\x02\n\x04Kind\x12\x10\n\x0cTYPE_UNKNOWN\x10\0\x12\ - \x0f\n\x0bTYPE_DOUBLE\x10\x01\x12\x0e\n\nTYPE_FLOAT\x10\x02\x12\x0e\n\nT\ - YPE_INT64\x10\x03\x12\x0f\n\x0bTYPE_UINT64\x10\x04\x12\x0e\n\nTYPE_INT32\ - \x10\x05\x12\x10\n\x0cTYPE_FIXED64\x10\x06\x12\x10\n\x0cTYPE_FIXED32\x10\ - \x07\x12\r\n\tTYPE_BOOL\x10\x08\x12\x0f\n\x0bTYPE_STRING\x10\t\x12\x0e\n\ - \nTYPE_GROUP\x10\n\x12\x10\n\x0cTYPE_MESSAGE\x10\x0b\x12\x0e\n\nTYPE_BYT\ - ES\x10\x0c\x12\x0f\n\x0bTYPE_UINT32\x10\r\x12\r\n\tTYPE_ENUM\x10\x0e\x12\ - \x11\n\rTYPE_SFIXED32\x10\x0f\x12\x11\n\rTYPE_SFIXED64\x10\x10\x12\x0f\n\ - \x0bTYPE_SINT32\x10\x11\x12\x0f\n\x0bTYPE_SINT64\x10\x12\"t\n\x0bCardina\ - lity\x12\x17\n\x13CARDINALITY_UNKNOWN\x10\0\x12\x18\n\x14CARDINALITY_OPT\ - IONAL\x10\x01\x12\x18\n\x14CARDINALITY_REQUIRED\x10\x02\x12\x18\n\x14CAR\ - DINALITY_REPEATED\x10\x03\"\xff\x01\n\x04Enum\x12\x12\n\x04name\x18\x01\ - \x20\x01(\tR\x04name\x128\n\tenumvalue\x18\x02\x20\x03(\x0b2\x1a.google.\ - protobuf.EnumValueR\tenumvalue\x121\n\x07options\x18\x03\x20\x03(\x0b2\ - \x17.google.protobuf.OptionR\x07options\x12E\n\x0esource_context\x18\x04\ - \x20\x01(\x0b2\x1e.google.protobuf.SourceContextR\rsourceContext\x12/\n\ - \x06syntax\x18\x05\x20\x01(\x0e2\x17.google.protobuf.SyntaxR\x06syntax\"\ - j\n\tEnumValue\x12\x12\n\x04name\x18\x01\x20\x01(\tR\x04name\x12\x16\n\ - \x06number\x18\x02\x20\x01(\x05R\x06number\x121\n\x07options\x18\x03\x20\ - \x03(\x0b2\x17.google.protobuf.OptionR\x07options\"H\n\x06Option\x12\x12\ - \n\x04name\x18\x01\x20\x01(\tR\x04name\x12*\n\x05value\x18\x02\x20\x01(\ - \x0b2\x14.google.protobuf.AnyR\x05value*.\n\x06Syntax\x12\x11\n\rSYNTAX_\ - PROTO2\x10\0\x12\x11\n\rSYNTAX_PROTO3\x10\x01B{\n\x13com.google.protobuf\ - B\tTypeProtoP\x01Z-google.golang.org/protobuf/types/known/typepb\xf8\x01\ - \x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesJ\xc38\n\ - \x07\x12\x05\x1e\0\xba\x01\x01\n\xcc\x0c\n\x01\x0c\x12\x03\x1e\0\x122\ - \xc1\x0c\x20Protocol\x20Buffers\x20-\x20Google's\x20data\x20interchange\ - \x20format\n\x20Copyright\x202008\x20Google\x20Inc.\x20\x20All\x20rights\ - \x20reserved.\n\x20https://developers.google.com/protocol-buffers/\n\n\ - \x20Redistribution\x20and\x20use\x20in\x20source\x20and\x20binary\x20for\ - ms,\x20with\x20or\x20without\n\x20modification,\x20are\x20permitted\x20p\ - rovided\x20that\x20the\x20following\x20conditions\x20are\n\x20met:\n\n\ - \x20\x20\x20\x20\x20*\x20Redistributions\x20of\x20source\x20code\x20must\ - \x20retain\x20the\x20above\x20copyright\n\x20notice,\x20this\x20list\x20\ - of\x20conditions\x20and\x20the\x20following\x20disclaimer.\n\x20\x20\x20\ - \x20\x20*\x20Redistributions\x20in\x20binary\x20form\x20must\x20reproduc\ - e\x20the\x20above\n\x20copyright\x20notice,\x20this\x20list\x20of\x20con\ - ditions\x20and\x20the\x20following\x20disclaimer\n\x20in\x20the\x20docum\ - entation\x20and/or\x20other\x20materials\x20provided\x20with\x20the\n\ - \x20distribution.\n\x20\x20\x20\x20\x20*\x20Neither\x20the\x20name\x20of\ - \x20Google\x20Inc.\x20nor\x20the\x20names\x20of\x20its\n\x20contributors\ - \x20may\x20be\x20used\x20to\x20endorse\x20or\x20promote\x20products\x20d\ - erived\x20from\n\x20this\x20software\x20without\x20specific\x20prior\x20\ - written\x20permission.\n\n\x20THIS\x20SOFTWARE\x20IS\x20PROVIDED\x20BY\ - \x20THE\x20COPYRIGHT\x20HOLDERS\x20AND\x20CONTRIBUTORS\n\x20\"AS\x20IS\"\ - \x20AND\x20ANY\x20EXPRESS\x20OR\x20IMPLIED\x20WARRANTIES,\x20INCLUDING,\ - \x20BUT\x20NOT\n\x20LIMITED\x20TO,\x20THE\x20IMPLIED\x20WARRANTIES\x20OF\ - \x20MERCHANTABILITY\x20AND\x20FITNESS\x20FOR\n\x20A\x20PARTICULAR\x20PUR\ - POSE\x20ARE\x20DISCLAIMED.\x20IN\x20NO\x20EVENT\x20SHALL\x20THE\x20COPYR\ - IGHT\n\x20OWNER\x20OR\x20CONTRIBUTORS\x20BE\x20LIABLE\x20FOR\x20ANY\x20D\ - IRECT,\x20INDIRECT,\x20INCIDENTAL,\n\x20SPECIAL,\x20EXEMPLARY,\x20OR\x20\ - CONSEQUENTIAL\x20DAMAGES\x20(INCLUDING,\x20BUT\x20NOT\n\x20LIMITED\x20TO\ - ,\x20PROCUREMENT\x20OF\x20SUBSTITUTE\x20GOODS\x20OR\x20SERVICES;\x20LOSS\ - \x20OF\x20USE,\n\x20DATA,\x20OR\x20PROFITS;\x20OR\x20BUSINESS\x20INTERRU\ - PTION)\x20HOWEVER\x20CAUSED\x20AND\x20ON\x20ANY\n\x20THEORY\x20OF\x20LIA\ - BILITY,\x20WHETHER\x20IN\x20CONTRACT,\x20STRICT\x20LIABILITY,\x20OR\x20T\ - ORT\n\x20(INCLUDING\x20NEGLIGENCE\x20OR\x20OTHERWISE)\x20ARISING\x20IN\ - \x20ANY\x20WAY\x20OUT\x20OF\x20THE\x20USE\n\x20OF\x20THIS\x20SOFTWARE,\ - \x20EVEN\x20IF\x20ADVISED\x20OF\x20THE\x20POSSIBILITY\x20OF\x20SUCH\x20D\ - AMAGE.\n\n\x08\n\x01\x02\x12\x03\x20\0\x18\n\t\n\x02\x03\0\x12\x03\"\0#\ - \n\t\n\x02\x03\x01\x12\x03#\0.\n\x08\n\x01\x08\x12\x03%\0;\n\t\n\x02\x08\ - %\x12\x03%\0;\n\x08\n\x01\x08\x12\x03&\0\x1f\n\t\n\x02\x08\x1f\x12\x03&\ - \0\x1f\n\x08\n\x01\x08\x12\x03'\0,\n\t\n\x02\x08\x01\x12\x03'\0,\n\x08\n\ - \x01\x08\x12\x03(\0*\n\t\n\x02\x08\x08\x12\x03(\0*\n\x08\n\x01\x08\x12\ - \x03)\0\"\n\t\n\x02\x08\n\x12\x03)\0\"\n\x08\n\x01\x08\x12\x03*\0!\n\t\n\ - \x02\x08$\x12\x03*\0!\n\x08\n\x01\x08\x12\x03+\0D\n\t\n\x02\x08\x0b\x12\ - \x03+\0D\n-\n\x02\x04\0\x12\x04.\0;\x01\x1a!\x20A\x20protocol\x20buffer\ - \x20message\x20type.\n\n\n\n\x03\x04\0\x01\x12\x03.\x08\x0c\n0\n\x04\x04\ - \0\x02\0\x12\x030\x02\x12\x1a#\x20The\x20fully\x20qualified\x20message\ - \x20name.\n\n\x0c\n\x05\x04\0\x02\0\x05\x12\x030\x02\x08\n\x0c\n\x05\x04\ - \0\x02\0\x01\x12\x030\t\r\n\x0c\n\x05\x04\0\x02\0\x03\x12\x030\x10\x11\n\ - \"\n\x04\x04\0\x02\x01\x12\x032\x02\x1c\x1a\x15\x20The\x20list\x20of\x20\ - fields.\n\n\x0c\n\x05\x04\0\x02\x01\x04\x12\x032\x02\n\n\x0c\n\x05\x04\0\ - \x02\x01\x06\x12\x032\x0b\x10\n\x0c\n\x05\x04\0\x02\x01\x01\x12\x032\x11\ - \x17\n\x0c\n\x05\x04\0\x02\x01\x03\x12\x032\x1a\x1b\nO\n\x04\x04\0\x02\ - \x02\x12\x034\x02\x1d\x1aB\x20The\x20list\x20of\x20types\x20appearing\ - \x20in\x20`oneof`\x20definitions\x20in\x20this\x20type.\n\n\x0c\n\x05\ - \x04\0\x02\x02\x04\x12\x034\x02\n\n\x0c\n\x05\x04\0\x02\x02\x05\x12\x034\ - \x0b\x11\n\x0c\n\x05\x04\0\x02\x02\x01\x12\x034\x12\x18\n\x0c\n\x05\x04\ - \0\x02\x02\x03\x12\x034\x1b\x1c\n+\n\x04\x04\0\x02\x03\x12\x036\x02\x1e\ - \x1a\x1e\x20The\x20protocol\x20buffer\x20options.\n\n\x0c\n\x05\x04\0\ - \x02\x03\x04\x12\x036\x02\n\n\x0c\n\x05\x04\0\x02\x03\x06\x12\x036\x0b\ - \x11\n\x0c\n\x05\x04\0\x02\x03\x01\x12\x036\x12\x19\n\x0c\n\x05\x04\0\ - \x02\x03\x03\x12\x036\x1c\x1d\n\"\n\x04\x04\0\x02\x04\x12\x038\x02#\x1a\ - \x15\x20The\x20source\x20context.\n\n\x0c\n\x05\x04\0\x02\x04\x06\x12\ - \x038\x02\x0f\n\x0c\n\x05\x04\0\x02\x04\x01\x12\x038\x10\x1e\n\x0c\n\x05\ - \x04\0\x02\x04\x03\x12\x038!\"\n!\n\x04\x04\0\x02\x05\x12\x03:\x02\x14\ - \x1a\x14\x20The\x20source\x20syntax.\n\n\x0c\n\x05\x04\0\x02\x05\x06\x12\ - \x03:\x02\x08\n\x0c\n\x05\x04\0\x02\x05\x01\x12\x03:\t\x0f\n\x0c\n\x05\ - \x04\0\x02\x05\x03\x12\x03:\x12\x13\n0\n\x02\x04\x01\x12\x05>\0\x8b\x01\ - \x01\x1a#\x20A\x20single\x20field\x20of\x20a\x20message\x20type.\n\n\n\n\ - \x03\x04\x01\x01\x12\x03>\x08\r\n\"\n\x04\x04\x01\x04\0\x12\x04@\x02g\ - \x03\x1a\x14\x20Basic\x20field\x20types.\n\n\x0c\n\x05\x04\x01\x04\0\x01\ - \x12\x03@\x07\x0b\n$\n\x06\x04\x01\x04\0\x02\0\x12\x03B\x04\x15\x1a\x15\ - \x20Field\x20type\x20unknown.\n\n\x0e\n\x07\x04\x01\x04\0\x02\0\x01\x12\ - \x03B\x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\0\x02\x12\x03B\x13\x14\n#\n\ - \x06\x04\x01\x04\0\x02\x01\x12\x03D\x04\x14\x1a\x14\x20Field\x20type\x20\ - double.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x01\x01\x12\x03D\x04\x0f\n\x0e\n\ - \x07\x04\x01\x04\0\x02\x01\x02\x12\x03D\x12\x13\n\"\n\x06\x04\x01\x04\0\ - \x02\x02\x12\x03F\x04\x13\x1a\x13\x20Field\x20type\x20float.\n\n\x0e\n\ - \x07\x04\x01\x04\0\x02\x02\x01\x12\x03F\x04\x0e\n\x0e\n\x07\x04\x01\x04\ - \0\x02\x02\x02\x12\x03F\x11\x12\n\"\n\x06\x04\x01\x04\0\x02\x03\x12\x03H\ - \x04\x13\x1a\x13\x20Field\x20type\x20int64.\n\n\x0e\n\x07\x04\x01\x04\0\ - \x02\x03\x01\x12\x03H\x04\x0e\n\x0e\n\x07\x04\x01\x04\0\x02\x03\x02\x12\ - \x03H\x11\x12\n#\n\x06\x04\x01\x04\0\x02\x04\x12\x03J\x04\x14\x1a\x14\ - \x20Field\x20type\x20uint64.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x04\x01\x12\ - \x03J\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\x04\x02\x12\x03J\x12\x13\n\"\ - \n\x06\x04\x01\x04\0\x02\x05\x12\x03L\x04\x13\x1a\x13\x20Field\x20type\ - \x20int32.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x05\x01\x12\x03L\x04\x0e\n\ - \x0e\n\x07\x04\x01\x04\0\x02\x05\x02\x12\x03L\x11\x12\n$\n\x06\x04\x01\ - \x04\0\x02\x06\x12\x03N\x04\x15\x1a\x15\x20Field\x20type\x20fixed64.\n\n\ - \x0e\n\x07\x04\x01\x04\0\x02\x06\x01\x12\x03N\x04\x10\n\x0e\n\x07\x04\ - \x01\x04\0\x02\x06\x02\x12\x03N\x13\x14\n$\n\x06\x04\x01\x04\0\x02\x07\ - \x12\x03P\x04\x15\x1a\x15\x20Field\x20type\x20fixed32.\n\n\x0e\n\x07\x04\ - \x01\x04\0\x02\x07\x01\x12\x03P\x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\ - \x07\x02\x12\x03P\x13\x14\n!\n\x06\x04\x01\x04\0\x02\x08\x12\x03R\x04\ - \x12\x1a\x12\x20Field\x20type\x20bool.\n\n\x0e\n\x07\x04\x01\x04\0\x02\ - \x08\x01\x12\x03R\x04\r\n\x0e\n\x07\x04\x01\x04\0\x02\x08\x02\x12\x03R\ - \x10\x11\n#\n\x06\x04\x01\x04\0\x02\t\x12\x03T\x04\x14\x1a\x14\x20Field\ - \x20type\x20string.\n\n\x0e\n\x07\x04\x01\x04\0\x02\t\x01\x12\x03T\x04\ - \x0f\n\x0e\n\x07\x04\x01\x04\0\x02\t\x02\x12\x03T\x12\x13\nF\n\x06\x04\ - \x01\x04\0\x02\n\x12\x03V\x04\x14\x1a7\x20Field\x20type\x20group.\x20Pro\ - to2\x20syntax\x20only,\x20and\x20deprecated.\n\n\x0e\n\x07\x04\x01\x04\0\ - \x02\n\x01\x12\x03V\x04\x0e\n\x0e\n\x07\x04\x01\x04\0\x02\n\x02\x12\x03V\ - \x11\x13\n$\n\x06\x04\x01\x04\0\x02\x0b\x12\x03X\x04\x16\x1a\x15\x20Fiel\ - d\x20type\x20message.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0b\x01\x12\x03X\ - \x04\x10\n\x0e\n\x07\x04\x01\x04\0\x02\x0b\x02\x12\x03X\x13\x15\n\"\n\ - \x06\x04\x01\x04\0\x02\x0c\x12\x03Z\x04\x14\x1a\x13\x20Field\x20type\x20\ - bytes.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0c\x01\x12\x03Z\x04\x0e\n\x0e\n\ - \x07\x04\x01\x04\0\x02\x0c\x02\x12\x03Z\x11\x13\n#\n\x06\x04\x01\x04\0\ - \x02\r\x12\x03\\\x04\x15\x1a\x14\x20Field\x20type\x20uint32.\n\n\x0e\n\ - \x07\x04\x01\x04\0\x02\r\x01\x12\x03\\\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\ - \x02\r\x02\x12\x03\\\x12\x14\n!\n\x06\x04\x01\x04\0\x02\x0e\x12\x03^\x04\ - \x13\x1a\x12\x20Field\x20type\x20enum.\n\n\x0e\n\x07\x04\x01\x04\0\x02\ - \x0e\x01\x12\x03^\x04\r\n\x0e\n\x07\x04\x01\x04\0\x02\x0e\x02\x12\x03^\ - \x10\x12\n%\n\x06\x04\x01\x04\0\x02\x0f\x12\x03`\x04\x17\x1a\x16\x20Fiel\ - d\x20type\x20sfixed32.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x0f\x01\x12\x03`\ - \x04\x11\n\x0e\n\x07\x04\x01\x04\0\x02\x0f\x02\x12\x03`\x14\x16\n%\n\x06\ - \x04\x01\x04\0\x02\x10\x12\x03b\x04\x17\x1a\x16\x20Field\x20type\x20sfix\ - ed64.\n\n\x0e\n\x07\x04\x01\x04\0\x02\x10\x01\x12\x03b\x04\x11\n\x0e\n\ - \x07\x04\x01\x04\0\x02\x10\x02\x12\x03b\x14\x16\n#\n\x06\x04\x01\x04\0\ - \x02\x11\x12\x03d\x04\x15\x1a\x14\x20Field\x20type\x20sint32.\n\n\x0e\n\ - \x07\x04\x01\x04\0\x02\x11\x01\x12\x03d\x04\x0f\n\x0e\n\x07\x04\x01\x04\ - \0\x02\x11\x02\x12\x03d\x12\x14\n#\n\x06\x04\x01\x04\0\x02\x12\x12\x03f\ - \x04\x15\x1a\x14\x20Field\x20type\x20sint64.\n\n\x0e\n\x07\x04\x01\x04\0\ - \x02\x12\x01\x12\x03f\x04\x0f\n\x0e\n\x07\x04\x01\x04\0\x02\x12\x02\x12\ - \x03f\x12\x14\nC\n\x04\x04\x01\x04\x01\x12\x04j\x02s\x03\x1a5\x20Whether\ - \x20a\x20field\x20is\x20optional,\x20required,\x20or\x20repeated.\n\n\ - \x0c\n\x05\x04\x01\x04\x01\x01\x12\x03j\x07\x12\n5\n\x06\x04\x01\x04\x01\ - \x02\0\x12\x03l\x04\x1c\x1a&\x20For\x20fields\x20with\x20unknown\x20card\ - inality.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\0\x01\x12\x03l\x04\x17\n\x0e\ - \n\x07\x04\x01\x04\x01\x02\0\x02\x12\x03l\x1a\x1b\n%\n\x06\x04\x01\x04\ - \x01\x02\x01\x12\x03n\x04\x1d\x1a\x16\x20For\x20optional\x20fields.\n\n\ - \x0e\n\x07\x04\x01\x04\x01\x02\x01\x01\x12\x03n\x04\x18\n\x0e\n\x07\x04\ - \x01\x04\x01\x02\x01\x02\x12\x03n\x1b\x1c\n9\n\x06\x04\x01\x04\x01\x02\ - \x02\x12\x03p\x04\x1d\x1a*\x20For\x20required\x20fields.\x20Proto2\x20sy\ - ntax\x20only.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\x02\x01\x12\x03p\x04\x18\ - \n\x0e\n\x07\x04\x01\x04\x01\x02\x02\x02\x12\x03p\x1b\x1c\n%\n\x06\x04\ - \x01\x04\x01\x02\x03\x12\x03r\x04\x1d\x1a\x16\x20For\x20repeated\x20fiel\ - ds.\n\n\x0e\n\x07\x04\x01\x04\x01\x02\x03\x01\x12\x03r\x04\x18\n\x0e\n\ - \x07\x04\x01\x04\x01\x02\x03\x02\x12\x03r\x1b\x1c\n\x1e\n\x04\x04\x01\ - \x02\0\x12\x03v\x02\x10\x1a\x11\x20The\x20field\x20type.\n\n\x0c\n\x05\ - \x04\x01\x02\0\x06\x12\x03v\x02\x06\n\x0c\n\x05\x04\x01\x02\0\x01\x12\ - \x03v\x07\x0b\n\x0c\n\x05\x04\x01\x02\0\x03\x12\x03v\x0e\x0f\n%\n\x04\ - \x04\x01\x02\x01\x12\x03x\x02\x1e\x1a\x18\x20The\x20field\x20cardinality\ - .\n\n\x0c\n\x05\x04\x01\x02\x01\x06\x12\x03x\x02\r\n\x0c\n\x05\x04\x01\ - \x02\x01\x01\x12\x03x\x0e\x19\n\x0c\n\x05\x04\x01\x02\x01\x03\x12\x03x\ - \x1c\x1d\n\x20\n\x04\x04\x01\x02\x02\x12\x03z\x02\x13\x1a\x13\x20The\x20\ - field\x20number.\n\n\x0c\n\x05\x04\x01\x02\x02\x05\x12\x03z\x02\x07\n\ - \x0c\n\x05\x04\x01\x02\x02\x01\x12\x03z\x08\x0e\n\x0c\n\x05\x04\x01\x02\ - \x02\x03\x12\x03z\x11\x12\n\x1e\n\x04\x04\x01\x02\x03\x12\x03|\x02\x12\ - \x1a\x11\x20The\x20field\x20name.\n\n\x0c\n\x05\x04\x01\x02\x03\x05\x12\ - \x03|\x02\x08\n\x0c\n\x05\x04\x01\x02\x03\x01\x12\x03|\t\r\n\x0c\n\x05\ - \x04\x01\x02\x03\x03\x12\x03|\x10\x11\n\x96\x01\n\x04\x04\x01\x02\x04\ - \x12\x03\x7f\x02\x16\x1a\x88\x01\x20The\x20field\x20type\x20URL,\x20with\ - out\x20the\x20scheme,\x20for\x20message\x20or\x20enumeration\n\x20types.\ - \x20Example:\x20`\"type.googleapis.com/google.protobuf.Timestamp\"`.\n\n\ - \x0c\n\x05\x04\x01\x02\x04\x05\x12\x03\x7f\x02\x08\n\x0c\n\x05\x04\x01\ - \x02\x04\x01\x12\x03\x7f\t\x11\n\x0c\n\x05\x04\x01\x02\x04\x03\x12\x03\ - \x7f\x14\x15\n\xa5\x01\n\x04\x04\x01\x02\x05\x12\x04\x82\x01\x02\x18\x1a\ - \x96\x01\x20The\x20index\x20of\x20the\x20field\x20type\x20in\x20`Type.on\ - eofs`,\x20for\x20message\x20or\x20enumeration\n\x20types.\x20The\x20firs\ - t\x20type\x20has\x20index\x201;\x20zero\x20means\x20the\x20type\x20is\ - \x20not\x20in\x20the\x20list.\n\n\r\n\x05\x04\x01\x02\x05\x05\x12\x04\ - \x82\x01\x02\x07\n\r\n\x05\x04\x01\x02\x05\x01\x12\x04\x82\x01\x08\x13\n\ - \r\n\x05\x04\x01\x02\x05\x03\x12\x04\x82\x01\x16\x17\nF\n\x04\x04\x01\ - \x02\x06\x12\x04\x84\x01\x02\x12\x1a8\x20Whether\x20to\x20use\x20alterna\ - tive\x20packed\x20wire\x20representation.\n\n\r\n\x05\x04\x01\x02\x06\ - \x05\x12\x04\x84\x01\x02\x06\n\r\n\x05\x04\x01\x02\x06\x01\x12\x04\x84\ - \x01\x07\r\n\r\n\x05\x04\x01\x02\x06\x03\x12\x04\x84\x01\x10\x11\n,\n\ - \x04\x04\x01\x02\x07\x12\x04\x86\x01\x02\x1e\x1a\x1e\x20The\x20protocol\ - \x20buffer\x20options.\n\n\r\n\x05\x04\x01\x02\x07\x04\x12\x04\x86\x01\ - \x02\n\n\r\n\x05\x04\x01\x02\x07\x06\x12\x04\x86\x01\x0b\x11\n\r\n\x05\ - \x04\x01\x02\x07\x01\x12\x04\x86\x01\x12\x19\n\r\n\x05\x04\x01\x02\x07\ - \x03\x12\x04\x86\x01\x1c\x1d\n$\n\x04\x04\x01\x02\x08\x12\x04\x88\x01\ - \x02\x18\x1a\x16\x20The\x20field\x20JSON\x20name.\n\n\r\n\x05\x04\x01\ - \x02\x08\x05\x12\x04\x88\x01\x02\x08\n\r\n\x05\x04\x01\x02\x08\x01\x12\ - \x04\x88\x01\t\x12\n\r\n\x05\x04\x01\x02\x08\x03\x12\x04\x88\x01\x15\x17\ - \nX\n\x04\x04\x01\x02\t\x12\x04\x8a\x01\x02\x1c\x1aJ\x20The\x20string\ - \x20value\x20of\x20the\x20default\x20value\x20of\x20this\x20field.\x20Pr\ - oto2\x20syntax\x20only.\n\n\r\n\x05\x04\x01\x02\t\x05\x12\x04\x8a\x01\ - \x02\x08\n\r\n\x05\x04\x01\x02\t\x01\x12\x04\x8a\x01\t\x16\n\r\n\x05\x04\ - \x01\x02\t\x03\x12\x04\x8a\x01\x19\x1b\n%\n\x02\x04\x02\x12\x06\x8e\x01\ - \0\x99\x01\x01\x1a\x17\x20Enum\x20type\x20definition.\n\n\x0b\n\x03\x04\ - \x02\x01\x12\x04\x8e\x01\x08\x0c\n\x1f\n\x04\x04\x02\x02\0\x12\x04\x90\ - \x01\x02\x12\x1a\x11\x20Enum\x20type\x20name.\n\n\r\n\x05\x04\x02\x02\0\ - \x05\x12\x04\x90\x01\x02\x08\n\r\n\x05\x04\x02\x02\0\x01\x12\x04\x90\x01\ - \t\r\n\r\n\x05\x04\x02\x02\0\x03\x12\x04\x90\x01\x10\x11\n'\n\x04\x04\ - \x02\x02\x01\x12\x04\x92\x01\x02#\x1a\x19\x20Enum\x20value\x20definition\ - s.\n\n\r\n\x05\x04\x02\x02\x01\x04\x12\x04\x92\x01\x02\n\n\r\n\x05\x04\ - \x02\x02\x01\x06\x12\x04\x92\x01\x0b\x14\n\r\n\x05\x04\x02\x02\x01\x01\ - \x12\x04\x92\x01\x15\x1e\n\r\n\x05\x04\x02\x02\x01\x03\x12\x04\x92\x01!\ - \"\n(\n\x04\x04\x02\x02\x02\x12\x04\x94\x01\x02\x1e\x1a\x1a\x20Protocol\ - \x20buffer\x20options.\n\n\r\n\x05\x04\x02\x02\x02\x04\x12\x04\x94\x01\ - \x02\n\n\r\n\x05\x04\x02\x02\x02\x06\x12\x04\x94\x01\x0b\x11\n\r\n\x05\ - \x04\x02\x02\x02\x01\x12\x04\x94\x01\x12\x19\n\r\n\x05\x04\x02\x02\x02\ - \x03\x12\x04\x94\x01\x1c\x1d\n#\n\x04\x04\x02\x02\x03\x12\x04\x96\x01\ - \x02#\x1a\x15\x20The\x20source\x20context.\n\n\r\n\x05\x04\x02\x02\x03\ - \x06\x12\x04\x96\x01\x02\x0f\n\r\n\x05\x04\x02\x02\x03\x01\x12\x04\x96\ - \x01\x10\x1e\n\r\n\x05\x04\x02\x02\x03\x03\x12\x04\x96\x01!\"\n\"\n\x04\ - \x04\x02\x02\x04\x12\x04\x98\x01\x02\x14\x1a\x14\x20The\x20source\x20syn\ - tax.\n\n\r\n\x05\x04\x02\x02\x04\x06\x12\x04\x98\x01\x02\x08\n\r\n\x05\ - \x04\x02\x02\x04\x01\x12\x04\x98\x01\t\x0f\n\r\n\x05\x04\x02\x02\x04\x03\ - \x12\x04\x98\x01\x12\x13\n&\n\x02\x04\x03\x12\x06\x9c\x01\0\xa3\x01\x01\ - \x1a\x18\x20Enum\x20value\x20definition.\n\n\x0b\n\x03\x04\x03\x01\x12\ - \x04\x9c\x01\x08\x11\n\x20\n\x04\x04\x03\x02\0\x12\x04\x9e\x01\x02\x12\ - \x1a\x12\x20Enum\x20value\x20name.\n\n\r\n\x05\x04\x03\x02\0\x05\x12\x04\ - \x9e\x01\x02\x08\n\r\n\x05\x04\x03\x02\0\x01\x12\x04\x9e\x01\t\r\n\r\n\ - \x05\x04\x03\x02\0\x03\x12\x04\x9e\x01\x10\x11\n\"\n\x04\x04\x03\x02\x01\ - \x12\x04\xa0\x01\x02\x13\x1a\x14\x20Enum\x20value\x20number.\n\n\r\n\x05\ - \x04\x03\x02\x01\x05\x12\x04\xa0\x01\x02\x07\n\r\n\x05\x04\x03\x02\x01\ - \x01\x12\x04\xa0\x01\x08\x0e\n\r\n\x05\x04\x03\x02\x01\x03\x12\x04\xa0\ - \x01\x11\x12\n(\n\x04\x04\x03\x02\x02\x12\x04\xa2\x01\x02\x1e\x1a\x1a\ - \x20Protocol\x20buffer\x20options.\n\n\r\n\x05\x04\x03\x02\x02\x04\x12\ - \x04\xa2\x01\x02\n\n\r\n\x05\x04\x03\x02\x02\x06\x12\x04\xa2\x01\x0b\x11\ - \n\r\n\x05\x04\x03\x02\x02\x01\x12\x04\xa2\x01\x12\x19\n\r\n\x05\x04\x03\ - \x02\x02\x03\x12\x04\xa2\x01\x1c\x1d\ng\n\x02\x04\x04\x12\x06\xa7\x01\0\ - \xb2\x01\x01\x1aY\x20A\x20protocol\x20buffer\x20option,\x20which\x20can\ - \x20be\x20attached\x20to\x20a\x20message,\x20field,\n\x20enumeration,\ - \x20etc.\n\n\x0b\n\x03\x04\x04\x01\x12\x04\xa7\x01\x08\x0e\n\xfc\x01\n\ - \x04\x04\x04\x02\0\x12\x04\xac\x01\x02\x12\x1a\xed\x01\x20The\x20option'\ - s\x20name.\x20For\x20protobuf\x20built-in\x20options\x20(options\x20defi\ - ned\x20in\n\x20descriptor.proto),\x20this\x20is\x20the\x20short\x20name.\ - \x20For\x20example,\x20`\"map_entry\"`.\n\x20For\x20custom\x20options,\ - \x20it\x20should\x20be\x20the\x20fully-qualified\x20name.\x20For\x20exam\ - ple,\n\x20`\"google.api.http\"`.\n\n\r\n\x05\x04\x04\x02\0\x05\x12\x04\ - \xac\x01\x02\x08\n\r\n\x05\x04\x04\x02\0\x01\x12\x04\xac\x01\t\r\n\r\n\ - \x05\x04\x04\x02\0\x03\x12\x04\xac\x01\x10\x11\n\xa0\x02\n\x04\x04\x04\ - \x02\x01\x12\x04\xb1\x01\x02\x10\x1a\x91\x02\x20The\x20option's\x20value\ - \x20packed\x20in\x20an\x20Any\x20message.\x20If\x20the\x20value\x20is\ - \x20a\x20primitive,\n\x20the\x20corresponding\x20wrapper\x20type\x20defi\ - ned\x20in\x20google/protobuf/wrappers.proto\n\x20should\x20be\x20used.\ - \x20If\x20the\x20value\x20is\x20an\x20enum,\x20it\x20should\x20be\x20sto\ - red\x20as\x20an\x20int32\n\x20value\x20using\x20the\x20google.protobuf.I\ - nt32Value\x20type.\n\n\r\n\x05\x04\x04\x02\x01\x06\x12\x04\xb1\x01\x02\ - \x05\n\r\n\x05\x04\x04\x02\x01\x01\x12\x04\xb1\x01\x06\x0b\n\r\n\x05\x04\ - \x04\x02\x01\x03\x12\x04\xb1\x01\x0e\x0f\nI\n\x02\x05\0\x12\x06\xb5\x01\ - \0\xba\x01\x01\x1a;\x20The\x20syntax\x20in\x20which\x20a\x20protocol\x20\ - buffer\x20element\x20is\x20defined.\n\n\x0b\n\x03\x05\0\x01\x12\x04\xb5\ - \x01\x05\x0b\n\x20\n\x04\x05\0\x02\0\x12\x04\xb7\x01\x02\x14\x1a\x12\x20\ - Syntax\x20`proto2`.\n\n\r\n\x05\x05\0\x02\0\x01\x12\x04\xb7\x01\x02\x0f\ - \n\r\n\x05\x05\0\x02\0\x02\x12\x04\xb7\x01\x12\x13\n\x20\n\x04\x05\0\x02\ - \x01\x12\x04\xb9\x01\x02\x14\x1a\x12\x20Syntax\x20`proto3`.\n\n\r\n\x05\ - \x05\0\x02\x01\x01\x12\x04\xb9\x01\x02\x0f\n\r\n\x05\x05\0\x02\x01\x02\ - \x12\x04\xb9\x01\x12\x13b\x06proto3\ -"; - -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() -} - -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() - }) -} diff --git a/src/well_known_types/wrappers.rs b/src/well_known_types/wrappers.rs index 4e056c7..7e96c21 100644 --- a/src/well_known_types/wrappers.rs +++ b/src/well_known_types/wrappers.rs @@ -1,4 +1,5 @@ -// This file is generated by rust-protobuf 2.26.0. Do not edit +// This file is generated by rust-protobuf 3.0.0-pre. Do not edit +// .proto file is parsed by protoc --rust-out=... // @generated // https://github.com/rust-lang/rust-clippy/issues/702 @@ -15,20 +16,24 @@ #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(trivial_casts)] -#![allow(unused_imports)] #![allow(unused_results)] +#![allow(unused_mut)] + //! Generated file from `google/protobuf/wrappers.proto` -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `double`. +/// +/// The JSON representation for `DoubleValue` is JSON number. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.DoubleValue) pub struct DoubleValue { // message fields + /// The double value. + // @@protoc_insertion_point(field:google.protobuf.DoubleValue.value) pub value: f64, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.DoubleValue.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a DoubleValue { @@ -42,40 +47,37 @@ impl DoubleValue { ::std::default::Default::default() } - // double value = 1; - - - pub fn get_value(&self) -> f64 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0.; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: f64) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &DoubleValue| { &m.value }, + |m: &mut DoubleValue| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<DoubleValue>( + "DoubleValue", + fields, + oneofs, + ) } } impl crate::Message for DoubleValue { + const NAME: &'static str = "DoubleValue"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeFixed64 { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_double()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 9 => { + self.value = is.read_double()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -84,106 +86,80 @@ impl crate::Message for DoubleValue { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0. { - my_size += 9; + my_size += 1 + 8; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0. { os.write_double(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> DoubleValue { DoubleValue::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeDouble>( - "value", - |m: &DoubleValue| { &m.value }, - |m: &mut DoubleValue| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<DoubleValue>( - "DoubleValue", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0.; + self.special_fields.clear(); } fn default_instance() -> &'static DoubleValue { - static instance: crate::rt::LazyV2<DoubleValue> = crate::rt::LazyV2::INIT; - instance.get(DoubleValue::new) + static instance: DoubleValue = DoubleValue { + value: 0., + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for DoubleValue { - fn clear(&mut self) { - self.value = 0.; - self.unknown_fields.clear(); +impl crate::MessageFull for DoubleValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("DoubleValue").unwrap()).clone() } } -impl ::std::fmt::Debug for DoubleValue { +impl ::std::fmt::Display for DoubleValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for DoubleValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `float`. +/// +/// The JSON representation for `FloatValue` is JSON number. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.FloatValue) pub struct FloatValue { // message fields + /// The float value. + // @@protoc_insertion_point(field:google.protobuf.FloatValue.value) pub value: f32, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.FloatValue.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a FloatValue { @@ -197,40 +173,37 @@ impl FloatValue { ::std::default::Default::default() } - // float value = 1; - - - pub fn get_value(&self) -> f32 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0.; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: f32) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &FloatValue| { &m.value }, + |m: &mut FloatValue| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<FloatValue>( + "FloatValue", + fields, + oneofs, + ) } } impl crate::Message for FloatValue { + const NAME: &'static str = "FloatValue"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeFixed32 { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_float()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 13 => { + self.value = is.read_float()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -239,106 +212,80 @@ impl crate::Message for FloatValue { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0. { - my_size += 5; + my_size += 1 + 4; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0. { os.write_float(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> FloatValue { FloatValue::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeFloat>( - "value", - |m: &FloatValue| { &m.value }, - |m: &mut FloatValue| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<FloatValue>( - "FloatValue", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0.; + self.special_fields.clear(); } fn default_instance() -> &'static FloatValue { - static instance: crate::rt::LazyV2<FloatValue> = crate::rt::LazyV2::INIT; - instance.get(FloatValue::new) + static instance: FloatValue = FloatValue { + value: 0., + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for FloatValue { - fn clear(&mut self) { - self.value = 0.; - self.unknown_fields.clear(); +impl crate::MessageFull for FloatValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("FloatValue").unwrap()).clone() } } -impl ::std::fmt::Debug for FloatValue { +impl ::std::fmt::Display for FloatValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for FloatValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `int64`. +/// +/// The JSON representation for `Int64Value` is JSON string. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Int64Value) pub struct Int64Value { // message fields + /// The int64 value. + // @@protoc_insertion_point(field:google.protobuf.Int64Value.value) pub value: i64, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Int64Value.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Int64Value { @@ -352,40 +299,37 @@ impl Int64Value { ::std::default::Default::default() } - // int64 value = 1; - - - pub fn get_value(&self) -> i64 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: i64) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &Int64Value| { &m.value }, + |m: &mut Int64Value| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Int64Value>( + "Int64Value", + fields, + oneofs, + ) } } impl crate::Message for Int64Value { + const NAME: &'static str = "Int64Value"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int64()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.value = is.read_int64()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -394,106 +338,80 @@ impl crate::Message for Int64Value { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0 { - my_size += crate::rt::value_size(1, self.value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int64_size(1, self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0 { os.write_int64(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Int64Value { Int64Value::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt64>( - "value", - |m: &Int64Value| { &m.value }, - |m: &mut Int64Value| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Int64Value>( - "Int64Value", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0; + self.special_fields.clear(); } fn default_instance() -> &'static Int64Value { - static instance: crate::rt::LazyV2<Int64Value> = crate::rt::LazyV2::INIT; - instance.get(Int64Value::new) + static instance: Int64Value = Int64Value { + value: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Int64Value { - fn clear(&mut self) { - self.value = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for Int64Value { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Int64Value").unwrap()).clone() } } -impl ::std::fmt::Debug for Int64Value { +impl ::std::fmt::Display for Int64Value { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Int64Value { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `uint64`. +/// +/// The JSON representation for `UInt64Value` is JSON string. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.UInt64Value) pub struct UInt64Value { // message fields + /// The uint64 value. + // @@protoc_insertion_point(field:google.protobuf.UInt64Value.value) pub value: u64, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.UInt64Value.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a UInt64Value { @@ -507,40 +425,37 @@ impl UInt64Value { ::std::default::Default::default() } - // uint64 value = 1; - - - pub fn get_value(&self) -> u64 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: u64) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &UInt64Value| { &m.value }, + |m: &mut UInt64Value| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<UInt64Value>( + "UInt64Value", + fields, + oneofs, + ) } } impl crate::Message for UInt64Value { + const NAME: &'static str = "UInt64Value"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint64()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.value = is.read_uint64()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -549,106 +464,80 @@ impl crate::Message for UInt64Value { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0 { - my_size += crate::rt::value_size(1, self.value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::uint64_size(1, self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0 { os.write_uint64(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> UInt64Value { UInt64Value::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeUint64>( - "value", - |m: &UInt64Value| { &m.value }, - |m: &mut UInt64Value| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<UInt64Value>( - "UInt64Value", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0; + self.special_fields.clear(); } fn default_instance() -> &'static UInt64Value { - static instance: crate::rt::LazyV2<UInt64Value> = crate::rt::LazyV2::INIT; - instance.get(UInt64Value::new) + static instance: UInt64Value = UInt64Value { + value: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for UInt64Value { - fn clear(&mut self) { - self.value = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for UInt64Value { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("UInt64Value").unwrap()).clone() } } -impl ::std::fmt::Debug for UInt64Value { +impl ::std::fmt::Display for UInt64Value { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for UInt64Value { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `int32`. +/// +/// The JSON representation for `Int32Value` is JSON number. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.Int32Value) pub struct Int32Value { // message fields + /// The int32 value. + // @@protoc_insertion_point(field:google.protobuf.Int32Value.value) pub value: i32, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.Int32Value.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a Int32Value { @@ -662,40 +551,37 @@ impl Int32Value { ::std::default::Default::default() } - // int32 value = 1; - - - pub fn get_value(&self) -> i32 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: i32) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &Int32Value| { &m.value }, + |m: &mut Int32Value| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<Int32Value>( + "Int32Value", + fields, + oneofs, + ) } } impl crate::Message for Int32Value { + const NAME: &'static str = "Int32Value"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_int32()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.value = is.read_int32()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -704,106 +590,80 @@ impl crate::Message for Int32Value { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0 { - my_size += crate::rt::value_size(1, self.value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::int32_size(1, self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0 { os.write_int32(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> Int32Value { Int32Value::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeInt32>( - "value", - |m: &Int32Value| { &m.value }, - |m: &mut Int32Value| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<Int32Value>( - "Int32Value", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0; + self.special_fields.clear(); } fn default_instance() -> &'static Int32Value { - static instance: crate::rt::LazyV2<Int32Value> = crate::rt::LazyV2::INIT; - instance.get(Int32Value::new) + static instance: Int32Value = Int32Value { + value: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for Int32Value { - fn clear(&mut self) { - self.value = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for Int32Value { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("Int32Value").unwrap()).clone() } } -impl ::std::fmt::Debug for Int32Value { +impl ::std::fmt::Display for Int32Value { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for Int32Value { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `uint32`. +/// +/// The JSON representation for `UInt32Value` is JSON number. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.UInt32Value) pub struct UInt32Value { // message fields + /// The uint32 value. + // @@protoc_insertion_point(field:google.protobuf.UInt32Value.value) pub value: u32, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.UInt32Value.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a UInt32Value { @@ -817,40 +677,37 @@ impl UInt32Value { ::std::default::Default::default() } - // uint32 value = 1; - - - pub fn get_value(&self) -> u32 { - self.value - } - pub fn clear_value(&mut self) { - self.value = 0; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: u32) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &UInt32Value| { &m.value }, + |m: &mut UInt32Value| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<UInt32Value>( + "UInt32Value", + fields, + oneofs, + ) } } impl crate::Message for UInt32Value { + const NAME: &'static str = "UInt32Value"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_uint32()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.value = is.read_uint32()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -859,106 +716,80 @@ impl crate::Message for UInt32Value { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != 0 { - my_size += crate::rt::value_size(1, self.value, crate::wire_format::WireTypeVarint); + my_size += crate::rt::uint32_size(1, self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != 0 { os.write_uint32(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() - } - - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> UInt32Value { UInt32Value::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeUint32>( - "value", - |m: &UInt32Value| { &m.value }, - |m: &mut UInt32Value| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<UInt32Value>( - "UInt32Value", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = 0; + self.special_fields.clear(); } fn default_instance() -> &'static UInt32Value { - static instance: crate::rt::LazyV2<UInt32Value> = crate::rt::LazyV2::INIT; - instance.get(UInt32Value::new) + static instance: UInt32Value = UInt32Value { + value: 0, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for UInt32Value { - fn clear(&mut self) { - self.value = 0; - self.unknown_fields.clear(); +impl crate::MessageFull for UInt32Value { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("UInt32Value").unwrap()).clone() } } -impl ::std::fmt::Debug for UInt32Value { +impl ::std::fmt::Display for UInt32Value { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for UInt32Value { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `bool`. +/// +/// The JSON representation for `BoolValue` is JSON `true` and `false`. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.BoolValue) pub struct BoolValue { // message fields + /// The bool value. + // @@protoc_insertion_point(field:google.protobuf.BoolValue.value) pub value: bool, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.BoolValue.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a BoolValue { @@ -972,40 +803,37 @@ impl BoolValue { ::std::default::Default::default() } - // bool value = 1; - - - pub fn get_value(&self) -> bool { - self.value - } - pub fn clear_value(&mut self) { - self.value = false; - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: bool) { - self.value = v; + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &BoolValue| { &m.value }, + |m: &mut BoolValue| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<BoolValue>( + "BoolValue", + fields, + oneofs, + ) } } impl crate::Message for BoolValue { + const NAME: &'static str = "BoolValue"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - if wire_type != crate::wire_format::WireTypeVarint { - return ::std::result::Result::Err(crate::rt::unexpected_wire_type(wire_type)); - } - let tmp = is.read_bool()?; - self.value = tmp; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 8 => { + self.value = is.read_bool()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -1014,106 +842,80 @@ impl crate::Message for BoolValue { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if self.value != false { - my_size += 2; + my_size += 1 + 1; } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if self.value != false { os.write_bool(1, self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> BoolValue { BoolValue::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBool>( - "value", - |m: &BoolValue| { &m.value }, - |m: &mut BoolValue| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<BoolValue>( - "BoolValue", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value = false; + self.special_fields.clear(); } fn default_instance() -> &'static BoolValue { - static instance: crate::rt::LazyV2<BoolValue> = crate::rt::LazyV2::INIT; - instance.get(BoolValue::new) + static instance: BoolValue = BoolValue { + value: false, + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for BoolValue { - fn clear(&mut self) { - self.value = false; - self.unknown_fields.clear(); +impl crate::MessageFull for BoolValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("BoolValue").unwrap()).clone() } } -impl ::std::fmt::Debug for BoolValue { +impl ::std::fmt::Display for BoolValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for BoolValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `string`. +/// +/// The JSON representation for `StringValue` is JSON string. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.StringValue) pub struct StringValue { // message fields + /// The string value. + // @@protoc_insertion_point(field:google.protobuf.StringValue.value) pub value: ::std::string::String, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.StringValue.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a StringValue { @@ -1127,47 +929,37 @@ impl StringValue { ::std::default::Default::default() } - // string value = 1; - - - pub fn get_value(&self) -> &str { - &self.value - } - pub fn clear_value(&mut self) { - self.value.clear(); - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: ::std::string::String) { - self.value = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_value(&mut self) -> &mut ::std::string::String { - &mut self.value - } - - // Take field - pub fn take_value(&mut self) -> ::std::string::String { - ::std::mem::replace(&mut self.value, ::std::string::String::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &StringValue| { &m.value }, + |m: &mut StringValue| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<StringValue>( + "StringValue", + fields, + oneofs, + ) } } impl crate::Message for StringValue { + const NAME: &'static str = "StringValue"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_string_into(wire_type, is, &mut self.value)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.value = is.read_string()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -1176,106 +968,80 @@ impl crate::Message for StringValue { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.value.is_empty() { my_size += crate::rt::string_size(1, &self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.value.is_empty() { os.write_string(1, &self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> StringValue { StringValue::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeString>( - "value", - |m: &StringValue| { &m.value }, - |m: &mut StringValue| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<StringValue>( - "StringValue", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static StringValue { - static instance: crate::rt::LazyV2<StringValue> = crate::rt::LazyV2::INIT; - instance.get(StringValue::new) + static instance: StringValue = StringValue { + value: ::std::string::String::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for StringValue { - fn clear(&mut self) { - self.value.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for StringValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("StringValue").unwrap()).clone() } } -impl ::std::fmt::Debug for StringValue { +impl ::std::fmt::Display for StringValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for StringValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } -#[derive(PartialEq,Clone,Default)] -#[cfg_attr(feature = "with-serde", derive(::serde::Serialize, ::serde::Deserialize))] +/// Wrapper message for `bytes`. +/// +/// The JSON representation for `BytesValue` is JSON string. +#[derive(PartialEq,Clone,Default,Debug)] +// @@protoc_insertion_point(message:google.protobuf.BytesValue) pub struct BytesValue { // message fields + /// The bytes value. + // @@protoc_insertion_point(field:google.protobuf.BytesValue.value) pub value: ::std::vec::Vec<u8>, // special fields - #[cfg_attr(feature = "with-serde", serde(skip))] - pub unknown_fields: crate::UnknownFields, - #[cfg_attr(feature = "with-serde", serde(skip))] - pub cached_size: crate::CachedSize, + // @@protoc_insertion_point(special_field:google.protobuf.BytesValue.special_fields) + pub special_fields: crate::SpecialFields, } impl<'a> ::std::default::Default for &'a BytesValue { @@ -1289,47 +1055,37 @@ impl BytesValue { ::std::default::Default::default() } - // bytes value = 1; - - - pub fn get_value(&self) -> &[u8] { - &self.value - } - pub fn clear_value(&mut self) { - self.value.clear(); - } - - // Param is passed by value, moved - pub fn set_value(&mut self, v: ::std::vec::Vec<u8>) { - self.value = v; - } - - // Mutable pointer to the field. - // If field is not initialized, it is initialized with default value first. - pub fn mut_value(&mut self) -> &mut ::std::vec::Vec<u8> { - &mut self.value - } - - // Take field - pub fn take_value(&mut self) -> ::std::vec::Vec<u8> { - ::std::mem::replace(&mut self.value, ::std::vec::Vec::new()) + fn generated_message_descriptor_data() -> crate::reflect::GeneratedMessageDescriptorData { + let mut fields = ::std::vec::Vec::with_capacity(1); + let mut oneofs = ::std::vec::Vec::with_capacity(0); + fields.push(crate::reflect::rt::v2::make_simpler_field_accessor::<_, _>( + "value", + |m: &BytesValue| { &m.value }, + |m: &mut BytesValue| { &mut m.value }, + )); + crate::reflect::GeneratedMessageDescriptorData::new_2::<BytesValue>( + "BytesValue", + fields, + oneofs, + ) } } impl crate::Message for BytesValue { + const NAME: &'static str = "BytesValue"; + fn is_initialized(&self) -> bool { true } - fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::ProtobufResult<()> { - while !is.eof()? { - let (field_number, wire_type) = is.read_tag_unpack()?; - match field_number { - 1 => { - crate::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.value)?; + fn merge_from(&mut self, is: &mut crate::CodedInputStream<'_>) -> crate::Result<()> { + while let Some(tag) = is.read_raw_tag_or_eof()? { + match tag { + 10 => { + self.value = is.read_bytes()?; }, - _ => { - crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; + tag => { + crate::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, }; } @@ -1338,94 +1094,65 @@ impl crate::Message for BytesValue { // Compute sizes of nested messages #[allow(unused_variables)] - fn compute_size(&self) -> u32 { + fn compute_size(&self) -> u64 { let mut my_size = 0; if !self.value.is_empty() { my_size += crate::rt::bytes_size(1, &self.value); } - my_size += crate::rt::unknown_fields_size(self.get_unknown_fields()); - self.cached_size.set(my_size); + my_size += crate::rt::unknown_fields_size(self.special_fields.unknown_fields()); + self.special_fields.cached_size().set(my_size as u32); my_size } - fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::ProtobufResult<()> { + fn write_to_with_cached_sizes(&self, os: &mut crate::CodedOutputStream<'_>) -> crate::Result<()> { if !self.value.is_empty() { os.write_bytes(1, &self.value)?; } - os.write_unknown_fields(self.get_unknown_fields())?; + os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } - fn get_cached_size(&self) -> u32 { - self.cached_size.get() + fn special_fields(&self) -> &crate::SpecialFields { + &self.special_fields } - fn get_unknown_fields(&self) -> &crate::UnknownFields { - &self.unknown_fields - } - - fn mut_unknown_fields(&mut self) -> &mut crate::UnknownFields { - &mut self.unknown_fields - } - - fn as_any(&self) -> &dyn (::std::any::Any) { - self as &dyn (::std::any::Any) - } - fn as_any_mut(&mut self) -> &mut dyn (::std::any::Any) { - self as &mut dyn (::std::any::Any) - } - fn into_any(self: ::std::boxed::Box<Self>) -> ::std::boxed::Box<dyn (::std::any::Any)> { - self - } - - fn descriptor(&self) -> &'static crate::reflect::MessageDescriptor { - Self::descriptor_static() + fn mut_special_fields(&mut self) -> &mut crate::SpecialFields { + &mut self.special_fields } fn new() -> BytesValue { BytesValue::new() } - fn descriptor_static() -> &'static crate::reflect::MessageDescriptor { - static descriptor: crate::rt::LazyV2<crate::reflect::MessageDescriptor> = crate::rt::LazyV2::INIT; - descriptor.get(|| { - let mut fields = ::std::vec::Vec::new(); - fields.push(crate::reflect::accessor::make_simple_field_accessor::<_, crate::types::ProtobufTypeBytes>( - "value", - |m: &BytesValue| { &m.value }, - |m: &mut BytesValue| { &mut m.value }, - )); - crate::reflect::MessageDescriptor::new_pb_name::<BytesValue>( - "BytesValue", - fields, - file_descriptor_proto() - ) - }) + fn clear(&mut self) { + self.value.clear(); + self.special_fields.clear(); } fn default_instance() -> &'static BytesValue { - static instance: crate::rt::LazyV2<BytesValue> = crate::rt::LazyV2::INIT; - instance.get(BytesValue::new) + static instance: BytesValue = BytesValue { + value: ::std::vec::Vec::new(), + special_fields: crate::SpecialFields::new(), + }; + &instance } } -impl crate::Clear for BytesValue { - fn clear(&mut self) { - self.value.clear(); - self.unknown_fields.clear(); +impl crate::MessageFull for BytesValue { + fn descriptor() -> crate::reflect::MessageDescriptor { + static descriptor: crate::rt::Lazy<crate::reflect::MessageDescriptor> = crate::rt::Lazy::new(); + descriptor.get(|| file_descriptor().message_by_package_relative_name("BytesValue").unwrap()).clone() } } -impl ::std::fmt::Debug for BytesValue { +impl ::std::fmt::Display for BytesValue { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { crate::text_format::fmt(self, f) } } impl crate::reflect::ProtobufValue for BytesValue { - fn as_ref(&self) -> crate::reflect::ReflectValueRef { - crate::reflect::ReflectValueRef::Message(self) - } + type RuntimeType = crate::reflect::rt::RuntimeTypeMessage<Self>; } static file_descriptor_proto_data: &'static [u8] = b"\ @@ -1549,14 +1276,39 @@ static file_descriptor_proto_data: &'static [u8] = b"\ b\x06proto3\ "; -static file_descriptor_proto_lazy: crate::rt::LazyV2<crate::descriptor::FileDescriptorProto> = crate::rt::LazyV2::INIT; - -fn parse_descriptor_proto() -> crate::descriptor::FileDescriptorProto { - crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() +/// `FileDescriptorProto` object which was a source for this generated file +fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { + static file_descriptor_proto_lazy: crate::rt::Lazy<crate::descriptor::FileDescriptorProto> = crate::rt::Lazy::new(); + file_descriptor_proto_lazy.get(|| { + crate::Message::parse_from_bytes(file_descriptor_proto_data).unwrap() + }) } -pub fn file_descriptor_proto() -> &'static crate::descriptor::FileDescriptorProto { - file_descriptor_proto_lazy.get(|| { - parse_descriptor_proto() +/// `FileDescriptor` object which allows dynamic access to files +pub fn file_descriptor() -> &'static crate::reflect::FileDescriptor { + static generated_file_descriptor_lazy: crate::rt::Lazy<crate::reflect::GeneratedFileDescriptor> = crate::rt::Lazy::new(); + static file_descriptor: crate::rt::Lazy<crate::reflect::FileDescriptor> = crate::rt::Lazy::new(); + file_descriptor.get(|| { + let generated_file_descriptor = generated_file_descriptor_lazy.get(|| { + let mut deps = ::std::vec::Vec::with_capacity(0); + let mut messages = ::std::vec::Vec::with_capacity(9); + messages.push(DoubleValue::generated_message_descriptor_data()); + messages.push(FloatValue::generated_message_descriptor_data()); + messages.push(Int64Value::generated_message_descriptor_data()); + messages.push(UInt64Value::generated_message_descriptor_data()); + messages.push(Int32Value::generated_message_descriptor_data()); + messages.push(UInt32Value::generated_message_descriptor_data()); + messages.push(BoolValue::generated_message_descriptor_data()); + messages.push(StringValue::generated_message_descriptor_data()); + messages.push(BytesValue::generated_message_descriptor_data()); + let mut enums = ::std::vec::Vec::with_capacity(0); + crate::reflect::GeneratedFileDescriptor::new_generated( + file_descriptor_proto(), + deps, + messages, + enums, + ) + }); + crate::reflect::FileDescriptor::new_generated_2(generated_file_descriptor) }) } diff --git a/src/well_known_types_util/any.rs b/src/well_known_types_util/any.rs index 7441e17..3af541a 100644 --- a/src/well_known_types_util/any.rs +++ b/src/well_known_types_util/any.rs @@ -1,14 +1,14 @@ +use crate::message_dyn::MessageDyn; use crate::reflect::MessageDescriptor; -use crate::well_known_types::Any; -use crate::Message; -use crate::ProtobufResult; +use crate::well_known_types::any::Any; +use crate::MessageFull; impl Any { fn type_url(type_url_prefix: &str, descriptor: &MessageDescriptor) -> String { format!("{}/{}", type_url_prefix, descriptor.full_name()) } - fn get_type_name_from_type_url(type_url: &str) -> Option<&str> { + fn type_name_from_type_url(type_url: &str) -> Option<&str> { match type_url.rfind('/') { Some(i) => Some(&type_url[i + 1..]), None => None, @@ -20,18 +20,17 @@ impl Any { /// # Examples /// /// ``` - /// # use protobuf::Message; - /// # use protobuf::ProtobufResult; - /// use protobuf::well_known_types::Any; + /// # use protobuf::MessageFull; + /// use protobuf::well_known_types::any::Any; /// - /// # fn the_test<MyMessage: Message>(message: &MyMessage) -> ProtobufResult<()> { + /// # fn the_test<MyMessage: MessageFull>(message: &MyMessage) -> protobuf::Result<()> { /// let message: &MyMessage = message; /// let any = Any::pack(message)?; /// assert!(any.is::<MyMessage>()); /// # Ok(()) /// # } /// ``` - pub fn pack<M: Message>(message: &M) -> ProtobufResult<Any> { + pub fn pack<M: MessageFull>(message: &M) -> crate::Result<Any> { Any::pack_dyn(message) } @@ -40,40 +39,39 @@ impl Any { /// # Examples /// /// ``` - /// use protobuf::Message; - /// # use protobuf::ProtobufResult; - /// use protobuf::well_known_types::Any; + /// use protobuf::{MessageFull, MessageDyn}; + /// use protobuf::well_known_types::any::Any; /// - /// # fn the_test(message: &dyn Message) -> ProtobufResult<()> { - /// let message: &dyn Message = message; + /// # fn the_test(message: &dyn MessageDyn) -> protobuf::Result<()> { + /// let message: &dyn MessageDyn = message; /// let any = Any::pack_dyn(message)?; - /// assert!(any.is_dyn(message.descriptor())); + /// assert!(any.is_dyn(&message.descriptor_dyn())); /// # Ok(()) /// # } /// ``` - pub fn pack_dyn(message: &dyn Message) -> ProtobufResult<Any> { + pub fn pack_dyn(message: &dyn MessageDyn) -> crate::Result<Any> { Any::pack_with_type_url_prefix(message, "type.googleapis.com") } fn pack_with_type_url_prefix( - message: &dyn Message, + message: &dyn MessageDyn, type_url_prefix: &str, - ) -> ProtobufResult<Any> { + ) -> crate::Result<Any> { Ok(Any { - type_url: Any::type_url(type_url_prefix, message.descriptor()), - value: message.write_to_bytes()?, + type_url: Any::type_url(type_url_prefix, &message.descriptor_dyn()), + value: message.write_to_bytes_dyn()?, ..Default::default() }) } /// Check if `Any` contains a message of given type. - pub fn is<M: Message>(&self) -> bool { - self.is_dyn(M::descriptor_static()) + pub fn is<M: MessageFull>(&self) -> bool { + self.is_dyn(&M::descriptor()) } /// Check if `Any` contains a message of given type. pub fn is_dyn(&self, descriptor: &MessageDescriptor) -> bool { - match Any::get_type_name_from_type_url(&self.type_url) { + match Any::type_name_from_type_url(&self.type_url) { Some(type_name) => type_name == descriptor.full_name(), None => false, } @@ -85,7 +83,7 @@ impl Any { /// /// * `Ok(None)` when message type mismatch /// * `Err` when parse failed - pub fn unpack<M: Message>(&self) -> ProtobufResult<Option<M>> { + pub fn unpack<M: MessageFull>(&self) -> crate::Result<Option<M>> { if !self.is::<M>() { return Ok(None); } @@ -101,13 +99,13 @@ impl Any { pub fn unpack_dyn( &self, descriptor: &MessageDescriptor, - ) -> ProtobufResult<Option<Box<dyn Message>>> { + ) -> crate::Result<Option<Box<dyn MessageDyn>>> { if !self.is_dyn(descriptor) { return Ok(None); } let mut message = descriptor.new_instance(); - message.merge_from_bytes(&self.value)?; - message.check_initialized()?; + message.merge_from_bytes_dyn(&self.value)?; + message.check_initialized_dyn()?; Ok(Some(message)) } } diff --git a/src/well_known_types_util/duration.rs b/src/well_known_types_util/duration.rs new file mode 100644 index 0000000..eb68e23 --- /dev/null +++ b/src/well_known_types_util/duration.rs @@ -0,0 +1,67 @@ +use crate::well_known_types::duration::Duration; +use crate::SpecialFields; + +impl Duration { + /// Zero seconds zero nanoseconds. + pub const ZERO: Duration = Duration { + seconds: 0, + nanos: 0, + special_fields: SpecialFields::new(), + }; +} + +/// Convert from `std::time::Duration`. +/// +/// # Panics +/// +/// If `std::time::Duration` value is outside of `Duration` supported range. +impl From<std::time::Duration> for Duration { + fn from(duration: std::time::Duration) -> Self { + Duration { + seconds: duration.as_secs() as i64, + nanos: duration.subsec_nanos() as i32, + ..Default::default() + } + } +} + +/// Convert to `std::time::Duration`. +/// +/// This conversion might be lossy if `std::time::Duration` precision is smaller than nanoseconds. +/// +/// # Panics +/// +/// If `Duration` value is outside of `std::time::Duration` supported range. +impl Into<std::time::Duration> for Duration { + fn into(self) -> std::time::Duration { + assert!(self.seconds >= 0); + std::time::Duration::from_secs(self.seconds as u64) + + std::time::Duration::from_nanos(self.nanos as u64) + } +} + +#[cfg(test)] +mod test { + use crate::well_known_types::duration::Duration; + + #[test] + fn to_from_duration() { + fn to_from(duration: Duration, std_time_duration: std::time::Duration) { + assert_eq!(duration, Duration::from(std_time_duration)); + assert_eq!( + std_time_duration, + Into::<std::time::Duration>::into(duration) + ); + } + + to_from(Duration::ZERO, std::time::Duration::from_secs(0)); + to_from( + Duration { + seconds: 4, + nanos: 123_000_000, + ..Default::default() + }, + std::time::Duration::from_millis(4_123), + ); + } +} diff --git a/src/well_known_types_util/mod.rs b/src/well_known_types_util/mod.rs index bd4c243..4c0d47d 100644 --- a/src/well_known_types_util/mod.rs +++ b/src/well_known_types_util/mod.rs @@ -1 +1,3 @@ mod any; +mod duration; +mod timestamp; diff --git a/src/well_known_types_util/timestamp.rs b/src/well_known_types_util/timestamp.rs new file mode 100644 index 0000000..0429fcf --- /dev/null +++ b/src/well_known_types_util/timestamp.rs @@ -0,0 +1,118 @@ +use std::time::Duration; +use std::time::SystemTime; + +use crate::well_known_types::timestamp::Timestamp; +use crate::SpecialFields; + +impl Timestamp { + /// Unix epoch value of timestamp. + pub const UNIX_EPOCH: Timestamp = Timestamp { + seconds: 0, + nanos: 0, + special_fields: SpecialFields::new(), + }; + + /// Return current time as `Timestamp`. + pub fn now() -> Timestamp { + Timestamp::from(SystemTime::now()) + } +} + +/// Convert from [`Timestamp`]. +/// +/// # Panics +/// +/// This function panics if given `SystemTime` is outside of `Timestamp` range. +impl From<SystemTime> for Timestamp { + fn from(time: SystemTime) -> Self { + match time.duration_since(SystemTime::UNIX_EPOCH) { + Ok(since_epoch) => Timestamp { + seconds: since_epoch.as_secs() as i64, + nanos: since_epoch.subsec_nanos() as i32, + ..Default::default() + }, + Err(e) => { + let before_epoch = e.duration(); + Timestamp { + seconds: -(before_epoch.as_secs() as i64) + - (before_epoch.subsec_nanos() != 0) as i64, + nanos: (1_000_000_000 - before_epoch.subsec_nanos() as i32) % 1_000_000_000, + ..Default::default() + } + } + } + } +} + +/// Convert into [`SystemTime`]. +/// +/// The conversion could be lossy if `SystemTime` precision is smaller than nanoseconds. +/// +/// # Panics +/// +/// This function panics: +/// * if given `Timestamp` is outside of `SystemTime` range +/// * if `Timestamp` is malformed +impl Into<SystemTime> for Timestamp { + fn into(self) -> SystemTime { + if self.seconds >= 0 { + let duration = + Duration::from_secs(self.seconds as u64) + Duration::from_nanos(self.nanos as u64); + SystemTime::UNIX_EPOCH + duration + } else { + let duration = + Duration::from_secs(-self.seconds as u64) - Duration::from_nanos(self.nanos as u64); + SystemTime::UNIX_EPOCH - duration + } + } +} + +#[cfg(test)] +mod test { + use std::time::Duration; + use std::time::SystemTime; + + use crate::well_known_types::timestamp::Timestamp; + + #[test] + fn to_from_system_time() { + fn to_from(timestamp: Timestamp, system_time: SystemTime) { + assert_eq!(timestamp, Timestamp::from(system_time)); + assert_eq!(system_time, Into::<SystemTime>::into(timestamp)); + } + + to_from(Timestamp::UNIX_EPOCH, SystemTime::UNIX_EPOCH); + to_from( + Timestamp { + seconds: 0, + nanos: 200_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH + Duration::from_millis(200), + ); + to_from( + Timestamp { + seconds: 3, + nanos: 200_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH + Duration::from_millis(3_200), + ); + to_from( + Timestamp { + seconds: -1, + nanos: 800_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH - Duration::from_millis(200), + ); + to_from( + Timestamp { + seconds: -4, + nanos: 800_000_000, + ..Default::default() + }, + SystemTime::UNIX_EPOCH - Duration::from_millis(3_200), + ); + } +} diff --git a/src/wire_format.rs b/src/wire_format.rs index 9f54af3..9e4b703 100644 --- a/src/wire_format.rs +++ b/src/wire_format.rs @@ -1,105 +1,142 @@ -//! Serialization constants. +//! Constants used in serializations. -// TODO: temporary -pub use self::WireType::*; +use crate::descriptor::field_descriptor_proto; +use crate::error::WireError; -/// Tag occupies 3 bits -pub const TAG_TYPE_BITS: u32 = 3; -/// Tag mask -pub const TAG_TYPE_MASK: u32 = (1u32 << TAG_TYPE_BITS) - 1; +/// Tag occupies three bits. +pub(crate) const TAG_TYPE_BITS: u32 = 3; +/// Apply this mask to varint value to obtain a tag. +pub(crate) const TAG_TYPE_MASK: u32 = (1u32 << TAG_TYPE_BITS as usize) - 1; /// Max possible field number -pub const FIELD_NUMBER_MAX: u32 = 0x1fffffff; +pub(crate) const FIELD_NUMBER_MAX: u32 = 0x1fffffff; -/// One of six defined protobuf wire types -#[derive(PartialEq, Eq, Clone, Debug)] -pub enum WireType { - /// Varint (e. g. `int32` or `sint64`) - WireTypeVarint = 0, - /// Fixed size 64 bit (e. g. `fixed64` or `double`) - WireTypeFixed64 = 1, - /// Length-delimited (e. g. `message` or `string`) - WireTypeLengthDelimited = 2, - /// Groups are not supported by rust-protobuf - WireTypeStartGroup = 3, - /// Groups are not supported by rust-protobuf - WireTypeEndGroup = 4, - /// Fixed size 64 bit (e. g. `fixed32` or `float`) - WireTypeFixed32 = 5, +pub(crate) const MAX_MESSAGE_SIZE: u64 = i32::MAX as u64; + +#[inline] +pub(crate) fn check_message_size(size: u64) -> crate::Result<u32> { + if size <= MAX_MESSAGE_SIZE { + Ok(size as u32) + } else { + #[cold] + fn message_too_large(size: u64) -> crate::Error { + WireError::MessageTooLarge(size).into() + } + + Err(message_too_large(size)) + } } -impl Copy for WireType {} +/// All supported "wire types" are listed in this enum. +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub enum WireType { + /// Variable-length integer + Varint = 0, + /// 32-bit field (e. g. `fixed64` or `double`) + Fixed64 = 1, + /// Length-delimited field + LengthDelimited = 2, + /// Groups are not supported in rust-protobuf + StartGroup = 3, + /// Groups are not supported in rust-protobuf + EndGroup = 4, + /// 32-bit field (e. g. `fixed32` or `float`) + Fixed32 = 5, +} impl WireType { - /// Parse wire type + /// Construct `WireType` from number, or return `None` if type is unknown. pub fn new(n: u32) -> Option<WireType> { match n { - 0 => Some(WireTypeVarint), - 1 => Some(WireTypeFixed64), - 2 => Some(WireTypeLengthDelimited), - 3 => Some(WireTypeStartGroup), - 4 => Some(WireTypeEndGroup), - 5 => Some(WireTypeFixed32), + 0 => Some(WireType::Varint), + 1 => Some(WireType::Fixed64), + 2 => Some(WireType::LengthDelimited), + 3 => Some(WireType::StartGroup), + 4 => Some(WireType::EndGroup), + 5 => Some(WireType::Fixed32), _ => None, } } + + #[doc(hidden)] + pub fn for_type(field_type: field_descriptor_proto::Type) -> WireType { + use field_descriptor_proto::Type; + match field_type { + Type::TYPE_INT32 => WireType::Varint, + Type::TYPE_INT64 => WireType::Varint, + Type::TYPE_UINT32 => WireType::Varint, + Type::TYPE_UINT64 => WireType::Varint, + Type::TYPE_SINT32 => WireType::Varint, + Type::TYPE_SINT64 => WireType::Varint, + Type::TYPE_BOOL => WireType::Varint, + Type::TYPE_ENUM => WireType::Varint, + Type::TYPE_FIXED32 => WireType::Fixed32, + Type::TYPE_FIXED64 => WireType::Fixed64, + Type::TYPE_SFIXED32 => WireType::Fixed32, + Type::TYPE_SFIXED64 => WireType::Fixed64, + Type::TYPE_FLOAT => WireType::Fixed32, + Type::TYPE_DOUBLE => WireType::Fixed64, + Type::TYPE_STRING => WireType::LengthDelimited, + Type::TYPE_BYTES => WireType::LengthDelimited, + Type::TYPE_MESSAGE => WireType::LengthDelimited, + Type::TYPE_GROUP => WireType::LengthDelimited, // not true + } + } } -/// Parsed protobuf tag, which is a pair of field number and wire type -#[derive(Clone)] -pub struct Tag { +/// Parsed field tag (a pair of field number and wire type) +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) struct Tag { field_number: u32, wire_type: WireType, } -impl Copy for Tag {} - impl Tag { - /// Pack a tag to integer - pub fn value(self) -> u32 { + /// Fold tag to a number to be serialized. + pub(crate) fn value(self) -> u32 { (self.field_number << TAG_TYPE_BITS) | (self.wire_type as u32) } - /// Parse integer into `Tag` object - // TODO: should return Result instead of Option - pub fn new(value: u32) -> Option<Tag> { + /// Extract wire type and field number from integer tag + pub(crate) fn new(value: u32) -> crate::Result<Tag> { let wire_type = WireType::new(value & TAG_TYPE_MASK); if wire_type.is_none() { - return None; + return Err(WireError::IncorrectTag(value).into()); } let field_number = value >> TAG_TYPE_BITS; if field_number == 0 { - return None; + return Err(WireError::IncorrectTag(value).into()); } - Some(Tag { - field_number: field_number, + Ok(Tag { + field_number, wire_type: wire_type.unwrap(), }) } - /// Create a tag from a field number and wire type. + /// Construct a tag from a field number and wire type. /// /// # Panics /// - /// If field number is outside of allowed range. - pub fn make(field_number: u32, wire_type: WireType) -> Tag { + /// If field number is outside of valid range. + pub(crate) fn make(field_number: u32, wire_type: WireType) -> Tag { assert!(field_number > 0 && field_number <= FIELD_NUMBER_MAX); Tag { - field_number: field_number, - wire_type: wire_type, + field_number, + wire_type, } } - /// Tag as pair of (field number, wire type) - pub fn unpack(self) -> (u32, WireType) { + /// Get field number and wire type + pub(crate) fn unpack(self) -> (u32, WireType) { (self.field_number(), self.wire_type()) } + /// Get wire type fn wire_type(self) -> WireType { self.wire_type } - /// Protobuf field number - pub fn field_number(self) -> u32 { + /// Get field number + pub(crate) fn field_number(self) -> u32 { self.field_number } } diff --git a/src/zigzag.rs b/src/zigzag.rs index 4c7d27d..f4d00b3 100644 --- a/src/zigzag.rs +++ b/src/zigzag.rs @@ -1,22 +1,43 @@ // ZigZag endoging used for efficient transfer of signed integers // https://developers.google.com/protocol-buffers/docs/encoding#types -pub fn decode_zig_zag_32(n: u32) -> i32 { +use crate::rt::compute_raw_varint32_size; +use crate::rt::compute_raw_varint64_size; + +pub(crate) fn decode_zig_zag_32(n: u32) -> i32 { ((n >> 1) as i32) ^ (-((n & 1) as i32)) } -pub fn decode_zig_zag_64(n: u64) -> i64 { +pub(crate) fn decode_zig_zag_64(n: u64) -> i64 { ((n >> 1) as i64) ^ (-((n & 1) as i64)) } -pub fn encode_zig_zag_32(n: i32) -> u32 { +pub(crate) fn encode_zig_zag_32(n: i32) -> u32 { ((n << 1) ^ (n >> 31)) as u32 } -pub fn encode_zig_zag_64(n: i64) -> u64 { +pub(crate) fn encode_zig_zag_64(n: i64) -> u64 { ((n << 1) ^ (n >> 63)) as u64 } +/// Helper trait implemented by integer types which could be encoded as zigzag varint. +pub(crate) trait ProtobufVarintZigzag { + /// Size of self when encoded as zigzag varint. + fn len_varint_zigzag(&self) -> u64; +} + +impl ProtobufVarintZigzag for i64 { + fn len_varint_zigzag(&self) -> u64 { + compute_raw_varint64_size(encode_zig_zag_64(*self)) + } +} + +impl ProtobufVarintZigzag for i32 { + fn len_varint_zigzag(&self) -> u64 { + compute_raw_varint32_size(encode_zig_zag_32(*self)) + } +} + #[cfg(test)] mod test { |