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 #include "convertor.h"
16 namespace OHOS::DistributedKv {
ToLocalDBKey(const Key & key) const17 std::vector<uint8_t> Convertor::ToLocalDBKey(const Key &key) const
18 {
19 return Convertor::GetPrefix(key);
20 }
21
ToWholeDBKey(const Key & key) const22 std::vector<uint8_t> Convertor::ToWholeDBKey(const Key &key) const
23 {
24 return Convertor::GetPrefix(key);
25 }
26
ToKey(DBKey && key,std::string & deviceId) const27 Key Convertor::ToKey(DBKey &&key, std::string &deviceId) const
28 {
29 return std::move(key);
30 }
31
GetPrefix(const Key & prefix) const32 std::vector<uint8_t> Convertor::GetPrefix(const Key &prefix) const
33 {
34 std::vector<uint8_t> dbKey = TrimKey(prefix);
35 if (dbKey.size() > MAX_KEY_LENGTH) {
36 dbKey.clear();
37 }
38 return dbKey;
39 }
40
GetPrefix(const DataQuery & query) const41 std::vector<uint8_t> Convertor::GetPrefix(const DataQuery &query) const
42 {
43 return Convertor::GetPrefix(Key(query.prefix_));
44 }
45
GetDBQuery(const DataQuery & query) const46 Convertor::DBQuery Convertor::GetDBQuery(const DataQuery &query) const
47 {
48 DBQuery dbQuery = *(query.query_);
49 if (query.hasPrefix_) {
50 dbQuery.PrefixKey(GetPrefix(query));
51 }
52
53 if (query.hasKeys_) {
54 std::set<DBKey> keys;
55 for (auto &key : query.keys_) {
56 keys.insert(ToWholeDBKey(GetRealKey(key, query)));
57 }
58 dbQuery.InKeys(keys);
59 }
60 return dbQuery;
61 }
62
GetRealKey(const std::string & key,const DataQuery & query) const63 std::string Convertor::GetRealKey(const std::string &key, const DataQuery &query) const
64 {
65 (void)query;
66 return key;
67 }
68
TrimKey(const Key & prefix) const69 std::vector<uint8_t> Convertor::TrimKey(const Key &prefix) const
70 {
71 auto begin = std::find_if(prefix.Data().begin(), prefix.Data().end(), [](int ch) { return !std::isspace(ch); });
72 auto rBegin = std::find_if(prefix.Data().rbegin(), prefix.Data().rend(), [](int ch) { return !std::isspace(ch); });
73 auto end = static_cast<decltype(begin)>(rBegin.base());
74 if (end <= begin) {
75 return {};
76 }
77 return {begin, end};
78 }
79 }