Blender V4.3
BLI_allocator.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2023 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4#pragma once
5
28#include <algorithm>
29#include <cstdlib>
30
31#include "MEM_guardedalloc.h"
32
33#include "BLI_utildefines.h"
34
35namespace blender {
36
42 public:
43 void *allocate(size_t size, size_t alignment, const char *name)
44 {
45 /* Should we use MEM_mallocN, when alignment is small? If yes, how small must alignment be? */
46 return MEM_mallocN_aligned(size, alignment, name);
47 }
48
49 void deallocate(void *ptr)
50 {
52 }
53};
54
60template<size_t Alignment = 64ul> class GuardedAlignedAllocator {
61 public:
62 static constexpr size_t min_alignment = Alignment;
63
64 void *allocate(size_t size, size_t alignment, const char *name)
65 {
66 return MEM_mallocN_aligned(size, std::max(alignment, min_alignment), name);
67 }
68
69 void deallocate(void *ptr)
70 {
72 }
73};
74
81 private:
82 struct MemHead {
83 int offset;
84 };
85
86 public:
87 void *allocate(size_t size, size_t alignment, const char * /*name*/)
88 {
89 BLI_assert(is_power_of_2(int(alignment)));
90 void *ptr = malloc(size + alignment + sizeof(MemHead));
91 void *used_ptr = reinterpret_cast<void *>(
92 uintptr_t(POINTER_OFFSET(ptr, alignment + sizeof(MemHead))) & ~(uintptr_t(alignment) - 1));
93 int offset = int(intptr_t(used_ptr) - intptr_t(ptr));
94 BLI_assert(offset >= int(sizeof(MemHead)));
95 (static_cast<MemHead *>(used_ptr) - 1)->offset = offset;
96 return used_ptr;
97 }
98
99 void deallocate(void *ptr)
100 {
101 MemHead *head = static_cast<MemHead *>(ptr) - 1;
102 int offset = -head->offset;
103 void *actual_pointer = POINTER_OFFSET(ptr, offset);
104 free(actual_pointer);
105 }
106};
107
108} // namespace blender
#define BLI_assert(a)
Definition BLI_assert.h:50
void BLI_kdtree_nd_ free(KDTree *tree)
#define POINTER_OFFSET(v, ofs)
Read Guarded memory(de)allocation.
static constexpr size_t min_alignment
void * allocate(size_t size, size_t alignment, const char *name)
void * allocate(size_t size, size_t alignment, const char *name)
void deallocate(void *ptr)
void * allocate(size_t size, size_t alignment, const char *)
draw_view push_constant(Type::INT, "radiance_src") .push_constant(Type capture_info_buf storage_buf(1, Qualifier::READ, "ObjectBounds", "bounds_buf[]") .push_constant(Type draw_view int
void * MEM_mallocN_aligned(size_t len, size_t alignment, const char *str)
Definition mallocn.cc:110
void MEM_freeN(void *vmemh)
Definition mallocn.cc:105
_W64 unsigned int uintptr_t
Definition stdint.h:119
_W64 int intptr_t
Definition stdint.h:118
PointerRNA * ptr
Definition wm_files.cc:4126