xref: /netbsd-src/external/bsd/zstd/dist/lib/common/allocations.h (revision 3117ece4fc4a4ca4489ba793710b60b0d26bab6c)
1*3117ece4Schristos /*
2*3117ece4Schristos  * Copyright (c) Meta Platforms, Inc. and affiliates.
3*3117ece4Schristos  * All rights reserved.
4*3117ece4Schristos  *
5*3117ece4Schristos  * This source code is licensed under both the BSD-style license (found in the
6*3117ece4Schristos  * LICENSE file in the root directory of this source tree) and the GPLv2 (found
7*3117ece4Schristos  * in the COPYING file in the root directory of this source tree).
8*3117ece4Schristos  * You may select, at your option, one of the above-listed licenses.
9*3117ece4Schristos  */
10*3117ece4Schristos 
11*3117ece4Schristos /* This file provides custom allocation primitives
12*3117ece4Schristos  */
13*3117ece4Schristos 
14*3117ece4Schristos #define ZSTD_DEPS_NEED_MALLOC
15*3117ece4Schristos #include "zstd_deps.h"   /* ZSTD_malloc, ZSTD_calloc, ZSTD_free, ZSTD_memset */
16*3117ece4Schristos 
17*3117ece4Schristos #include "compiler.h" /* MEM_STATIC */
18*3117ece4Schristos #define ZSTD_STATIC_LINKING_ONLY
19*3117ece4Schristos #include "../zstd.h" /* ZSTD_customMem */
20*3117ece4Schristos 
21*3117ece4Schristos #ifndef ZSTD_ALLOCATIONS_H
22*3117ece4Schristos #define ZSTD_ALLOCATIONS_H
23*3117ece4Schristos 
24*3117ece4Schristos /* custom memory allocation functions */
25*3117ece4Schristos 
26*3117ece4Schristos MEM_STATIC void* ZSTD_customMalloc(size_t size, ZSTD_customMem customMem)
27*3117ece4Schristos {
28*3117ece4Schristos     if (customMem.customAlloc)
29*3117ece4Schristos         return customMem.customAlloc(customMem.opaque, size);
30*3117ece4Schristos     return ZSTD_malloc(size);
31*3117ece4Schristos }
32*3117ece4Schristos 
33*3117ece4Schristos MEM_STATIC void* ZSTD_customCalloc(size_t size, ZSTD_customMem customMem)
34*3117ece4Schristos {
35*3117ece4Schristos     if (customMem.customAlloc) {
36*3117ece4Schristos         /* calloc implemented as malloc+memset;
37*3117ece4Schristos          * not as efficient as calloc, but next best guess for custom malloc */
38*3117ece4Schristos         void* const ptr = customMem.customAlloc(customMem.opaque, size);
39*3117ece4Schristos         ZSTD_memset(ptr, 0, size);
40*3117ece4Schristos         return ptr;
41*3117ece4Schristos     }
42*3117ece4Schristos     return ZSTD_calloc(1, size);
43*3117ece4Schristos }
44*3117ece4Schristos 
45*3117ece4Schristos MEM_STATIC void ZSTD_customFree(void* ptr, ZSTD_customMem customMem)
46*3117ece4Schristos {
47*3117ece4Schristos     if (ptr!=NULL) {
48*3117ece4Schristos         if (customMem.customFree)
49*3117ece4Schristos             customMem.customFree(customMem.opaque, ptr);
50*3117ece4Schristos         else
51*3117ece4Schristos             ZSTD_free(ptr);
52*3117ece4Schristos     }
53*3117ece4Schristos }
54*3117ece4Schristos 
55*3117ece4Schristos #endif /* ZSTD_ALLOCATIONS_H */
56