blob: bae1dc7047c73c487b927b264d84d394a503e089 [file] [log] [blame]
joshualittcdad12f2016-02-08 07:08:21 -08001/*
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
8#ifndef SkUrlDataManager_DEFINED
9#define SkUrlDataManager_DEFINED
10
joshualittcdad12f2016-02-08 07:08:21 -080011#include "SkData.h"
mtklein4e976072016-08-08 09:06:27 -070012#include "SkOpts.h"
joshualittcdad12f2016-02-08 07:08:21 -080013#include "SkString.h"
14#include "SkTDynamicHash.h"
15
16/*
17 * A simple class which allows clients to add opaque data types, and returns a url where this data
18 * will be hosted. Its up to the owner of this class to actually serve the data.
19 */
20bool operator==(const SkData& a, const SkData& b);
21
22class UrlDataManager {
23public:
24 UrlDataManager(SkString rootUrl);
25 ~UrlDataManager() { this->reset(); }
26
27 /*
28 * Adds a data blob to the cache with a particular content type. UrlDataManager will hash
29 * the blob data to ensure uniqueness
30 */
31 SkString addData(SkData*, const char* contentType);
32
33 struct UrlData : public SkRefCnt {
34 SkString fUrl;
35 SkString fContentType;
bungemanffae30d2016-08-03 13:32:32 -070036 sk_sp<SkData> fData;
joshualittcdad12f2016-02-08 07:08:21 -080037 };
38
39 /*
40 * returns the UrlData object which should be hosted at 'url'
41 */
42 UrlData* getDataFromUrl(SkString url) {
43 return fUrlLookup.find(url);
44 }
45 void reset();
46
47private:
48 struct LookupTrait {
49 // We use the data as a hash, this is not really optimal but is fine until proven otherwise
50 static const SkData& GetKey(const UrlData& data) {
51 return *data.fData.get();
52 }
53
54 static uint32_t Hash(const SkData& key) {
mtklein4e976072016-08-08 09:06:27 -070055 return SkOpts::hash(key.bytes(), key.size());
joshualittcdad12f2016-02-08 07:08:21 -080056 }
57 };
58
59 struct ReverseLookupTrait {
60 static const SkString& GetKey(const UrlData& data) {
61 return data.fUrl;
62 }
63
64 static uint32_t Hash(const SkString& key) {
mtklein4e976072016-08-08 09:06:27 -070065 return SkOpts::hash(key.c_str(), strlen(key.c_str()));
joshualittcdad12f2016-02-08 07:08:21 -080066 }
67 };
68
69
70 SkString fRootUrl;
71 SkTDynamicHash<UrlData, SkData, LookupTrait> fCache;
72 SkTDynamicHash<UrlData, SkString, ReverseLookupTrait> fUrlLookup;
73 uint32_t fDataId;
74};
75
76#endif