SweepingAPI.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
  2. * This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef js_SweepingAPI_h
  6. #define js_SweepingAPI_h
  7. #include "js/HeapAPI.h"
  8. namespace js {
  9. template <typename T>
  10. class WeakCacheBase {};
  11. } // namespace js
  12. namespace JS {
  13. template <typename T> class WeakCache;
  14. namespace shadow {
  15. JS_PUBLIC_API(void)
  16. RegisterWeakCache(JS::Zone* zone, JS::WeakCache<void*>* cachep);
  17. } // namespace shadow
  18. // A WeakCache stores the given Sweepable container and links itself into a
  19. // list of such caches that are swept during each GC.
  20. template <typename T>
  21. class WeakCache : public js::WeakCacheBase<T>,
  22. private mozilla::LinkedListElement<WeakCache<T>>
  23. {
  24. friend class mozilla::LinkedListElement<WeakCache<T>>;
  25. friend class mozilla::LinkedList<WeakCache<T>>;
  26. WeakCache() = delete;
  27. WeakCache(const WeakCache&) = delete;
  28. using SweepFn = void (*)(T*);
  29. SweepFn sweeper;
  30. T cache;
  31. public:
  32. using Type = T;
  33. template <typename U>
  34. WeakCache(Zone* zone, U&& initial)
  35. : cache(mozilla::Forward<U>(initial))
  36. {
  37. sweeper = GCPolicy<T>::sweep;
  38. shadow::RegisterWeakCache(zone, reinterpret_cast<WeakCache<void*>*>(this));
  39. }
  40. WeakCache(WeakCache&& other)
  41. : sweeper(other.sweeper),
  42. cache(mozilla::Move(other.cache))
  43. {
  44. }
  45. const T& get() const { return cache; }
  46. T& get() { return cache; }
  47. void sweep() { sweeper(&cache); }
  48. };
  49. } // namespace JS
  50. #endif // js_SweepingAPI_h