joshualitt | cdad12f | 2016-02-08 07:08:21 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2016 Google Inc. |
| 3 | * |
| 4 | * Use of this source code is governed by a BSD-style license that can be |
| 5 | * found in the LICENSE file. |
| 6 | */ |
| 7 | |
Mike Klein | c0bd9f9 | 2019-04-23 12:05:21 -0500 | [diff] [blame] | 8 | #include "tools/UrlDataManager.h" |
joshualitt | cdad12f | 2016-02-08 07:08:21 -0800 | [diff] [blame] | 9 | |
Nathaniel Nifong | a14d809 | 2020-01-03 10:29:13 -0500 | [diff] [blame] | 10 | #include <unordered_map> |
| 11 | |
joshualitt | cdad12f | 2016-02-08 07:08:21 -0800 | [diff] [blame] | 12 | bool operator==(const SkData& a, const SkData& b) { |
| 13 | return a.equals(&b); |
| 14 | } |
| 15 | |
| 16 | UrlDataManager::UrlDataManager(SkString rootUrl) : fRootUrl(rootUrl), fDataId(0) {} |
| 17 | |
| 18 | SkString UrlDataManager::addData(SkData* data, const char* contentType) { |
| 19 | UrlData* urlData = fCache.find(*data); |
| 20 | if (fCache.find(*data)) { |
| 21 | SkASSERT(data->equals(urlData->fData.get())); |
| 22 | return urlData->fUrl; |
| 23 | } |
| 24 | |
| 25 | urlData = new UrlData; |
| 26 | urlData->fData.reset(SkRef(data)); |
| 27 | urlData->fContentType.set(contentType); |
| 28 | urlData->fUrl.appendf("%s/%d", fRootUrl.c_str(), fDataId++); |
| 29 | |
| 30 | fCache.add(urlData); |
| 31 | |
| 32 | SkASSERT(!fUrlLookup.find(urlData->fUrl)); |
| 33 | fUrlLookup.add(urlData); |
| 34 | return urlData->fUrl; |
| 35 | } |
| 36 | |
| 37 | void UrlDataManager::reset() { |
Mike Klein | cff6396 | 2020-03-14 16:22:45 -0500 | [diff] [blame] | 38 | fCache.foreach([&](UrlData* urlData) { |
joshualitt | cdad12f | 2016-02-08 07:08:21 -0800 | [diff] [blame] | 39 | urlData->unref(); |
Mike Klein | cff6396 | 2020-03-14 16:22:45 -0500 | [diff] [blame] | 40 | }); |
joshualitt | cdad12f | 2016-02-08 07:08:21 -0800 | [diff] [blame] | 41 | fCache.rewind(); |
| 42 | } |
Nathaniel Nifong | a14d809 | 2020-01-03 10:29:13 -0500 | [diff] [blame] | 43 | |
| 44 | void UrlDataManager::indexImages(const std::vector<sk_sp<SkImage>>& images) { |
| 45 | SkASSERT(imageMap.size() == 0); // this method meant only for initialization once. |
| 46 | for (size_t i = 0; i < images.size(); ++i) { |
| 47 | imageMap.insert({images[i].get(), i}); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | int UrlDataManager::lookupImage(const SkImage* im) { |
| 52 | auto search = imageMap.find(im); |
| 53 | if (search != imageMap.end()) { |
| 54 | return search->second; |
| 55 | } else { |
| 56 | // -1 signals the pointer to this image wasn't in the original list. |
| 57 | // Maybe it was synthesized after file load? If so, you shouldn't be looking it up here. |
| 58 | return -1; |
| 59 | } |
| 60 | } |