1 /*
2 * Copyright (c) 2024 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 #include "preferences_utils.h"
16
17 #include <string>
18
19 #include "log_print.h"
20 #include "preferences_errno.h"
21 #include "preferences_value.h"
22
23 namespace OHOS {
24 namespace NativePreferences {
25
MakeFilePath(const std::string & prefPath,const std::string & suffix)26 std::string MakeFilePath(const std::string &prefPath, const std::string &suffix)
27 {
28 return prefPath + suffix;
29 }
30
CheckKey(const std::string & key)31 int CheckKey(const std::string &key)
32 {
33 if (key.empty()) {
34 LOG_ERROR("The key string is null or empty.");
35 return E_KEY_EMPTY;
36 }
37 if (MAX_KEY_LENGTH < key.length()) {
38 LOG_ERROR("The key string length should shorter than 1024.");
39 return E_KEY_EXCEED_MAX_LENGTH;
40 }
41 return E_OK;
42 }
43
CheckValue(const PreferencesValue & value)44 int CheckValue(const PreferencesValue &value)
45 {
46 auto lengthCheck = [] (uint32_t length, const std::string &errMsg) {
47 if (MAX_VALUE_LENGTH < length) {
48 LOG_ERROR("%{public}s", errMsg.c_str());
49 return E_VALUE_EXCEED_MAX_LENGTH;
50 }
51 return E_OK;
52 };
53
54 if (value.IsString()) {
55 std::string val = value;
56 return lengthCheck(val.length(), "the value string length should shorter than 16 * 1024 * 1024.");
57 }
58
59 if (value.IsObject()) {
60 Object obj = value;
61 return lengthCheck(obj.valueStr.length(), "the length of the object converted to JSON should be less than 16 *"
62 " 1024 * 1024");
63 }
64
65 if (value.IsBigInt()) {
66 BigInt bigint = value;
67 if (bigint.words_.empty()) {
68 LOG_ERROR("BigInt words cannot be empty.");
69 return E_ERROR;
70 }
71 return E_OK;
72 }
73 return E_OK;
74 }
75 } // End of namespace NativePreferences
76 } // End of namespace OHOS
77