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