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