Skip to content

Commit

Permalink
Promote extensions in place of the unknown field they were promoted from
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 708100356
  • Loading branch information
protobuf-github-bot authored and copybara-github committed Dec 20, 2024
1 parent e890d15 commit a673dcc
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
12 changes: 12 additions & 0 deletions upb/message/internal/extension.c
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,15 @@ upb_Extension* UPB_PRIVATE(_upb_Message_GetOrCreateExtension)(
in->aux_data[in->size++] = upb_TaggedAuxPtr_MakeExtension(ext);
return ext;
}

void upb_Message_ReplaceUnknownWithExtension(struct upb_Message* msg,
uintptr_t iter,
const upb_Extension* ext) {
UPB_ASSERT(iter != 0);
upb_Message_Internal* in = UPB_PRIVATE(_upb_Message_GetInternal)(msg);
UPB_ASSERT(in);
size_t index = iter - 1;
upb_TaggedAuxPtr tagged_ptr = in->aux_data[index];
UPB_ASSERT(upb_TaggedAuxPtr_IsUnknown(tagged_ptr));
in->aux_data[index] = upb_TaggedAuxPtr_MakeExtension(ext);
}
4 changes: 4 additions & 0 deletions upb/message/internal/extension.h
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ UPB_INLINE bool UPB_PRIVATE(_upb_Extension_IsEmpty)(const upb_Extension* ext) {
UPB_UNREACHABLE();
}

// Replaces the unknown field at iter with the provided extension.
void upb_Message_ReplaceUnknownWithExtension(struct upb_Message* msg,
uintptr_t iter,
const upb_Extension* ext);
#ifdef __cplusplus
} /* extern "C" */
#endif
Expand Down
9 changes: 3 additions & 6 deletions upb/message/promote.c
Original file line number Diff line number Diff line change
Expand Up @@ -101,17 +101,14 @@ upb_GetExtension_Status upb_Message_GetOrPromoteExtension(
}
upb_Message* extension_msg = parse_result.message;
// Add to extensions.
upb_Extension* ext =
UPB_PRIVATE(_upb_Message_GetOrCreateExtension)(msg, ext_table, arena);
upb_Extension* ext = upb_Arena_Malloc(arena, sizeof(upb_Extension));
if (!ext) {
return kUpb_GetExtension_OutOfMemory;
}
ext->ext = ext_table;
ext->data.msg_val = extension_msg;
upb_Message_ReplaceUnknownWithExtension(msg, result.iter, ext);
value->msg_val = extension_msg;
// Our storage may have been reallocated by adding the extension, but our
// iterators are stable.
upb_StringView data = upb_StringView_FromDataAndSize(result.ptr, result.len);
upb_Message_DeleteUnknown(msg, &data, &result.iter);
return kUpb_GetExtension_Ok;
}

Expand Down

0 comments on commit a673dcc

Please sign in to comment.