summaryrefslogtreecommitdiff
path: root/src/mbgl/storage/file_source_manager.cpp
blob: 6817717f1a170d03868673aabdf8797b0b6b5a49 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <mbgl/storage/file_source_manager.hpp>
#include <mbgl/storage/resource_options.hpp>
#include <mbgl/util/string.hpp>

#include <map>
#include <mutex>
#include <tuple>

namespace mbgl {

class FileSourceManager::Impl {
public:
    using Key = std::tuple<FileSourceType, std::string>;
    std::map<Key, std::weak_ptr<FileSource>> fileSources;
    std::map<FileSourceType, FileSourceFactory> fileSourceFactories;
    std::recursive_mutex mutex;
};

FileSourceManager::FileSourceManager() : impl(std::make_unique<Impl>()) {}

FileSourceManager::~FileSourceManager() = default;

std::shared_ptr<FileSource> FileSourceManager::getFileSource(FileSourceType type,
                                                             const ResourceOptions& options) noexcept {
    std::lock_guard<std::recursive_mutex> lock(impl->mutex);

    // Remove released file sources.
    for (auto it = impl->fileSources.begin(); it != impl->fileSources.end();) {
        it = it->second.expired() ? impl->fileSources.erase(it) : ++it;
    }

    const auto context = reinterpret_cast<uint64_t>(options.platformContext());
    const std::string optionsKey =
        options.baseURL() + '|' + options.accessToken() + '|' + options.cachePath() + '|' + util::toString(context);
    const auto key = std::tie(type, optionsKey);

    std::shared_ptr<FileSource> fileSource;
    auto tuple = impl->fileSources.find(key);
    if (tuple != impl->fileSources.end()) {
        fileSource = tuple->second.lock();
    }

    if (!fileSource) {
        auto it = impl->fileSourceFactories.find(type);
        if (it != impl->fileSourceFactories.end()) {
            assert(it->second);
            impl->fileSources[key] = fileSource = it->second(options);
        }
    }

    return fileSource;
}

void FileSourceManager::registerFileSourceFactory(FileSourceType type, FileSourceFactory&& factory) noexcept {
    assert(factory);
    std::lock_guard<std::recursive_mutex> lock(impl->mutex);
    impl->fileSourceFactories[type] = std::move(factory);
}

FileSourceManager::FileSourceFactory FileSourceManager::unRegisterFileSourceFactory(FileSourceType type) noexcept {
    std::lock_guard<std::recursive_mutex> lock(impl->mutex);
    auto it = impl->fileSourceFactories.find(type);
    FileSourceFactory factory;
    if (it != impl->fileSourceFactories.end()) {
        factory = std::move(it->second);
        impl->fileSourceFactories.erase(it);
    }
    return factory;
}

} // namespace mbgl