MÃ¥rten Kongstad | 0275123 | 2018-04-27 13:16:32 +0200 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <memory> |
| 18 | #include <string> |
| 19 | #include <utility> |
| 20 | |
| 21 | #include "idmap2/ZipFile.h" |
| 22 | |
| 23 | namespace android { |
| 24 | namespace idmap2 { |
| 25 | |
| 26 | std::unique_ptr<MemoryChunk> MemoryChunk::Allocate(size_t size) { |
| 27 | void* ptr = ::operator new(sizeof(MemoryChunk) + size); |
| 28 | std::unique_ptr<MemoryChunk> chunk(reinterpret_cast<MemoryChunk*>(ptr)); |
| 29 | chunk->size = size; |
| 30 | return chunk; |
| 31 | } |
| 32 | |
| 33 | std::unique_ptr<const ZipFile> ZipFile::Open(const std::string& path) { |
| 34 | ::ZipArchiveHandle handle; |
| 35 | int32_t status = ::OpenArchive(path.c_str(), &handle); |
| 36 | if (status != 0) { |
| 37 | return nullptr; |
| 38 | } |
| 39 | return std::unique_ptr<ZipFile>(new ZipFile(handle)); |
| 40 | } |
| 41 | |
| 42 | ZipFile::~ZipFile() { |
| 43 | ::CloseArchive(handle_); |
| 44 | } |
| 45 | |
| 46 | std::unique_ptr<const MemoryChunk> ZipFile::Uncompress(const std::string& entryPath) const { |
| 47 | ::ZipEntry entry; |
| 48 | int32_t status = ::FindEntry(handle_, ::ZipString(entryPath.c_str()), &entry); |
| 49 | if (status != 0) { |
| 50 | return nullptr; |
| 51 | } |
| 52 | std::unique_ptr<MemoryChunk> chunk = MemoryChunk::Allocate(entry.uncompressed_length); |
| 53 | status = ::ExtractToMemory(handle_, &entry, chunk->buf, chunk->size); |
| 54 | if (status != 0) { |
| 55 | return nullptr; |
| 56 | } |
| 57 | return chunk; |
| 58 | } |
| 59 | |
| 60 | std::pair<bool, uint32_t> ZipFile::Crc(const std::string& entryPath) const { |
| 61 | ::ZipEntry entry; |
| 62 | int32_t status = ::FindEntry(handle_, ::ZipString(entryPath.c_str()), &entry); |
| 63 | return std::make_pair(status == 0, entry.crc32); |
| 64 | } |
| 65 | |
| 66 | } // namespace idmap2 |
| 67 | } // namespace android |