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#include "ctype.h" 22 23int32_t InitUint8Buff(Uint8Buff *buff, uint32_t buffLen) 24{ 25 if (buff == NULL) { 26 return CLIB_ERR_NULL_PTR; 27 } 28 if (buffLen == 0) { 29 return CLIB_ERR_INVALID_LEN; 30 } 31 buff->val = (uint8_t *)HcMalloc(buffLen, 0); 32 if (buff->val == NULL) { 33 return CLIB_ERR_BAD_ALLOC; 34 } 35 buff->length = buffLen; 36 return CLIB_SUCCESS; 37} 38 39int32_t DeepCopyUint8Buff(const Uint8Buff *buff, Uint8Buff *newBuff) 40{ 41 if (buff == NULL || buff->val == NULL || newBuff == NULL) { 42 return CLIB_ERR_NULL_PTR; 43 } 44 if (buff->length == 0) { 45 return CLIB_ERR_INVALID_LEN; 46 } 47 uint8_t *val = (uint8_t *)HcMalloc(buff->length, 0); 48 if (val == NULL) { 49 return CLIB_ERR_BAD_ALLOC; 50 } 51 (void)memcpy_s(val, buff->length, buff->val, buff->length); 52 newBuff->val = val; 53 newBuff->length = buff->length; 54 return CLIB_SUCCESS; 55} 56 57void FreeUint8Buff(Uint8Buff *buff) 58{ 59 if (buff == NULL || buff->val == NULL || buff->length == 0) { 60 return; 61 } 62 HcFree(buff->val); 63 buff->val = NULL; 64 buff->length = 0; 65} 66 67void ClearFreeUint8Buff(Uint8Buff *buff) 68{ 69 if (buff == NULL || buff->val == NULL || buff->length == 0) { 70 return; 71 } 72 (void)memset_s(buff->val, buff->length, 0, buff->length); 73 HcFree(buff->val); 74 buff->val = NULL; 75 buff->length = 0; 76} 77 78bool IsUint8BuffValid(const Uint8Buff *buff, uint32_t maxLen) 79{ 80 return ((buff != NULL) && (buff->val != NULL) && (0 < buff->length) && (buff->length <= maxLen)); 81} 82 83int32_t ToLowerCase(Uint8Buff *buff) 84{ 85 uint32_t buffLen = buff->length; 86 char *buffStr = (char *)HcMalloc(buffLen + 1, 0); 87 if (buffStr == NULL) { 88 return CLIB_ERR_BAD_ALLOC; 89 } 90 if (memcpy_s(buffStr, buffLen + 1, buff->val, buffLen) != EOK) { 91 HcFree(buffStr); 92 return CLIB_FAILED; 93 } 94 for (uint32_t i = 0; i < buffLen; i++) { 95 buffStr[i] = tolower(buffStr[i]); 96 } 97 if (memcpy_s(buff->val, buffLen, buffStr, buffLen) != EOK) { 98 HcFree(buffStr); 99 return CLIB_FAILED; 100 } 101 HcFree(buffStr); 102 return CLIB_SUCCESS; 103} 104