• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024-2024 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 "byte_array_utils.h"
17 #include "signature_tools_errno.h"
18 #include "securec.h"
19 
20 namespace OHOS {
21 namespace SignatureTools {
InsertIntToByteArray(std::vector<int8_t> & desByte,int index,int num)22 int ByteArrayUtils::InsertIntToByteArray(std::vector<int8_t>& desByte, int index, int num)
23 {
24     if (index + sizeof(int) > desByte.size()) {
25         return RET_FAILED;
26     }
27     int pos = index;
28     desByte[pos] = (num >> TRIPLE_BIT_SIZE) & 0xff;
29     pos++;
30     desByte[pos] = (num >> DOUBLE_BIT_SIZE) & 0xff;
31     pos++;
32     desByte[pos] = (num >> BIT_SIZE) & 0xff;
33     pos++;
34     desByte[pos] = num & 0xff;
35     pos++;
36     return pos;
37 }
38 
InsertShortToByteArray(std::vector<int8_t> & desByte,size_t desByteLen,int index,short num)39 int ByteArrayUtils::InsertShortToByteArray(std::vector<int8_t>& desByte, size_t desByteLen, int index, short num)
40 {
41     if (index + HALF_INTEGER_BYTES > desByteLen) {
42         return RET_FAILED;
43     }
44     int pos = index;
45     desByte[pos] = (num >> BIT_SIZE) & 0xff;
46     pos++;
47     desByte[pos] = num & 0xff;
48     pos++;
49     return pos;
50 }
51 
InsertByteToByteArray(std::vector<int8_t> & des,int start,std::vector<int8_t> src,int srcLen)52 int ByteArrayUtils::InsertByteToByteArray(std::vector<int8_t>& des, int start, std::vector<int8_t> src, int srcLen)
53 {
54     if (src.size() < srcLen) {
55         return -1;
56     }
57     if (memcpy_s(des.data() + start, srcLen, src.data(), srcLen) != EOK) {
58         return -1;
59     }
60     return start + srcLen;
61 }
62 
InsertCharToByteArray(std::vector<int8_t> & des,int start,std::string src)63 int ByteArrayUtils::InsertCharToByteArray(std::vector<int8_t>& des, int start, std::string src)
64 {
65     if (src.length() + start > des.size()) {
66         return RET_FAILED;
67     }
68     for (int i = 0; i < src.length(); ++i) {
69         des[i + start] = src[i];
70     }
71     return start + src.length();
72 }
73 
74 } // namespace SignatureTools
75 } // namespace OHOS
76