xref: /aosp_15_r20/external/grpc-grpc/third_party/upb/upb/base/internal/log2.h (revision cc02d7e222339f7a4f6ba5f422e6413f4bd931f2)
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2023 Google LLC.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 ///
5 // Use of this source code is governed by a BSD-style
6 // license that can be found in the LICENSE file or at
7 // https://developers.google.com/open-source/licenses/bsd
8 
9 #ifndef UPB_BASE_INTERNAL_LOG2_H_
10 #define UPB_BASE_INTERNAL_LOG2_H_
11 
12 // Must be last.
13 #include "upb/port/def.inc"
14 
15 #ifdef __cplusplus
16 extern "C" {
17 #endif
18 
upb_Log2Ceiling(int x)19 UPB_INLINE int upb_Log2Ceiling(int x) {
20   if (x <= 1) return 0;
21 #ifdef __GNUC__
22   return 32 - __builtin_clz(x - 1);
23 #else
24   int lg2 = 0;
25   while ((1 << lg2) < x) lg2++;
26   return lg2;
27 #endif
28 }
29 
upb_Log2CeilingSize(int x)30 UPB_INLINE int upb_Log2CeilingSize(int x) { return 1 << upb_Log2Ceiling(x); }
31 
32 #ifdef __cplusplus
33 } /* extern "C" */
34 #endif
35 
36 #include "upb/port/undef.inc"
37 
38 #endif /* UPB_BASE_INTERNAL_LOG2_H_ */
39