blob: 15ec3f9d3afecadf337cc175c9e0fd8cf35eacae [file] [log] [blame]
Mårten Kongstad02751232018-04-27 13:16:32 +02001/*
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>
Mårten Kongstad02751232018-04-27 13:16:32 +020019
Mårten Kongstad0f763112018-11-19 14:14:37 +010020#include "idmap2/Result.h"
Mårten Kongstad02751232018-04-27 13:16:32 +020021#include "idmap2/ZipFile.h"
22
Mårten Kongstad0eba72a2018-11-29 08:23:14 +010023namespace android::idmap2 {
Mårten Kongstad02751232018-04-27 13:16:32 +020024
25std::unique_ptr<MemoryChunk> MemoryChunk::Allocate(size_t size) {
26 void* ptr = ::operator new(sizeof(MemoryChunk) + size);
27 std::unique_ptr<MemoryChunk> chunk(reinterpret_cast<MemoryChunk*>(ptr));
28 chunk->size = size;
29 return chunk;
30}
31
32std::unique_ptr<const ZipFile> ZipFile::Open(const std::string& path) {
33 ::ZipArchiveHandle handle;
34 int32_t status = ::OpenArchive(path.c_str(), &handle);
35 if (status != 0) {
36 return nullptr;
37 }
38 return std::unique_ptr<ZipFile>(new ZipFile(handle));
39}
40
41ZipFile::~ZipFile() {
42 ::CloseArchive(handle_);
43}
44
45std::unique_ptr<const MemoryChunk> ZipFile::Uncompress(const std::string& entryPath) const {
46 ::ZipEntry entry;
47 int32_t status = ::FindEntry(handle_, ::ZipString(entryPath.c_str()), &entry);
48 if (status != 0) {
49 return nullptr;
50 }
51 std::unique_ptr<MemoryChunk> chunk = MemoryChunk::Allocate(entry.uncompressed_length);
52 status = ::ExtractToMemory(handle_, &entry, chunk->buf, chunk->size);
53 if (status != 0) {
54 return nullptr;
55 }
56 return chunk;
57}
58
Mårten Kongstad0f763112018-11-19 14:14:37 +010059Result<uint32_t> ZipFile::Crc(const std::string& entryPath) const {
Mårten Kongstad02751232018-04-27 13:16:32 +020060 ::ZipEntry entry;
61 int32_t status = ::FindEntry(handle_, ::ZipString(entryPath.c_str()), &entry);
Mårten Kongstad0f763112018-11-19 14:14:37 +010062 return status == 0 ? Result<uint32_t>(entry.crc32) : kResultError;
Mårten Kongstad02751232018-04-27 13:16:32 +020063}
64
Mårten Kongstad0eba72a2018-11-29 08:23:14 +010065} // namespace android::idmap2