• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef OHOS_HIVIEWDFX_PARCELABLE_VECTOR_RW_H
17 #define OHOS_HIVIEWDFX_PARCELABLE_VECTOR_RW_H
18 
19 #include <typeinfo>
20 
21 #include "parcel.h"
22 
23 namespace OHOS {
24 namespace HiviewDFX {
25 // no object in parcel
26 constexpr int VALUE_NULL = -1;
27 // object exist in parcel
28 constexpr int VALUE_OBJECT = 1;
29 constexpr int RULE_COUNT_LIMIT = 512 * 1024;
30 
31 template<typename T>
ReadVectorFromParcel(Parcel & parcel,std::vector<T> & rules)32 bool ReadVectorFromParcel(Parcel& parcel, std::vector<T>& rules)
33 {
34     int empty = VALUE_NULL;
35     if (!parcel.ReadInt32(empty)) {
36         return false;
37     }
38     if (empty == VALUE_OBJECT) {
39         int size = 0;
40         if (!parcel.ReadInt32(size) || (size > RULE_COUNT_LIMIT)) {
41             return false;
42         }
43         rules.clear();
44         for (int i = 0; i < size; i++) {
45             T* rulePtr = parcel.ReadParcelable<T>();
46             if (rulePtr == nullptr) {
47                 return false;
48             }
49             rules.emplace_back(*rulePtr);
50             delete rulePtr;
51             rulePtr = nullptr;
52         }
53     }
54     return true;
55 }
56 
57 template<typename T>
WriteVectorToParcel(Parcel & parcel,const std::vector<T> & rules)58 bool WriteVectorToParcel(Parcel& parcel, const std::vector<T>& rules)
59 {
60     if (rules.size() == 0) {
61         if (!parcel.WriteInt32(VALUE_NULL)) {
62             return false;
63         }
64     } else {
65         if (!parcel.WriteInt32(VALUE_OBJECT)) {
66             return false;
67         }
68         size_t size = rules.size();
69         if (!parcel.WriteInt32(size)) {
70             return false;
71         }
72         for (size_t i = 0; i < size; i++) {
73             if (!parcel.WriteParcelable(&rules[i])) {
74                 return false;
75             }
76         }
77     }
78     return true;
79 }
80 } // namespace HiviewDFX
81 } // namespace OHOS
82 
83 #endif // OHOS_HIVIEWDFX_PARCELABLE_VECTOR_RW_H