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