SweepingAPI.h 1.7 KB

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