blob: 467e60464a68e26a54188927d52e89eec534bf86 [file] [log] [blame]
Adam Lesinskia40e9722015-11-24 19:11:46 -08001/*
2 * Copyright (C) 2015 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#ifndef AAPT_IO_DATA_H
18#define AAPT_IO_DATA_H
19
20#include <utils/FileMap.h>
21
22#include <memory>
23
24namespace aapt {
25namespace io {
26
27/**
28 * Interface for a block of contiguous memory. An instance of this interface owns the data.
29 */
30class IData {
31public:
32 virtual ~IData() = default;
33
34 virtual const void* data() const = 0;
35 virtual size_t size() const = 0;
36};
37
38/**
39 * Implementation of IData that exposes a memory mapped file. The mmapped file is owned by this
40 * object.
41 */
42class MmappedData : public IData {
43public:
44 explicit MmappedData(android::FileMap&& map) : mMap(std::forward<android::FileMap>(map)) {
45 }
46
47 const void* data() const override {
48 return mMap.getDataPtr();
49 }
50
51 size_t size() const override {
52 return mMap.getDataLength();
53 }
54
55private:
56 android::FileMap mMap;
57};
58
59/**
60 * Implementation of IData that exposes a block of memory that was malloc'ed (new'ed). The
61 * memory is owned by this object.
62 */
63class MallocData : public IData {
64public:
65 MallocData(std::unique_ptr<const uint8_t[]> data, size_t size) :
66 mData(std::move(data)), mSize(size) {
67 }
68
69 const void* data() const override {
70 return mData.get();
71 }
72
73 size_t size() const override {
74 return mSize;
75 }
76
77private:
78 std::unique_ptr<const uint8_t[]> mData;
79 size_t mSize;
80};
81
Adam Lesinski52364f72016-01-11 13:10:24 -080082/**
83 * When mmap fails because the file has length 0, we use the EmptyData to simulate data of length 0.
84 */
85class EmptyData : public IData {
86public:
87 const void* data() const override {
88 static const uint8_t d = 0;
89 return &d;
90 }
91
92 size_t size() const override {
93 return 0u;
94 }
95};
96
Adam Lesinskia40e9722015-11-24 19:11:46 -080097} // namespace io
98} // namespace aapt
99
100#endif /* AAPT_IO_DATA_H */