Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-03-13 09:28:29

0001 // Protocol Buffers - Google's data interchange format
0002 // Copyright 2023 Google LLC.  All rights reserved.
0003 //
0004 // Use of this source code is governed by a BSD-style
0005 // license that can be found in the LICENSE file or at
0006 // https://developers.google.com/open-source/licenses/bsd
0007 
0008 #ifndef UPB_MEM_ALLOC_H_
0009 #define UPB_MEM_ALLOC_H_
0010 
0011 // Must be last.
0012 #include "upb/port/def.inc"
0013 
0014 #ifdef __cplusplus
0015 extern "C" {
0016 #endif
0017 
0018 typedef struct upb_alloc upb_alloc;
0019 
0020 /* A combined `malloc()`/`free()` function.
0021  * If `size` is 0 then the function acts like `free()`, otherwise it acts like
0022  * `realloc()`.  Only `oldsize` bytes from a previous allocation are
0023  * preserved. */
0024 typedef void* upb_alloc_func(upb_alloc* alloc, void* ptr, size_t oldsize,
0025                              size_t size);
0026 
0027 /* A upb_alloc is a possibly-stateful allocator object.
0028  *
0029  * It could either be an arena allocator (which doesn't require individual
0030  * `free()` calls) or a regular `malloc()` (which does).  The client must
0031  * therefore free memory unless it knows that the allocator is an arena
0032  * allocator. */
0033 struct upb_alloc {
0034   upb_alloc_func* func;
0035 };
0036 
0037 UPB_INLINE void* upb_malloc(upb_alloc* alloc, size_t size) {
0038   UPB_ASSERT(alloc);
0039   return alloc->func(alloc, NULL, 0, size);
0040 }
0041 
0042 UPB_INLINE void* upb_realloc(upb_alloc* alloc, void* ptr, size_t oldsize,
0043                              size_t size) {
0044   UPB_ASSERT(alloc);
0045   return alloc->func(alloc, ptr, oldsize, size);
0046 }
0047 
0048 UPB_INLINE void upb_free(upb_alloc* alloc, void* ptr) {
0049   UPB_ASSERT(alloc);
0050   alloc->func(alloc, ptr, 0, 0);
0051 }
0052 
0053 // The global allocator used by upb. Uses the standard malloc()/free().
0054 
0055 extern upb_alloc upb_alloc_global;
0056 
0057 /* Functions that hard-code the global malloc.
0058  *
0059  * We still get benefit because we can put custom logic into our global
0060  * allocator, like injecting out-of-memory faults in debug/testing builds. */
0061 
0062 UPB_INLINE void* upb_gmalloc(size_t size) {
0063   return upb_malloc(&upb_alloc_global, size);
0064 }
0065 
0066 UPB_INLINE void* upb_grealloc(void* ptr, size_t oldsize, size_t size) {
0067   return upb_realloc(&upb_alloc_global, ptr, oldsize, size);
0068 }
0069 
0070 UPB_INLINE void upb_gfree(void* ptr) { upb_free(&upb_alloc_global, ptr); }
0071 
0072 #ifdef __cplusplus
0073 } /* extern "C" */
0074 #endif
0075 
0076 #include "upb/port/undef.inc"
0077 
0078 #endif /* UPB_MEM_ALLOC_H_ */