1 /*
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 #include "Source.h"
18 #include "io/FileSystem.h"
19 #include "util/Files.h"
20 #include "util/Maybe.h"
21 #include "util/StringPiece.h"
22 #include "util/Util.h"
23 
24 #include <utils/FileMap.h>
25 
26 namespace aapt {
27 namespace io {
28 
RegularFile(const Source & source)29 RegularFile::RegularFile(const Source& source) : mSource(source) {
30 }
31 
openAsData()32 std::unique_ptr<IData> RegularFile::openAsData() {
33     android::FileMap map;
34     if (Maybe<android::FileMap> map = file::mmapPath(mSource.path, nullptr)) {
35         if (map.value().getDataPtr() && map.value().getDataLength() > 0) {
36             return util::make_unique<MmappedData>(std::move(map.value()));
37         }
38         return util::make_unique<EmptyData>();
39     }
40     return {};
41 }
42 
getSource() const43 const Source& RegularFile::getSource() const {
44     return mSource;
45 }
46 
FileCollectionIterator(FileCollection * collection)47 FileCollectionIterator::FileCollectionIterator(FileCollection* collection) :
48         mCurrent(collection->mFiles.begin()), mEnd(collection->mFiles.end()) {
49 }
50 
hasNext()51 bool FileCollectionIterator::hasNext() {
52     return mCurrent != mEnd;
53 }
54 
next()55 IFile* FileCollectionIterator::next() {
56     IFile* result = mCurrent->second.get();
57     ++mCurrent;
58     return result;
59 }
60 
insertFile(const StringPiece & path)61 IFile* FileCollection::insertFile(const StringPiece& path) {
62     return (mFiles[path.toString()] = util::make_unique<RegularFile>(Source(path))).get();
63 }
64 
findFile(const StringPiece & path)65 IFile* FileCollection::findFile(const StringPiece& path) {
66     auto iter = mFiles.find(path.toString());
67     if (iter != mFiles.end()) {
68         return iter->second.get();
69     }
70     return nullptr;
71 }
72 
iterator()73 std::unique_ptr<IFileCollectionIterator> FileCollection::iterator() {
74     return util::make_unique<FileCollectionIterator>(this);
75 }
76 
77 } // namespace io
78 } // namespace aapt
79