Registry.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright 2009 The Android Open Source Project
  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 sk_tools_Registry_DEFINED
  8. #define sk_tools_Registry_DEFINED
  9. #include "include/core/SkTypes.h"
  10. #include "include/private/SkNoncopyable.h"
  11. namespace sk_tools {
  12. /** Template class that registers itself (in the constructor) into a linked-list
  13. and provides a function-pointer. This can be used to auto-register a set of
  14. services, e.g. a set of image codecs.
  15. */
  16. template <typename T> class Registry : SkNoncopyable {
  17. public:
  18. explicit Registry(T value) : fValue(value) {
  19. #ifdef SK_BUILD_FOR_ANDROID
  20. // work-around for double-initialization bug
  21. {
  22. Registry* reg = gHead;
  23. while (reg) {
  24. if (reg == this) {
  25. return;
  26. }
  27. reg = reg->fChain;
  28. }
  29. }
  30. #endif
  31. fChain = gHead;
  32. gHead = this;
  33. }
  34. static const Registry* Head() { return gHead; }
  35. const Registry* next() const { return fChain; }
  36. const T& get() const { return fValue; }
  37. // for (const T& t : sk_tools::Registry<T>::Range()) { process(t); }
  38. struct Range {
  39. struct Iterator {
  40. const Registry* fPtr;
  41. const T& operator*() { return SkASSERT(fPtr), fPtr->get(); }
  42. void operator++() { if (fPtr) { fPtr = fPtr->next(); } }
  43. bool operator!=(const Iterator& other) const { return fPtr != other.fPtr; }
  44. };
  45. Iterator begin() const { return Iterator{Registry::Head()}; }
  46. Iterator end() const { return Iterator{nullptr}; }
  47. };
  48. private:
  49. T fValue;
  50. Registry* fChain;
  51. static Registry* gHead;
  52. };
  53. // The caller still needs to declare an instance of this somewhere
  54. template <typename T> Registry<T>* Registry<T>::gHead;
  55. } // namespace sk_tools
  56. #endif