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 "edm_utils.h"
17
18 #include <codecvt>
19 #include "edm_constants.h"
20 #include "edm_log.h"
21 #include "securec.h"
22
23 namespace OHOS {
24 namespace EDM {
25 const std::string ERROR_STRING = "error";
26 const std::u16string ERROR_USTRING = u"error";
27
ParseStringToInt(const std::string & str,int32_t & result)28 ErrCode EdmUtils::ParseStringToInt(const std::string &str, int32_t &result)
29 {
30 int64_t tmp;
31 int32_t ret = EdmUtils::ParseStringToLong(str, tmp);
32 result = tmp;
33 return ret;
34 }
35
ParseStringToLong(const std::string & str,int64_t & result)36 ErrCode EdmUtils::ParseStringToLong(const std::string &str, int64_t &result)
37 {
38 char* end = nullptr;
39 const char* p = str.c_str();
40 errno = 0;
41 result = strtol(p, &end, EdmConstants::DECIMAL);
42 if (errno == ERANGE || end ==p || *end != '\0') {
43 EDMLOGE("EdmUtils ParseStringToLong: parse str failed: %{public}s", p);
44 return EdmReturnErrCode::PARAM_ERROR;
45 }
46 return ERR_OK;
47 }
48
Utf16ToUtf8(const std::u16string & str16)49 std::string EdmUtils::Utf16ToUtf8(const std::u16string &str16)
50 {
51 if (str16 == ERROR_USTRING) {
52 return ERROR_STRING;
53 }
54 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(ERROR_STRING);
55 std::string result = convert.to_bytes(str16);
56 return result == ERROR_STRING ? "" : result;
57 }
58
ClearString(std::string & str)59 void EdmUtils::ClearString(std::string &str)
60 {
61 std::fill(str.begin(), str.end(), '\0');
62 str.clear();
63 }
64
ClearCharArray(char * & str,size_t size)65 void EdmUtils::ClearCharArray(char* &str, size_t size)
66 {
67 if (str != nullptr) {
68 memset_s(str, size, '\0', size);
69 free(str);
70 str = nullptr;
71 }
72 }
73 } // namespace EDM
74 } // namespace OHOS