Skip to content

Commit

Permalink
Add upb_Message_ClearOneOf
Browse files Browse the repository at this point in the history
upb users currently need to manually fetch a oneof field in order to clear it.
In this CL, we add a convenience method to do that in one fell swoop.

PiperOrigin-RevId: 627796728
  • Loading branch information
honglooker authored and Copybara-Service committed Apr 25, 2024
1 parent 62f2b14 commit ab8f2de
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
14 changes: 14 additions & 0 deletions upb/message/accessors.h
Expand Up @@ -74,6 +74,20 @@ UPB_API_INLINE uint32_t upb_Message_WhichOneofFieldNumber(
return UPB_PRIVATE(_upb_Message_GetOneofCase)(message, oneof_field);
}

UPB_API_INLINE void upb_Message_ClearOneof(upb_Message* msg,
const upb_MiniTable* m,
const upb_MiniTableField* f) {
uint32_t field_number = upb_Message_WhichOneofFieldNumber(msg, f);
if (field_number == 0) {
// if the field_number is zero, the field is not set
return;
}

const upb_MiniTableField* field =
upb_MiniTable_FindFieldByNumber(m, field_number);
upb_Message_ClearBaseField(msg, field);
}

// NOTE: The default_val is only used for fields that support presence.
// For repeated/map fields, the resulting upb_Array*/upb_Map* can be NULL if a
// upb_Array/upb_Map has not been allocated yet. Array/map fields do not have
Expand Down
17 changes: 17 additions & 0 deletions upb/message/accessors_test.cc
Expand Up @@ -477,5 +477,22 @@ TEST(GeneratedCode, EnumClosedCheck) {
EXPECT_TRUE(upb_MiniTableField_IsClosedEnum(closedEnumField));
upb_Arena_Free(arena);
}
TEST(GeneratedCode, OneofClear) {
upb_Arena* arena = upb_Arena_New();

protobuf_test_messages_proto2_TestAllTypesProto2* msg =
protobuf_test_messages_proto2_TestAllTypesProto2_new(arena);

const upb_MiniTable* x =
&protobuf_0test_0messages__proto2__TestAllTypesProto2_msg_init;

const upb_MiniTableField* oneofField =
upb_MiniTable_FindFieldByNumber(x, 111);
EXPECT_TRUE(upb_MiniTableField_IsInOneof(oneofField));
upb_Message_ClearOneof((upb_Message*)msg, x, oneofField);
EXPECT_FALSE(UPB_PRIVATE(_upb_MiniTableField_HasHasbit)(oneofField));

upb_Arena_Free(arena);
}

} // namespace

0 comments on commit ab8f2de

Please sign in to comment.