From 2c85f72765c95628812fb1458f920a67b7ae15fe Mon Sep 17 00:00:00 2001 From: Protobuf Team Bot Date: Mon, 16 Dec 2024 14:31:47 -0800 Subject: [PATCH] Make generated enums derive(Hash) to allow them to be used in collections like HashSet or as keys in HashMaps. PiperOrigin-RevId: 706837705 --- rust/test/shared/enum_test.rs | 12 ++++++++++++ src/google/protobuf/compiler/rust/enum.cc | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/rust/test/shared/enum_test.rs b/rust/test/shared/enum_test.rs index 383c2608b259d..706bad0f133ef 100644 --- a/rust/test/shared/enum_test.rs +++ b/rust/test/shared/enum_test.rs @@ -208,3 +208,15 @@ fn test_debug_string() { eq("TestEnumWithNumericNames::from(42)") ); } + +#[gtest] +fn test_enum_in_hash_set() { + use test_all_types::NestedEnum; + let mut s = std::collections::HashSet::::new(); + s.insert(NestedEnum::Foo); + s.insert(NestedEnum::Bar); + s.insert(NestedEnum::try_from(1).unwrap()); // FOO = 1 + assert_that!(s.len(), eq(2)); + assert_that!(s.contains(&NestedEnum::Bar), eq(true)); + assert_that!(s.contains(&NestedEnum::Baz), eq(false)); +} diff --git a/src/google/protobuf/compiler/rust/enum.cc b/src/google/protobuf/compiler/rust/enum.cc index fc51f2d3d5160..a069e130bdf8a 100644 --- a/src/google/protobuf/compiler/rust/enum.cc +++ b/src/google/protobuf/compiler/rust/enum.cc @@ -224,7 +224,7 @@ void GenerateEnumDefinition(Context& ctx, const EnumDescriptor& desc) { }, R"rs( #[repr(transparent)] - #[derive(Clone, Copy, PartialEq, Eq)] + #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct $name$(i32); #[allow(non_upper_case_globals)]