intrusive_heap.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_TASK_COMMON_INTRUSIVE_HEAP_H_
  5. #define BASE_TASK_COMMON_INTRUSIVE_HEAP_H_
  6. #include "base/containers/intrusive_heap.h"
  7. namespace base {
  8. namespace internal {
  9. using HeapHandle = base::HeapHandle;
  10. template <typename T>
  11. struct IntrusiveHeapImpl {
  12. struct GreaterUsingLessEqual {
  13. bool operator()(const T& t1, const T& t2) const { return t2 <= t1; }
  14. };
  15. using type = base::IntrusiveHeap<T, GreaterUsingLessEqual>;
  16. };
  17. // base/task wants a min-heap that uses the <= operator, whereas
  18. // base::IntrusiveHeap is a max-heap by default. This is a very thin adapter
  19. // over that class that exposes minimal functionality required by the
  20. // base/task IntrusiveHeap clients.
  21. template <typename T>
  22. class IntrusiveHeap : private IntrusiveHeapImpl<T>::type {
  23. public:
  24. using IntrusiveHeapImplType = typename IntrusiveHeapImpl<T>::type;
  25. // The majority of sets in the scheduler have 0-3 items in them (a few will
  26. // have perhaps up to 100), so this means we usually only have to allocate
  27. // memory once.
  28. static constexpr size_t kMinimumHeapSize = 4;
  29. IntrusiveHeap() { IntrusiveHeapImplType::reserve(kMinimumHeapSize); }
  30. ~IntrusiveHeap() = default;
  31. IntrusiveHeap& operator=(IntrusiveHeap&& other) = default;
  32. bool empty() const { return IntrusiveHeapImplType::empty(); }
  33. size_t size() const { return IntrusiveHeapImplType::size(); }
  34. void Clear() {
  35. IntrusiveHeapImplType::clear();
  36. IntrusiveHeapImplType::reserve(kMinimumHeapSize);
  37. }
  38. const T& Min() const { return IntrusiveHeapImplType::top(); }
  39. void Pop() { IntrusiveHeapImplType::pop(); }
  40. void insert(T&& element) {
  41. IntrusiveHeapImplType::insert(std::move(element));
  42. }
  43. void erase(HeapHandle handle) { IntrusiveHeapImplType::erase(handle); }
  44. void ReplaceMin(T&& element) {
  45. IntrusiveHeapImplType::ReplaceTop(std::move(element));
  46. }
  47. void ChangeKey(HeapHandle handle, T&& element) {
  48. IntrusiveHeapImplType::Replace(handle, std::move(element));
  49. }
  50. const T& at(HeapHandle handle) const {
  51. return IntrusiveHeapImplType::at(handle);
  52. }
  53. // Caution, mutating the heap invalidates iterators!
  54. const T* begin() const { return IntrusiveHeapImplType::data(); }
  55. const T* end() const { return IntrusiveHeapImplType::data() + size(); }
  56. };
  57. } // namespace internal
  58. } // namespace base
  59. #endif // BASE_TASK_COMMON_INTRUSIVE_HEAP_H_