blob: 9a217e15739c7a510dabdff07661559f8890fd6a [file] [log] [blame]
Marek BehĂșne87e2002019-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 */
12#include <linux/kernel.h>
13
14/*=**************************************************************
15* Custom allocator
16****************************************************************/
17
18#define stack_push(stack, size) \
19 ({ \
20 void *const ptr = ZSTD_PTR_ALIGN((stack)->ptr); \
21 (stack)->ptr = (char *)ptr + (size); \
22 (stack)->ptr <= (stack)->end ? ptr : NULL; \
23 })
24
25ZSTD_customMem ZSTD_initStack(void *workspace, size_t workspaceSize)
26{
27 ZSTD_customMem stackMem = {ZSTD_stackAlloc, ZSTD_stackFree, workspace};
28 ZSTD_stack *stack = (ZSTD_stack *)workspace;
29 /* Verify preconditions */
30 if (!workspace || workspaceSize < sizeof(ZSTD_stack) || workspace != ZSTD_PTR_ALIGN(workspace)) {
31 ZSTD_customMem error = {NULL, NULL, NULL};
32 return error;
33 }
34 /* Initialize the stack */
35 stack->ptr = workspace;
36 stack->end = (char *)workspace + workspaceSize;
37 stack_push(stack, sizeof(ZSTD_stack));
38 return stackMem;
39}
40
41void *ZSTD_stackAllocAll(void *opaque, size_t *size)
42{
43 ZSTD_stack *stack = (ZSTD_stack *)opaque;
44 *size = (BYTE const *)stack->end - (BYTE *)ZSTD_PTR_ALIGN(stack->ptr);
45 return stack_push(stack, *size);
46}
47
48void *ZSTD_stackAlloc(void *opaque, size_t size)
49{
50 ZSTD_stack *stack = (ZSTD_stack *)opaque;
51 return stack_push(stack, size);
52}
53void ZSTD_stackFree(void *opaque, void *address)
54{
55 (void)opaque;
56 (void)address;
57}
58
59void *ZSTD_malloc(size_t size, ZSTD_customMem customMem) { return customMem.customAlloc(customMem.opaque, size); }
60
61void ZSTD_free(void *ptr, ZSTD_customMem customMem)
62{
63 if (ptr != NULL)
64 customMem.customFree(customMem.opaque, ptr);
65}