1 /*
2 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
3 *
4 * HDF is dual licensed: you can use it either under the terms of
5 * the GPL, or the BSD license, at your option.
6 * See the LICENSE file in the root of this repository for complete details.
7 */
8
9 #include "hdf_cstring.h"
10 #include "hdf_log.h"
11 #include "osal_mem.h"
12 #include "securec.h"
13
14 #define CSTRING_MAX 1024
15
HdfStringMakeHashKey(const char * key,uint32_t mask)16 uint32_t HdfStringMakeHashKey(const char *key, uint32_t mask)
17 {
18 uint32_t hashValue = 0;
19 const uint32_t seed = 131; // 31 131 1313 13131 131313 etc..
20 while ((key != NULL) && *key) {
21 hashValue = hashValue * seed + (*key++);
22 }
23 return (hashValue & 0x7FFFFFFF) | mask;
24 }
25
HdfCStringObtain(const char * str)26 struct HdfCString *HdfCStringObtain(const char *str)
27 {
28 struct HdfCString *instance = NULL;
29 size_t size;
30 if (str != NULL) {
31 size_t strLen = strlen(str);
32 if (strLen > CSTRING_MAX) {
33 return NULL;
34 }
35 size = sizeof(struct HdfCString) + strLen + 1;
36 instance = (struct HdfCString *)OsalMemCalloc(size);
37 if (instance == NULL) {
38 HDF_LOGE("HdfCStringObtain failed, alloc memory failed");
39 return NULL;
40 }
41 if (strncpy_s(instance->value, strLen + 1, str, strLen) != EOK) {
42 HDF_LOGE("HdfCStringObtain failed, strncpy_s failed");
43 OsalMemFree(instance);
44 return NULL;
45 }
46 instance->size = (int)strLen;
47 }
48 return instance;
49 }
50
HdfCStringRecycle(struct HdfCString * inst)51 void HdfCStringRecycle(struct HdfCString *inst)
52 {
53 if (inst != NULL) {
54 OsalMemFree(inst);
55 }
56 }
57
HdfStringCopy(const char * src)58 char *HdfStringCopy(const char *src)
59 {
60 char *newStr = NULL;
61 size_t srcSize;
62 size_t dstSize;
63
64 if (src == NULL) {
65 return NULL;
66 }
67 srcSize = strlen(src);
68 dstSize = srcSize + 1;
69 newStr = OsalMemAlloc(dstSize);
70 if (newStr == NULL) {
71 return NULL;
72 }
73
74 if (strncpy_s(newStr, dstSize, src, srcSize) != EOK) {
75 OsalMemFree(newStr);
76 newStr = NULL;
77 }
78
79 return newStr;
80 }
81