• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.h"
17 
18 #include <atomic>
19 #include <chrono>
20 #include <climits>
21 #include <memory>
22 #include <sys/stat.h>
23 
24 #include "zip_file_reader_io.h"
25 #include "zip_file_reader_mem.h"
26 
27 namespace panda {
28 namespace ecmascript {
29 constexpr size_t MEM_MAX_FILE_SIZE = 1u;
30 
CreateZipFileReader(const std::string & filePath)31 std::shared_ptr<ZipFileReader> ZipFileReader::CreateZipFileReader(const std::string &filePath)
32 {
33     size_t fileSize = GetFileLen(filePath);
34     if (fileSize == 0) {
35         return nullptr;
36     }
37 
38     std::shared_ptr<ZipFileReader> result;
39     if (fileSize <= MEM_MAX_FILE_SIZE) {
40         result = std::make_shared<ZipFileReaderMem>(filePath);
41     } else {
42         result = std::make_shared<ZipFileReaderIo>(filePath);
43     }
44 
45     result->fileLen_ = fileSize;
46     if (result->init()) {
47         return result;
48     }
49     return nullptr;
50 }
51 
~ZipFileReader()52 ZipFileReader::~ZipFileReader()
53 {
54     if (fd_ >= 0 && closable_) {
55         close(fd_);
56         fd_ = -1;
57     }
58 }
59 
GetFileLen(const std::string & filePath)60 size_t ZipFileReader::GetFileLen(const std::string &filePath)
61 {
62     if (filePath.empty()) {
63         return 0;
64     }
65 
66     struct stat fileStat{};
67     if (stat(filePath.c_str(), &fileStat) == 0) {
68         return fileStat.st_size;
69     }
70 
71     return 0;
72 }
73 
init()74 bool ZipFileReader::init()
75 {
76     if (filePath_.empty()) {
77         return false;
78     }
79     fd_ = open(filePath_.c_str(), O_RDONLY);
80     if (fd_ < 0) {
81         return false;
82     }
83 
84     return true;
85 }
86 }
87 }