UrlDataManager.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. #ifndef SkUrlDataManager_DEFINED
  8. #define SkUrlDataManager_DEFINED
  9. #include "include/core/SkData.h"
  10. #include "include/core/SkString.h"
  11. #include "src/core/SkOpts.h"
  12. #include "src/core/SkTDynamicHash.h"
  13. /*
  14. * A simple class which allows clients to add opaque data types, and returns a url where this data
  15. * will be hosted. Its up to the owner of this class to actually serve the data.
  16. */
  17. bool operator==(const SkData& a, const SkData& b);
  18. class UrlDataManager {
  19. public:
  20. UrlDataManager(SkString rootUrl);
  21. ~UrlDataManager() { this->reset(); }
  22. /*
  23. * Adds a data blob to the cache with a particular content type. UrlDataManager will hash
  24. * the blob data to ensure uniqueness
  25. */
  26. SkString addData(SkData*, const char* contentType);
  27. struct UrlData : public SkRefCnt {
  28. SkString fUrl;
  29. SkString fContentType;
  30. sk_sp<SkData> fData;
  31. };
  32. /*
  33. * returns the UrlData object which should be hosted at 'url'
  34. */
  35. UrlData* getDataFromUrl(SkString url) {
  36. return fUrlLookup.find(url);
  37. }
  38. void reset();
  39. private:
  40. struct LookupTrait {
  41. // We use the data as a hash, this is not really optimal but is fine until proven otherwise
  42. static const SkData& GetKey(const UrlData& data) {
  43. return *data.fData.get();
  44. }
  45. static uint32_t Hash(const SkData& key) {
  46. return SkOpts::hash(key.bytes(), key.size());
  47. }
  48. };
  49. struct ReverseLookupTrait {
  50. static const SkString& GetKey(const UrlData& data) {
  51. return data.fUrl;
  52. }
  53. static uint32_t Hash(const SkString& key) {
  54. return SkOpts::hash(key.c_str(), strlen(key.c_str()));
  55. }
  56. };
  57. SkString fRootUrl;
  58. SkTDynamicHash<UrlData, SkData, LookupTrait> fCache;
  59. SkTDynamicHash<UrlData, SkString, ReverseLookupTrait> fUrlLookup;
  60. uint32_t fDataId;
  61. };
  62. #endif