Skip to content

Commit

Permalink
Make generated enums derive(Hash) to allow them to be used in collect…
Browse files Browse the repository at this point in the history
…ions like HashSet or as keys in HashMaps.

PiperOrigin-RevId: 706837705
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Dec 16, 2024
1 parent 547938c commit 2c85f72
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions rust/test/shared/enum_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<NestedEnum>::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));
}
2 changes: 1 addition & 1 deletion src/google/protobuf/compiler/rust/enum.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down

0 comments on commit 2c85f72

Please sign in to comment.