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 #include "zip_file_reader_mem.h"
17 
18 #include <cstdlib>
19 #include "securec.h"
20 
21 
22 namespace panda {
23 namespace ecmascript {
init()24 bool ZipFileReaderMem::init()
25 {
26     if (!ZipFileReader::init()) {
27         return false;
28     }
29     posix_fadvise(fd_, 0, 0, POSIX_FADV_SEQUENTIAL);
30 
31     fileContent_.resize(fileLen_);
32     auto pos = std::string::size_type{};
33     while (true) {
34         auto const readCount = read(fd_, fileContent_.data() + pos, fileContent_.size() - pos);
35         if (readCount < 0) {
36             fileContent_.clear();
37             return false;
38         } else if (readCount == 0) {
39             break;
40         }
41 
42         pos += readCount;
43     }
44     return true;
45 }
46 
ReadBuffer(size_t startPos, size_t bufferSize)47 std::string ZipFileReaderMem::ReadBuffer(size_t startPos, size_t bufferSize)
48 {
49     if (startPos + bufferSize > fileContent_.length()) {
50         return "";
51     }
52 
53     return fileContent_.substr(startPos, bufferSize);
54 }
55 
ReadBuffer(uint8_t *dst, size_t startPos, size_t bufferSize)56 bool ZipFileReaderMem::ReadBuffer(uint8_t *dst, size_t startPos, size_t bufferSize)
57 {
58     if (!dst || startPos + bufferSize > fileContent_.length()) {
59         return false;
60     }
61 
62     if (memcpy_s(dst, bufferSize, fileContent_.data() + startPos, bufferSize) != EOK) {
63         return false;
64     }
65 
66     return true;
67 }
68 }
69 }