xref: /aosp_15_r20/external/grpc-grpc/third_party/upb/upb/mini_table/internal/enum.h (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 #ifndef UPB_MINI_TABLE_INTERNAL_ENUM_H_
9 #define UPB_MINI_TABLE_INTERNAL_ENUM_H_
10 
11 #include <stdint.h>
12 
13 // Must be last.
14 #include "upb/port/def.inc"
15 
16 struct upb_MiniTableEnum {
17   uint32_t UPB_PRIVATE(mask_limit);   // Highest that can be tested with mask.
18   uint32_t UPB_PRIVATE(value_count);  // Number of values after the bitfield.
19   uint32_t UPB_PRIVATE(data)[];       // Bitmask + enumerated values follow.
20 };
21 
22 #ifdef __cplusplus
23 extern "C" {
24 #endif
25 
UPB_PRIVATE(_upb_MiniTableEnum_CheckValue)26 UPB_INLINE bool UPB_PRIVATE(_upb_MiniTableEnum_CheckValue)(
27     const struct upb_MiniTableEnum* e, uint32_t val) {
28   if (UPB_LIKELY(val < 64)) {
29     const uint64_t mask =
30         e->UPB_PRIVATE(data)[0] | ((uint64_t)e->UPB_PRIVATE(data)[1] << 32);
31     const uint64_t bit = 1ULL << val;
32     return (mask & bit) != 0;
33   }
34   if (UPB_LIKELY(val < e->UPB_PRIVATE(mask_limit))) {
35     const uint32_t mask = e->UPB_PRIVATE(data)[val / 32];
36     const uint32_t bit = 1ULL << (val % 32);
37     return (mask & bit) != 0;
38   }
39 
40   // OPT: binary search long lists?
41   const uint32_t* start =
42       &e->UPB_PRIVATE(data)[e->UPB_PRIVATE(mask_limit) / 32];
43   const uint32_t* limit = &e->UPB_PRIVATE(
44       data)[e->UPB_PRIVATE(mask_limit) / 32 + e->UPB_PRIVATE(value_count)];
45   for (const uint32_t* p = start; p < limit; p++) {
46     if (*p == val) return true;
47   }
48   return false;
49 }
50 
51 #ifdef __cplusplus
52 } /* extern "C" */
53 #endif
54 
55 #include "upb/port/undef.inc"
56 
57 #endif /* UPB_MINI_TABLE_INTERNAL_ENUM_H_ */
58