1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "spunge_mem.h"
17 #include "utils.h"
18 
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
SpungeAlloc(size_t blockNum,size_t blockSize,FILLP_INT allocType)22 void *SpungeAlloc(size_t blockNum, size_t blockSize, FILLP_INT allocType)
23 {
24     if (blockSize == 0) {
25         return FILLP_NULL_PTR;
26     }
27 
28     switch (allocType) {
29         case SPUNGE_ALLOC_TYPE_MALLOC: {
30             FILLP_UINT32 totalSize = (FILLP_UINT32)(blockSize * blockNum);
31             if ((totalSize == 0) || (blockNum != totalSize / blockSize)) {
32                 return FILLP_NULL_PTR;
33             }
34 
35             return FILLP_MALLOC((FILLP_UINT32)totalSize);
36         }
37         case SPUNGE_ALLOC_TYPE_CALLOC: {
38             if ((blockNum == 0) || (blockNum > FILLP_INVALID_UINT32) || (blockSize > FILLP_INVALID_UINT32)) {
39                 return FILLP_NULL_PTR;
40             }
41             return FILLP_CALLOC((FILLP_UINT32)blockNum, (FILLP_UINT32)blockSize);
42         }
43         default:
44             return FILLP_NULL_PTR;
45     }
46 }
47 
SpungeFree(void * p,FILLP_INT allocType)48 void SpungeFree(void *p, FILLP_INT allocType)
49 {
50     if (p == FILLP_NULL_PTR) {
51         return;
52     }
53 
54     switch (allocType) {
55         case SPUNGE_ALLOC_TYPE_MALLOC:
56         /* fall-through: mem alloc by malloc or calloc, can be freed by free func */
57         case SPUNGE_ALLOC_TYPE_CALLOC:
58             FILLP_FREE(p);
59 
60             FILLP_UNUSED_PARA(p);
61             return;
62         default:
63             return;
64     }
65 }
66 
67 #ifdef __cplusplus
68 }
69 #endif
70