1 /*
2  * Copyright (c) 2021 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 "frameworks/bridge/codec/byte_buffer_operator.h"
17 
18 namespace OHOS::Ace::Framework {
19 
ReadData(std::map<std::string,std::string> & mapValue) const20 bool ByteBufferReader::ReadData(std::map<std::string, std::string>& mapValue) const
21 {
22     int32_t size = -1;
23     if (!ReadData(size) || size < 0) {
24         LOGW("Could not read map size or map size is invalid");
25         return false;
26     }
27 
28     mapValue.clear();
29 
30     std::string key;
31     std::string value;
32     for (int32_t idx = 0; idx < size; ++idx) {
33         if (!ReadData(key) || !ReadData(value)) {
34             LOGW("Failed to read key or value");
35             return false;
36         }
37         mapValue.emplace(std::move(key), std::move(value));
38     }
39     return true;
40 }
41 
ReadData(std::set<std::string> & setValue) const42 bool ByteBufferReader::ReadData(std::set<std::string>& setValue) const
43 {
44     int32_t size = -1;
45     if (!ReadData(size) || size < 0) {
46         LOGW("Could not read map size or map size is invalid");
47         return false;
48     }
49 
50     setValue.clear();
51 
52     std::string value;
53     for (int32_t idx = 0; idx < size; ++idx) {
54         if (!ReadData(value)) {
55             LOGW("Failed to read string value");
56             return false;
57         }
58         setValue.emplace(std::move(value));
59     }
60     return true;
61 }
62 
WriteData(const std::map<std::string,std::string> & mapValue)63 void ByteBufferWriter::WriteData(const std::map<std::string, std::string>& mapValue)
64 {
65     WriteData(static_cast<int32_t>(mapValue.size()));
66     for (const auto& [key, value] : mapValue) {
67         WriteData(key);
68         WriteData(value);
69     }
70 }
71 
WriteData(const std::set<std::string> & setValue)72 void ByteBufferWriter::WriteData(const std::set<std::string>& setValue)
73 {
74     WriteData(static_cast<int32_t>(setValue.size()));
75     for (const auto& value : setValue) {
76         WriteData(value);
77     }
78 }
79 
80 } // namespace OHOS::Ace::Framework