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