xref: /aosp_15_r20/external/grpc-grpc/third_party/upb/upb/message/internal/message.c (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 Google LLC.  All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7 
8 #include "upb/message/internal/message.h"
9 
10 #include <math.h>
11 #include <string.h>
12 
13 #include "upb/base/internal/log2.h"
14 #include "upb/mem/arena.h"
15 #include "upb/message/internal/types.h"
16 
17 // Must be last.
18 #include "upb/port/def.inc"
19 
20 const float kUpb_FltInfinity = INFINITY;
21 const double kUpb_Infinity = INFINITY;
22 const double kUpb_NaN = NAN;
23 
UPB_PRIVATE(_upb_Message_Realloc)24 bool UPB_PRIVATE(_upb_Message_Realloc)(struct upb_Message* msg, size_t need,
25                                        upb_Arena* a) {
26   const size_t overhead = sizeof(upb_Message_Internal);
27 
28   upb_Message_Internal* in = msg->internal;
29   if (!in) {
30     // No internal data, allocate from scratch.
31     size_t size = UPB_MAX(128, upb_Log2CeilingSize(need + overhead));
32     in = upb_Arena_Malloc(a, size);
33     if (!in) return false;
34 
35     in->size = size;
36     in->unknown_end = overhead;
37     in->ext_begin = size;
38     msg->internal = in;
39   } else if (in->ext_begin - in->unknown_end < need) {
40     // Internal data is too small, reallocate.
41     size_t new_size = upb_Log2CeilingSize(in->size + need);
42     size_t ext_bytes = in->size - in->ext_begin;
43     size_t new_ext_begin = new_size - ext_bytes;
44     in = upb_Arena_Realloc(a, in, in->size, new_size);
45     if (!in) return false;
46 
47     if (ext_bytes) {
48       // Need to move extension data to the end.
49       char* ptr = (char*)in;
50       memmove(ptr + new_ext_begin, ptr + in->ext_begin, ext_bytes);
51     }
52     in->ext_begin = new_ext_begin;
53     in->size = new_size;
54     msg->internal = in;
55   }
56 
57   UPB_ASSERT(in->ext_begin - in->unknown_end >= need);
58   return true;
59 }
60