From 9d32945a0c9bae5dfe4780c49fce912f5c1967b5 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Wed, 4 Sep 2024 19:02:58 +0200 Subject: [PATCH 1/5] fix: allow commas and semicolons between fields in constant messages According to the Protobuf Specification the fields in a constant message can be separated by spaces, commas or semicolons. All the following variants are accepted by the official compiler`protoc`. ``` {foo: 1,bar: 2,baz: 3,} {foo: 1;bar: 2;baz: 3;} {foo: 1 bar: 2 baz: 3} {foo: 1,bar: 2;baz: 3} {foo: 1,bar: 2 baz: 3} ``` --- protobuf-parse/src/pure/parser.rs | 35 +++++++++++++++++++++++++ protobuf-support/src/lexer/tokenizer.rs | 12 ++++++--- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/protobuf-parse/src/pure/parser.rs b/protobuf-parse/src/pure/parser.rs index a4f16e87a..a61a110b1 100644 --- a/protobuf-parse/src/pure/parser.rs +++ b/protobuf-parse/src/pure/parser.rs @@ -377,6 +377,18 @@ impl<'a> Parser<'a> { while !self.tokenizer.lookahead_is_symbol('}')? { let n = self.next_message_constant_field_name()?; let v = self.next_field_value()?; + + // Consume the comma or semicolon if present. Commas and semicolons + // between message fields are optional, all these are valid: + // + // {foo: 1,bar: 2,baz: 3,} + // {foo: 1;bar: 2;baz: 3;} + // {foo: 1 bar: 2 baz: 3} + // {foo: 1,bar: 2;baz: 3} + // {foo: 1,bar: 2 baz: 3} + // + self.tokenizer.next_symbol_if_in(&[',', ';'])?; + r.fields.insert(n, v); } self.tokenizer @@ -1336,6 +1348,29 @@ mod test { assert_eq!("10", mess.t.options[0].value.format()); } + #[test] + fn test_field_options() { + let msg = r#" (my_opt).my_field = {foo: 1 bar: 2} "#; + let opt = parse(msg, |p| p.next_field_option()); + assert_eq!(r#"{ foo: 1 bar: 2 }"#, opt.value.format()); + + let msg = r#" (my_opt).my_field = {foo: 1; bar:2;} "#; + let opt = parse(msg, |p| p.next_field_option()); + assert_eq!(r#"{ foo: 1 bar: 2 }"#, opt.value.format()); + + let msg = r#" (my_opt).my_field = {foo: 1, bar: 2} "#; + let opt = parse(msg, |p| p.next_field_option()); + assert_eq!(r#"{ foo: 1 bar: 2 }"#, opt.value.format()); + + let msg = r#" (my_opt).my_field = "foo" "#; + let opt = parse(msg, |p| p.next_field_option()); + assert_eq!(r#""foo""#, opt.value.format()); + + let msg = r#" (my_opt) = { my_field: "foo"} "#; + let opt = parse(msg, |p| p.next_field_option()); + assert_eq!(r#"{ my_field: "foo" }"#, opt.value.format()); + } + #[test] fn test_message() { let msg = r#"message ReferenceData diff --git a/protobuf-support/src/lexer/tokenizer.rs b/protobuf-support/src/lexer/tokenizer.rs index c5e84a0a9..94b641d3d 100644 --- a/protobuf-support/src/lexer/tokenizer.rs +++ b/protobuf-support/src/lexer/tokenizer.rs @@ -194,11 +194,15 @@ impl<'a> Tokenizer<'a> { Ok(()) } - pub fn next_symbol_if_eq(&mut self, symbol: char) -> TokenizerResult { - Ok(self.next_token_if(|token| match token { - &Token::Symbol(c) if c == symbol => true, + pub fn next_symbol_if_in(&mut self, symbols: &[char]) -> TokenizerResult { + self.next_token_if(|token| match token { + Token::Symbol(c) if symbols.contains(c) => true, _ => false, - })? != None) + }).map(|token| token.is_some()) + } + + pub fn next_symbol_if_eq(&mut self, symbol: char) -> TokenizerResult { + self.next_symbol_if_in(&[symbol]) } pub fn next_symbol_expect_eq( From 6d98abac0acc210217ccb538114b61405185b228 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Wed, 4 Sep 2024 19:13:15 +0200 Subject: [PATCH 2/5] fix: minor spacing issue while formatting constant messages --- protobuf-parse/src/pure/model.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/protobuf-parse/src/pure/model.rs b/protobuf-parse/src/pure/model.rs index 8e2cb5fa9..25a57de47 100644 --- a/protobuf-parse/src/pure/model.rs +++ b/protobuf-parse/src/pure/model.rs @@ -426,11 +426,11 @@ impl fmt::Display for ProtobufConstant { impl ProtobufConstantMessage { pub fn format(&self) -> String { let mut s = String::new(); - write!(s, "{{").unwrap(); + write!(s, "{{ ").unwrap(); for (n, v) in &self.fields { match v { ProtobufConstant::Message(m) => write!(s, "{} {}", n, m.format()).unwrap(), - v => write!(s, "{}: {}", n, v.format()).unwrap(), + v => write!(s, "{}: {} ", n, v.format()).unwrap(), } } write!(s, "}}").unwrap(); From 6951916d9c6411d15e12fedbb79ec5f38693dd51 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Wed, 4 Sep 2024 23:19:22 +0200 Subject: [PATCH 3/5] style: fix format --- protobuf-support/src/lexer/tokenizer.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/protobuf-support/src/lexer/tokenizer.rs b/protobuf-support/src/lexer/tokenizer.rs index 94b641d3d..5541b1d2d 100644 --- a/protobuf-support/src/lexer/tokenizer.rs +++ b/protobuf-support/src/lexer/tokenizer.rs @@ -198,7 +198,8 @@ impl<'a> Tokenizer<'a> { self.next_token_if(|token| match token { Token::Symbol(c) if symbols.contains(c) => true, _ => false, - }).map(|token| token.is_some()) + }) + .map(|token| token.is_some()) } pub fn next_symbol_if_eq(&mut self, symbol: char) -> TokenizerResult { From 35d421f6ce1b645afc833fb12b3ef180631c2858 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Thu, 5 Sep 2024 00:27:34 +0200 Subject: [PATCH 4/5] chore: apply fixes to all the codebase with `cargo clippy --fix` Checking the source code with Clippy is a good practice that helps maintaining the code in good shape and ensures an homogeneous style. Most of the automatic fixes in this commit are small cosmetic changes, but some of them improve legibility or even performance. If this change is accepted I plan to keep applying more fixes for hints that Clippy reports but can't fix automatically. --- ci-gen/src/ghwf.rs | 35 ++++--- ci-gen/src/main.rs | 16 ++-- ci-gen/src/yaml.rs | 11 +-- protobuf-codegen/src/codegen/mod.rs | 13 +-- protobuf-codegen/src/gen/all.rs | 6 +- protobuf-codegen/src/gen/code_writer.rs | 12 ++- protobuf-codegen/src/gen/enums.rs | 6 +- protobuf-codegen/src/gen/field/accessor.rs | 4 +- protobuf-codegen/src/gen/field/mod.rs | 42 ++++---- protobuf-codegen/src/gen/field/option_kind.rs | 8 +- protobuf-codegen/src/gen/file.rs | 4 +- protobuf-codegen/src/gen/file_descriptor.rs | 16 ++-- protobuf-codegen/src/gen/message.rs | 8 +- protobuf-codegen/src/gen/mod_rs.rs | 2 +- protobuf-codegen/src/gen/oneof.rs | 7 +- protobuf-codegen/src/gen/paths.rs | 4 +- protobuf-codegen/src/gen/rust/keywords.rs | 11 +-- protobuf-codegen/src/gen/rust/rel_path.rs | 2 +- protobuf-codegen/src/gen/rust_types_values.rs | 72 +++++++------- protobuf-codegen/src/gen/scope.rs | 26 ++--- protobuf-codegen/src/gen/strx.rs | 2 +- protobuf-codegen/src/gen/well_known_types.rs | 2 +- protobuf-examples/customize-serde/build.rs | 2 +- protobuf-json-mapping/src/base64.rs | 6 +- protobuf-json-mapping/src/parse.rs | 8 +- protobuf-json-mapping/src/print.rs | 19 ++-- protobuf-json-mapping/src/rfc_3339.rs | 20 ++-- protobuf-parse/src/parser.rs | 4 +- protobuf-parse/src/protobuf_abs_path.rs | 6 +- protobuf-parse/src/protobuf_ident.rs | 10 +- protobuf-parse/src/protobuf_rel_path.rs | 6 +- protobuf-parse/src/protoc/command.rs | 10 +- protobuf-parse/src/pure/convert/mod.rs | 26 ++--- .../src/pure/convert/option_resolver.rs | 95 +++++++++---------- .../src/pure/convert/type_resolver.rs | 14 +-- protobuf-parse/src/pure/model.rs | 16 +--- .../src/pure/parse_and_typecheck.rs | 8 +- protobuf-parse/src/pure/parser.rs | 20 ++-- .../src/test_against_protobuf_protos.rs | 2 +- protobuf-parse/src/which_parser.rs | 7 +- protobuf-support/src/lexer/float.rs | 2 +- protobuf-support/src/lexer/lexer_impl.rs | 59 +++++------- protobuf-support/src/lexer/token.rs | 10 +- protobuf-support/src/lexer/tokenizer.rs | 20 ++-- protobuf-support/src/toposort.rs | 2 +- protobuf/build.rs | 2 +- protobuf/src/chars.rs | 8 +- .../src/coded_input_stream/buf_read_iter.rs | 35 +++---- protobuf/src/coded_input_stream/input_buf.rs | 2 +- protobuf/src/coded_input_stream/mod.rs | 21 ++-- protobuf/src/coded_output_stream/buffer.rs | 6 +- protobuf/src/coded_output_stream/with.rs | 4 +- protobuf/src/lazy.rs | 6 ++ protobuf/src/message.rs | 4 +- protobuf/src/message_dyn.rs | 4 +- protobuf/src/message_field.rs | 4 +- protobuf/src/owning_ref.rs | 4 +- protobuf/src/reflect/dynamic/map.rs | 2 +- protobuf/src/reflect/dynamic/mod.rs | 6 +- protobuf/src/reflect/dynamic/optional.rs | 2 +- protobuf/src/reflect/dynamic/repeated.rs | 36 +++---- protobuf/src/reflect/enums/mod.rs | 2 +- protobuf/src/reflect/field/dynamic.rs | 10 +- protobuf/src/reflect/file/index.rs | 9 +- protobuf/src/reflect/file/mod.rs | 4 +- protobuf/src/reflect/find_message_or_enum.rs | 2 +- protobuf/src/reflect/map/generated.rs | 5 +- protobuf/src/reflect/message/mod.rs | 8 +- protobuf/src/reflect/name.rs | 14 ++- protobuf/src/reflect/oneof/mod.rs | 2 +- protobuf/src/reflect/repeated/iter.rs | 2 +- protobuf/src/reflect/repeated/mod.rs | 8 +- protobuf/src/reflect/runtime_types.rs | 8 +- protobuf/src/reflect/types.rs | 12 +-- protobuf/src/rt/packed.rs | 2 +- protobuf/src/text_format/parse.rs | 6 +- protobuf/src/text_format/print.rs | 12 +-- protobuf/src/unknown.rs | 16 ++-- protobuf/src/varint/decode.rs | 4 +- .../src/well_known_types_util/duration.rs | 10 +- .../src/well_known_types_util/timestamp.rs | 10 +- test-crates/perftest/bytes/build.rs | 4 +- test-crates/perftest/misc/build.rs | 2 +- test-crates/perftest/vs-cxx/perftest.rs | 15 ++- .../tests/diff.rs | 20 ++-- .../protobuf-codegen-protoc-test/build.rs | 4 +- .../v2/test_dynamic_repeated_get_set.rs | 2 +- .../v2/test_dynamic_singular_get_set.rs | 4 +- .../src/common/v2/test_ext.rs | 2 +- .../src/common/v2/test_fmt_json.rs | 4 +- .../src/common/v2/test_fmt_json_well_known.rs | 4 +- .../src/common/v2/test_fmt_text_format.rs | 2 +- .../src/common/v2/test_generate_accessors.rs | 2 +- .../src/common/v2/test_message_getter.rs | 2 +- .../src/common/v2/test_oneof_basic.rs | 6 +- .../src/common/v2/test_oneof_nonexhaustive.rs | 2 - .../src/common/v2/test_reflect_basic.rs | 3 +- .../src/v2/test_default_values.rs | 4 +- .../protobuf-codegen-pure-test/build.rs | 14 +-- test-crates/protobuf-fuzz/src/lib.rs | 4 +- test-crates/protobuf-test-common/src/build.rs | 18 ++-- test-crates/protobuf-test-common/src/hex.rs | 8 +- .../protobuf-test-common/src/interop.rs | 2 +- .../protobuf-test-common/src/json_tests.rs | 6 +- .../protobuf-test-common/src/reflect_tests.rs | 2 +- .../src/text_format_tests.rs | 16 ++-- 106 files changed, 521 insertions(+), 604 deletions(-) diff --git a/ci-gen/src/ghwf.rs b/ci-gen/src/ghwf.rs index 8ec483243..30dc1d517 100644 --- a/ci-gen/src/ghwf.rs +++ b/ci-gen/src/ghwf.rs @@ -4,17 +4,14 @@ use crate::yaml::Yaml; #[allow(dead_code)] #[derive(Copy, Clone, Eq, PartialEq)] +#[derive(Default)] pub enum Env { WindowsLatest, + #[default] UbuntuLatest, MacosLatest, } -impl Default for Env { - fn default() -> Self { - Env::UbuntuLatest - } -} impl fmt::Display for Env { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -60,7 +57,7 @@ impl Step { name: name.to_owned(), uses: Some(uses.to_owned()), env: env - .into_iter() + .iter() .map(|(k, v)| (String::from(*k), String::from(*v))) .collect(), with: Some(with), @@ -85,8 +82,8 @@ impl Step { } } -impl Into for Step { - fn into(self) -> Yaml { +impl From for Yaml { + fn from(val: Step) -> Self { let Step { name, uses, @@ -94,7 +91,7 @@ impl Into for Step { run, shell, env, - } = self; + } = val; let mut entries = Vec::new(); entries.push(("name", Yaml::string(name))); if let Some(uses) = uses { @@ -134,23 +131,23 @@ impl Job { } } -impl Into<(String, Yaml)> for Job { - fn into(self) -> (String, Yaml) { - assert!(!self.id.is_empty()); +impl From for (String, Yaml) { + fn from(val: Job) -> Self { + assert!(!val.id.is_empty()); let mut entries = vec![ - ("name", Yaml::string(self.name)), - ("runs-on", Yaml::string(format!("{}", self.runs_on))), + ("name", Yaml::string(val.name)), + ("runs-on", Yaml::string(format!("{}", val.runs_on))), ]; - if let Some(timeout_minutes) = self.timeout_minutes { + if let Some(timeout_minutes) = val.timeout_minutes { entries.push(( "timeout-minutes", Yaml::string(format!("{}", timeout_minutes)), )); } - if !self.env.is_empty() { - entries.push(("env", Yaml::map(self.env))); + if !val.env.is_empty() { + entries.push(("env", Yaml::map(val.env))); } - entries.push(("steps", Yaml::list(self.steps))); - (self.id, Yaml::map(entries)) + entries.push(("steps", Yaml::list(val.steps))); + (val.id, Yaml::map(entries)) } } diff --git a/ci-gen/src/main.rs b/ci-gen/src/main.rs index 362f42894..2e6d1c97d 100644 --- a/ci-gen/src/main.rs +++ b/ci-gen/src/main.rs @@ -55,9 +55,9 @@ enum Features { impl Features { fn flag(&self) -> String { match self { - Features::Default => format!(""), + Features::Default => String::new(), Features::Specific(f) => format!("--features={}", f.join(",")), - Features::All => format!("--all-features"), + Features::All => "--all-features".to_string(), } } @@ -72,16 +72,16 @@ impl Features { fn id(&self) -> String { match self { - Features::Default => format!("default-features"), - Features::All => format!("all-features"), + Features::Default => "default-features".to_string(), + Features::All => "all-features".to_string(), Features::Specific(s) => s.join("-"), } } fn name(&self) -> String { match self { - Features::Default => format!("default features"), - Features::All => format!("all features"), + Features::Default => "default features".to_string(), + Features::All => "all features".to_string(), Features::Specific(s) => s.join(","), } } @@ -89,8 +89,8 @@ impl Features { fn self_check_job() -> Job { Job { - id: format!("self-check"), - name: format!("CI self-check"), + id: "self-check".to_string(), + name: "CI self-check".to_string(), runs_on: LINUX.ghwf, steps: vec![ checkout_sources(), diff --git a/ci-gen/src/yaml.rs b/ci-gen/src/yaml.rs index c672c6e69..1446a9da6 100644 --- a/ci-gen/src/yaml.rs +++ b/ci-gen/src/yaml.rs @@ -62,22 +62,19 @@ pub struct YamlWriter { } #[derive(Eq, PartialEq)] +#[derive(Default)] enum MinusState { + #[default] No, Yes, Already, } -impl Default for MinusState { - fn default() -> Self { - MinusState::No - } -} impl YamlWriter { pub fn write_line(&mut self, line: &str) { if line.is_empty() { - self.buffer.push_str("\n"); + self.buffer.push('\n'); } else { for _ in 0..self.indent { self.buffer.push_str(" "); @@ -95,7 +92,7 @@ impl YamlWriter { } self.buffer.push_str(line); - self.buffer.push_str("\n"); + self.buffer.push('\n'); } } diff --git a/protobuf-codegen/src/codegen/mod.rs b/protobuf-codegen/src/codegen/mod.rs index 2e6406cdc..c1ee69464 100644 --- a/protobuf-codegen/src/codegen/mod.rs +++ b/protobuf-codegen/src/codegen/mod.rs @@ -15,16 +15,13 @@ use crate::gen_and_write::gen_and_write; use crate::Customize; #[derive(Debug)] +#[derive(Default)] enum WhichParser { + #[default] Pure, Protoc, } -impl Default for WhichParser { - fn default() -> WhichParser { - WhichParser::Pure - } -} #[derive(Debug, thiserror::Error)] enum CodegenError { @@ -221,9 +218,9 @@ impl Codegen { if self.create_out_dir { if out_dir.exists() { - fs::remove_dir_all(&out_dir)?; + fs::remove_dir_all(out_dir)?; } - fs::create_dir(&out_dir)?; + fs::create_dir(out_dir)?; } let mut parser = Parser::new(); @@ -257,7 +254,7 @@ impl Codegen { &parsed_and_typechecked.file_descriptors, &parsed_and_typechecked.parser, &parsed_and_typechecked.relative_paths, - &out_dir, + out_dir, &self.customize, &*self.customize_callback, ) diff --git a/protobuf-codegen/src/gen/all.rs b/protobuf-codegen/src/gen/all.rs index 312b8dbe6..b9738c8ec 100644 --- a/protobuf-codegen/src/gen/all.rs +++ b/protobuf-codegen/src/gen/all.rs @@ -42,11 +42,9 @@ pub(crate) fn gen_all( }; for file_name in files_to_generate { - let file = files_map.get(file_name.as_path()).expect(&format!( - "file not found in file descriptors: {:?}, files: {:?}", + let file = files_map.get(file_name.as_path()).unwrap_or_else(|| panic!("file not found in file descriptors: {:?}, files: {:?}", file_name, - files_map.keys() - )); + files_map.keys())); let gen_file_result = gen_file(file, &files_map, &root_scope, &customize, parser)?; results.push(gen_file_result.compiler_plugin_result); mods.push(gen_file_result.mod_name); diff --git a/protobuf-codegen/src/gen/code_writer.rs b/protobuf-codegen/src/gen/code_writer.rs index 17b177f7e..05243ae7d 100644 --- a/protobuf-codegen/src/gen/code_writer.rs +++ b/protobuf-codegen/src/gen/code_writer.rs @@ -23,7 +23,10 @@ impl<'a> CodeWriter<'a> { } pub(crate) fn with_no_error(f: impl FnOnce(&mut CodeWriter)) -> String { - Self::with_impl::(|w| Ok(f(w))).unwrap_or_else(|e| match e {}) + Self::with_impl::(|w| { + f(w); + Ok(()) + }).unwrap_or_else(|e| match e {}) } pub(crate) fn with(f: F) -> anyhow::Result @@ -47,7 +50,7 @@ impl<'a> CodeWriter<'a> { pub(crate) fn write_line>(&mut self, line: S) { if line.as_ref().is_empty() { - self.writer.push_str("\n"); + self.writer.push('\n'); } else { let s: String = [self.indent.as_ref(), line.as_ref(), "\n"].concat(); self.writer.push_str(&s); @@ -96,7 +99,7 @@ impl<'a> CodeWriter<'a> { } pub(crate) fn unimplemented(&mut self) { - self.write_line(format!("unimplemented!();")); + self.write_line("unimplemented!();"); } pub(crate) fn indented(&mut self, cb: F) @@ -333,8 +336,7 @@ impl<'a> CodeWriter<'a> { let lines = doc .iter() - .map(|doc| doc.lines()) - .flatten() + .flat_map(|doc| doc.lines()) .collect::>(); // Skip comments with code blocks to avoid rustdoc trying to compile them. diff --git a/protobuf-codegen/src/gen/enums.rs b/protobuf-codegen/src/gen/enums.rs index e6d891d25..83fec7d2d 100644 --- a/protobuf-codegen/src/gen/enums.rs +++ b/protobuf-codegen/src/gen/enums.rs @@ -167,7 +167,7 @@ impl<'a> EnumGen<'a> { w.comment("Note: you cannot use pattern matching for enums with allow_alias option"); } w.derive(&derive); - let ref type_name = self.type_name; + let type_name = &self.type_name; write_protoc_insertion_point_for_enum( w, &self.customize.for_elem, @@ -294,7 +294,7 @@ impl<'a> EnumGen<'a> { } fn write_impl_enum_full(&self, w: &mut CodeWriter) { - let ref type_name = self.type_name; + let type_name = &self.type_name; w.impl_for_block( &format!( "{}::EnumFull", @@ -351,7 +351,7 @@ impl<'a> EnumGen<'a> { }); w.write_line("};"); } - w.write_line(&format!("Self::enum_descriptor().value_by_index(index)")); + w.write_line("Self::enum_descriptor().value_by_index(index)"); }); } diff --git a/protobuf-codegen/src/gen/field/accessor.rs b/protobuf-codegen/src/gen/field/accessor.rs index 0fa7ec3bf..0dbbc8615 100644 --- a/protobuf-codegen/src/gen/field/accessor.rs +++ b/protobuf-codegen/src/gen/field/accessor.rs @@ -27,9 +27,9 @@ impl AccessorFn { s.push_str("::<_"); for p in &self.type_params { s.push_str(", "); - s.push_str(&p); + s.push_str(p); } - s.push_str(">"); + s.push('>'); s } } diff --git a/protobuf-codegen/src/gen/field/mod.rs b/protobuf-codegen/src/gen/field/mod.rs index 344aca2e2..d691fa279 100644 --- a/protobuf-codegen/src/gen/field/mod.rs +++ b/protobuf-codegen/src/gen/field/mod.rs @@ -47,7 +47,7 @@ use crate::gen::scope::FieldWithContext; use crate::gen::scope::MessageWithScope; use crate::gen::scope::RootScope; -fn field_type_protobuf_name<'a>(field: &'a FieldDescriptorProto) -> &'a str { +fn field_type_protobuf_name(field: &FieldDescriptorProto) -> &str { if field.has_type_name() { field.type_name() } else { @@ -250,7 +250,7 @@ impl<'a> FieldGen<'a> { Ok(FieldGen { syntax: field.message.message.file_descriptor().syntax(), - rust_name: rust_field_name_for_protobuf_field_name(&field.field.name()), + rust_name: rust_field_name_for_protobuf_field_name(field.field.name()), proto_type: field.field.proto().type_(), wire_type: WireType::for_type(field.field.proto().type_()), proto_field: field, @@ -291,9 +291,9 @@ impl<'a> FieldGen<'a> { pub(crate) fn elem(&self) -> &FieldElem { match self.kind { - FieldKind::Singular(SingularField { ref elem, .. }) => &elem, - FieldKind::Repeated(RepeatedField { ref elem, .. }) => &elem, - FieldKind::Oneof(OneofField { ref elem, .. }) => &elem, + FieldKind::Singular(SingularField { ref elem, .. }) => elem, + FieldKind::Repeated(RepeatedField { ref elem, .. }) => elem, + FieldKind::Oneof(OneofField { ref elem, .. }) => elem, FieldKind::Map(..) => unreachable!(), } } @@ -423,9 +423,9 @@ impl<'a> FieldGen<'a> { ReflectValueRef::String(v) => quote_escape_str(v), ReflectValueRef::Bytes(v) => quote_escape_bytes(v), ReflectValueRef::F32(v) => Self::defaut_value_from_proto_float(v as f64, "f32"), - ReflectValueRef::F64(v) => Self::defaut_value_from_proto_float(v as f64, "f64"), + ReflectValueRef::F64(v) => Self::defaut_value_from_proto_float(v, "f64"), ReflectValueRef::Enum(_e, _v) => { - if let &FieldElem::Enum(ref e) = elem { + if let FieldElem::Enum(e) = elem { format!("{}", e.default_value_rust_expr(&self.file_and_mod())) } else { unreachable!() @@ -988,14 +988,10 @@ impl<'a> FieldGen<'a> { fn write_merge_from_map_case_block(&self, map: &MapField, w: &mut CodeWriter) { let MapField { key, value, .. } = map; w.case_block(&format!("{}", self.tag()), |w| { - w.write_line(&format!("let len = is.read_raw_varint32()?;",)); - w.write_line(&format!("let old_limit = is.push_limit(len as u64)?;")); - w.write_line(&format!( - "let mut key = ::std::default::Default::default();" - )); - w.write_line(&format!( - "let mut value = ::std::default::Default::default();" - )); + w.write_line("let len = is.read_raw_varint32()?;"); + w.write_line("let old_limit = is.push_limit(len as u64)?;"); + w.write_line("let mut key = ::std::default::Default::default();"); + w.write_line("let mut value = ::std::default::Default::default();"); w.while_block("let Some(tag) = is.read_raw_tag_or_eof()?", |w| { w.match_block("tag", |w| { let key_tag = make_tag(1, WireType::for_type(key.proto_type())); @@ -1017,7 +1013,7 @@ impl<'a> FieldGen<'a> { ); }); }); - w.write_line(&format!("is.pop_limit(old_limit);")); + w.write_line("is.pop_limit(old_limit);"); w.write_line(&format!( "{field}.insert(key, value);", field = self.self_field() @@ -1169,7 +1165,7 @@ impl<'a> FieldGen<'a> { match &self.kind { FieldKind::Singular(s @ SingularField { elem, .. }) => { self.write_if_let_self_field_is_some(s, w, |v, w| { - self.write_write_element(&elem, w, os, &v); + self.write_write_element(elem, w, os, v); }); } FieldKind::Repeated(RepeatedField { @@ -1244,7 +1240,7 @@ impl<'a> FieldGen<'a> { match &self.kind { FieldKind::Singular(s @ SingularField { elem, .. }) => { self.write_if_let_self_field_is_some(s, w, |v, w| { - self.write_element_size(&elem, w, v, sum_var) + self.write_element_size(elem, w, v, sum_var) }); } FieldKind::Repeated(RepeatedField { @@ -1294,7 +1290,7 @@ impl<'a> FieldGen<'a> { SingularFieldFlag::WithoutFlag => unimplemented!(), SingularFieldFlag::WithFlag { option_kind, .. } => { let self_field = self.self_field(); - let ref field_type_name = self.elem().rust_storage_elem_type( + let field_type_name = &self.elem().rust_storage_elem_type( &self .proto_field .message @@ -1324,10 +1320,10 @@ impl<'a> FieldGen<'a> { w.write_line(&format!("self.{}.enum_value_or_default()", self.rust_name)); } SingularFieldFlag::WithFlag { .. } => { - w.match_expr(&self.self_field(), |w| { + w.match_expr(self.self_field(), |w| { let default_value = self.xxx_default_value_rust(); w.case_expr("Some(e)", &format!("e.enum_value_or({})", default_value)); - w.case_expr("None", &format!("{}", default_value)); + w.case_expr("None", &default_value); }); } } @@ -1764,7 +1760,7 @@ impl<'a> FieldGen<'a> { } => { if !elem.is_copy() { w.write_line( - &option_kind.unwrap_or_else( + option_kind.unwrap_or_else( &format!("{}.take()", self.self_field()), &elem .rust_storage_elem_type( @@ -1819,7 +1815,7 @@ impl<'a> FieldGen<'a> { take_xxx_return_type.to_code(&self.customize) ), |w| match self.kind { - FieldKind::Singular(ref s) => self.write_message_field_take_singular(&s, w), + FieldKind::Singular(ref s) => self.write_message_field_take_singular(s, w), FieldKind::Oneof(ref o) => self.write_message_field_take_oneof(o, w), FieldKind::Repeated(..) | FieldKind::Map(..) => { w.write_line(&format!( diff --git a/protobuf-codegen/src/gen/field/option_kind.rs b/protobuf-codegen/src/gen/field/option_kind.rs index 0fde11a94..43eed29f4 100644 --- a/protobuf-codegen/src/gen/field/option_kind.rs +++ b/protobuf-codegen/src/gen/field/option_kind.rs @@ -35,15 +35,11 @@ impl OptionKind { } pub(crate) fn unwrap_or_else(&self, what: &str, default_value: &str) -> String { - match self { - _ => format!("{}.unwrap_or_else(|| {})", what, default_value), - } + format!("{}.unwrap_or_else(|| {})", what, default_value) } pub(crate) fn unwrap_ref_or_else(&self, what: &str, default_value: &str) -> String { - match self { - _ => format!("{}.unwrap_or_else(|| {})", what, default_value), - } + format!("{}.unwrap_or_else(|| {})", what, default_value) } pub(crate) fn wrap_value(&self, value: &str, customize: &Customize) -> String { diff --git a/protobuf-codegen/src/gen/file.rs b/protobuf-codegen/src/gen/file.rs index 119a8f1eb..5d3c27afa 100644 --- a/protobuf-codegen/src/gen/file.rs +++ b/protobuf-codegen/src/gen/file.rs @@ -96,7 +96,7 @@ pub(crate) fn gen_file( MessageGen::new( file_descriptor, message, - &root_scope, + root_scope, &customize, &path, file_descriptor.proto().source_code_info.as_ref(), @@ -129,7 +129,7 @@ pub(crate) fn gen_file( .write(w); } - write_extensions(file_descriptor, &root_scope, w, &customize); + write_extensions(file_descriptor, root_scope, w, &customize); if !lite_runtime { w.write_line(""); diff --git a/protobuf-codegen/src/gen/file_descriptor.rs b/protobuf-codegen/src/gen/file_descriptor.rs index 2c8249c36..b069fc2c8 100644 --- a/protobuf-codegen/src/gen/file_descriptor.rs +++ b/protobuf-codegen/src/gen/file_descriptor.rs @@ -76,13 +76,13 @@ fn write_generate_file_descriptor( w.write_line(&format!( "{}::reflect::GeneratedFileDescriptor::new_generated(", - protobuf_crate_path(&customize), + protobuf_crate_path(customize), )); w.indented(|w| { - w.write_line(&format!("file_descriptor_proto(),")); - w.write_line(&format!("deps,")); - w.write_line(&format!("messages,")); - w.write_line(&format!("enums,")); + w.write_line("file_descriptor_proto(),"); + w.write_line("deps,"); + w.write_line("messages,"); + w.write_line("enums,"); }); w.write_line(")"); } @@ -122,7 +122,7 @@ fn write_file_descriptor( ); w.write_line(&format!( "{protobuf_crate}::reflect::FileDescriptor::new_generated_2(generated_file_descriptor)", - protobuf_crate=protobuf_crate_path(&customize), + protobuf_crate=protobuf_crate_path(customize), )); } ); @@ -165,9 +165,9 @@ pub(crate) fn write_file_descriptor_data( }); w.write_line("\";"); w.write_line(""); - write_file_descriptor_proto(&customize, w); + write_file_descriptor_proto(customize, w); w.write_line(""); - write_file_descriptor(file, &customize, w); + write_file_descriptor(file, customize, w); } fn write_file_descriptor_proto(customize: &Customize, w: &mut CodeWriter) { diff --git a/protobuf-codegen/src/gen/message.rs b/protobuf-codegen/src/gen/message.rs index bd8a1098a..84718ad06 100644 --- a/protobuf-codegen/src/gen/message.rs +++ b/protobuf-codegen/src/gen/message.rs @@ -207,7 +207,7 @@ impl<'a> MessageGen<'a> { |w| { w.match_block("v", |w| { for variant in variants { - let ref field = variant.field; + let field = &variant.field; let (refv, vtype) = if field.elem_type_is_copy() { ("v", variant.rust_type(&self.file_and_mod())) @@ -450,7 +450,7 @@ impl<'a> MessageGen<'a> { } fn write_is_initialized(&self, w: &mut CodeWriter) { - w.def_fn(&format!("is_initialized(&self) -> bool"), |w| { + w.def_fn("is_initialized(&self) -> bool", |w| { if !self.message.message.is_initialized_is_always_true() { // TODO: use single loop @@ -684,7 +684,7 @@ impl<'a> MessageGen<'a> { self.write_impl_value(w); } - let mod_name = message_name_to_nested_mod_name(&self.message.message.name()); + let mod_name = message_name_to_nested_mod_name(self.message.message.name()); let oneofs = self.oneofs(); let nested_messages: Vec<_> = self @@ -733,7 +733,7 @@ impl<'a> MessageGen<'a> { } first = false; MessageGen::new( - &self.file_descriptor, + self.file_descriptor, nested, self.root_scope, &self.customize, diff --git a/protobuf-codegen/src/gen/mod_rs.rs b/protobuf-codegen/src/gen/mod_rs.rs index a149319ff..4b5679f53 100644 --- a/protobuf-codegen/src/gen/mod_rs.rs +++ b/protobuf-codegen/src/gen/mod_rs.rs @@ -5,7 +5,7 @@ pub(crate) fn gen_mod_rs(mods: &[String]) -> compiler_plugin::GenResult { let v = CodeWriter::with_no_error(|w| { w.comment(&format!("{}generated", "@")); w.write_line(""); - let mut mods: Vec<&String> = mods.into_iter().collect(); + let mut mods: Vec<&String> = mods.iter().collect(); mods.sort(); for m in mods { w.write_line(&format!("pub mod {};", m)); diff --git a/protobuf-codegen/src/gen/oneof.rs b/protobuf-codegen/src/gen/oneof.rs index e1bd33901..4de50579e 100644 --- a/protobuf-codegen/src/gen/oneof.rs +++ b/protobuf-codegen/src/gen/oneof.rs @@ -65,7 +65,6 @@ impl<'a> OneofField<'a> { message .message .fields() - .into_iter() .filter(|f| f.containing_oneof().is_some()), ); } @@ -206,10 +205,8 @@ impl<'a> OneofGen<'a> { let field = self .message .fields - .iter() - .filter(|f| f.proto_field.name() == v.field.name()) - .next() - .expect(&format!("field not found by name: {}", v.field.name())); + .iter().find(|f| f.proto_field.name() == v.field.name()) + .unwrap_or_else(|| panic!("field not found by name: {}", v.field.name())); match field.proto_type { field_descriptor_proto::Type::TYPE_GROUP => None, _ => Some(OneofVariantGen::parse( diff --git a/protobuf-codegen/src/gen/paths.rs b/protobuf-codegen/src/gen/paths.rs index 2bc958d0f..69f4bff04 100644 --- a/protobuf-codegen/src/gen/paths.rs +++ b/protobuf-codegen/src/gen/paths.rs @@ -7,12 +7,12 @@ use crate::Customize; // Copy-pasted from libsyntax. fn ident_start(c: char) -> bool { - (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' + c.is_ascii_lowercase() || c.is_ascii_uppercase() || c == '_' } // Copy-pasted from libsyntax. fn ident_continue(c: char) -> bool { - (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' + c.is_ascii_lowercase() || c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_' } pub(crate) fn proto_path_to_rust_mod(path: &str) -> RustIdent { diff --git a/protobuf-codegen/src/gen/rust/keywords.rs b/protobuf-codegen/src/gen/rust/keywords.rs index 155977da9..648a3b475 100644 --- a/protobuf-codegen/src/gen/rust/keywords.rs +++ b/protobuf-codegen/src/gen/rust/keywords.rs @@ -1,5 +1,5 @@ -#[cfg_attr(rustfmt, rustfmt_skip)] -static RUST_KEYWORDS: &'static [&'static str] = &[ +#[rustfmt::skip] +static RUST_KEYWORDS: &[&str] = &[ "_", "as", "async", @@ -59,8 +59,8 @@ static RUST_KEYWORDS: &'static [&'static str] = &[ ]; // https://internals.rust-lang.org/t/raw-identifiers-dont-work-for-all-identifiers/9094/3 -#[cfg_attr(rustfmt, rustfmt_skip)] -static RUST_KEYWORDS_WHICH_CANNOT_BE_RAW: &'static [&'static str] = &[ +#[rustfmt::skip] +static RUST_KEYWORDS_WHICH_CANNOT_BE_RAW: &[&str] = &[ "super", "self", "Self", @@ -81,6 +81,5 @@ pub(crate) fn is_rust_keyword_which_cannot_be_raw(ident: &str) -> bool { RUST_KEYWORDS_WHICH_CANNOT_BE_RAW .iter() .cloned() - .find(|&kw| kw == ident) - .is_some() + .any(|kw| kw == ident) } diff --git a/protobuf-codegen/src/gen/rust/rel_path.rs b/protobuf-codegen/src/gen/rust/rel_path.rs index 6188ce6c0..f45532a56 100644 --- a/protobuf-codegen/src/gen/rust/rel_path.rs +++ b/protobuf-codegen/src/gen/rust/rel_path.rs @@ -37,7 +37,7 @@ impl RustRelativePath { } pub fn first(&self) -> Option { - self.path.iter().cloned().next() + self.path.first().cloned() } pub fn remove_first(&mut self) -> Option { diff --git a/protobuf-codegen/src/gen/rust_types_values.rs b/protobuf-codegen/src/gen/rust_types_values.rs index ee2f730cd..be291c44c 100644 --- a/protobuf-codegen/src/gen/rust_types_values.rs +++ b/protobuf-codegen/src/gen/rust_types_values.rs @@ -69,7 +69,7 @@ impl RustType { RustType::Int(true, bits) => format!("i{}", bits), RustType::Int(false, bits) => format!("u{}", bits), RustType::Float(bits) => format!("f{}", bits), - RustType::Bool => format!("bool"), + RustType::Bool => "bool".to_string(), RustType::Vec(ref param) => format!("::std::vec::Vec<{}>", param.to_code(customize)), RustType::HashMap(ref key, ref value) => format!( "::std::collections::HashMap<{}, {}>", @@ -81,9 +81,9 @@ impl RustType { key.to_code(customize), value.to_code(customize) ), - RustType::String => format!("::std::string::String"), + RustType::String => "::std::string::String".to_string(), RustType::Slice(ref param) => format!("[{}]", param.to_code(customize)), - RustType::Str => format!("str"), + RustType::Str => "str".to_string(), RustType::Option(ref param) => { format!("::std::option::Option<{}>", param.to_code(customize)) } @@ -101,8 +101,8 @@ impl RustType { protobuf_crate_path(customize), name ), - RustType::Group => format!(""), - RustType::Bytes => format!("::bytes::Bytes"), + RustType::Group => "".to_string(), + RustType::Bytes => "::bytes::Bytes".to_string(), RustType::Chars => format!("{}::Chars", protobuf_crate_path(customize)), } } @@ -289,11 +289,11 @@ impl RustType { // expression to convert `v` of type `self` to type `target` pub fn into_target(&self, target: &RustType, v: &str, customize: &Customize) -> String { self.try_into_target(target, v, customize) - .expect(&format!("failed to convert {:?} into {:?}", self, target)) + .unwrap_or_else(|_| panic!("failed to convert {:?} into {:?}", self, target)) } // https://github.com/rust-lang-nursery/rustfmt/issues/3131 - #[cfg_attr(rustfmt, rustfmt_skip)] + #[rustfmt::skip] fn try_into_target(&self, target: &RustType, v: &str, customize: &Customize) -> Result { { if let Some(t1) = self.is_ref().and_then(|t| t.is_box()) { @@ -306,27 +306,27 @@ impl RustType { } match (self, target) { - (x, y) if x == y => return Ok(format!("{}", v)), - (&RustType::Ref(ref x), y) if **x == *y => return Ok(format!("*{}", v)), - (x, &RustType::Uniq(ref y)) if *x == **y => { + (x, y) if x == y => return Ok(v.to_string()), + (RustType::Ref(x), y) if **x == *y => return Ok(format!("*{}", v)), + (x, RustType::Uniq(y)) if *x == **y => { return Ok(format!("::std::boxed::Box::new({})", v)) } - (&RustType::Uniq(ref x), y) if **x == *y => return Ok(format!("*{}", v)), - (&RustType::String, &RustType::Ref(ref t)) if **t == RustType::Str => { + (RustType::Uniq(x), y) if **x == *y => return Ok(format!("*{}", v)), + (&RustType::String, RustType::Ref(t)) if **t == RustType::Str => { return Ok(format!("&{}", v)) } - (&RustType::Chars, &RustType::Ref(ref t)) if **t == RustType::Str => { + (&RustType::Chars, RustType::Ref(t)) if **t == RustType::Str => { return Ok(format!("&{}", v)) } - (&RustType::Ref(ref t1), &RustType::Ref(ref t2)) if t1.is_string() && t2.is_str() => { + (RustType::Ref(t1), RustType::Ref(t2)) if t1.is_string() && t2.is_str() => { return Ok(format!("&{}", v)) } - (&RustType::Ref(ref t1), &RustType::String) + (RustType::Ref(t1), &RustType::String) if match **t1 { RustType::Str => true, _ => false, } => return Ok(format!("{}.to_owned()", v)), - (&RustType::Ref(ref t1), &RustType::Chars) + (RustType::Ref(t1), &RustType::Chars) if match **t1 { RustType::Str => true, _ => false, @@ -334,27 +334,27 @@ impl RustType { return Ok(format!("<{}::Chars as ::std::convert::From<_>>::from({}.to_owned())", protobuf_crate_path(customize), v)) }, - (&RustType::Ref(ref t1), &RustType::Vec(ref t2)) + (RustType::Ref(t1), RustType::Vec(t2)) if match (&**t1, &**t2) { - (&RustType::Slice(ref x), ref y) => **x == **y, + (RustType::Slice(x), y) => **x == *y, _ => false, } => return Ok(format!("{}.to_vec()", v)), - (&RustType::Ref(ref t1), &RustType::Bytes) + (RustType::Ref(t1), &RustType::Bytes) if t1.is_slice_u8() => return Ok(format!("<::bytes::Bytes as ::std::convert::From<_>>::from({}.to_vec())", v)), - (&RustType::Vec(ref x), &RustType::Ref(ref t)) + (RustType::Vec(x), RustType::Ref(t)) if match **t { RustType::Slice(ref y) => x == y, _ => false, } => return Ok(format!("&{}", v)), - (&RustType::Bytes, &RustType::Ref(ref t)) + (&RustType::Bytes, RustType::Ref(t)) if match **t { RustType::Slice(ref y) => **y == RustType::u8(), _ => false, } => return Ok(format!("&{}", v)), - (&RustType::Ref(ref t1), &RustType::Ref(ref t2)) + (RustType::Ref(t1), RustType::Ref(t2)) if match (&**t1, &**t2) { - (&RustType::Vec(ref x), &RustType::Slice(ref y)) => x == y, + (RustType::Vec(x), RustType::Slice(y)) => x == y, _ => false, } => return Ok(format!("&{}", v)), (&RustType::Enum(..), &RustType::Int(true, 32)) => { @@ -363,22 +363,22 @@ impl RustType { (&RustType::EnumOrUnknown(..), &RustType::Int(true, 32)) => { return Ok(format!("{}::EnumOrUnknown::value(&{})", protobuf_crate_path(customize), v)) }, - (&RustType::Ref(ref t), &RustType::Int(true, 32)) if t.is_enum() => { + (RustType::Ref(t), &RustType::Int(true, 32)) if t.is_enum() => { return Ok(format!("{}::Enum::value({})", protobuf_crate_path(customize), v)) } - (&RustType::Ref(ref t), &RustType::Int(true, 32)) if t.is_enum_or_unknown() => { + (RustType::Ref(t), &RustType::Int(true, 32)) if t.is_enum_or_unknown() => { return Ok(format!("{}::EnumOrUnknown::value({})", protobuf_crate_path(customize), v)) }, - (&RustType::EnumOrUnknown(ref f, ..), &RustType::Enum(ref t, ..)) if f == t => { + (RustType::EnumOrUnknown(f, ..), RustType::Enum(t, ..)) if f == t => { return Ok(format!("{}::EnumOrUnknown::enum_value_or_default(&{})", protobuf_crate_path(customize), v)) } - (&RustType::Enum(ref f, ..), &RustType::EnumOrUnknown(ref t, ..)) if f == t => { + (RustType::Enum(f, ..), RustType::EnumOrUnknown(t, ..)) if f == t => { return Ok(format!("{}::EnumOrUnknown::new({})", protobuf_crate_path(customize), v)) } _ => (), }; - if let &RustType::Ref(ref s) = self { + if let RustType::Ref(s) = self { if let Ok(conv) = s.try_into_target(target, v, customize) { return Ok(conv); } @@ -391,10 +391,10 @@ impl RustType { pub fn ref_type(&self) -> RustType { RustType::Ref(Box::new(match self { &RustType::String | &RustType::Chars => RustType::Str, - &RustType::Vec(ref p) => RustType::Slice(p.clone()), + RustType::Vec(p) => RustType::Slice(p.clone()), &RustType::Bytes => RustType::Slice(Box::new(RustType::u8())), - &RustType::Message(ref p) => RustType::Message(p.clone()), - &RustType::Uniq(ref p) => RustType::Uniq(p.clone()), + RustType::Message(p) => RustType::Message(p.clone()), + RustType::Uniq(p) => RustType::Uniq(p.clone()), x => panic!("no ref type for {:?}", x), })) } @@ -409,8 +409,8 @@ impl RustType { pub fn elem_type(&self) -> RustType { match self { - &RustType::Option(ref ty) => (**ty).clone(), - &RustType::MessageField(ref ty) => (**ty).clone(), + RustType::Option(ty) => (**ty).clone(), + RustType::MessageField(ty) => (**ty).clone(), x => panic!("cannot get elem type of {:?}", x), } } @@ -427,7 +427,7 @@ impl RustType { pub fn value(self, value: String) -> RustValueTyped { RustValueTyped { - value: value, + value, rust_type: self, } } @@ -595,12 +595,12 @@ impl ProtobufTypeGen { protobuf_crate_path(customize) ), &ProtobufTypeGen::Primitive(.., PrimitiveTypeVariant::TokioBytes) => unreachable!(), - &ProtobufTypeGen::Message(ref name) => format!( + ProtobufTypeGen::Message(name) => format!( "{}::reflect::types::ProtobufTypeMessage<{}>", protobuf_crate_path(customize), name ), - &ProtobufTypeGen::EnumOrUnknown(ref name) => format!( + ProtobufTypeGen::EnumOrUnknown(name) => format!( "{}::reflect::types::ProtobufTypeEnumOrUnknown<{}>", protobuf_crate_path(customize), name diff --git a/protobuf-codegen/src/gen/scope.rs b/protobuf-codegen/src/gen/scope.rs index f70d233f1..1677bcde4 100644 --- a/protobuf-codegen/src/gen/scope.rs +++ b/protobuf-codegen/src/gen/scope.rs @@ -60,7 +60,7 @@ impl<'a> RootScope<'a> { .into_iter() .flat_map(|p| p.find_message_or_enum_abs(fqn)) .next() - .expect(&format!("enum not found by name: {}", fqn)) + .unwrap_or_else(|| panic!("enum not found by name: {}", fqn)) } } @@ -94,9 +94,7 @@ impl<'a> FileScope<'a> { name: &ProtobufRelPathRef, ) -> Option> { self.find_messages_and_enums() - .into_iter() - .filter(|e| e.protobuf_name_to_package().as_ref() == name) - .next() + .into_iter().find(|e| e.protobuf_name_to_package().as_ref() == name) } fn find_message_or_enum_abs( @@ -105,7 +103,7 @@ impl<'a> FileScope<'a> { ) -> Option> { let name = name.to_owned(); match name.remove_prefix(&self.package()) { - Some(rem) => self.find_message_or_enum(&rem), + Some(rem) => self.find_message_or_enum(rem), None => None, } } @@ -207,11 +205,11 @@ impl<'a> Scope<'a> { pub fn messages_and_enums(&self) -> Vec> { self.messages() .into_iter() - .map(|m| MessageOrEnumWithScope::Message(m)) + .map(MessageOrEnumWithScope::Message) .chain( self.enums() .into_iter() - .map(|m| MessageOrEnumWithScope::Enum(m)), + .map(MessageOrEnumWithScope::Enum), ) .collect() } @@ -297,7 +295,7 @@ pub(crate) trait WithScope<'a> { fn name_to_package(&self) -> String { let mut r = self.scope().prefix(); - r.push_str(&self.name()); + r.push_str(self.name()); r } @@ -315,7 +313,7 @@ pub(crate) trait WithScope<'a> { // rust type name of this descriptor fn rust_name(&self) -> RustIdent { - let rust_name = capitalize(&self.name()); + let rust_name = capitalize(self.name()); RustIdent::new(&rust_name) } @@ -365,7 +363,6 @@ impl<'a> MessageWithScope<'a> { pub fn fields(&self) -> Vec> { self.message .fields() - .into_iter() .map(|field| FieldWithContext { field, message: self.clone(), @@ -376,7 +373,6 @@ impl<'a> MessageWithScope<'a> { pub fn oneofs(&self) -> Vec> { self.message .oneofs() - .into_iter() .map(|oneof| OneofWithContext { message: self.clone(), oneof, @@ -404,7 +400,6 @@ impl<'a> EnumWithScope<'a> { pub fn values(&self) -> Vec> { self.en .values() - .into_iter() .map(|v| EnumValueWithContext { en: self.clone(), proto: v, @@ -485,13 +480,10 @@ impl<'a> FieldWithContext<'a> { } pub fn oneof(&self) -> Option> { - match self.field.containing_oneof() { - Some(oneof) => Some(OneofWithContext { + self.field.containing_oneof().map(|oneof| OneofWithContext { message: self.message.clone(), oneof, - }), - None => None, - } + }) } } diff --git a/protobuf-codegen/src/gen/strx.rs b/protobuf-codegen/src/gen/strx.rs index d1b26fa64..7284cfb35 100644 --- a/protobuf-codegen/src/gen/strx.rs +++ b/protobuf-codegen/src/gen/strx.rs @@ -1,4 +1,4 @@ -pub fn remove_to<'s, P>(s: &'s str, pattern: P) -> &'s str +pub fn remove_to

(s: &str, pattern: P) -> &str where P: Fn(char) -> bool, { diff --git a/protobuf-codegen/src/gen/well_known_types.rs b/protobuf-codegen/src/gen/well_known_types.rs index 6b0b389e4..938a28c47 100644 --- a/protobuf-codegen/src/gen/well_known_types.rs +++ b/protobuf-codegen/src/gen/well_known_types.rs @@ -32,7 +32,7 @@ pub(crate) static WELL_KNOWN_TYPES_PROTO_FILE_FULL_NAMES: &[&str] = &[ "google/protobuf/wrappers.proto", ]; -static NAMES: &'static [&'static str] = &[ +static NAMES: &[&str] = &[ "Any", "Api", "BoolValue", diff --git a/protobuf-examples/customize-serde/build.rs b/protobuf-examples/customize-serde/build.rs index 53e06fb30..aacce115f 100644 --- a/protobuf-examples/customize-serde/build.rs +++ b/protobuf-examples/customize-serde/build.rs @@ -31,7 +31,7 @@ fn main() { Codegen::new() .cargo_out_dir("protos") .include("src") - .inputs(&["src/customize_example.proto"]) + .inputs(["src/customize_example.proto"]) .customize_callback(GenSerde) .run_from_script(); } diff --git a/protobuf-json-mapping/src/base64.rs b/protobuf-json-mapping/src/base64.rs index c8461c691..3cfd5b8ae 100644 --- a/protobuf-json-mapping/src/base64.rs +++ b/protobuf-json-mapping/src/base64.rs @@ -8,11 +8,11 @@ enum _CharacterSet { _UrlSafe, } -static STANDARD_CHARS: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ +static STANDARD_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789+/"; -static _URLSAFE_CHARS: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ +static _URLSAFE_CHARS: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789-_"; @@ -46,7 +46,7 @@ pub fn encode(input: &[u8]) -> String { write(enc((n >> 18) & 63)); write(enc((n >> 12) & 63)); write(enc((n >> 6) & 63)); - write(enc((n >> 0) & 63)); + write(enc(n & 63)); } // Heh, would be cool if we knew this was exhaustive diff --git a/protobuf-json-mapping/src/parse.rs b/protobuf-json-mapping/src/parse.rs index 923238010..5fe2ce0be 100644 --- a/protobuf-json-mapping/src/parse.rs +++ b/protobuf-json-mapping/src/parse.rs @@ -414,9 +414,9 @@ impl<'a> Parser<'a> { RuntimeType::String => self.read_string().map(ReflectValueBox::from), RuntimeType::VecU8 => self.read_bytes().map(ReflectValueBox::from), RuntimeType::Enum(e) => self - .read_enum(&e) + .read_enum(e) .map(|v| ReflectValueBox::Enum(e.clone(), v)), - RuntimeType::Message(m) => self.read_message(&m).map(ReflectValueBox::from), + RuntimeType::Message(m) => self.read_message(m).map(ReflectValueBox::from), } } @@ -693,9 +693,9 @@ impl<'a> Parser<'a> { let mut lexer = Lexer::new(&s, ParserLanguage::Json); fn next_dec(lexer: &mut Lexer) -> ParseResultWithoutLoc<(u64, u32)> { - let s = lexer.take_while(|c| c >= '0' && c <= '9'); + let s = lexer.take_while(|c: char| c.is_ascii_digit()); - if s.len() == 0 { + if s.is_empty() { Ok((0, 0)) } else { match s.parse() { diff --git a/protobuf-json-mapping/src/print.rs b/protobuf-json-mapping/src/print.rs index eef44ca93..8c8fe23dd 100644 --- a/protobuf-json-mapping/src/print.rs +++ b/protobuf-json-mapping/src/print.rs @@ -75,7 +75,7 @@ trait JsonFloat: fmt::Display + fmt::Debug + PrintableToJson { fn is_neg_infinity(&self) -> bool; fn print_to_json_impl(&self, w: &mut String) -> PrintResult<()> { - Ok(if self.is_nan() { + if self.is_nan() { write!(w, "\"{}\"", float::PROTOBUF_JSON_NAN)? } else if self.is_pos_infinity() { write!(w, "\"{}\"", float::PROTOBUF_JSON_INF)? @@ -83,7 +83,8 @@ trait JsonFloat: fmt::Display + fmt::Debug + PrintableToJson { write!(w, "\"{}\"", float::PROTOBUF_JSON_MINUS_INF)? } else { write!(w, "{:?}", self)? - }) + }; + Ok(()) } } @@ -103,7 +104,7 @@ impl JsonFloat for f32 { impl PrintableToJson for f32 { fn print_to_json(&self, w: &mut Printer) -> PrintResult<()> { - Ok(self.print_to_json_impl(&mut w.buf)?) + self.print_to_json_impl(&mut w.buf) } } @@ -266,7 +267,7 @@ impl PrintableToJson for Value { } Some(value::Kind::BoolValue(b)) => w.print_printable(&b), Some(value::Kind::NumberValue(n)) => w.print_printable(&n), - Some(value::Kind::StringValue(ref s)) => w.print_printable::(&s), + Some(value::Kind::StringValue(ref s)) => w.print_printable::(s), Some(value::Kind::StructValue(ref s)) => w.print_printable(&s), Some(value::Kind::ListValue(ref l)) => w.print_printable(&l), Some(_) => Err(PrintError(PrintErrorInner::UnknownStructValueKind)), @@ -403,18 +404,16 @@ impl Printer { } fn print_map(&mut self, map: &ReflectMapRef) -> PrintResult<()> { - self.print_object(map.into_iter()) + self.print_object(map) } fn print_enum_known(&mut self, value: &EnumValueDescriptor) -> PrintResult<()> { if let Some(null_value) = value.cast() { self.print_wk_null_value(&null_value) + } else if self.print_options.enum_values_int { + self.print_printable(&value.value()) } else { - if self.print_options.enum_values_int { - self.print_printable(&value.value()) - } else { - Ok(write!(self.buf, "\"{}\"", value.name())?) - } + Ok(write!(self.buf, "\"{}\"", value.name())?) } } diff --git a/protobuf-json-mapping/src/rfc_3339.rs b/protobuf-json-mapping/src/rfc_3339.rs index ef04bcf04..a8507d726 100644 --- a/protobuf-json-mapping/src/rfc_3339.rs +++ b/protobuf-json-mapping/src/rfc_3339.rs @@ -12,11 +12,7 @@ fn is_leap_year(year: i64) -> bool { false } else if year % 100 != 0 { true - } else if year % 400 != 0 { - false - } else { - true - } + } else { year % 400 == 0 } } fn days_in_year(year: i64) -> u32 { @@ -42,7 +38,7 @@ const YEARS_1970_2000_SECONDS: u64 = 946684800; const YEARS_1600_1970_SECONDS: u64 = CYCLE_SECONDS - YEARS_1970_2000_SECONDS; // For each year in the cycle, number of leap years before in the cycle. -#[cfg_attr(rustfmt, rustfmt_skip)] +#[rustfmt::skip] static YEAR_DELTAS: [u8; 401] = [ 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, @@ -111,7 +107,7 @@ impl TmUtc { debug_assert!(day_of_cycle < CYCLE_DAYS); let mut year_mod_400 = (day_of_cycle / 365) as i64; - let mut day_or_year = (day_of_cycle % 365) as u32; + let mut day_or_year = day_of_cycle % 365; let delta = YEAR_DELTAS[year_mod_400 as usize] as u32; if day_or_year < delta { @@ -171,7 +167,7 @@ impl TmUtc { month += 1; } - debug_assert!(rem_days + 1 <= days_in_months[month - 1]); + debug_assert!(rem_days < days_in_months[month - 1]); (month as u32, rem_days + 1) } @@ -289,7 +285,7 @@ impl TmUtc { let mut r = 0; for i in 0..len { let c = self.s[self.pos + i]; - if c >= b'0' && c <= b'9' { + if c.is_ascii_digit() { r = r * 10 + (c - b'0') as u32; } else { return Err(Rfc3339ParseError::ExpectingDigits); @@ -328,11 +324,11 @@ impl TmUtc { parser.next_char(b'-')?; let day = parser.next_number(2)?; - if month < 1 || month > 12 { + if !(1..=12).contains(&month) { return Err(Rfc3339ParseError::DateTimeFieldOutOfRange); } - if day < 1 || day > TmUtc::days_in_months(year as i64)[month as usize - 1] { + if day < 1 || day > TmUtc::days_in_months(year)[month as usize - 1] { return Err(Rfc3339ParseError::DateTimeFieldOutOfRange); } @@ -452,7 +448,7 @@ impl fmt::Display for TmUtc { subsec /= 10; } - write!(f, ".{:0width$}", subsec, width = width as usize)?; + write!(f, ".{:0width$}", subsec, width = { width })?; // Adding more than 9 digits is meaningless, // but if user requests it, we should print zeros. diff --git a/protobuf-parse/src/parser.rs b/protobuf-parse/src/parser.rs index e642ab4c8..774145971 100644 --- a/protobuf-parse/src/parser.rs +++ b/protobuf-parse/src/parser.rs @@ -101,9 +101,9 @@ impl Parser { pub fn parse_and_typecheck(&self) -> anyhow::Result { match &self.which_parser { WhichParser::Pure => { - pure::parse_and_typecheck::parse_and_typecheck(&self).context("using pure parser") + pure::parse_and_typecheck::parse_and_typecheck(self).context("using pure parser") } - WhichParser::Protoc => protoc::parse_and_typecheck::parse_and_typecheck(&self) + WhichParser::Protoc => protoc::parse_and_typecheck::parse_and_typecheck(self) .context("using protoc parser"), } } diff --git a/protobuf-parse/src/protobuf_abs_path.rs b/protobuf-parse/src/protobuf_abs_path.rs index f6789531e..06c3ad77a 100644 --- a/protobuf-parse/src/protobuf_abs_path.rs +++ b/protobuf-parse/src/protobuf_abs_path.rs @@ -107,7 +107,7 @@ impl ProtobufAbsPathRef { let mut r: Vec<&ProtobufAbsPathRef> = Vec::new(); - r.push(&self); + r.push(self); while let Some(parent) = tmp.parent() { r.push(parent); @@ -175,7 +175,7 @@ impl ProtobufAbsPath { } pub fn from_message(message: &MessageDescriptor) -> ProtobufAbsPath { - Self::new_from_rel(&message.full_name()) + Self::new_from_rel(message.full_name()) } pub fn concat(a: &ProtobufAbsPathRef, b: &ProtobufRelPathRef) -> ProtobufAbsPath { @@ -201,7 +201,7 @@ impl ProtobufAbsPath { pub fn push_simple(&mut self, simple: &ProtobufIdentRef) { self.path.push('.'); - self.path.push_str(&simple); + self.path.push_str(simple); } pub fn push_relative(&mut self, relative: &ProtobufRelPathRef) { diff --git a/protobuf-parse/src/protobuf_ident.rs b/protobuf-parse/src/protobuf_ident.rs index 24608824e..bd252c178 100644 --- a/protobuf-parse/src/protobuf_ident.rs +++ b/protobuf-parse/src/protobuf_ident.rs @@ -42,9 +42,9 @@ impl From for ProtobufIdent { } } -impl Into for ProtobufIdent { - fn into(self) -> String { - self.0 +impl From for String { + fn from(val: ProtobufIdent) -> Self { + val.0 } } @@ -55,14 +55,14 @@ impl fmt::Display for ProtobufIdent { } impl ProtobufIdentRef { - pub fn new<'a>(ident: &'a str) -> &'a ProtobufIdentRef { + pub fn new(ident: &str) -> &ProtobufIdentRef { assert!(!ident.is_empty()); // SAFETY: ProtobufIdentRef is repr(transparent) unsafe { mem::transmute(ident) } } pub fn as_str(&self) -> &str { - &*self + self } pub fn to_owned(&self) -> ProtobufIdent { diff --git a/protobuf-parse/src/protobuf_rel_path.rs b/protobuf-parse/src/protobuf_rel_path.rs index f6d7a092c..9856e1103 100644 --- a/protobuf-parse/src/protobuf_rel_path.rs +++ b/protobuf-parse/src/protobuf_rel_path.rs @@ -23,7 +23,7 @@ impl From<&'_ str> for ProtobufRelPath { impl ProtobufRelPathRef { pub fn as_str(&self) -> &str { - &self + self } pub fn empty() -> &'static ProtobufRelPathRef { @@ -57,7 +57,7 @@ impl ProtobufRelPathRef { pub fn components(&self) -> impl Iterator { iter::once(&self.0) .filter(|s| !s.is_empty()) - .flat_map(|p| p.split('.').map(|s| ProtobufIdentRef::new(s))) + .flat_map(|p| p.split('.').map(ProtobufIdentRef::new)) } fn parent(&self) -> Option<&ProtobufRelPathRef> { @@ -115,7 +115,7 @@ impl ProtobufRelPathRef { impl ProtobufRelPath { pub fn as_ref(&self) -> &ProtobufRelPathRef { - &self + self } pub fn empty() -> ProtobufRelPath { diff --git a/protobuf-parse/src/protoc/command.rs b/protobuf-parse/src/protoc/command.rs index f29d7e377..036a8a66f 100644 --- a/protobuf-parse/src/protoc/command.rs +++ b/protobuf-parse/src/protoc/command.rs @@ -217,7 +217,7 @@ impl Protoc { .stdin(process::Stdio::null()) .stdout(process::Stdio::piped()) .stderr(process::Stdio::piped()) - .args(&["--version"]), + .args(["--version"]), )?; let output = child.wait_with_output()?; @@ -238,7 +238,7 @@ impl Protoc { return Err(Error::VersionIsEmpty.into()); } let first = output.chars().next().unwrap(); - if !first.is_digit(10) { + if !first.is_ascii_digit() { return Err(Error::VersionDoesNotStartWithDigit.into()); } Ok(Version { @@ -265,10 +265,8 @@ impl Protoc { let stderr = stderr.trim_end().to_owned(); return Err(Error::ProtocNamedNonZeroStderr(format!("{:?}", cmd), stderr).into()); } - } else { - if !child.wait()?.success() { - return Err(Error::ProtocNamedNonZero(format!("{:?}", cmd)).into()); - } + } else if !child.wait()?.success() { + return Err(Error::ProtocNamedNonZero(format!("{:?}", cmd)).into()); } Ok(()) diff --git a/protobuf-parse/src/pure/convert/mod.rs b/protobuf-parse/src/pure/convert/mod.rs index a18b5e203..fca49915d 100644 --- a/protobuf-parse/src/pure/convert/mod.rs +++ b/protobuf-parse/src/pure/convert/mod.rs @@ -155,7 +155,7 @@ impl<'a> Resolver<'a> { output.set_name(name.to_owned()); output.set_number(number); - let t = self.field_type(&scope, name, field_type)?; + let t = self.field_type(scope, name, field_type)?; output.set_type(t.type_enum()); if let Some(t_name) = t.type_name() { output.set_type_name(t_name.path.clone()); @@ -163,7 +163,7 @@ impl<'a> Resolver<'a> { output.set_label(field_descriptor_proto::Label::LABEL_OPTIONAL); - output.set_json_name(json_name(&name)); + output.set_json_name(json_name(name)); Ok(output) } @@ -181,10 +181,10 @@ impl<'a> Resolver<'a> { output.set_name(Resolver::map_entry_name_for_field_name(field_name).into_string()); output .field - .push(self.map_entry_field(&scope, "key", 1, key)?); + .push(self.map_entry_field(scope, "key", 1, key)?); output .field - .push(self.map_entry_field(&scope, "value", 2, value)?); + .push(self.map_entry_field(scope, "value", 2, value)?); Ok(output) } @@ -317,7 +317,7 @@ impl<'a> Resolver<'a> { reserved_range.set_end(*reserved.end() + 1); output.reserved_range.push(reserved_range); } - output.reserved_name = input.reserved_names.clone().into(); + output.reserved_name = input.reserved_names.clone(); Ok(output) } @@ -403,14 +403,14 @@ impl<'a> Resolver<'a> { if let Some(ref default) = input.t.options.as_slice().by_name("default") { let default = match output.type_() { protobuf::descriptor::field_descriptor_proto::Type::TYPE_STRING => { - if let &model::ProtobufConstant::String(ref s) = default { + if let model::ProtobufConstant::String(s) = default { s.decode_utf8()? } else { return Err(ConvertError::DefaultValueIsNotStringLiteral.into()); } } protobuf::descriptor::field_descriptor_proto::Type::TYPE_BYTES => { - if let &model::ProtobufConstant::String(ref s) = default { + if let model::ProtobufConstant::String(s) = default { let mut buf = String::new(); escape_bytes_to(&s.decode_bytes()?, &mut buf); buf @@ -489,7 +489,7 @@ impl<'a> Resolver<'a> { model::FieldType::String => TypeResolved::String, model::FieldType::Bytes => TypeResolved::Bytes, model::FieldType::MessageOrEnum(ref name) => { - let t = self.type_resolver.resolve_message_or_enum(scope, &name)?; + let t = self.type_resolver.resolve_message_or_enum(scope, name)?; match t.t { MessageOrEnum::Message(..) => TypeResolved::Message(t.full_name), MessageOrEnum::Enum(..) => TypeResolved::Enum(t.full_name), @@ -532,7 +532,7 @@ impl<'a> Resolver<'a> { output.value = input .values .iter() - .map(|v| self.enum_value(scope, &v)) + .map(|v| self.enum_value(scope, v)) .collect::>()?; for reserved in &input.reserved_nums { @@ -544,7 +544,7 @@ impl<'a> Resolver<'a> { output.reserved_range.push(reserved_range); } - output.reserved_name = input.reserved_names.clone().into(); + output.reserved_name = input.reserved_names.clone(); Ok(output) } @@ -627,9 +627,9 @@ pub(crate) fn file_descriptor( deps: &[FileDescriptorPair], ) -> anyhow::Result { let resolver = Resolver { - current_file: &input, + current_file: input, type_resolver: TypeResolver { - current_file: &input, + current_file: input, deps, }, }; @@ -642,7 +642,7 @@ pub(crate) fn file_descriptor( output.set_package(input.package.to_root_rel().to_string()); } - populate_dependencies(&input, &mut output); + populate_dependencies(input, &mut output); let mut messages = Vec::new(); let mut services = Vec::new(); diff --git a/protobuf-parse/src/pure/convert/option_resolver.rs b/protobuf-parse/src/pure/convert/option_resolver.rs index 948d3e3b3..4069bb03c 100644 --- a/protobuf-parse/src/pure/convert/option_resolver.rs +++ b/protobuf-parse/src/pure/convert/option_resolver.rs @@ -195,7 +195,7 @@ impl<'a> ProtobufOptions for &'a [model::ProtobufOption] { let option_name = ProtobufOptionName::simple(name); for model::ProtobufOption { name, value } in *self { if name == &option_name { - return Some(&value); + return Some(value); } } None @@ -313,7 +313,7 @@ impl<'a> OptionResoler<'a> { if ProtobufAbsPath::new(field.proto().extendee()) != expected_extendee { return Err(OptionResolverError::WrongExtensionType( format!("{}", field_name), - format!("{}", field.proto().extendee()), + field.proto().extendee().to_string(), format!("{}", expected_extendee), ) .into()); @@ -395,7 +395,7 @@ impl<'a> OptionResoler<'a> { "parsing custom option `{}` value `{}` at `{}`", option_name, option_value, scope )); - return Err(e.into()); + return Err(e); } }; @@ -598,53 +598,48 @@ impl<'a> OptionResoler<'a> { TypeResolved::Sint32 => return Ok(UnknownValue::sint32(f as i32)), _ => {} }, - &model::ProtobufConstant::String(ref s) => match field_type { + model::ProtobufConstant::String(s) => match field_type { TypeResolved::String => { return Ok(UnknownValue::LengthDelimited(s.decode_utf8()?.into_bytes())) } TypeResolved::Bytes => return Ok(UnknownValue::LengthDelimited(s.decode_bytes()?)), _ => {} }, - model::ProtobufConstant::Ident(ident) => match &field_type { - TypeResolved::Enum(e) => { - let e = self - .resolver - .find_enum_by_abs_name(e) - .map_err(OptionResolverError::OtherError)?; - let n = match e - .values - .iter() - .find(|v| v.name == format!("{}", ident)) - .map(|v| v.number) - { - Some(n) => n, - None => { - return Err( - OptionResolverError::UnknownEnumValue(ident.to_string()).into() - ) - } - }; - return Ok(UnknownValue::int32(n)); - } - _ => {} + model::ProtobufConstant::Ident(ident) => if let TypeResolved::Enum(e) = &field_type { + let e = self + .resolver + .find_enum_by_abs_name(e) + .map_err(OptionResolverError::OtherError)?; + let n = match e + .values + .iter() + .find(|v| v.name == format!("{}", ident)) + .map(|v| v.number) + { + Some(n) => n, + None => { + return Err( + OptionResolverError::UnknownEnumValue(ident.to_string()).into() + ) + } + }; + return Ok(UnknownValue::int32(n)); }, model::ProtobufConstant::Message(mo) => { return self.option_value_message_to_unknown_value( - &field_type, + field_type, mo, option_name_for_diag, ); } }; - Err(match field_type { - _ => OptionResolverError::UnsupportedExtensionType( - option_name_for_diag.to_owned(), - format!("{:?}", field_type), - value.clone(), - ) - .into(), - }) + Err(OptionResolverError::UnsupportedExtensionType( + option_name_for_diag.to_owned(), + format!("{:?}", field_type), + value.clone(), + ) + .into()) } fn option_value_field_to_unknown_value( @@ -655,10 +650,10 @@ impl<'a> OptionResoler<'a> { field_type: &model::FieldType, option_name_for_diag: &str, ) -> anyhow::Result { - let field_type = self.resolver.field_type(&scope, name, field_type)?; - Ok(self + let field_type = self.resolver.field_type(scope, name, field_type)?; + self .option_value_to_unknown_value(&field_type, value, option_name_for_diag) - .context("parsing custom option value")?) + .context("parsing custom option value") } fn custom_option_builtin( @@ -671,11 +666,9 @@ impl<'a> OptionResoler<'a> { where M: MessageFull, { - if M::descriptor().full_name() == "google.protobuf.FieldOptions" { - if option.get() == "default" || option.get() == "json_name" { - // some options are written to non-options message and handled outside - return Ok(()); - } + if M::descriptor().full_name() == "google.protobuf.FieldOptions" && (option.get() == "default" || option.get() == "json_name") { + // some options are written to non-options message and handled outside + return Ok(()); } match M::descriptor().field_by_name(option.get()) { Some(field) => { @@ -691,7 +684,7 @@ impl<'a> OptionResoler<'a> { options, option_value.as_type(field.singular_runtime_type())?, ); - return Ok(()); + Ok(()) } None => { return Err(OptionResolverError::BuiltinOptionNotFound( @@ -821,12 +814,12 @@ impl<'a> OptionResoler<'a> { service_proto.options = self.service_options(&service_model.options)?.into(); for service_method_model in &service_model.methods { - let mut method_proto = service_proto + let method_proto = service_proto .method .iter_mut() .find(|method| method.name() == service_method_model.name) .unwrap(); - self.method(&mut method_proto, service_method_model)?; + self.method(method_proto, service_method_model)?; } Ok(()) @@ -853,12 +846,12 @@ impl<'a> OptionResoler<'a> { enum_proto.options = self.enum_options(scope, &enum_model.options)?.into(); for enum_value_model in &enum_model.values { - let mut enum_value_proto = enum_proto + let enum_value_proto = enum_proto .value .iter_mut() .find(|v| v.name() == enum_value_model.name) .unwrap(); - self.enum_value(scope, &mut enum_value_proto, enum_value_model)?; + self.enum_value(scope, enum_value_proto, enum_value_model)?; } Ok(()) @@ -893,15 +886,15 @@ impl<'a> OptionResoler<'a> { message_proto.options = self.message_options(scope, &message_model.options)?.into(); let mut nested_scope = scope.to_owned(); - nested_scope.push_simple(ProtobufIdentRef::new(&message_proto.name())); + nested_scope.push_simple(ProtobufIdentRef::new(message_proto.name())); for field_model in &message_model.regular_fields_including_in_oneofs() { - let mut field_proto = message_proto + let field_proto = message_proto .field .iter_mut() .find(|field| field.name() == field_model.name) .unwrap(); - self.field(&nested_scope, &mut field_proto, field_model)?; + self.field(&nested_scope, field_proto, field_model)?; } for field_model in &message_model.extensions { let field_proto = message_proto diff --git a/protobuf-parse/src/pure/convert/type_resolver.rs b/protobuf-parse/src/pure/convert/type_resolver.rs index f0549232a..215a2230a 100644 --- a/protobuf-parse/src/pure/convert/type_resolver.rs +++ b/protobuf-parse/src/pure/convert/type_resolver.rs @@ -61,7 +61,7 @@ impl<'a> LookupScope<'a> { fn find_message(&self, simple_name: &ProtobufIdentRef) -> Option<&'a model::Message> { self.messages() - .into_iter() + .iter() .find(|m| m.t.name == simple_name.as_str()) .map(|m| &m.t) } @@ -77,10 +77,10 @@ impl<'a> LookupScope<'a> { let mut r = Vec::new(); r.extend( self.enums() - .into_iter() + .iter() .map(|e| (ProtobufIdent::from(&e.name[..]), MessageOrEnum::Enum(e))), ); - r.extend(self.messages().into_iter().map(|m| { + r.extend(self.messages().iter().map(|m| { ( ProtobufIdent::from(&m.t.name[..]), MessageOrEnum::Message(&m.t), @@ -156,13 +156,13 @@ impl<'a> TypeResolver<'a> { ) -> anyhow::Result>> { for file in self.all_files() { if let Some(relative) = absolute_path.remove_prefix(&file.package) { - if let Some(w) = LookupScope::File(file).find_message_or_enum(&relative) { + if let Some(w) = LookupScope::File(file).find_message_or_enum(relative) { return Ok(w); } } } - return Err(TypeResolverError::NotFoundByAbsPath(absolute_path.clone()).into()); + Err(TypeResolverError::NotFoundByAbsPath(absolute_path.clone()).into()) } pub(crate) fn resolve_message_or_enum( @@ -171,12 +171,12 @@ impl<'a> TypeResolver<'a> { name: &ProtobufPath, ) -> anyhow::Result> { match name { - ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(&name)?), + ProtobufPath::Abs(name) => Ok(self.find_message_or_enum_by_abs_name(name)?), ProtobufPath::Rel(name) => { // find message or enum in current package for p in scope.self_and_parents() { let mut fq = p.to_owned(); - fq.push_relative(&name); + fq.push_relative(name); if let Ok(me) = self.find_message_or_enum_by_abs_name(&fq) { return Ok(me); } diff --git a/protobuf-parse/src/pure/model.rs b/protobuf-parse/src/pure/model.rs index 25a57de47..179c80b5d 100644 --- a/protobuf-parse/src/pure/model.rs +++ b/protobuf-parse/src/pure/model.rs @@ -47,25 +47,22 @@ impl WithLoc { pub fn with_loc(loc: Loc) -> impl FnOnce(T) -> WithLoc { move |t| WithLoc { t, - loc: loc.clone(), + loc, } } } /// Protobuf syntax. #[derive(Debug, Clone, Copy, Eq, PartialEq)] +#[derive(Default)] pub(crate) enum Syntax { /// Protobuf syntax [2](https://developers.google.com/protocol-buffers/docs/proto) (default) + #[default] Proto2, /// Protobuf syntax [3](https://developers.google.com/protocol-buffers/docs/proto3) Proto3, } -impl Default for Syntax { - fn default() -> Syntax { - Syntax::Proto2 - } -} /// A field rule #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] @@ -529,17 +526,14 @@ pub(crate) struct ProtobufOption { /// Visibility of import statement #[derive(Debug, Clone, Eq, PartialEq)] +#[derive(Default)] pub(crate) enum ImportVis { + #[default] Default, Public, Weak, } -impl Default for ImportVis { - fn default() -> Self { - ImportVis::Default - } -} /// Import statement #[derive(Debug, Default, Clone)] diff --git a/protobuf-parse/src/pure/parse_and_typecheck.rs b/protobuf-parse/src/pure/parse_and_typecheck.rs index 4101c4be7..211764b56 100644 --- a/protobuf-parse/src/pure/parse_and_typecheck.rs +++ b/protobuf-parse/src/pure/parse_and_typecheck.rs @@ -64,7 +64,7 @@ where protobuf_path: &ProtoPath, result: &mut IndexMap, ) { - if let Some(_) = result.get(protobuf_path) { + if result.get(protobuf_path).is_some() { return; } @@ -95,7 +95,7 @@ where let content = str::from_utf8(&resolved.content) .map_err(|_| ParseAndTypeckError::FileContentIsNotUtf8(protobuf_path.to_string()))?; - let parsed = model::FileDescriptor::parse(&content).map_err(|e| WithFileError { + let parsed = model::FileDescriptor::parse(content).map_err(|e| WithFileError { file: resolved.path.clone(), error: e.into(), })?; @@ -112,7 +112,7 @@ where let descriptor_proto = convert::file_descriptor(protobuf_path, &parsed, &this_file_deps) .map_err(|e| WithFileError { file: resolved.path.clone(), - error: e.into(), + error: e, })?; let deps: Vec = self @@ -135,7 +135,7 @@ where } fn add_imported_file(&mut self, protobuf_path: &ProtoPath) -> anyhow::Result<()> { - if let Some(_) = self.parsed_files.get(protobuf_path) { + if self.parsed_files.get(protobuf_path).is_some() { return Ok(()); } diff --git a/protobuf-parse/src/pure/parser.rs b/protobuf-parse/src/pure/parser.rs index a61a110b1..56652306c 100644 --- a/protobuf-parse/src/pure/parser.rs +++ b/protobuf-parse/src/pure/parser.rs @@ -412,12 +412,12 @@ impl<'a> Parser<'a> { if c == '+' || c == '-' { self.tokenizer.advance()?; let sign = c == '+'; - return Ok(self.next_num_lit()?.to_option_value(sign)?); + return self.next_num_lit()?.to_option_value(sign); } } if let Some(r) = self.tokenizer.next_token_if_map(|token| match token { - &Token::StrLit(ref s) => Some(ProtobufConstant::String(s.clone())), + Token::StrLit(s) => Some(ProtobufConstant::String(s.clone())), _ => None, })? { return Ok(r); @@ -595,7 +595,7 @@ impl<'a> Parser<'a> { ("float", FieldType::Float), ("double", FieldType::Double), ]; - for &(ref n, ref t) in simple { + for (n, ref t) in simple { if self.tokenizer.next_ident_if_eq(n)? { return Ok(t.clone()); } @@ -1293,11 +1293,11 @@ mod test { { let mut parser = Parser::new(input); let r = - parse_what(&mut parser).expect(&format!("parse failed at {}", parser.tokenizer.loc())); + parse_what(&mut parser).unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); let eof = parser .tokenizer .syntax_eof() - .expect(&format!("check eof failed at {}", parser.tokenizer.loc())); + .unwrap_or_else(|_| panic!("check eof failed at {}", parser.tokenizer.loc())); assert!(eof, "{}", parser.tokenizer.loc()); r } @@ -1308,11 +1308,9 @@ mod test { { let mut parser = Parser::new(input); let o = - parse_what(&mut parser).expect(&format!("parse failed at {}", parser.tokenizer.loc())); - let r = o.expect(&format!( - "parser returned none at {}", - parser.tokenizer.loc() - )); + parse_what(&mut parser).unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); + let r = o.unwrap_or_else(|| panic!("parser returned none at {}", + parser.tokenizer.loc())); assert!(parser.tokenizer.syntax_eof().unwrap()); r } @@ -1604,7 +1602,7 @@ mod test { dfgdg "#; - let err = FileDescriptor::parse(msg).err().expect("err"); + let err = FileDescriptor::parse(msg).expect_err("err"); assert_eq!(4, err.line); } } diff --git a/protobuf-parse/src/test_against_protobuf_protos.rs b/protobuf-parse/src/test_against_protobuf_protos.rs index 5c1707aff..87802ce22 100644 --- a/protobuf-parse/src/test_against_protobuf_protos.rs +++ b/protobuf-parse/src/test_against_protobuf_protos.rs @@ -36,5 +36,5 @@ fn parse_recursively(path: &Path) { #[test] fn test() { let path = &Path::new("../google-protobuf-all-protos/protobuf"); - parse_recursively(&Path::new(path)); + parse_recursively(Path::new(path)); } diff --git a/protobuf-parse/src/which_parser.rs b/protobuf-parse/src/which_parser.rs index 223da0d98..09364c2df 100644 --- a/protobuf-parse/src/which_parser.rs +++ b/protobuf-parse/src/which_parser.rs @@ -1,14 +1,11 @@ /// Which parse to use to parse `.proto` files. #[derive(Debug, Copy, Clone)] +#[derive(Default)] pub(crate) enum WhichParser { /// Pure Rust parser implemented by this crate. + #[default] Pure, /// Parse `.proto` files using `protoc --descriptor_set_out=...` command. Protoc, } -impl Default for WhichParser { - fn default() -> Self { - WhichParser::Pure - } -} diff --git a/protobuf-support/src/lexer/float.rs b/protobuf-support/src/lexer/float.rs index f09c101e9..14d972e9b 100644 --- a/protobuf-support/src/lexer/float.rs +++ b/protobuf-support/src/lexer/float.rs @@ -15,7 +15,7 @@ pub fn format_protobuf_float(f: f64) -> String { PROTOBUF_NAN.to_owned() } else if f.is_infinite() { if f > 0.0 { - format!("{}", PROTOBUF_INF) + PROTOBUF_INF.to_string() } else { format!("-{}", PROTOBUF_INF) } diff --git a/protobuf-support/src/lexer/lexer_impl.rs b/protobuf-support/src/lexer/lexer_impl.rs index f0d6a9609..b17bcf198 100644 --- a/protobuf-support/src/lexer/lexer_impl.rs +++ b/protobuf-support/src/lexer/lexer_impl.rs @@ -233,7 +233,7 @@ impl<'a> Lexer<'a> { where P: FnOnce(char) -> bool, { - let mut clone = self.clone(); + let mut clone = *self; match clone.next_char_opt() { Some(c) if p(c) => { *self = clone; @@ -244,16 +244,11 @@ impl<'a> Lexer<'a> { } pub fn next_char_if_eq(&mut self, expect: char) -> bool { - self.next_char_if(|c| c == expect) != None + self.next_char_if(|c| c == expect).is_some() } fn next_char_if_in(&mut self, alphabet: &str) -> Option { - for c in alphabet.chars() { - if self.next_char_if_eq(c) { - return Some(c); - } - } - None + alphabet.chars().find(|&c| self.next_char_if_eq(c)) } fn next_char_expect_eq(&mut self, expect: char) -> LexerResult<()> { @@ -296,7 +291,7 @@ impl<'a> Lexer<'a> { // capitalLetter = "A" … "Z" fn _next_capital_letter_opt(&mut self) -> Option { - self.next_char_if(|c| c >= 'A' && c <= 'Z') + self.next_char_if(|c: char| c.is_ascii_uppercase()) } fn next_ident_part(&mut self) -> Option { @@ -326,7 +321,7 @@ impl<'a> Lexer<'a> { 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) + Some(u64::from_str_radix(s, 16)?) } else { None }, @@ -337,11 +332,11 @@ impl<'a> Lexer<'a> { // octalLit = "0" { octalDigit } fn next_decimal_octal_lit_opt(&mut self) -> LexerResult> { // do not advance on number parse error - let mut clone = self.clone(); + let mut clone = *self; let pos = clone.pos; - Ok(if clone.next_char_if(|c| c.is_ascii_digit()) != None { + Ok(if clone.next_char_if(|c| c.is_ascii_digit()).is_some() { clone.take_while(|c| c.is_ascii_digit()); let value = clone.input[pos..clone.pos].parse()?; *self = clone; @@ -353,11 +348,11 @@ impl<'a> Lexer<'a> { // hexDigit = "0" … "9" | "A" … "F" | "a" … "f" fn next_hex_digit(&mut self) -> LexerResult { - let mut clone = self.clone(); + let mut clone = *self; 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, + c if c.is_ascii_digit() => c as u32 - b'0' as u32, + c if ('A'..='F').contains(&c) => c as u32 - b'A' as u32 + 10, + c if ('a'..='f').contains(&c) => c as u32 - b'a' as u32 + 10, _ => return Err(LexerError::ExpectHexDigit), }; *self = clone; @@ -366,20 +361,20 @@ impl<'a> Lexer<'a> { // octalDigit = "0" … "7" fn next_octal_digit(&mut self) -> LexerResult { - self.next_char_expect(|c| c >= '0' && c <= '9', LexerError::ExpectOctDigit) + self.next_char_expect(|c: char| c.is_ascii_digit(), LexerError::ExpectOctDigit) .map(|c| c as u32 - '0' as u32) } // decimalDigit = "0" … "9" fn next_decimal_digit(&mut self) -> LexerResult { - self.next_char_expect(|c| c >= '0' && c <= '9', LexerError::ExpectDecDigit) + self.next_char_expect(|c: char| c.is_ascii_digit(), 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'); + self.take_while(|c: char| c.is_ascii_digit()); Ok(()) } @@ -401,7 +396,7 @@ impl<'a> Lexer<'a> { // exponent = ( "e" | "E" ) [ "+" | "-" ] decimals fn next_exponent_opt(&mut self) -> LexerResult> { - if self.next_char_if_in("eE") != None { + if self.next_char_if_in("eE").is_some() { self.next_char_if_in("+-"); self.next_decimal_digits()?; Ok(Some(())) @@ -423,10 +418,8 @@ impl<'a> Lexer<'a> { 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); - } + } else if (self.next_exponent_opt()?).is_none() { + return Err(LexerError::IncorrectFloatLit); } } Ok(()) @@ -457,9 +450,9 @@ impl<'a> Lexer<'a> { 'x' => { let d1 = self.next_hex_digit()? as u8; let d2 = self.next_hex_digit()? as u8; - Ok(((d1 << 4) | d2) as u8) + Ok((d1 << 4) | d2) } - d if d >= '0' && d <= '7' => { + d if ('0'..='7').contains(&d) => { let mut r = d as u8 - b'0'; for _ in 0..2 { match self.next_octal_digit() { @@ -552,11 +545,11 @@ impl<'a> Lexer<'a> { assert_eq!(ParserLanguage::Json, self.language); fn is_digit(c: char) -> bool { - c >= '0' && c <= '9' + c.is_ascii_digit() } fn is_digit_1_9(c: char) -> bool { - c >= '1' && c <= '9' + ('1'..='9').contains(&c) } if !self.lookahead_char_is_in("-0123456789") { @@ -618,9 +611,9 @@ impl<'a> Lexer<'a> { } if self.language != ParserLanguage::Json { - let mut clone = self.clone(); + let mut clone = *self; let pos = clone.pos; - if let Ok(_) = clone.next_float_lit() { + if clone.next_float_lit().is_ok() { let f = float::parse_protobuf_float(&self.input[pos..clone.pos])?; *self = clone; return Ok(Token::FloatLit(f)); @@ -672,7 +665,7 @@ mod test { P: FnOnce(&mut Lexer) -> LexerResult, { let mut lexer = Lexer::new(input, ParserLanguage::Proto); - let r = parse_what(&mut lexer).expect(&format!("lexer failed at {}", lexer.loc)); + let r = parse_what(&mut lexer).unwrap_or_else(|_| panic!("lexer failed at {}", lexer.loc)); assert!(lexer.eof(), "check eof failed at {}", lexer.loc); r } @@ -682,8 +675,8 @@ mod test { P: FnOnce(&mut Lexer) -> LexerResult>, { 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)); + let o = parse_what(&mut lexer).unwrap_or_else(|_| panic!("lexer failed at {}", lexer.loc)); + let r = o.unwrap_or_else(|| panic!("lexer returned none at {}", lexer.loc)); assert!(lexer.eof(), "check eof failed at {}", lexer.loc); r } diff --git a/protobuf-support/src/lexer/token.rs b/protobuf-support/src/lexer/token.rs index b20aba61f..139edeff4 100644 --- a/protobuf-support/src/lexer/token.rs +++ b/protobuf-support/src/lexer/token.rs @@ -22,12 +22,12 @@ impl Token { /// Back to original pub fn format(&self) -> String { match self { - &Token::Ident(ref s) => s.clone(), + Token::Ident(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(), + Token::IntLit(i) => i.to_string(), + Token::StrLit(s) => s.quoted(), + Token::FloatLit(f) => f.to_string(), + Token::JsonNumber(f) => f.to_string(), } } diff --git a/protobuf-support/src/lexer/tokenizer.rs b/protobuf-support/src/lexer/tokenizer.rs index 5541b1d2d..6c5be3a33 100644 --- a/protobuf-support/src/lexer/tokenizer.rs +++ b/protobuf-support/src/lexer/tokenizer.rs @@ -60,9 +60,9 @@ impl<'a> Tokenizer<'a> { // After lookahead return the location of the next token self.next_token .as_ref() - .map(|t| t.loc.clone()) + .map(|t| t.loc) // After token consumed return the location of that token - .or(self.last_token_loc.clone()) + .or(self.last_token_loc) // Otherwise return the position of lexer .unwrap_or(self.lexer.loc) } @@ -78,7 +78,7 @@ impl<'a> Tokenizer<'a> { Some(ref token) => Some(&token.token), None => { self.next_token = self.lexer.next_token()?; - self.last_token_loc = self.next_token.as_ref().map(|t| t.loc.clone()); + self.last_token_loc = self.next_token.as_ref().map(|t| t.loc); match self.next_token { Some(ref token) => Some(&token.token), None => None, @@ -161,8 +161,8 @@ impl<'a> Tokenizer<'a> { pub fn next_ident_if_in(&mut self, idents: &[&str]) -> TokenizerResult> { let v = match self.lookahead()? { - Some(&Token::Ident(ref next)) => { - if idents.into_iter().find(|&i| i == next).is_some() { + Some(Token::Ident(next)) => { + if idents.iter().any(|i| i == next) { next.clone() } else { return Ok(None); @@ -175,7 +175,7 @@ impl<'a> Tokenizer<'a> { } pub fn next_ident_if_eq(&mut self, word: &str) -> TokenizerResult { - Ok(self.next_ident_if_in(&[word])? != None) + Ok((self.next_ident_if_in(&[word])?).is_some()) } pub fn next_ident_expect_eq(&mut self, word: &str) -> TokenizerResult<()> { @@ -269,14 +269,14 @@ impl<'a> Tokenizer<'a> { pub fn next_ident(&mut self) -> TokenizerResult { self.next_token_check_map(|token| match token { - &Token::Ident(ref ident) => Ok(ident.clone()), + Token::Ident(ident) => Ok(ident.clone()), _ => Err(TokenizerError::ExpectIdent), }) } pub fn next_str_lit(&mut self) -> TokenizerResult { self.next_token_check_map(|token| match token { - &Token::StrLit(ref str_lit) => Ok(str_lit.clone()), + Token::StrLit(str_lit) => Ok(str_lit.clone()), _ => Err(TokenizerError::ExpectStrLit), }) } @@ -306,10 +306,10 @@ mod test { P: FnOnce(&mut Tokenizer) -> TokenizerResult, { let mut tokenizer = Tokenizer::new(input, ParserLanguage::Proto); - let r = what(&mut tokenizer).expect(&format!("parse failed at {}", tokenizer.loc())); + let r = what(&mut tokenizer).unwrap_or_else(|_| panic!("parse failed at {}", tokenizer.loc())); let eof = tokenizer .syntax_eof() - .expect(&format!("check eof failed at {}", tokenizer.loc())); + .unwrap_or_else(|_| panic!("check eof failed at {}", tokenizer.loc())); assert!(eof, "{}", tokenizer.loc()); r } diff --git a/protobuf-support/src/toposort.rs b/protobuf-support/src/toposort.rs index 5e4459046..de70108e0 100644 --- a/protobuf-support/src/toposort.rs +++ b/protobuf-support/src/toposort.rs @@ -92,7 +92,7 @@ mod tests { .get(k) .map(|v| v.as_slice()) .unwrap_or_default() - .into_iter() + .iter() .copied() }) } diff --git a/protobuf/build.rs b/protobuf/build.rs index ba76c5659..511bdf613 100644 --- a/protobuf/build.rs +++ b/protobuf/build.rs @@ -21,7 +21,7 @@ fn cfg_rust_version() { let rustc = env::var("RUSTC").expect("RUSTC unset"); let mut child = process::Command::new(rustc) - .args(&["--version"]) + .args(["--version"]) .stdin(process::Stdio::null()) .stdout(process::Stdio::piped()) .spawn() diff --git a/protobuf/src/chars.rs b/protobuf/src/chars.rs index 9a2109eea..389f547cd 100644 --- a/protobuf/src/chars.rs +++ b/protobuf/src/chars.rs @@ -53,10 +53,10 @@ impl From for Chars { } } -impl Into for Chars { - fn into(self) -> String { +impl From for String { + fn from(val: Chars) -> Self { // This is safe because `Chars` is guaranteed to store a valid UTF-8 string - unsafe { String::from_utf8_unchecked(self.0.as_ref().to_owned()) } + unsafe { String::from_utf8_unchecked(val.0.as_ref().to_owned()) } } } @@ -77,7 +77,7 @@ impl Deref for Chars { impl Borrow for Chars { fn borrow(&self) -> &str { - &*self + self } } diff --git a/protobuf/src/coded_input_stream/buf_read_iter.rs b/protobuf/src/coded_input_stream/buf_read_iter.rs index e79e22718..dda46615d 100644 --- a/protobuf/src/coded_input_stream/buf_read_iter.rs +++ b/protobuf/src/coded_input_stream/buf_read_iter.rs @@ -51,10 +51,7 @@ 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.buf.pos_within_buf()), - _ => {} - } + if let InputSource::Read(ref mut buf_read) = self.input_source { buf_read.consume(self.buf.pos_within_buf()) } } } @@ -93,7 +90,7 @@ impl<'a> BufReadIter<'a> { pub(crate) fn from_bytes(bytes: &'a Bytes) -> BufReadIter<'a> { BufReadIter { input_source: InputSource::Bytes(bytes), - buf: InputBuf::from_bytes(&bytes), + buf: InputBuf::from_bytes(bytes), pos_of_buf_start: 0, limit: NO_LIMIT, } @@ -207,22 +204,20 @@ impl<'a> BufReadIter<'a> { let r = bytes.slice(self.buf.pos_within_buf()..end); self.buf.consume(len); Ok(r) + } else if len >= READ_RAW_BYTES_MAX_ALLOC { + // We cannot trust `len` because protobuf message could be malformed. + // Reading should not result in OOM when allocating a buffer. + let mut v = Vec::new(); + self.read_exact_to_vec(len, &mut v)?; + Ok(Bytes::from(v)) } else { - if len >= READ_RAW_BYTES_MAX_ALLOC { - // We cannot trust `len` because protobuf message could be malformed. - // Reading should not result in OOM when allocating a buffer. - let mut v = Vec::new(); - self.read_exact_to_vec(len, &mut v)?; - Ok(Bytes::from(v)) - } else { - let mut r = BytesMut::with_capacity(len); - unsafe { - let buf = Self::uninit_slice_as_mut_slice(&mut r.chunk_mut()[..len]); - self.read_exact(buf)?; - r.advance_mut(len); - } - Ok(r.freeze()) + let mut r = BytesMut::with_capacity(len); + unsafe { + let buf = Self::uninit_slice_as_mut_slice(&mut r.chunk_mut()[..len]); + self.read_exact(buf)?; + r.advance_mut(len); } + Ok(r.freeze()) } } @@ -464,7 +459,7 @@ mod test { impl BufRead for Read5ThenPanic { fn fill_buf(&mut self) -> io::Result<&[u8]> { assert_eq!(0, self.pos); - static ZERO_TO_FIVE: &'static [u8] = &[0, 1, 2, 3, 4]; + static ZERO_TO_FIVE: &[u8] = &[0, 1, 2, 3, 4]; Ok(ZERO_TO_FIVE) } diff --git a/protobuf/src/coded_input_stream/input_buf.rs b/protobuf/src/coded_input_stream/input_buf.rs index d5d625225..5537543aa 100644 --- a/protobuf/src/coded_input_stream/input_buf.rs +++ b/protobuf/src/coded_input_stream/input_buf.rs @@ -67,7 +67,7 @@ impl<'a> InputBuf<'a> { #[inline(always)] pub(crate) fn read_byte(&mut self) -> Option { let r = self.remaining_in_buf().first().copied(); - if let Some(..) = r { + if r.is_some() { self.pos_within_buf += 1; } r diff --git a/protobuf/src/coded_input_stream/mod.rs b/protobuf/src/coded_input_stream/mod.rs index a979df19c..9f5ab3539 100644 --- a/protobuf/src/coded_input_stream/mod.rs +++ b/protobuf/src/coded_input_stream/mod.rs @@ -6,7 +6,6 @@ mod input_source; use std::io; use std::io::BufRead; use std::io::Read; -use std::mem; use std::mem::MaybeUninit; #[cfg(feature = "bytes")] @@ -190,7 +189,7 @@ impl<'a> CodedInputStream<'a> { if i == 9 && (b & 0x7f) > 1 { return Err(ProtobufError::WireError(WireError::IncorrectVarint).into()); } - r = r | (((b & 0x7f) as u64) << (i * 7)); + r |= ((b & 0x7f) as u64) << (i * 7); i += 1; if b < 0x80 { return Ok(r); @@ -524,13 +523,13 @@ impl<'a> CodedInputStream<'a> { /// Read `UnknownValue` pub fn read_unknown(&mut self, wire_type: WireType) -> crate::Result { 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::Varint => self.read_raw_varint64().map(UnknownValue::Varint), + WireType::Fixed64 => self.read_fixed64().map(UnknownValue::Fixed64), + WireType::Fixed32 => self.read_fixed32().map(UnknownValue::Fixed32), WireType::LengthDelimited => { let len = self.read_raw_varint32()?; self.read_raw_bytes(len) - .map(|v| UnknownValue::LengthDelimited(v)) + .map(UnknownValue::LengthDelimited) } WireType::StartGroup => { self.skip_group()?; @@ -617,7 +616,7 @@ impl<'a> CodedInputStream<'a> { 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(); + let mut vec = std::mem::take(target).into_bytes(); self.read_bytes_into(&mut vec)?; let s = match String::from_utf8(vec) { @@ -638,11 +637,11 @@ impl<'a> CodedInputStream<'a> { } } - let mut decr = DecrRecursion(self); + let decr = DecrRecursion(self); let len = decr.0.read_raw_varint64()?; let old_limit = decr.0.push_limit(len)?; - message.merge_from(&mut decr.0)?; + message.merge_from(decr.0)?; decr.0.pop_limit(old_limit); Ok(()) } @@ -871,10 +870,10 @@ mod test { 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[..]); + assert_eq!(&[0xaa_u8], &r1[..]); is.pop_limit(old_limit); let r2 = is.read_raw_bytes(2).unwrap(); - assert_eq!(&[0xbb as u8, 0xcc], &r2[..]); + assert_eq!(&[0xbb_u8, 0xcc], &r2[..]); }); } diff --git a/protobuf/src/coded_output_stream/buffer.rs b/protobuf/src/coded_output_stream/buffer.rs index ec4c62f75..a2da4ac64 100644 --- a/protobuf/src/coded_output_stream/buffer.rs +++ b/protobuf/src/coded_output_stream/buffer.rs @@ -83,7 +83,7 @@ impl OutputBuffer { #[inline] pub(crate) fn replace_buffer_keep_pos(&mut self, buffer: *mut [MaybeUninit]) { unsafe { - assert!(self.pos_within_buf <= (&*buffer).len()); + assert!(self.pos_within_buf <= (*buffer).len()); } self.buffer = buffer; } @@ -100,8 +100,8 @@ impl OutputBuffer { #[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); + let bottom = self.pos_within_buf; + let top = bottom + bytes.len(); // 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); diff --git a/protobuf/src/coded_output_stream/with.rs b/protobuf/src/coded_output_stream/with.rs index b41d71a7e..91af68a27 100644 --- a/protobuf/src/coded_output_stream/with.rs +++ b/protobuf/src/coded_output_stream/with.rs @@ -21,11 +21,11 @@ impl<'a> WithCodedOutputStream for &'a mut (dyn Write + 'a) { } impl<'a> WithCodedOutputStream for &'a mut Vec { - fn with_coded_output_stream(mut self, cb: F) -> crate::Result + fn with_coded_output_stream(self, cb: F) -> crate::Result where F: FnOnce(&mut CodedOutputStream) -> crate::Result, { - let mut os = CodedOutputStream::vec(&mut self); + let mut os = CodedOutputStream::vec(self); let r = cb(&mut os)?; os.flush()?; Ok(r) diff --git a/protobuf/src/lazy.rs b/protobuf/src/lazy.rs index 217f7592a..366180c91 100644 --- a/protobuf/src/lazy.rs +++ b/protobuf/src/lazy.rs @@ -9,6 +9,12 @@ pub struct Lazy { once_cell: OnceCell, } +impl Default for Lazy { + fn default() -> Self { + Self::new() + } +} + impl Lazy { /// Uninitialized state. pub const fn new() -> Lazy { diff --git a/protobuf/src/message.rs b/protobuf/src/message.rs index 9d7d4292d..74ab2c3c8 100644 --- a/protobuf/src/message.rs +++ b/protobuf/src/message.rs @@ -160,7 +160,7 @@ pub trait Message: Default + Clone + Send + Sync + Sized + PartialEq + 'static { /// Write the message to bytes vec. /// /// > **Note**: You can use [`Message::parse_from_bytes`] - /// to do the reverse. + /// > to do the reverse. fn write_to_bytes(&self) -> crate::Result> { self.check_initialized()?; @@ -194,7 +194,7 @@ pub trait Message: Default + Clone + Send + Sync + Sized + PartialEq + 'static { /// Get a reference to unknown fields. fn unknown_fields(&self) -> &UnknownFields { - &self.special_fields().unknown_fields() + self.special_fields().unknown_fields() } /// Get a mutable reference to unknown fields. fn mut_unknown_fields(&mut self) -> &mut UnknownFields { diff --git a/protobuf/src/message_dyn.rs b/protobuf/src/message_dyn.rs index 1b8c36b57..483193e11 100644 --- a/protobuf/src/message_dyn.rs +++ b/protobuf/src/message_dyn.rs @@ -128,7 +128,7 @@ impl dyn MessageDyn { /// Write the message to bytes vec. /// /// > **Note**: You can use [`Message::parse_from_bytes`](crate::Message::parse_from_bytes) - /// to do the reverse. + /// > to do the reverse. pub fn write_to_bytes_dyn(&self) -> crate::Result> { self.check_initialized_dyn()?; @@ -216,7 +216,7 @@ impl dyn MessageDyn { /// # } /// ``` pub fn downcast_ref<'a, M: MessageFull + 'a>(&'a self) -> Option<&'a M> { - if Any::type_id(&*self) == TypeId::of::() { + if Any::type_id(self) == TypeId::of::() { unsafe { Some(&*(self as *const dyn MessageDyn as *const M)) } } else { None diff --git a/protobuf/src/message_field.rs b/protobuf/src/message_field.rs index 5fc533178..f3c293c16 100644 --- a/protobuf/src/message_field.rs +++ b/protobuf/src/message_field.rs @@ -75,13 +75,13 @@ impl MessageField { /// View data as reference option. #[inline] pub fn as_ref(&self) -> Option<&T> { - self.0.as_ref().map(|v| &**v) + self.0.as_deref() } /// View data as mutable reference option. #[inline] pub fn as_mut(&mut self) -> Option<&mut T> { - self.0.as_mut().map(|v| &mut **v) + self.0.as_deref_mut() } /// Take the data. diff --git a/protobuf/src/owning_ref.rs b/protobuf/src/owning_ref.rs index f7d2c5fde..6cf7781e9 100644 --- a/protobuf/src/owning_ref.rs +++ b/protobuf/src/owning_ref.rs @@ -15,7 +15,7 @@ impl Deref for Owner { fn deref(&self) -> &A { match self { - Owner::Arc(a) => &*a, + Owner::Arc(a) => a, Owner::Static(a) => a, } } @@ -98,7 +98,7 @@ impl OwningRef { where C: 'static, { - f(&self).into_iter().map(|ptr| OwningRef { + f(self).iter().map(|ptr| OwningRef { ptr, owner: self.owner.clone(), }) diff --git a/protobuf/src/reflect/dynamic/map.rs b/protobuf/src/reflect/dynamic/map.rs index 7292b70b8..38b8a463e 100644 --- a/protobuf/src/reflect/dynamic/map.rs +++ b/protobuf/src/reflect/dynamic/map.rs @@ -181,7 +181,7 @@ impl ReflectMap for DynamicMap { (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), + (Maps::String(m), ReflectValueRef::String(v)) => m.get(v), _ => None, } .map(ReflectValueBox::as_value_ref) diff --git a/protobuf/src/reflect/dynamic/mod.rs b/protobuf/src/reflect/dynamic/mod.rs index 96fa20216..ca1f767d1 100644 --- a/protobuf/src/reflect/dynamic/mod.rs +++ b/protobuf/src/reflect/dynamic/mod.rs @@ -209,7 +209,7 @@ impl DynamicMessage { } pub(crate) fn downcast_ref(message: &dyn MessageDyn) -> &DynamicMessage { - assert!(Any::type_id(&*message) == TypeId::of::()); + assert!(Any::type_id(message) == TypeId::of::()); unsafe { &*(message as *const dyn MessageDyn as *const DynamicMessage) } } @@ -265,7 +265,7 @@ impl DynamicMessage { } } - handler.unknown_fields(&self.special_fields.unknown_fields())?; + handler.unknown_fields(self.special_fields.unknown_fields())?; Ok(()) } } @@ -350,7 +350,7 @@ impl MessageDyn for DynamicMessage { field, wire_type, is, - &mut self.special_fields.mut_unknown_fields(), + self.special_fields.mut_unknown_fields(), )?; continue; } diff --git a/protobuf/src/reflect/dynamic/optional.rs b/protobuf/src/reflect/dynamic/optional.rs index b9cc7ea29..3ad621f25 100644 --- a/protobuf/src/reflect/dynamic/optional.rs +++ b/protobuf/src/reflect/dynamic/optional.rs @@ -15,7 +15,7 @@ impl DynamicOptional { } pub(crate) fn mut_or_default(&mut self) -> ReflectValueMut { - if let None = self.value { + if self.value.is_none() { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() diff --git a/protobuf/src/reflect/dynamic/repeated.rs b/protobuf/src/reflect/dynamic/repeated.rs index 40c04115a..b32a1dbf3 100644 --- a/protobuf/src/reflect/dynamic/repeated.rs +++ b/protobuf/src/reflect/dynamic/repeated.rs @@ -33,15 +33,15 @@ pub(crate) enum DynamicRepeated { 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::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)), @@ -69,7 +69,7 @@ impl ReflectRepeated for DynamicRepeated { .map(|v| ReflectValueBox::Enum(descriptor.clone(), v)), ), DynamicRepeated::Message(_descriptor, v) => { - ReflectRepeatedDrainIter::new(v.drain(..).map(|v| ReflectValueBox::Message(v))) + ReflectRepeatedDrainIter::new(v.drain(..).map(ReflectValueBox::Message)) } } } @@ -218,56 +218,56 @@ impl ReflectRepeated for DynamicRepeated { fn data_enum_values(&self) -> &[i32] { match self { - DynamicRepeated::Enum(_descriptor, vs) => &vs, + DynamicRepeated::Enum(_descriptor, vs) => vs, _ => panic!("Expected enum value"), } } fn data_bool(&self) -> &[bool] { match self { - DynamicRepeated::Bool(vs) => &vs, + DynamicRepeated::Bool(vs) => vs, _ => panic!("Expected bool value"), } } fn data_u32(&self) -> &[u32] { match self { - DynamicRepeated::U32(vs) => &vs, + DynamicRepeated::U32(vs) => vs, _ => panic!("Expected u32 value"), } } fn data_u64(&self) -> &[u64] { match self { - DynamicRepeated::U64(vs) => &vs, + DynamicRepeated::U64(vs) => vs, _ => panic!("Expected u64 value"), } } fn data_i32(&self) -> &[i32] { match self { - DynamicRepeated::I32(vs) => &vs, + DynamicRepeated::I32(vs) => vs, _ => panic!("Expected i32 value"), } } fn data_i64(&self) -> &[i64] { match self { - DynamicRepeated::I64(vs) => &vs, + DynamicRepeated::I64(vs) => vs, _ => panic!("Expected i64 value"), } } fn data_f32(&self) -> &[f32] { match self { - DynamicRepeated::F32(vs) => &vs, + DynamicRepeated::F32(vs) => vs, _ => panic!("Expected f32 value"), } } fn data_f64(&self) -> &[f64] { match self { - DynamicRepeated::F64(vs) => &vs, + DynamicRepeated::F64(vs) => vs, _ => panic!("Expected f64 value"), } } diff --git a/protobuf/src/reflect/enums/mod.rs b/protobuf/src/reflect/enums/mod.rs index 4081c4a96..00b727600 100644 --- a/protobuf/src/reflect/enums/mod.rs +++ b/protobuf/src/reflect/enums/mod.rs @@ -175,7 +175,7 @@ impl EnumDescriptor { } /// This enum values - pub fn values<'a>(&'a self) -> impl Iterator + 'a { + pub fn values(&self) -> impl Iterator + '_ { let value_len = self.proto().value.len(); (0..value_len).map(move |index| EnumValueDescriptor { enum_descriptor: self.clone(), diff --git a/protobuf/src/reflect/field/dynamic.rs b/protobuf/src/reflect/field/dynamic.rs index f8bc1b31e..dbfd4ba69 100644 --- a/protobuf/src/reflect/field/dynamic.rs +++ b/protobuf/src/reflect/field/dynamic.rs @@ -12,25 +12,25 @@ pub(crate) struct DynamicFieldDescriptorRef<'a> { 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) + 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) + 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) + 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) + 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) + DynamicMessage::downcast_mut(message).clear_field(self.field) } } diff --git a/protobuf/src/reflect/file/index.rs b/protobuf/src/reflect/file/index.rs index f574357d9..41c1cb21b 100644 --- a/protobuf/src/reflect/file/index.rs +++ b/protobuf/src/reflect/file/index.rs @@ -393,13 +393,10 @@ impl FileDescriptorCommon { return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); } - if field_index.json_name != f.name() { - if index_by_name_or_json_name + if field_index.json_name != f.name() && index_by_name_or_json_name .insert(field_index.json_name.clone(), i) - .is_some() - { - return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); - } + .is_some() { + return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); } } diff --git a/protobuf/src/reflect/file/mod.rs b/protobuf/src/reflect/file/mod.rs index 068840b89..3cf91a19d 100644 --- a/protobuf/src/reflect/file/mod.rs +++ b/protobuf/src/reflect/file/mod.rs @@ -35,7 +35,7 @@ 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 + std::ptr::eq(*a, *b) } (FileDescriptorImpl::Dynamic(a), FileDescriptorImpl::Dynamic(b)) => Arc::ptr_eq(a, b), _ => false, @@ -234,7 +234,7 @@ impl FileDescriptor { /// `.proto` data for this file. pub fn proto(&self) -> &FileDescriptorProto { match &self.imp { - FileDescriptorImpl::Generated(g) => &g.proto, + FileDescriptorImpl::Generated(g) => g.proto, FileDescriptorImpl::Dynamic(d) => &d.proto, } } diff --git a/protobuf/src/reflect/find_message_or_enum.rs b/protobuf/src/reflect/find_message_or_enum.rs index 32d69d573..45c80186f 100644 --- a/protobuf/src/reflect/find_message_or_enum.rs +++ b/protobuf/src/reflect/find_message_or_enum.rs @@ -43,7 +43,7 @@ pub(crate) fn find_message_or_enum<'a>( }; if !package_to_name.is_empty() { - package_to_name.push_str("."); + package_to_name.push('.'); } package_to_name.push_str(message.name()); diff --git a/protobuf/src/reflect/map/generated.rs b/protobuf/src/reflect/map/generated.rs index cd3d2588f..71e05402d 100644 --- a/protobuf/src/reflect/map/generated.rs +++ b/protobuf/src/reflect/map/generated.rs @@ -108,10 +108,7 @@ impl<'a, K: ProtobufValue, V: ProtobufValue, I: Iterator> ReflectMapIterTrait<'a> for GeneratedMapIterImpl<'a, K, V, I> { 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, - } + self.iter.next().map(|(k, v)| (K::RuntimeType::as_ref(k), V::RuntimeType::as_ref(v))) } fn _key_type(&self) -> RuntimeType { diff --git a/protobuf/src/reflect/message/mod.rs b/protobuf/src/reflect/message/mod.rs index 583fa3b43..7b2b905d0 100644 --- a/protobuf/src/reflect/message/mod.rs +++ b/protobuf/src/reflect/message/mod.rs @@ -228,7 +228,7 @@ impl MessageDescriptor { } /// Nested oneofs including synthetic. - pub fn all_oneofs<'a>(&'a self) -> impl Iterator + 'a { + pub fn all_oneofs(&self) -> impl Iterator + '_ { self.index_entry() .oneofs .clone() @@ -239,7 +239,7 @@ impl MessageDescriptor { } /// Non-synthetic oneofs. - pub fn oneofs<'a>(&'a self) -> impl Iterator + 'a { + pub fn oneofs(&self) -> impl Iterator + '_ { self.all_oneofs().filter(|oneof| !oneof.is_synthetic()) } @@ -249,7 +249,7 @@ impl MessageDescriptor { } /// Message field descriptors. - pub fn fields<'a>(&'a self) -> impl Iterator + 'a { + pub fn fields(&self) -> impl Iterator + '_ { self.index() .message_index .regular_field_range() @@ -291,7 +291,7 @@ impl MessageDescriptor { } /// Find message field by field name or field JSON name - pub fn field_by_name_or_json_name<'a>(&'a self, name: &str) -> Option { + pub fn field_by_name_or_json_name(&self, name: &str) -> Option { let &index = self .index() .message_index diff --git a/protobuf/src/reflect/name.rs b/protobuf/src/reflect/name.rs index 7fd39afa1..b9428cbca 100644 --- a/protobuf/src/reflect/name.rs +++ b/protobuf/src/reflect/name.rs @@ -28,17 +28,15 @@ pub(crate) fn protobuf_name_starts_with_package<'a>( 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 if name.starts_with(package) { + let rem = &name[package.len()..]; + if rem.starts_with(".") { + Some(&rem[1..]) } else { None } + } else { + None } } diff --git a/protobuf/src/reflect/oneof/mod.rs b/protobuf/src/reflect/oneof/mod.rs index f355ed1ac..f97ec6472 100644 --- a/protobuf/src/reflect/oneof/mod.rs +++ b/protobuf/src/reflect/oneof/mod.rs @@ -70,7 +70,7 @@ impl OneofDescriptor { } /// Fields in this oneof. - pub fn fields<'a>(&'a self) -> impl Iterator + 'a { + pub fn fields(&self) -> impl Iterator + '_ { let message = self.containing_message(); self.index_entry() .fields diff --git a/protobuf/src/reflect/repeated/iter.rs b/protobuf/src/reflect/repeated/iter.rs index 68c072e3c..c6540171b 100644 --- a/protobuf/src/reflect/repeated/iter.rs +++ b/protobuf/src/reflect/repeated/iter.rs @@ -16,7 +16,7 @@ impl<'a> ReflectRepeatedIter<'a> { } pub(crate) fn new_slice(slice: &'a [V]) -> ReflectRepeatedIter<'a> { - ReflectRepeatedIter::new(slice.into_iter().map(V::RuntimeType::as_ref)) + ReflectRepeatedIter::new(slice.iter().map(V::RuntimeType::as_ref)) } } diff --git a/protobuf/src/reflect/repeated/mod.rs b/protobuf/src/reflect/repeated/mod.rs index f8af5e4a7..44dc9c72a 100644 --- a/protobuf/src/reflect/repeated/mod.rs +++ b/protobuf/src/reflect/repeated/mod.rs @@ -75,11 +75,11 @@ fn data_impl(v: &Vec) -> &[X] { } impl ReflectRepeated for Vec { - fn reflect_iter<'a>(&'a self) -> ReflectRepeatedIter<'a> { + fn reflect_iter(&self) -> ReflectRepeatedIter<'_> { ReflectRepeatedIter::new_slice(self.as_slice()) } - fn reflect_drain_iter<'a>(&'a mut self) -> ReflectRepeatedDrainIter<'a> { + fn reflect_drain_iter(&mut self) -> ReflectRepeatedDrainIter<'_> { ReflectRepeatedDrainIter::new_vec(self) } @@ -128,7 +128,7 @@ impl ReflectRepeated for Vec { } fn data_enum_values(&self) -> &[i32] { - V::RuntimeType::cast_to_enum_values(&self) + V::RuntimeType::cast_to_enum_values(self) } fn data_bool(&self) -> &[bool] { @@ -337,7 +337,7 @@ impl<'a> PartialEq<[ReflectValueBox]> for ReflectRepeatedRef<'a> { } } - return true; + true } } diff --git a/protobuf/src/reflect/runtime_types.rs b/protobuf/src/reflect/runtime_types.rs index bb7302c3c..60830f071 100644 --- a/protobuf/src/reflect/runtime_types.rs +++ b/protobuf/src/reflect/runtime_types.rs @@ -630,7 +630,7 @@ impl RuntimeTypeTrait for RuntimeTypeString { } fn as_ref(value: &String) -> ReflectValueRef { - ReflectValueRef::String(&*value) + ReflectValueRef::String(value) } fn as_mut(_value: &mut Self::Value) -> ReflectValueMut { @@ -656,7 +656,7 @@ impl RuntimeTypeWithDeref for RuntimeTypeString { impl RuntimeTypeMapKey for RuntimeTypeString { fn hash_map_get<'a, V>(map: &'a HashMap, key: ReflectValueRef) -> Option<&'a V> { match key { - ReflectValueRef::String(s) => map.get(*&s), + ReflectValueRef::String(s) => map.get(s), _ => None, } } @@ -834,13 +834,13 @@ impl RuntimeTypeWithDeref for RuntimeTypeTokioChars { impl RuntimeTypeMapKey for RuntimeTypeTokioChars { fn hash_map_get<'a, V>(map: &'a HashMap, key: ReflectValueRef) -> Option<&'a V> { match key { - ReflectValueRef::String(s) => map.get(&*s), + ReflectValueRef::String(s) => map.get(s), _ => None, } } fn btree_map_get<'a, V>(map: &'a BTreeMap, key: ReflectValueRef) -> Option<&'a V> { match key { - ReflectValueRef::String(s) => map.get(&*s), + ReflectValueRef::String(s) => map.get(s), _ => None, } } diff --git a/protobuf/src/reflect/types.rs b/protobuf/src/reflect/types.rs index 59ff1e678..339c8ea1e 100644 --- a/protobuf/src/reflect/types.rs +++ b/protobuf/src/reflect/types.rs @@ -324,7 +324,7 @@ impl ProtobufTypeTrait for ProtobufTypeUint64 { fn get_from_unknown(unknown: UnknownValueRef) -> Option { match unknown { - UnknownValueRef::Varint(v) => Some(v as u64), + UnknownValueRef::Varint(v) => Some(v), _ => None, } } @@ -580,7 +580,7 @@ impl ProtobufTypeTrait for ProtobufTypeString { value: &String, os: &mut CodedOutputStream, ) -> Result<()> { - os.write_string(field_number, &value) + os.write_string(field_number, value) } } @@ -609,7 +609,7 @@ impl ProtobufTypeTrait for ProtobufTypeBytes { value: &Vec, os: &mut CodedOutputStream, ) -> Result<()> { - os.write_bytes(field_number, &value) + os.write_bytes(field_number, value) } } @@ -636,7 +636,7 @@ impl ProtobufTypeTrait for ProtobufTypeTokioBytes { value: &Bytes, os: &mut CodedOutputStream, ) -> Result<()> { - os.write_bytes(field_number, &value) + os.write_bytes(field_number, value) } } @@ -663,7 +663,7 @@ impl ProtobufTypeTrait for ProtobufTypeTokioChars { value: &Chars, os: &mut CodedOutputStream, ) -> Result<()> { - os.write_string(field_number, &value) + os.write_string(field_number, value) } } @@ -704,7 +704,7 @@ impl ProtobufTypeTrait for ProtobufTypeMessage fn get_from_unknown(unknown: UnknownValueRef) -> Option { match unknown { - UnknownValueRef::LengthDelimited(v) => M::parse_from_bytes(&v).ok(), + UnknownValueRef::LengthDelimited(v) => M::parse_from_bytes(v).ok(), _ => None, } } diff --git a/protobuf/src/rt/packed.rs b/protobuf/src/rt/packed.rs index d7132d4eb..686e1491a 100644 --- a/protobuf/src/rt/packed.rs +++ b/protobuf/src/rt/packed.rs @@ -8,7 +8,7 @@ use crate::EnumOrUnknown; /// Size of serialized repeated packed field, excluding length and tag. pub(crate) fn vec_packed_varint_data_size(vec: &[T]) -> u64 { - vec.iter().map(|v| v.len_varint() as u64).sum() + vec.iter().map(|v| v.len_varint()).sum() } /// Size of serialized repeated packed field, excluding length and tag. diff --git a/protobuf/src/text_format/parse.rs b/protobuf/src/text_format/parse.rs index 905f6412e..1af5c548d 100644 --- a/protobuf/src/text_format/parse.rs +++ b/protobuf/src/text_format/parse.rs @@ -69,7 +69,7 @@ impl<'a> Parser<'a> { Ok(self.tokenizer.next_symbol_expect_eq(':', desc)?) } - fn read_enum<'e>(&mut self, e: &'e EnumDescriptor) -> ParseResult { + fn read_enum(&mut self, e: &EnumDescriptor) -> ParseResult { self.read_colon("enum")?; // TODO: read integer? @@ -226,7 +226,7 @@ impl<'a> Parser<'a> { fn read_value_of_type(&mut self, t: &RuntimeType) -> ParseResult { Ok(match t { RuntimeType::Enum(d) => { - let value = self.read_enum(&d)?.value(); + let value = self.read_enum(d)?.value(); ReflectValueBox::Enum(d.clone(), value) } RuntimeType::U32 => ReflectValueBox::U32(self.read_u32()?), @@ -238,7 +238,7 @@ impl<'a> Parser<'a> { 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)?), + RuntimeType::Message(m) => ReflectValueBox::Message(self.read_message(m)?), }) } diff --git a/protobuf/src/text_format/print.rs b/protobuf/src/text_format/print.rs index f975a6d32..c6c01a968 100644 --- a/protobuf/src/text_format/print.rs +++ b/protobuf/src/text_format/print.rs @@ -34,7 +34,7 @@ fn print_start_field( field_name: F, ) { if !*first && !pretty { - buf.push_str(" "); + buf.push(' '); } do_indent(buf, pretty, indent); *first = false; @@ -43,7 +43,7 @@ fn print_start_field( fn print_end_field(buf: &mut String, pretty: bool) { if pretty { - buf.push_str("\n"); + buf.push('\n'); } } @@ -61,11 +61,11 @@ fn print_field( ReflectValueRef::Message(m) => { buf.push_str(" {"); if pretty { - buf.push_str("\n"); + buf.push('\n'); } print_to_internal(&m, buf, pretty, indent + 1); do_indent(buf, pretty, indent); - buf.push_str("}"); + buf.push('}'); } ReflectValueRef::Enum(d, v) => { buf.push_str(": "); @@ -118,7 +118,7 @@ fn print_to_internal(m: &MessageRef, buf: &mut String, pretty: bool, indent: usi print_start_field(buf, pretty, indent, &mut first, f.name()); buf.push_str(" {"); if pretty { - buf.push_str("\n"); + buf.push('\n'); } let mut entry_first = true; @@ -126,7 +126,7 @@ fn print_to_internal(m: &MessageRef, buf: &mut String, pretty: bool, indent: usi 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("}"); + buf.push('}'); print_end_field(buf, pretty); } } diff --git a/protobuf/src/unknown.rs b/protobuf/src/unknown.rs index c54b20c4c..3f9d0980b 100644 --- a/protobuf/src/unknown.rs +++ b/protobuf/src/unknown.rs @@ -36,12 +36,12 @@ impl UnknownValue { } /// As ref - pub fn get_ref<'s>(&'s self) -> UnknownValueRef<'s> { + pub fn get_ref(&self) -> UnknownValueRef<'_> { match *self { UnknownValue::Fixed32(fixed32) => UnknownValueRef::Fixed32(fixed32), UnknownValue::Fixed64(fixed64) => UnknownValueRef::Fixed64(fixed64), UnknownValue::Varint(varint) => UnknownValueRef::Varint(varint), - UnknownValue::LengthDelimited(ref bytes) => UnknownValueRef::LengthDelimited(&bytes), + UnknownValue::LengthDelimited(ref bytes) => UnknownValueRef::LengthDelimited(bytes), } } @@ -151,7 +151,7 @@ impl UnknownValues { } /// Iterate over unknown values - pub fn iter<'s>(&'s self) -> UnknownValuesIter<'s> { + pub fn iter(&self) -> UnknownValuesIter<'_> { UnknownValuesIter { fixed32: self.fixed32.iter(), fixed64: self.fixed64.iter(), @@ -167,11 +167,7 @@ impl UnknownValues { 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 - } + } else { self.length_delimited.last().map(|last| UnknownValueRef::LengthDelimited(last)) } } } @@ -206,7 +202,7 @@ impl<'o> Iterator for UnknownValuesIter<'o> { return Some(UnknownValueRef::Varint(*varint)); } if let Some(length_delimited) = self.length_delimited.next() { - return Some(UnknownValueRef::LengthDelimited(&length_delimited)); + return Some(UnknownValueRef::LengthDelimited(length_delimited)); } None } @@ -320,7 +316,7 @@ impl UnknownFields { } /// Iterate over all unknowns - pub fn iter<'s>(&'s self) -> UnknownFieldsIter<'s> { + pub fn iter(&self) -> UnknownFieldsIter<'_> { UnknownFieldsIter { entries: self.fields.as_ref().map(|m| UnknownFieldsNotEmptyIter { fields: m.iter(), diff --git a/protobuf/src/varint/decode.rs b/protobuf/src/varint/decode.rs index 714534350..58280ee3f 100644 --- a/protobuf/src/varint/decode.rs +++ b/protobuf/src/varint/decode.rs @@ -42,7 +42,7 @@ fn decode_varint_full(rem: &[u8]) -> crate::Result(rem: &[u8]) -> crate::Result(buf: &[u8]) -> crate::Result> { - if buf.len() >= 1 && buf[0] < 0x80 { + if !buf.is_empty() && buf[0] < 0x80 { // The the most common case. let ret = buf[0] as u64; let consume = 1; diff --git a/protobuf/src/well_known_types_util/duration.rs b/protobuf/src/well_known_types_util/duration.rs index eb68e2386..2dbefa421 100644 --- a/protobuf/src/well_known_types_util/duration.rs +++ b/protobuf/src/well_known_types_util/duration.rs @@ -32,11 +32,11 @@ impl From for Duration { /// # Panics /// /// If `Duration` value is outside of `std::time::Duration` supported range. -impl Into 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) +impl From for std::time::Duration { + fn from(val: Duration) -> Self { + assert!(val.seconds >= 0); + std::time::Duration::from_secs(val.seconds as u64) + + std::time::Duration::from_nanos(val.nanos as u64) } } diff --git a/protobuf/src/well_known_types_util/timestamp.rs b/protobuf/src/well_known_types_util/timestamp.rs index 0429fcfa1..247152c95 100644 --- a/protobuf/src/well_known_types_util/timestamp.rs +++ b/protobuf/src/well_known_types_util/timestamp.rs @@ -53,15 +53,15 @@ impl From for Timestamp { /// This function panics: /// * if given `Timestamp` is outside of `SystemTime` range /// * if `Timestamp` is malformed -impl Into for Timestamp { - fn into(self) -> SystemTime { - if self.seconds >= 0 { +impl From for SystemTime { + fn from(val: Timestamp) -> Self { + if val.seconds >= 0 { let duration = - Duration::from_secs(self.seconds as u64) + Duration::from_nanos(self.nanos as u64); + Duration::from_secs(val.seconds as u64) + Duration::from_nanos(val.nanos as u64); SystemTime::UNIX_EPOCH + duration } else { let duration = - Duration::from_secs(-self.seconds as u64) - Duration::from_nanos(self.nanos as u64); + Duration::from_secs(-val.seconds as u64) - Duration::from_nanos(val.nanos as u64); SystemTime::UNIX_EPOCH - duration } } diff --git a/test-crates/perftest/bytes/build.rs b/test-crates/perftest/bytes/build.rs index 7d3251045..06fb53e5d 100644 --- a/test-crates/perftest/bytes/build.rs +++ b/test-crates/perftest/bytes/build.rs @@ -10,7 +10,7 @@ fn generate_protos() { .pure() .out_dir("src") .input("src/messages.proto") - .includes(&["src", "../../proto"]) + .includes(["src", "../../proto"]) .customize(Customize::default().gen_mod_rs(false)) .run_from_script(); } @@ -29,7 +29,7 @@ fn export_rustc_cfg() { let rustc = env::var("RUSTC").expect("RUSTC unset"); let mut child = process::Command::new(rustc) - .args(&["--version"]) + .args(["--version"]) .stdin(process::Stdio::null()) .stdout(process::Stdio::piped()) .spawn() diff --git a/test-crates/perftest/misc/build.rs b/test-crates/perftest/misc/build.rs index 61f68c752..f2063b7d1 100644 --- a/test-crates/perftest/misc/build.rs +++ b/test-crates/perftest/misc/build.rs @@ -16,7 +16,7 @@ fn export_rustc_cfg() { let rustc = env::var("RUSTC").expect("RUSTC unset"); let mut child = process::Command::new(rustc) - .args(&["--version"]) + .args(["--version"]) .stdin(process::Stdio::null()) .stdout(process::Stdio::piped()) .spawn() diff --git a/test-crates/perftest/vs-cxx/perftest.rs b/test-crates/perftest/vs-cxx/perftest.rs index 4cfa6eb79..a463533b3 100644 --- a/test-crates/perftest/vs-cxx/perftest.rs +++ b/test-crates/perftest/vs-cxx/perftest.rs @@ -32,7 +32,7 @@ struct TestRunner { impl TestRunner { fn run_test(&self, name: &str, data: &[M]) { - assert!(data.len() > 0, "empty string for test: {}", name); + assert!(!data.is_empty(), "empty string for test: {}", name); let mut rng: StdRng = SeedableRng::from_seed([ 10, 20, 30, 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -43,7 +43,7 @@ impl TestRunner { let mut total_size = 0; while total_size < self.data_size { - let ref item = data[rng.gen_range(0, data.len())]; + let item = &data[rng.gen_range(0, data.len())]; random_data.push(item.clone()); total_size += item.compute_size() as u32; } @@ -111,19 +111,18 @@ fn main() { panic!("usage: {} [data_size] [test]", args[0]) } let data_size = args - .iter() - .nth(1) + .get(1) .map(|x| x.parse().unwrap()) .unwrap_or(1000000); - let selected = args.iter().nth(2).cloned(); + let selected = args.get(2).cloned(); let mut runner = TestRunner { - selected: selected, + selected, any_matched: false, - data_size: data_size, + data_size, }; - let mut is = File::open(&Path::new("perftest_data.pbbin")).unwrap(); + let mut is = File::open(Path::new("perftest_data.pbbin")).unwrap(); let test_data = PerftestData::parse_from_reader(&mut is).unwrap(); runner.test("test1", &test_data.test1); diff --git a/test-crates/protobuf-codegen-identical-test/tests/diff.rs b/test-crates/protobuf-codegen-identical-test/tests/diff.rs index 25cd914c6..8946fa4da 100644 --- a/test-crates/protobuf-codegen-identical-test/tests/diff.rs +++ b/test-crates/protobuf-codegen-identical-test/tests/diff.rs @@ -203,13 +203,11 @@ fn normalize_service(service: &mut ServiceDescriptorProto) { fn normalize_field(field: &mut FieldDescriptorProto) { field.options.mut_or_insert_default(); - if field.has_default_value() { - if field.type_() == field_descriptor_proto::Type::TYPE_FLOAT { - field.set_default_value(format!( - "{}", - parse_protobuf_float(field.default_value()).unwrap() - )); - } + if field.has_default_value() && field.type_() == field_descriptor_proto::Type::TYPE_FLOAT { + field.set_default_value(format!( + "{}", + parse_protobuf_float(field.default_value()).unwrap() + )); } } @@ -332,12 +330,12 @@ where normalize_generated_file_in_place(Path::new(&pure_rs)); let protoc_rs_contents = - fs::read_to_string(&protoc_rs).expect(&format!("while reading {}", protoc_rs)); + fs::read_to_string(&protoc_rs).unwrap_or_else(|_| panic!("while reading {}", protoc_rs)); let pure_rs_contents = - fs::read_to_string(&pure_rs).expect(&format!("while reading {}", pure_rs)); + fs::read_to_string(&pure_rs).unwrap_or_else(|_| panic!("while reading {}", pure_rs)); - let protoc_descriptor_for_file = descriptor_for_file(&protoc_descriptors, &proto_file_name); - let pure_descriptor_for_file = descriptor_for_file(&pure_descriptors, &proto_file_name); + let protoc_descriptor_for_file = descriptor_for_file(&protoc_descriptors, proto_file_name); + let pure_descriptor_for_file = descriptor_for_file(&pure_descriptors, proto_file_name); let skip = should_skip(input.to_str().unwrap()); if protoc_rs_contents == pure_rs_contents diff --git a/test-crates/protobuf-codegen-protoc-test/build.rs b/test-crates/protobuf-codegen-protoc-test/build.rs index fbc0aec98..0b2c34559 100644 --- a/test-crates/protobuf-codegen-protoc-test/build.rs +++ b/test-crates/protobuf-codegen-protoc-test/build.rs @@ -29,7 +29,7 @@ fn gen_in_dir(dir: &str, include_dir: &str) { codegen() .out_dir(out_dir) .inputs(input) - .includes(&["../../proto", include_dir]) + .includes(["../../proto", include_dir]) .customize(customize) .run_from_script() }, @@ -54,7 +54,7 @@ fn generate_in_v2_v3() { fn generate_interop() { codegen() .out_dir("src/interop") - .includes(&["../../test-crates/interop/cxx", "../../proto"]) + .includes(["../../test-crates/interop/cxx", "../../proto"]) .input("../../test-crates/interop/cxx/interop_pb.proto") .run_from_script(); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_repeated_get_set.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_repeated_get_set.rs index 98170ae39..1252e95d2 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_repeated_get_set.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_repeated_get_set.rs @@ -38,5 +38,5 @@ fn generated_repeated() { #[test] fn dynamic_repeated() { - do_test_repeated(&test_dynamic_repeated_get_set_pb::file_descriptor()); + do_test_repeated(test_dynamic_repeated_get_set_pb::file_descriptor()); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_singular_get_set.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_singular_get_set.rs index 084c7972b..5af06676a 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_singular_get_set.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_dynamic_singular_get_set.rs @@ -30,7 +30,7 @@ fn do_test_get_set(file_descriptor: &FileDescriptor) { #[test] fn generated_get_set() { - do_test_get_set(&test_dynamic_singular_get_set_pb::file_descriptor()); + do_test_get_set(test_dynamic_singular_get_set_pb::file_descriptor()); } #[test] @@ -51,7 +51,7 @@ fn do_test_set_panic_on_wrong_field_type(file_descriptor: &FileDescriptor) { #[test] #[should_panic] fn generated_set_panic_on_wrong_field_type() { - do_test_set_panic_on_wrong_field_type(&test_dynamic_singular_get_set_pb::file_descriptor()); + do_test_set_panic_on_wrong_field_type(test_dynamic_singular_get_set_pb::file_descriptor()); } #[test] diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_ext.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_ext.rs index 28de12784..952eb2f91 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_ext.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_ext.rs @@ -18,7 +18,7 @@ fn test_get() { assert_eq!(16, exts::fixed64_field.get(message).unwrap_or_default()); assert_eq!(7, exts::sfixed32_field.get(message).unwrap_or_default()); assert_eq!(-17, exts::sfixed64_field.get(message).unwrap_or_default()); - assert_eq!(true, exts::bool_field.get(message).unwrap_or_default()); + assert!(exts::bool_field.get(message).unwrap_or_default()); assert_eq!( "Hello world!", exts::string_field.get(message).unwrap_or_default() diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json.rs index 238a2dc2f..606130756 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json.rs @@ -196,7 +196,7 @@ fn test_string() { test_json_print_parse_message("{\"stringSingular\": \"ab\"}", &m); let mut m = TestTypes::new(); - m.set_string_repeated(vec!["".to_owned(), "\0".to_owned(), "A\nB".to_owned()].into()); + m.set_string_repeated(vec!["".to_owned(), "\0".to_owned(), "A\nB".to_owned()]); test_json_print_parse_message("{\"stringRepeated\": [\"\", \"\\u0000\", \"A\\nB\"]}", &m); } @@ -207,7 +207,7 @@ fn test_bytes() { test_json_print_parse_message("{\"bytesSingular\": \"YWI=\"}", &m); let mut m = TestTypes::new(); - m.set_bytes_repeated(vec![b"".to_vec(), b"\0".to_vec(), b"A\nB".to_vec()].into()); + m.set_bytes_repeated(vec![b"".to_vec(), b"\0".to_vec(), b"A\nB".to_vec()]); test_json_print_parse_message("{\"bytesRepeated\": [\"\", \"AA==\", \"QQpC\"]}", &m); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json_well_known.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json_well_known.rs index 2c344e8db..654807f51 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json_well_known.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_json_well_known.rs @@ -148,14 +148,14 @@ fn test_field_mask() { m.set_field_mask({ let mut v = FieldMask::new(); - v.paths = vec!["a.b".to_owned()].into(); + v.paths = vec!["a.b".to_owned()]; v }); test_json_print_parse_message("{\"fieldMask\": \"a.b\"}", &m); m.set_field_mask({ let mut v = FieldMask::new(); - v.paths = vec!["ab".to_owned(), "c.d.e".to_owned()].into(); + v.paths = vec!["ab".to_owned(), "c.d.e".to_owned()]; v }); test_json_print_parse_message("{\"fieldMask\": \"ab,c.d.e\"}", &m); diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_text_format.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_text_format.rs index eb5d8cc83..a5b663bbc 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_text_format.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_fmt_text_format.rs @@ -173,7 +173,7 @@ fn test_reflect() { let mut l = TestTypesList::new(); // TODO: make `ts` field public in codegen - l.set_ts(special_messages_typed().into()); + l.set_ts(special_messages_typed()); test_text_format_message(&l); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_generate_accessors.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_generate_accessors.rs index 5eae05a3f..5544b4fbb 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_generate_accessors.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_generate_accessors.rs @@ -8,5 +8,5 @@ fn test() { // Check that field is public // even if it's not requested explicitly - WithoutAccessors::new().f; + WithoutAccessors::new(); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_message_getter.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_message_getter.rs index 394499f10..f6e91c8ff 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_message_getter.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_message_getter.rs @@ -4,5 +4,5 @@ use super::test_message_getter_pb::MessageForTestGetter; fn get_returns_default_value() { let m = MessageForTestGetter::new(); assert_eq!(0, m.i()); - assert_eq!(false, m.b()); + assert!(!m.b()); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_basic.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_basic.rs index 5226c4efc..e5c9d0548 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_basic.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_basic.rs @@ -18,18 +18,18 @@ fn test_set_clear_field() { assert!(test_message.has_int32_field()); assert_eq!(10, test_message.int32_field()); assert!(!test_message.has_bool_field()); - assert_eq!(false, test_message.bool_field()); + assert!(!test_message.bool_field()); test_message.set_bool_field(true); assert!(test_message.has_bool_field()); - assert_eq!(true, test_message.bool_field()); + assert!(test_message.bool_field()); assert!(!test_message.has_int32_field()); assert_eq!(0, test_message.int32_field()); test_message.clear_int32_field(); assert!(!test_message.has_int32_field()); assert!(!test_message.has_bool_field()); - assert_eq!(false, test_message.bool_field()); + assert!(!test_message.bool_field()); assert_eq!(0, test_message.int32_field()); } diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs index 9353a53cc..85053f8a5 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs @@ -1,5 +1,3 @@ -use protobuf::OneofFull; -use protobuf_test_common::*; use super::test_oneof_nonexhaustive_pb::*; diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs index cd22189b7..bb5172ed5 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs @@ -46,8 +46,7 @@ fn test_singular_basic() { bool_field.set_singular_field(&mut message, ReflectValueBox::Bool(true)); assert!(bool_field.has_field(&message)); - assert_eq!( - true, + assert!( bool_field .get_singular_field_or_default(&message) .to_bool() diff --git a/test-crates/protobuf-codegen-protoc-test/src/v2/test_default_values.rs b/test-crates/protobuf-codegen-protoc-test/src/v2/test_default_values.rs index 27b5c51bd..dc0f75b0b 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/v2/test_default_values.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/v2/test_default_values.rs @@ -15,8 +15,8 @@ fn test_default_value_simple() { assert_eq!(10, d.fixed64_field()); assert_eq!(11, d.sfixed32_field()); assert_eq!(12, d.sfixed64_field()); - assert_eq!(true, d.bool_field()); - assert_eq!(false, d.bool_default_false_field()); + assert!(d.bool_field()); + assert!(!d.bool_default_false_field()); assert_eq!("abc\n22", d.string_field()); assert_eq!(b"cde\n33", d.bytes_field()); assert_eq!(EnumForDefaultValue::TWO, d.enum_field()); diff --git a/test-crates/protobuf-codegen-pure-test/build.rs b/test-crates/protobuf-codegen-pure-test/build.rs index eda1d969d..f8737e6a1 100644 --- a/test-crates/protobuf-codegen-pure-test/build.rs +++ b/test-crates/protobuf-codegen-pure-test/build.rs @@ -12,14 +12,14 @@ fn copy_test, P2: AsRef>(src: P1, dst: P2) { eprintln!("copy {:?} to {:?}", src.as_ref(), dst.as_ref()); let mut content = Vec::new(); fs::File::open(src.as_ref()) - .expect(&format!("open {}", src.as_ref().display())) + .unwrap_or_else(|_| panic!("open {}", src.as_ref().display())) .read_to_end(&mut content) - .expect(&format!("read_to_end {}", src.as_ref().display())); + .unwrap_or_else(|_| panic!("read_to_end {}", src.as_ref().display())); let mut write = fs::File::create(dst).expect("create"); writeln!(write, "// @generated").expect("write"); writeln!(write, "// copied from {}", src.as_ref().display()).expect("write"); - writeln!(write, "").expect("write"); + writeln!(write).expect("write"); write.write_all(&content).expect("write_all"); // Print generated twice to avoid overlooking it accidentally writeln!(write, "// @generated").expect("write"); @@ -29,7 +29,7 @@ fn copy_test, P2: AsRef>(src: P1, dst: P2) { fn copy_from_protobuf_test(path: &str) { copy_test( &format!("../../test-crates/protobuf-codegen-protoc-test/{}", path), - &format!("{}", path), + &path.to_string(), ) } @@ -64,7 +64,7 @@ fn classify_file_name(dir: &str, name: &str) -> FileNameClass { // Copy tests from `protobuf-test` directory to the same directory here fn copy_tests(dir: &str) { let src_dir = format!("../../test-crates/protobuf-codegen-protoc-test/{}", dir); - for entry in fs::read_dir(&src_dir).expect(&format!("read_dir {}", src_dir)) { + for entry in fs::read_dir(&src_dir).unwrap_or_else(|_| panic!("read_dir {}", src_dir)) { let file_name = entry.expect("entry").file_name().into_string().unwrap(); match classify_file_name(dir, &file_name) { @@ -88,7 +88,7 @@ fn gen_in_dir(dir: &str, include_dir: &str) { .pure() .out_dir(out_dir) .inputs(input) - .includes(&[include_dir]) + .includes([include_dir]) .customize(customize) .run_from_script() }, @@ -103,7 +103,7 @@ fn generate_interop() { Codegen::new() .pure() .out_dir("src/interop") - .includes(&["../../test-crates/interop/cxx", "../../proto"]) + .includes(["../../test-crates/interop/cxx", "../../proto"]) .input("../../test-crates/interop/cxx/interop_pb.proto") .run_from_script(); } diff --git a/test-crates/protobuf-fuzz/src/lib.rs b/test-crates/protobuf-fuzz/src/lib.rs index 318722c23..4c47d074a 100644 --- a/test-crates/protobuf-fuzz/src/lib.rs +++ b/test-crates/protobuf-fuzz/src/lib.rs @@ -73,7 +73,7 @@ pub fn fuzz_target_map_read(bytes: &[u8]) { } fn test_message(bytes: &[u8]) { - if bytes.len() < 1 { + if bytes.is_empty() { return; } match bytes[0] { @@ -87,7 +87,7 @@ fn test_message(bytes: &[u8]) { } pub fn fuzz_target_all(bytes: &[u8]) { - if bytes.len() < 1 { + if bytes.is_empty() { return; } match bytes[0] { diff --git a/test-crates/protobuf-test-common/src/build.rs b/test-crates/protobuf-test-common/src/build.rs index ae35d07bf..70c622cd4 100644 --- a/test-crates/protobuf-test-common/src/build.rs +++ b/test-crates/protobuf-test-common/src/build.rs @@ -34,7 +34,7 @@ fn read_gitignore(dir: &Path) -> Vec { let gitignore = &Path::new(&gitignore); if gitignore.exists() { let gitignore = - fs::File::open(gitignore).expect(&format!("open gitignore {:?}", gitignore)); + fs::File::open(gitignore).unwrap_or_else(|_| panic!("open gitignore {:?}", gitignore)); for line in BufReader::new(gitignore).lines() { let line = line.expect("read_line"); if line.is_empty() || line.starts_with("#") { @@ -68,7 +68,7 @@ fn clean_recursively(dir: &Path, patterns: &[&str]) { let file_name = entry_path.as_path().file_name().unwrap().to_str().unwrap(); if entry .metadata() - .expect(&format!("metadata of {:?}", entry_path)) + .unwrap_or_else(|_| panic!("metadata of {:?}", entry_path)) .is_dir() { clean_recursively(&entry_path, &patterns); @@ -77,7 +77,7 @@ fn clean_recursively(dir: &Path, patterns: &[&str]) { } else { for pattern in &patterns_compiled { if pattern.matches(file_name) { - fs::remove_file(&entry_path).expect(&format!("remove_file {:?}", entry_path)); + fs::remove_file(&entry_path).unwrap_or_else(|_| panic!("remove_file {:?}", entry_path)); break; } } @@ -86,7 +86,7 @@ fn clean_recursively(dir: &Path, patterns: &[&str]) { } pub fn clean_old_files() { - clean_recursively(&Path::new("src"), &["*_pb.rs", "*_pb_proto3.rs"]); + clean_recursively(Path::new("src"), &["*_pb.rs", "*_pb_proto3.rs"]); } #[derive(Default)] @@ -103,7 +103,7 @@ pub fn gen_mod_rs_in_dir(dir: &str) { let mut mod_rs = fs::File::create(&format!("{}/mod.rs", dir)).expect("create"); writeln!(mod_rs, "// @generated by {}", module_path!()).expect("write"); - writeln!(mod_rs, "").expect("write"); + writeln!(mod_rs).expect("write"); let rs_files = glob_simple(&format!("{}/*.rs", dir)); @@ -160,9 +160,9 @@ fn test_version_from_file_path(mut file_path: &Path) -> TestProtobufVersions { } fn test_version_from_file_content(file_path: &Path) -> ProtobufSyntax { - let content = fs::read_to_string(file_path).expect(&format!("read_to_string {:?}", file_path)); + let content = fs::read_to_string(file_path).unwrap_or_else(|_| panic!("read_to_string {:?}", file_path)); if content.contains("syntax = \"proto2\"") { - return ProtobufSyntax::V2; + ProtobufSyntax::V2 } else if content.contains("syntax = \"proto3\"") { return ProtobufSyntax::V3; } else { @@ -277,11 +277,11 @@ pub fn copy_tests_v2_v3(v2_dir: &str, v3_dir: &str) { let proto = proto.replace("optional ", ""); let proto = proto.replace("required ", ""); let proto = proto.replace("syntax = \"proto2\";", "syntax = \"proto3\";"); - write!(p3f, "// @generated\n").expect("write"); + writeln!(p3f, "// @generated").expect("write"); write!(p3f, "{}", proto).expect("write"); p3f.flush().expect("flush"); - write!(r3f, "// @generated\n").expect("write"); + writeln!(r3f, "// @generated").expect("write"); write!(r3f, "{}", rs).expect("write"); r3f.flush().expect("flush"); } diff --git a/test-crates/protobuf-test-common/src/hex.rs b/test-crates/protobuf-test-common/src/hex.rs index 0e9bf7313..28a73dc20 100644 --- a/test-crates/protobuf-test-common/src/hex.rs +++ b/test-crates/protobuf-test-common/src/hex.rs @@ -4,9 +4,9 @@ use std::char; fn decode_hex_digit(digit: char) -> u8 { match digit { - '0'..='9' => digit as u8 - '0' as u8, - 'a'..='f' => digit as u8 - 'a' as u8 + 10, - 'A'..='F' => digit as u8 - 'A' as u8 + 10, + '0'..='9' => digit as u8 - b'0', + 'a'..='f' => digit as u8 - b'a' + 10, + 'A'..='F' => digit as u8 - b'A' + 10, _ => panic!(), } } @@ -45,7 +45,7 @@ fn encode_hex_byte(byte: u8) -> [char; 2] { pub fn encode_hex(bytes: &[u8]) -> String { let strs: Vec = bytes .iter() - .map(|byte| encode_hex_byte(*byte).iter().map(|c| *c).collect()) + .map(|byte| encode_hex_byte(*byte).iter().copied().collect()) .collect(); strs.join(" ") } diff --git a/test-crates/protobuf-test-common/src/interop.rs b/test-crates/protobuf-test-common/src/interop.rs index 0c5d523ee..996bbbae1 100644 --- a/test-crates/protobuf-test-common/src/interop.rs +++ b/test-crates/protobuf-test-common/src/interop.rs @@ -5,7 +5,7 @@ use std::process; /// Invoke `interop` binary, pass given data as stdin, return stdout. pub fn interop_command(command: &str, stdin: &[u8]) -> Vec { let mut interop = process::Command::new("../test-crates/interop/cxx/interop") - .args(&[command]) + .args([command]) .stdin(process::Stdio::piped()) .stdout(process::Stdio::piped()) .stderr(process::Stdio::inherit()) diff --git a/test-crates/protobuf-test-common/src/json_tests.rs b/test-crates/protobuf-test-common/src/json_tests.rs index 427b671da..d6798813a 100644 --- a/test-crates/protobuf-test-common/src/json_tests.rs +++ b/test-crates/protobuf-test-common/src/json_tests.rs @@ -31,10 +31,8 @@ pub fn test_json_message(m: &dyn MessageDyn) { let s = protobuf_json_mapping::print_to_string(m).expect("print_to_string"); let mut new = descriptor.new_instance(); - protobuf_json_mapping::merge_from_str(&mut *new, &s).expect(&format!( - "failed to parse serialized: {}; from message: {:?}", - s, m - )); + protobuf_json_mapping::merge_from_str(&mut *new, &s).unwrap_or_else(|_| panic!("failed to parse serialized: {}; from message: {:?}", + s, m)); assert!( m.reflect_eq_dyn(&*new, &ReflectEqMode::nan_equal()), "{:?} should be == {:?}", diff --git a/test-crates/protobuf-test-common/src/reflect_tests.rs b/test-crates/protobuf-test-common/src/reflect_tests.rs index 4bc7ddaa3..f3c658519 100644 --- a/test-crates/protobuf-test-common/src/reflect_tests.rs +++ b/test-crates/protobuf-test-common/src/reflect_tests.rs @@ -102,7 +102,7 @@ pub fn values_for_runtime_type(field_type: &RuntimeType) -> Vec ReflectValueBox::from(e.values().next().unwrap()), ReflectValueBox::from(e.values().last().unwrap()), ], - RuntimeType::Message(m) => values_for_message_type(&m) + RuntimeType::Message(m) => values_for_message_type(m) .into_iter() .map(ReflectValueBox::from) .collect(), diff --git a/test-crates/protobuf-test-common/src/text_format_tests.rs b/test-crates/protobuf-test-common/src/text_format_tests.rs index 347e36d10..ca71e3573 100644 --- a/test-crates/protobuf-test-common/src/text_format_tests.rs +++ b/test-crates/protobuf-test-common/src/text_format_tests.rs @@ -36,8 +36,7 @@ fn parse_using_protoc(text: &str, message_descriptor: &MessageDescriptor) -> Box descriptor::file_descriptor().proto().clone(), rustproto::file_descriptor().proto().clone(), message_descriptor.file_descriptor_proto().clone(), - ] - .into(); + ]; let mut temp_file = temp_dir.path().to_owned(); temp_file.push("fds"); @@ -46,7 +45,7 @@ fn parse_using_protoc(text: &str, message_descriptor: &MessageDescriptor) -> Box // TODO: use protoc crate let mut protoc = process::Command::new("protoc") - .args(&[ + .args([ &format!( "--descriptor_set_in={}", temp_file.to_str().expect("to_str") @@ -103,8 +102,7 @@ fn print_using_protoc(message: &dyn MessageDyn) -> String { descriptor::file_descriptor().proto().clone(), rustproto::file_descriptor().proto().clone(), message_descriptor.file_descriptor_proto().clone(), - ] - .into(); + ]; let mut temp_file = temp_dir.path().to_owned(); temp_file.push("fds"); @@ -113,7 +111,7 @@ fn print_using_protoc(message: &dyn MessageDyn) -> String { // TODO: use protoc crate let mut protoc = process::Command::new("protoc") - .args(&[ + .args([ &format!( "--descriptor_set_in={}", temp_file.to_str().expect("to_str") @@ -154,7 +152,7 @@ fn print_using_protoc(message: &dyn MessageDyn) -> String { pub fn test_text_format_str_descriptor(text: &str, message_descriptor: &MessageDescriptor) { let message = parse_using_rust_protobuf(text, message_descriptor) - .expect(format!("parse_using_rust_protobuf: {:?}", &text).as_str()); + .unwrap_or_else(|_| panic!("parse_using_rust_protobuf: {:?}", &text)); let expected = parse_using_protoc(text, message_descriptor); assert!( @@ -167,7 +165,7 @@ pub fn test_text_format_str_descriptor(text: &str, message_descriptor: &MessageD // print using protoc and parse using rust-protobuf let printed_using_protoc = print_using_protoc(&*message); let pp = parse_using_rust_protobuf(&printed_using_protoc, message_descriptor) - .expect(format!("parse_using_rust_protobuf: {:?}", &printed_using_protoc).as_str()); + .unwrap_or_else(|_| panic!("parse_using_rust_protobuf: {:?}", &printed_using_protoc)); assert!( message_descriptor.eq(&*expected, &*pp), @@ -190,7 +188,7 @@ pub fn test_text_format_message(message: &dyn MessageDyn) { let printed_with_protoc = print_using_protoc(message); let from_protoc = parse_using_rust_protobuf(&printed_with_protoc, &descriptor) - .expect(format!("parse_using_rust_protobuf: {:?}", &printed_with_protoc).as_str()); + .unwrap_or_else(|_| panic!("parse_using_rust_protobuf: {:?}", &printed_with_protoc)); let from_protobuf = parse_using_protoc(&printed_with_rust_protobuf, &descriptor); assert!( From dd08537cae2c5972a47322e67726c32f02055536 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Thu, 5 Sep 2024 00:38:14 +0200 Subject: [PATCH 5/5] style: run `cargo fmt --all` --- ci-gen/src/ghwf.rs | 4 +- ci-gen/src/yaml.rs | 4 +- protobuf-codegen/src/codegen/mod.rs | 4 +- protobuf-codegen/src/gen/all.rs | 10 ++-- protobuf-codegen/src/gen/code_writer.rs | 8 ++- protobuf-codegen/src/gen/oneof.rs | 3 +- protobuf-codegen/src/gen/scope.rs | 15 +++--- protobuf-json-mapping/src/rfc_3339.rs | 4 +- .../src/pure/convert/option_resolver.rs | 49 ++++++++++--------- protobuf-parse/src/pure/model.rs | 13 ++--- protobuf-parse/src/pure/parser.rs | 11 ++--- protobuf-parse/src/which_parser.rs | 4 +- protobuf-support/src/lexer/tokenizer.rs | 3 +- .../src/coded_input_stream/buf_read_iter.rs | 4 +- protobuf/src/coded_input_stream/mod.rs | 3 +- protobuf/src/reflect/file/index.rs | 6 ++- protobuf/src/reflect/map/generated.rs | 4 +- protobuf/src/unknown.rs | 6 ++- test-crates/perftest/vs-cxx/perftest.rs | 5 +- .../tests/diff.rs | 4 +- .../src/common/v2/test_oneof_nonexhaustive.rs | 1 - .../src/common/v2/test_reflect_basic.rs | 10 ++-- test-crates/protobuf-test-common/src/build.rs | 6 ++- .../protobuf-test-common/src/json_tests.rs | 4 +- 24 files changed, 90 insertions(+), 95 deletions(-) diff --git a/ci-gen/src/ghwf.rs b/ci-gen/src/ghwf.rs index 30dc1d517..cbcd1a506 100644 --- a/ci-gen/src/ghwf.rs +++ b/ci-gen/src/ghwf.rs @@ -3,8 +3,7 @@ use std::fmt; use crate::yaml::Yaml; #[allow(dead_code)] -#[derive(Copy, Clone, Eq, PartialEq)] -#[derive(Default)] +#[derive(Copy, Clone, Eq, PartialEq, Default)] pub enum Env { WindowsLatest, #[default] @@ -12,7 +11,6 @@ pub enum Env { MacosLatest, } - impl fmt::Display for Env { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { diff --git a/ci-gen/src/yaml.rs b/ci-gen/src/yaml.rs index 1446a9da6..4002c5157 100644 --- a/ci-gen/src/yaml.rs +++ b/ci-gen/src/yaml.rs @@ -61,8 +61,7 @@ pub struct YamlWriter { minus: MinusState, } -#[derive(Eq, PartialEq)] -#[derive(Default)] +#[derive(Eq, PartialEq, Default)] enum MinusState { #[default] No, @@ -70,7 +69,6 @@ enum MinusState { Already, } - impl YamlWriter { pub fn write_line(&mut self, line: &str) { if line.is_empty() { diff --git a/protobuf-codegen/src/codegen/mod.rs b/protobuf-codegen/src/codegen/mod.rs index c1ee69464..eb9b3ac39 100644 --- a/protobuf-codegen/src/codegen/mod.rs +++ b/protobuf-codegen/src/codegen/mod.rs @@ -14,15 +14,13 @@ use crate::customize::CustomizeCallbackHolder; use crate::gen_and_write::gen_and_write; use crate::Customize; -#[derive(Debug)] -#[derive(Default)] +#[derive(Debug, Default)] enum WhichParser { #[default] Pure, Protoc, } - #[derive(Debug, thiserror::Error)] enum CodegenError { #[error("out_dir is not specified")] diff --git a/protobuf-codegen/src/gen/all.rs b/protobuf-codegen/src/gen/all.rs index b9738c8ec..28720add3 100644 --- a/protobuf-codegen/src/gen/all.rs +++ b/protobuf-codegen/src/gen/all.rs @@ -42,9 +42,13 @@ pub(crate) fn gen_all( }; for file_name in files_to_generate { - let file = files_map.get(file_name.as_path()).unwrap_or_else(|| panic!("file not found in file descriptors: {:?}, files: {:?}", - file_name, - files_map.keys())); + let file = files_map.get(file_name.as_path()).unwrap_or_else(|| { + panic!( + "file not found in file descriptors: {:?}, files: {:?}", + file_name, + files_map.keys() + ) + }); let gen_file_result = gen_file(file, &files_map, &root_scope, &customize, parser)?; results.push(gen_file_result.compiler_plugin_result); mods.push(gen_file_result.mod_name); diff --git a/protobuf-codegen/src/gen/code_writer.rs b/protobuf-codegen/src/gen/code_writer.rs index 05243ae7d..043bbc100 100644 --- a/protobuf-codegen/src/gen/code_writer.rs +++ b/protobuf-codegen/src/gen/code_writer.rs @@ -26,7 +26,8 @@ impl<'a> CodeWriter<'a> { Self::with_impl::(|w| { f(w); Ok(()) - }).unwrap_or_else(|e| match e {}) + }) + .unwrap_or_else(|e| match e {}) } pub(crate) fn with(f: F) -> anyhow::Result @@ -334,10 +335,7 @@ impl<'a> CodeWriter<'a> { .and_then(|ls| ls.iter().find(|l| l.path == path)) .map(|l| l.leading_comments()); - let lines = doc - .iter() - .flat_map(|doc| doc.lines()) - .collect::>(); + let lines = doc.iter().flat_map(|doc| doc.lines()).collect::>(); // Skip comments with code blocks to avoid rustdoc trying to compile them. if !lines.iter().any(|line| line.starts_with(" ")) { diff --git a/protobuf-codegen/src/gen/oneof.rs b/protobuf-codegen/src/gen/oneof.rs index 4de50579e..a96a2a0fa 100644 --- a/protobuf-codegen/src/gen/oneof.rs +++ b/protobuf-codegen/src/gen/oneof.rs @@ -205,7 +205,8 @@ impl<'a> OneofGen<'a> { let field = self .message .fields - .iter().find(|f| f.proto_field.name() == v.field.name()) + .iter() + .find(|f| f.proto_field.name() == v.field.name()) .unwrap_or_else(|| panic!("field not found by name: {}", v.field.name())); match field.proto_type { field_descriptor_proto::Type::TYPE_GROUP => None, diff --git a/protobuf-codegen/src/gen/scope.rs b/protobuf-codegen/src/gen/scope.rs index 1677bcde4..cc8e8177f 100644 --- a/protobuf-codegen/src/gen/scope.rs +++ b/protobuf-codegen/src/gen/scope.rs @@ -94,7 +94,8 @@ impl<'a> FileScope<'a> { name: &ProtobufRelPathRef, ) -> Option> { self.find_messages_and_enums() - .into_iter().find(|e| e.protobuf_name_to_package().as_ref() == name) + .into_iter() + .find(|e| e.protobuf_name_to_package().as_ref() == name) } fn find_message_or_enum_abs( @@ -206,11 +207,7 @@ impl<'a> Scope<'a> { self.messages() .into_iter() .map(MessageOrEnumWithScope::Message) - .chain( - self.enums() - .into_iter() - .map(MessageOrEnumWithScope::Enum), - ) + .chain(self.enums().into_iter().map(MessageOrEnumWithScope::Enum)) .collect() } @@ -481,9 +478,9 @@ impl<'a> FieldWithContext<'a> { pub fn oneof(&self) -> Option> { self.field.containing_oneof().map(|oneof| OneofWithContext { - message: self.message.clone(), - oneof, - }) + message: self.message.clone(), + oneof, + }) } } diff --git a/protobuf-json-mapping/src/rfc_3339.rs b/protobuf-json-mapping/src/rfc_3339.rs index a8507d726..eed2e3e83 100644 --- a/protobuf-json-mapping/src/rfc_3339.rs +++ b/protobuf-json-mapping/src/rfc_3339.rs @@ -12,7 +12,9 @@ fn is_leap_year(year: i64) -> bool { false } else if year % 100 != 0 { true - } else { year % 400 == 0 } + } else { + year % 400 == 0 + } } fn days_in_year(year: i64) -> u32 { diff --git a/protobuf-parse/src/pure/convert/option_resolver.rs b/protobuf-parse/src/pure/convert/option_resolver.rs index 4069bb03c..6e09a03c1 100644 --- a/protobuf-parse/src/pure/convert/option_resolver.rs +++ b/protobuf-parse/src/pure/convert/option_resolver.rs @@ -605,26 +605,28 @@ impl<'a> OptionResoler<'a> { TypeResolved::Bytes => return Ok(UnknownValue::LengthDelimited(s.decode_bytes()?)), _ => {} }, - model::ProtobufConstant::Ident(ident) => if let TypeResolved::Enum(e) = &field_type { - let e = self - .resolver - .find_enum_by_abs_name(e) - .map_err(OptionResolverError::OtherError)?; - let n = match e - .values - .iter() - .find(|v| v.name == format!("{}", ident)) - .map(|v| v.number) - { - Some(n) => n, - None => { - return Err( - OptionResolverError::UnknownEnumValue(ident.to_string()).into() - ) - } - }; - return Ok(UnknownValue::int32(n)); - }, + model::ProtobufConstant::Ident(ident) => { + if let TypeResolved::Enum(e) = &field_type { + let e = self + .resolver + .find_enum_by_abs_name(e) + .map_err(OptionResolverError::OtherError)?; + let n = match e + .values + .iter() + .find(|v| v.name == format!("{}", ident)) + .map(|v| v.number) + { + Some(n) => n, + None => { + return Err( + OptionResolverError::UnknownEnumValue(ident.to_string()).into() + ) + } + }; + return Ok(UnknownValue::int32(n)); + } + } model::ProtobufConstant::Message(mo) => { return self.option_value_message_to_unknown_value( field_type, @@ -651,8 +653,7 @@ impl<'a> OptionResoler<'a> { option_name_for_diag: &str, ) -> anyhow::Result { let field_type = self.resolver.field_type(scope, name, field_type)?; - self - .option_value_to_unknown_value(&field_type, value, option_name_for_diag) + self.option_value_to_unknown_value(&field_type, value, option_name_for_diag) .context("parsing custom option value") } @@ -666,7 +667,9 @@ impl<'a> OptionResoler<'a> { where M: MessageFull, { - if M::descriptor().full_name() == "google.protobuf.FieldOptions" && (option.get() == "default" || option.get() == "json_name") { + if M::descriptor().full_name() == "google.protobuf.FieldOptions" + && (option.get() == "default" || option.get() == "json_name") + { // some options are written to non-options message and handled outside return Ok(()); } diff --git a/protobuf-parse/src/pure/model.rs b/protobuf-parse/src/pure/model.rs index 179c80b5d..9fe5acdc9 100644 --- a/protobuf-parse/src/pure/model.rs +++ b/protobuf-parse/src/pure/model.rs @@ -45,16 +45,12 @@ impl Deref for WithLoc { impl WithLoc { pub fn with_loc(loc: Loc) -> impl FnOnce(T) -> WithLoc { - move |t| WithLoc { - t, - loc, - } + move |t| WithLoc { t, loc } } } /// Protobuf syntax. -#[derive(Debug, Clone, Copy, Eq, PartialEq)] -#[derive(Default)] +#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)] pub(crate) enum Syntax { /// Protobuf syntax [2](https://developers.google.com/protocol-buffers/docs/proto) (default) #[default] @@ -63,7 +59,6 @@ pub(crate) enum Syntax { Proto3, } - /// A field rule #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub(crate) enum Rule { @@ -525,8 +520,7 @@ pub(crate) struct ProtobufOption { } /// Visibility of import statement -#[derive(Debug, Clone, Eq, PartialEq)] -#[derive(Default)] +#[derive(Debug, Clone, Eq, PartialEq, Default)] pub(crate) enum ImportVis { #[default] Default, @@ -534,7 +528,6 @@ pub(crate) enum ImportVis { Weak, } - /// Import statement #[derive(Debug, Default, Clone)] pub(crate) struct Import { diff --git a/protobuf-parse/src/pure/parser.rs b/protobuf-parse/src/pure/parser.rs index 56652306c..02fe92789 100644 --- a/protobuf-parse/src/pure/parser.rs +++ b/protobuf-parse/src/pure/parser.rs @@ -1292,8 +1292,8 @@ mod test { P: FnOnce(&mut Parser) -> anyhow::Result, { let mut parser = Parser::new(input); - let r = - parse_what(&mut parser).unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); + let r = parse_what(&mut parser) + .unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); let eof = parser .tokenizer .syntax_eof() @@ -1307,10 +1307,9 @@ mod test { P: FnOnce(&mut Parser) -> anyhow::Result>, { let mut parser = Parser::new(input); - let o = - parse_what(&mut parser).unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); - let r = o.unwrap_or_else(|| panic!("parser returned none at {}", - parser.tokenizer.loc())); + let o = parse_what(&mut parser) + .unwrap_or_else(|_| panic!("parse failed at {}", parser.tokenizer.loc())); + let r = o.unwrap_or_else(|| panic!("parser returned none at {}", parser.tokenizer.loc())); assert!(parser.tokenizer.syntax_eof().unwrap()); r } diff --git a/protobuf-parse/src/which_parser.rs b/protobuf-parse/src/which_parser.rs index 09364c2df..cee9a2244 100644 --- a/protobuf-parse/src/which_parser.rs +++ b/protobuf-parse/src/which_parser.rs @@ -1,6 +1,5 @@ /// Which parse to use to parse `.proto` files. -#[derive(Debug, Copy, Clone)] -#[derive(Default)] +#[derive(Debug, Copy, Clone, Default)] pub(crate) enum WhichParser { /// Pure Rust parser implemented by this crate. #[default] @@ -8,4 +7,3 @@ pub(crate) enum WhichParser { /// Parse `.proto` files using `protoc --descriptor_set_out=...` command. Protoc, } - diff --git a/protobuf-support/src/lexer/tokenizer.rs b/protobuf-support/src/lexer/tokenizer.rs index 6c5be3a33..057bc9547 100644 --- a/protobuf-support/src/lexer/tokenizer.rs +++ b/protobuf-support/src/lexer/tokenizer.rs @@ -306,7 +306,8 @@ mod test { P: FnOnce(&mut Tokenizer) -> TokenizerResult, { let mut tokenizer = Tokenizer::new(input, ParserLanguage::Proto); - let r = what(&mut tokenizer).unwrap_or_else(|_| panic!("parse failed at {}", tokenizer.loc())); + let r = + what(&mut tokenizer).unwrap_or_else(|_| panic!("parse failed at {}", tokenizer.loc())); let eof = tokenizer .syntax_eof() .unwrap_or_else(|_| panic!("check eof failed at {}", tokenizer.loc())); diff --git a/protobuf/src/coded_input_stream/buf_read_iter.rs b/protobuf/src/coded_input_stream/buf_read_iter.rs index dda46615d..d8217dbc4 100644 --- a/protobuf/src/coded_input_stream/buf_read_iter.rs +++ b/protobuf/src/coded_input_stream/buf_read_iter.rs @@ -51,7 +51,9 @@ pub(crate) struct BufReadIter<'a> { impl<'a> Drop for BufReadIter<'a> { fn drop(&mut self) { - if let InputSource::Read(ref mut buf_read) = self.input_source { buf_read.consume(self.buf.pos_within_buf()) } + if let InputSource::Read(ref mut buf_read) = self.input_source { + buf_read.consume(self.buf.pos_within_buf()) + } } } diff --git a/protobuf/src/coded_input_stream/mod.rs b/protobuf/src/coded_input_stream/mod.rs index 9f5ab3539..6f9b67053 100644 --- a/protobuf/src/coded_input_stream/mod.rs +++ b/protobuf/src/coded_input_stream/mod.rs @@ -528,8 +528,7 @@ impl<'a> CodedInputStream<'a> { WireType::Fixed32 => self.read_fixed32().map(UnknownValue::Fixed32), WireType::LengthDelimited => { let len = self.read_raw_varint32()?; - self.read_raw_bytes(len) - .map(UnknownValue::LengthDelimited) + self.read_raw_bytes(len).map(UnknownValue::LengthDelimited) } WireType::StartGroup => { self.skip_group()?; diff --git a/protobuf/src/reflect/file/index.rs b/protobuf/src/reflect/file/index.rs index 41c1cb21b..590c50183 100644 --- a/protobuf/src/reflect/file/index.rs +++ b/protobuf/src/reflect/file/index.rs @@ -393,9 +393,11 @@ impl FileDescriptorCommon { return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); } - if field_index.json_name != f.name() && index_by_name_or_json_name + if field_index.json_name != f.name() + && index_by_name_or_json_name .insert(field_index.json_name.clone(), i) - .is_some() { + .is_some() + { return Err(ReflectError::NonUniqueFieldName(f.name().to_owned()).into()); } } diff --git a/protobuf/src/reflect/map/generated.rs b/protobuf/src/reflect/map/generated.rs index 71e05402d..e825016a1 100644 --- a/protobuf/src/reflect/map/generated.rs +++ b/protobuf/src/reflect/map/generated.rs @@ -108,7 +108,9 @@ impl<'a, K: ProtobufValue, V: ProtobufValue, I: Iterator> ReflectMapIterTrait<'a> for GeneratedMapIterImpl<'a, K, V, I> { fn next(&mut self) -> Option<(ReflectValueRef<'a>, ReflectValueRef<'a>)> { - self.iter.next().map(|(k, v)| (K::RuntimeType::as_ref(k), V::RuntimeType::as_ref(v))) + self.iter + .next() + .map(|(k, v)| (K::RuntimeType::as_ref(k), V::RuntimeType::as_ref(v))) } fn _key_type(&self) -> RuntimeType { diff --git a/protobuf/src/unknown.rs b/protobuf/src/unknown.rs index 3f9d0980b..545fc5075 100644 --- a/protobuf/src/unknown.rs +++ b/protobuf/src/unknown.rs @@ -167,7 +167,11 @@ impl UnknownValues { Some(UnknownValueRef::Fixed64(*last)) } else if let Some(last) = self.varint.last() { Some(UnknownValueRef::Varint(*last)) - } else { self.length_delimited.last().map(|last| UnknownValueRef::LengthDelimited(last)) } + } else { + self.length_delimited + .last() + .map(|last| UnknownValueRef::LengthDelimited(last)) + } } } diff --git a/test-crates/perftest/vs-cxx/perftest.rs b/test-crates/perftest/vs-cxx/perftest.rs index a463533b3..359f79ecc 100644 --- a/test-crates/perftest/vs-cxx/perftest.rs +++ b/test-crates/perftest/vs-cxx/perftest.rs @@ -110,10 +110,7 @@ fn main() { if args.len() > 3 { panic!("usage: {} [data_size] [test]", args[0]) } - let data_size = args - .get(1) - .map(|x| x.parse().unwrap()) - .unwrap_or(1000000); + let data_size = args.get(1).map(|x| x.parse().unwrap()).unwrap_or(1000000); let selected = args.get(2).cloned(); let mut runner = TestRunner { diff --git a/test-crates/protobuf-codegen-identical-test/tests/diff.rs b/test-crates/protobuf-codegen-identical-test/tests/diff.rs index 8946fa4da..b148e1020 100644 --- a/test-crates/protobuf-codegen-identical-test/tests/diff.rs +++ b/test-crates/protobuf-codegen-identical-test/tests/diff.rs @@ -329,8 +329,8 @@ where normalize_generated_file_in_place(Path::new(&protoc_rs)); normalize_generated_file_in_place(Path::new(&pure_rs)); - let protoc_rs_contents = - fs::read_to_string(&protoc_rs).unwrap_or_else(|_| panic!("while reading {}", protoc_rs)); + let protoc_rs_contents = fs::read_to_string(&protoc_rs) + .unwrap_or_else(|_| panic!("while reading {}", protoc_rs)); let pure_rs_contents = fs::read_to_string(&pure_rs).unwrap_or_else(|_| panic!("while reading {}", pure_rs)); diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs index 85053f8a5..be6592438 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_oneof_nonexhaustive.rs @@ -1,4 +1,3 @@ - use super::test_oneof_nonexhaustive_pb::*; #[test] diff --git a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs index bb5172ed5..e2e733f4d 100644 --- a/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs +++ b/test-crates/protobuf-codegen-protoc-test/src/common/v2/test_reflect_basic.rs @@ -46,12 +46,10 @@ fn test_singular_basic() { bool_field.set_singular_field(&mut message, ReflectValueBox::Bool(true)); assert!(bool_field.has_field(&message)); - assert!( - bool_field - .get_singular_field_or_default(&message) - .to_bool() - .unwrap() - ); + assert!(bool_field + .get_singular_field_or_default(&message) + .to_bool() + .unwrap()); } fn test_singular_field(message: &mut dyn MessageDyn, field: &FieldDescriptor) { diff --git a/test-crates/protobuf-test-common/src/build.rs b/test-crates/protobuf-test-common/src/build.rs index 70c622cd4..682b88a1a 100644 --- a/test-crates/protobuf-test-common/src/build.rs +++ b/test-crates/protobuf-test-common/src/build.rs @@ -77,7 +77,8 @@ fn clean_recursively(dir: &Path, patterns: &[&str]) { } else { for pattern in &patterns_compiled { if pattern.matches(file_name) { - fs::remove_file(&entry_path).unwrap_or_else(|_| panic!("remove_file {:?}", entry_path)); + fs::remove_file(&entry_path) + .unwrap_or_else(|_| panic!("remove_file {:?}", entry_path)); break; } } @@ -160,7 +161,8 @@ fn test_version_from_file_path(mut file_path: &Path) -> TestProtobufVersions { } fn test_version_from_file_content(file_path: &Path) -> ProtobufSyntax { - let content = fs::read_to_string(file_path).unwrap_or_else(|_| panic!("read_to_string {:?}", file_path)); + let content = + fs::read_to_string(file_path).unwrap_or_else(|_| panic!("read_to_string {:?}", file_path)); if content.contains("syntax = \"proto2\"") { ProtobufSyntax::V2 } else if content.contains("syntax = \"proto3\"") { diff --git a/test-crates/protobuf-test-common/src/json_tests.rs b/test-crates/protobuf-test-common/src/json_tests.rs index d6798813a..f71716d6c 100644 --- a/test-crates/protobuf-test-common/src/json_tests.rs +++ b/test-crates/protobuf-test-common/src/json_tests.rs @@ -31,8 +31,8 @@ pub fn test_json_message(m: &dyn MessageDyn) { let s = protobuf_json_mapping::print_to_string(m).expect("print_to_string"); let mut new = descriptor.new_instance(); - protobuf_json_mapping::merge_from_str(&mut *new, &s).unwrap_or_else(|_| panic!("failed to parse serialized: {}; from message: {:?}", - s, m)); + protobuf_json_mapping::merge_from_str(&mut *new, &s) + .unwrap_or_else(|_| panic!("failed to parse serialized: {}; from message: {:?}", s, m)); assert!( m.reflect_eq_dyn(&*new, &ReflectEqMode::nan_equal()), "{:?} should be == {:?}",