20#include <winpr/config.h>
23#include <winpr/assert.h>
25#include <winpr/collections.h>
46static void ObjectPool_Lock(wObjectPool* pool)
49 if (pool->synchronized)
50 EnterCriticalSection(&pool->lock);
53static void ObjectPool_Unlock(wObjectPool* pool)
56 if (pool->synchronized)
57 LeaveCriticalSection(&pool->lock);
64void* ObjectPool_Take(wObjectPool* pool)
68 ObjectPool_Lock(pool);
71 obj = pool->array[--(pool->size)];
75 if (pool->object.fnObjectNew)
79 if (pool->object.fnObjectInit)
80 pool->object.fnObjectInit(obj);
82 ObjectPool_Unlock(pool);
87static BOOL ObjectPool_EnsureCapacity(wObjectPool* pool,
size_t add)
89 WINPR_ASSERT(pool->size < SIZE_MAX - add);
91 const size_t blocksize = 128ull;
92 const size_t required = pool->size + add;
93 if (required >= pool->capacity)
95 const size_t new_cap = required + blocksize - required % blocksize;
97 void** new_arr = (
void**)realloc((
void*)pool->array,
sizeof(
void*) * new_cap);
101 pool->array = new_arr;
102 pool->capacity = new_cap;
111void ObjectPool_Return(wObjectPool* pool,
void* obj)
113 ObjectPool_Lock(pool);
115 if (!ObjectPool_EnsureCapacity(pool, 1))
118 pool->array[(pool->size)++] = obj;
120 if (pool->object.fnObjectUninit)
121 pool->object.fnObjectUninit(obj);
124 ObjectPool_Unlock(pool);
127wObject* ObjectPool_Object(wObjectPool* pool)
130 return &pool->object;
137void ObjectPool_Clear(wObjectPool* pool)
139 ObjectPool_Lock(pool);
141 while (pool->size > 0)
145 if (pool->object.fnObjectFree)
146 pool->object.fnObjectFree(pool->array[pool->size]);
149 ObjectPool_Unlock(pool);
156wObjectPool* ObjectPool_New(BOOL
synchronized)
158 wObjectPool* pool = (wObjectPool*)calloc(1,
sizeof(wObjectPool));
163 pool->synchronized =
synchronized;
165 if (pool->synchronized)
167 if (!InitializeCriticalSectionAndSpinCount(&pool->lock, 4000))
171 if (!ObjectPool_EnsureCapacity(pool, 32))
177 ObjectPool_Free(pool);
181void ObjectPool_Free(wObjectPool* pool)
186 ObjectPool_Clear(pool);
188 if (pool->synchronized)
189 DeleteCriticalSection(&pool->lock);
191 free((
void*)pool->array);
This struct contains function pointer to initialize/free objects.
OBJECT_NEW_FN fnObjectNew