diff options
| author | Mattias Andrée <maandree@kth.se> | 2016-03-05 22:27:04 +0100 |
|---|---|---|
| committer | Mattias Andrée <maandree@kth.se> | 2016-03-05 22:28:33 +0100 |
| commit | c1f4d263ec1004512cdd6b38b351eb2fe2321c22 (patch) | |
| tree | ff884393424694c79eb87d16f13b151ba0233ec7 /src/allocator.c | |
| parent | zinit is now an inline function (diff) | |
| download | libzahl-c1f4d263ec1004512cdd6b38b351eb2fe2321c22.tar.gz libzahl-c1f4d263ec1004512cdd6b38b351eb2fe2321c22.tar.bz2 libzahl-c1f4d263ec1004512cdd6b38b351eb2fe2321c22.tar.xz | |
Add memory pool, also let the user know that libzahl is not designed for cryptography
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'src/allocator.c')
| -rw-r--r-- | src/allocator.c | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/allocator.c b/src/allocator.c new file mode 100644 index 0000000..46cca89 --- /dev/null +++ b/src/allocator.c @@ -0,0 +1,41 @@ +/* See LICENSE file for copyright and license details. */ +#include "internals.h" + +#include <stdint.h> + + +void +libzahl_realloc(z_t a, size_t need) +{ + size_t i, x; + zahl_char_t *new; + + /* Find n such that n is a minimal power of 2 ≥ need. */ + if ((need & (~need + 1)) != need) { + need |= need >> 1; + need |= need >> 2; + need |= need >> 4; + for (i = sizeof(need), x = 8; i; i >>= 1, x <<= 1) + need |= need >> x; + need += 1; + } + + for (i = 0, x = need; x; x >>= 1) + i += 1; + + if (libzahl_pool_n[i]) { + libzahl_pool_n[i]--; + new = libzahl_pool[i][libzahl_pool_n[i]]; + zmemcpy(new, a->chars, a->alloced); + zfree(a); + a->chars = new; + } else { + a->chars = realloc(a->chars, need * sizeof(zahl_char_t)); + if (!a->chars) { + if (!errno) /* sigh... */ + errno = ENOMEM; + FAILURE(errno); + } + } + a->alloced = need; +} |
