1 /*
2 * Copyright (C) 2023 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 "uint8buff_utils.h"
17
18 #include "securec.h"
19 #include "clib_error.h"
20 #include "hc_types.h"
21
InitUint8Buff(Uint8Buff * buff,uint32_t buffLen)22 int32_t InitUint8Buff(Uint8Buff *buff, uint32_t buffLen)
23 {
24 if (buff == NULL) {
25 return CLIB_ERR_NULL_PTR;
26 }
27 if (buffLen == 0) {
28 return CLIB_ERR_INVALID_LEN;
29 }
30 buff->val = (uint8_t *)HcMalloc(buffLen, 0);
31 if (buff->val == NULL) {
32 return CLIB_ERR_BAD_ALLOC;
33 }
34 buff->length = buffLen;
35 return CLIB_SUCCESS;
36 }
37
DeepCopyUint8Buff(const Uint8Buff * buff,Uint8Buff * newBuff)38 int32_t DeepCopyUint8Buff(const Uint8Buff *buff, Uint8Buff *newBuff)
39 {
40 if (buff == NULL || buff->val == NULL || newBuff == NULL) {
41 return CLIB_ERR_NULL_PTR;
42 }
43 if (buff->length == 0) {
44 return CLIB_ERR_INVALID_LEN;
45 }
46 uint8_t *val = (uint8_t *)HcMalloc(buff->length, 0);
47 if (val == NULL) {
48 return CLIB_ERR_BAD_ALLOC;
49 }
50 (void)memcpy_s(val, buff->length, buff->val, buff->length);
51 newBuff->val = val;
52 newBuff->length = buff->length;
53 return CLIB_SUCCESS;
54 }
55
FreeUint8Buff(Uint8Buff * buff)56 void FreeUint8Buff(Uint8Buff *buff)
57 {
58 if (buff == NULL || buff->val == NULL || buff->length == 0) {
59 return;
60 }
61 HcFree(buff->val);
62 buff->val = NULL;
63 buff->length = 0;
64 }
65
ClearFreeUint8Buff(Uint8Buff * buff)66 void ClearFreeUint8Buff(Uint8Buff *buff)
67 {
68 if (buff == NULL || buff->val == NULL || buff->length == 0) {
69 return;
70 }
71 (void)memset_s(buff->val, buff->length, 0, buff->length);
72 HcFree(buff->val);
73 buff->val = NULL;
74 buff->length = 0;
75 }
76
IsUint8BuffValid(const Uint8Buff * buff,uint32_t maxLen)77 bool IsUint8BuffValid(const Uint8Buff *buff, uint32_t maxLen)
78 {
79 return ((buff != NULL) && (buff->val != NULL) && (0 < buff->length) && (buff->length <= maxLen));
80 }
81