allocations.h 1.6 KB

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