• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #ifndef BYTES_UTILS_H
17 #define BYTES_UTILS_H
18 
19 #include "logger.h"
20 #include "objectstore_errors.h"
21 
22 namespace OHOS::ObjectStore {
23 class BytesUtils final {
24 public:
25     BytesUtils() = delete;
26     ~BytesUtils() = delete;
27 
PutNum(void * val,uint32_t offset,uint32_t valLen,Bytes & data)28     static void PutNum(void *val, uint32_t offset, uint32_t valLen, Bytes &data)
29     {
30         uint32_t len = valLen + offset;
31         if (len > sizeof(data.front()) * data.size()) {
32             data.resize(len);
33         }
34 
35         for (uint32_t i = 0; i < valLen; i++) {
36             // 8 bit = 1 byte
37             data[offset + i] = *(static_cast<uint8_t *>(val) + valLen - i - 1);
38         }
39     }
40 
GetNum(Bytes & data,uint32_t offset,void * val,uint32_t valLen)41     static uint32_t GetNum(Bytes &data, uint32_t offset, void *val, uint32_t valLen)
42     {
43         uint8_t *value = static_cast<uint8_t *>(val);
44         uint32_t len = offset + valLen;
45         uint32_t dataLen = data.size();
46         if (dataLen < len) {
47             LOG_ERROR("GetNum data.size() %{public}d, offset %{public}d, valLen %{public}d", dataLen, offset, valLen);
48             return ERR_DATA_LEN;
49         }
50         for (uint32_t i = 0; i < valLen; i++) {
51             value[i] = data[len - 1 - i];
52         }
53         return SUCCESS;
54     }
55 };
56 } // namespace OHOS::ObjectStore
57 #endif // BYTES_UTILS_H
58