blob: b047edacbc9f7652cf606f0a4d7ccd60e20b145b [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
11#include "SkChecksum.h"
12#include "SkData.h"
13#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;
36 SkAutoTUnref<SkData> fData;
37 };
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) {
55 return SkChecksum::Murmur3(key.bytes(), key.size());
56 }
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) {
65 return SkChecksum::Murmur3(key.c_str(), strlen(key.c_str()));
66 }
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