blob: 6b2c79eeb656ea9d99cea362472e4dacf3723905 [file] [log] [blame]
Marek BehĂșn8509f222019-04-29 22:40:44 +02001// SPDX-License-Identifier: (GPL-2.0 or BSD-3-Clause-Clear)
2/**
3 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
4 * All rights reserved.
5 */
6
7/*-*************************************
8* Dependencies
9***************************************/
10#include "error_private.h"
11#include "zstd_internal.h" /* declaration of ZSTD_isError, ZSTD_getErrorName, ZSTD_getErrorCode, ZSTD_getErrorString, ZSTD_versionNumber */
Simon Glass336d4612020-02-03 07:36:16 -070012#include <malloc.h>
Marek BehĂșn8509f222019-04-29 22:40:44 +020013#include <linux/kernel.h>
14
15/*=**************************************************************
16* Custom allocator
17****************************************************************/
18
19#define stack_push(stack, size) \
20 ({ \
21 void *const ptr = ZSTD_PTR_ALIGN((stack)->ptr); \
22 (stack)->ptr = (char *)ptr + (size); \
23 (stack)->ptr <= (stack)->end ? ptr : NULL; \
24 })
25
26ZSTD_customMem ZSTD_initStack(void *workspace, size_t workspaceSize)
27{
28 ZSTD_customMem stackMem = {ZSTD_stackAlloc, ZSTD_stackFree, workspace};
29 ZSTD_stack *stack = (ZSTD_stack *)workspace;
30 /* Verify preconditions */
31 if (!workspace || workspaceSize < sizeof(ZSTD_stack) || workspace != ZSTD_PTR_ALIGN(workspace)) {
32 ZSTD_customMem error = {NULL, NULL, NULL};
33 return error;
34 }
35 /* Initialize the stack */
36 stack->ptr = workspace;
37 stack->end = (char *)workspace + workspaceSize;
38 stack_push(stack, sizeof(ZSTD_stack));
39 return stackMem;
40}
41
42void *ZSTD_stackAllocAll(void *opaque, size_t *size)
43{
44 ZSTD_stack *stack = (ZSTD_stack *)opaque;
45 *size = (BYTE const *)stack->end - (BYTE *)ZSTD_PTR_ALIGN(stack->ptr);
46 return stack_push(stack, *size);
47}
48
49void *ZSTD_stackAlloc(void *opaque, size_t size)
50{
51 ZSTD_stack *stack = (ZSTD_stack *)opaque;
52 return stack_push(stack, size);
53}
54void ZSTD_stackFree(void *opaque, void *address)
55{
56 (void)opaque;
57 (void)address;
58}
59
60void *ZSTD_malloc(size_t size, ZSTD_customMem customMem) { return customMem.customAlloc(customMem.opaque, size); }
61
62void ZSTD_free(void *ptr, ZSTD_customMem customMem)
63{
64 if (ptr != NULL)
65 customMem.customFree(customMem.opaque, ptr);
66}