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 "hilog_realloc.h"
17 #include "securec.h"
18 #include "hilog_string.h"
19
20 namespace OHOS {
21 namespace ACELite {
22 static const size_t ORG_STRING_LEN = 2;
23
HilogString()24 HilogString::HilogString() : size(0), maxSize(0), str(nullptr) {}
25
~HilogString()26 HilogString::~HilogString()
27 {
28 size = 0;
29 maxSize = 0;
30 if (str != nullptr) {
31 free(str);
32 str = nullptr;
33 }
34 }
35
Get(const HilogString * str)36 char *HilogString::Get(const HilogString *str)
37 {
38 if (str != nullptr) {
39 return str->str;
40 }
41 return nullptr;
42 }
43
Length(const HilogString * str)44 size_t HilogString::Length(const HilogString *str)
45 {
46 if (str != nullptr) {
47 return str->size;
48 }
49 return 0;
50 }
51
Puts(const char * src,HilogString * str,size_t strLen)52 size_t HilogString::Puts(const char *src, HilogString *str, size_t strLen)
53 {
54 if (src == nullptr || str == nullptr) {
55 return 0;
56 }
57
58 size_t len = strlen(src);
59 len = (len > strLen) ? ((strLen == 0) ? len : strLen) : len;
60 if (str->size + len + 1 >= str->maxSize) {
61 str->maxSize = str->size + len + ORG_STRING_LEN;
62 char *tmp = static_cast<char*>(
63 HilogRealloc::Realloc(str->str, sizeof(char) * str->maxSize, sizeof(char) * str->size));
64 if (tmp != nullptr) {
65 str->str = tmp;
66 } else {
67 return 0;
68 }
69 }
70 if (memcpy_s(str->str + str->size, str->maxSize, src, len) != 0) {
71 return 0;
72 }
73 str->size += len;
74 str->str[str->size] = 0;
75 return len;
76 }
77
Putc(char c,HilogString * str)78 char HilogString::Putc(char c, HilogString *str)
79 {
80 if (str == nullptr) {
81 return EOF;
82 }
83 if (str->size + 1 >= str->maxSize) {
84 str->maxSize = str->size + ORG_STRING_LEN;
85 char *tmp = static_cast<char*>(
86 HilogRealloc::Realloc(str->str, sizeof(char) * str->maxSize, sizeof(char) * str->size));
87 if (tmp != nullptr) {
88 str->str = tmp;
89 } else {
90 return EOF;
91 }
92 }
93 str->str[str->size++] = c;
94 str->str[str->size] = 0;
95 return c;
96 }
97 } // namespace ACELite
98 } // namespace OHOS