zstd_common.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of https://github.com/facebook/zstd.
  7. * An additional grant of patent rights can be found in the PATENTS file in the
  8. * same directory.
  9. *
  10. * This program is free software; you can redistribute it and/or modify it under
  11. * the terms of the GNU General Public License version 2 as published by the
  12. * Free Software Foundation. This program is dual-licensed; you may select
  13. * either version 2 of the GNU General Public License ("GPL") or BSD license
  14. * ("BSD").
  15. */
  16. /*-*************************************
  17. * Dependencies
  18. ***************************************/
  19. #include "error_private.h"
  20. #include "zstd_internal.h" /* declaration of ZSTD_isError, ZSTD_getErrorName, ZSTD_getErrorCode, ZSTD_getErrorString, ZSTD_versionNumber */
  21. #include <linux/kernel.h>
  22. /*=**************************************************************
  23. * Custom allocator
  24. ****************************************************************/
  25. #define stack_push(stack, size) \
  26. ({ \
  27. void *const ptr = ZSTD_PTR_ALIGN((stack)->ptr); \
  28. (stack)->ptr = (char *)ptr + (size); \
  29. (stack)->ptr <= (stack)->end ? ptr : NULL; \
  30. })
  31. ZSTD_customMem ZSTD_initStack(void *workspace, size_t workspaceSize)
  32. {
  33. ZSTD_customMem stackMem = {ZSTD_stackAlloc, ZSTD_stackFree, workspace};
  34. ZSTD_stack *stack = (ZSTD_stack *)workspace;
  35. /* Verify preconditions */
  36. if (!workspace || workspaceSize < sizeof(ZSTD_stack) || workspace != ZSTD_PTR_ALIGN(workspace)) {
  37. ZSTD_customMem error = {NULL, NULL, NULL};
  38. return error;
  39. }
  40. /* Initialize the stack */
  41. stack->ptr = workspace;
  42. stack->end = (char *)workspace + workspaceSize;
  43. stack_push(stack, sizeof(ZSTD_stack));
  44. return stackMem;
  45. }
  46. void *ZSTD_stackAllocAll(void *opaque, size_t *size)
  47. {
  48. ZSTD_stack *stack = (ZSTD_stack *)opaque;
  49. *size = (BYTE const *)stack->end - (BYTE *)ZSTD_PTR_ALIGN(stack->ptr);
  50. return stack_push(stack, *size);
  51. }
  52. void *ZSTD_stackAlloc(void *opaque, size_t size)
  53. {
  54. ZSTD_stack *stack = (ZSTD_stack *)opaque;
  55. return stack_push(stack, size);
  56. }
  57. void ZSTD_stackFree(void *opaque, void *address)
  58. {
  59. (void)opaque;
  60. (void)address;
  61. }
  62. void *ZSTD_malloc(size_t size, ZSTD_customMem customMem) { return customMem.customAlloc(customMem.opaque, size); }
  63. void ZSTD_free(void *ptr, ZSTD_customMem customMem)
  64. {
  65. if (ptr != NULL)
  66. customMem.customFree(customMem.opaque, ptr);
  67. }