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 #ifndef TEST_FUZZTEST_DATA_SOURCE_H
17 #define TEST_FUZZTEST_DATA_SOURCE_H
18 
19 #include <string>
20 #include <vector>
21 #include <cstdint>
22 #include <securec.h>
23 
24 namespace OHOS::Rosen {
25 class DataSource  {
26 public:
DataSource(const std::uint8_t * data,size_t size)27     DataSource(const std::uint8_t* data, size_t size) : data_(data), size_(size), pos_(0) {}
28 
29     template<class T>
GetObject()30     T GetObject()
31     {
32         T object{};
33         auto objSize = sizeof(object);
34         if (!data_ || (objSize > size_ - pos_)) {
35             return object;
36         }
37         auto ret = memcpy_s(&object, objSize, data_ + pos_, objSize);
38         if (ret != EOK) {
39             return {};
40         }
41         pos_ += objSize;
42         return object;
43     }
44 
GetRaw(size_t rawSize)45     const std::uint8_t* GetRaw(size_t rawSize)
46     {
47         if (!data_ || (rawSize > size_ - pos_)) {
48             return nullptr;
49         }
50         auto current = pos_;
51         pos_ += rawSize;
52         return data_ + current;
53     }
54 
GetString()55     std::string GetString()
56     {
57         size_t num = GetObject<uint8_t>();
58         std::string str;
59         str.resize(num);
60         auto rawSize = sizeof(std::string::value_type) * num;
61         auto buf =  GetRaw(rawSize);
62         if (buf) {
63             memcpy_s(str.data(), rawSize, buf, rawSize);
64         }
65         return str;
66     }
67 
68     const std::uint8_t* data_;
69     size_t size_;
70     size_t pos_;
71 };
72 }
73 
74 #endif
75