| 6 | #define BASE_CONTAINERS_INTRUSIVE_HEAP_H_ |
| 7 |
| 8 | // Implements a standard max-heap, but with arbitrary element removal. To |
| 9 | // facilitate this, each element has associated with it a HeapHandle (an opaque |
| 10 | // wrapper around the index at which the element is stored), which is maintained |
| 11 | // by the heap as elements move within it. |
| 12 | // |
| 13 | // An IntrusiveHeap is implemented as a standard max-heap over a std::vector<T>, |
| 14 | // like std::make_heap. Insertion, removal and updating are amortized O(lg size) |
| 15 | // (occasional O(size) cost if a new vector allocation is required). Retrieving |
| 16 | // an element by handle is O(1). Looking up the top element is O(1). Insertions, |
| 17 | // removals and updates invalidate all iterators, but handles remain valid. |
| 18 | // Similar to a std::set, all iterators are read-only so as to disallow changing |
| 19 | // elements and violating the heap property. That being said, if the type you |
| 20 | // are storing is able to have its sort key be changed externally you can |
| 21 | // repair the heap by resorting the modified element via a call to "Update". |
| 22 | // |
| 23 | // Example usage: |
| 24 | // |
| 25 | // // Create a heap, wrapping integer elements with WithHeapHandle in order to |
| 26 | // // endow them with heap handles. |
| 27 | // IntrusiveHeap<WithHeapHandle<int>> heap; |
| 28 | // |
| 29 | // // WithHeapHandle<T> is for simple or opaque types. In cases where you |
| 30 | // // control the type declaration you can also provide HeapHandle storage by |
| 31 | // // deriving from InternalHeapHandleStorage. |
| 32 | // class Foo : public InternalHeapHandleStorage { |
| 33 | // public: |
| 34 | // explicit Foo(int); |
| 35 | // ... |
| 36 | // }; |
| 37 | // IntrusiveHeap<Foo> heap2; |
| 38 | // |
| 39 | // // Insert some elements. Like most containers, "insert" returns an iterator |
| 40 | // // to the element in the container. |
| 41 | // heap.insert(3); |
| 42 | // heap.insert(1); |
| 43 | // auto it = heap.insert(4); |
| 44 | // |
| 45 | // // By default this is a max heap, so the top element should be 4 at this |
| 46 | // // point. |
| 47 | // EXPECT_EQ(4, heap.top().value()); |
| 48 | // |
| 49 | // // Iterators are invalidated by further heap operations, but handles are |
| 50 | // // not. Grab a handle to the current top element so we can track it across |
| 51 | // // changes. |
| 52 | // HeapHandle* handle = it->handle(); |
| 53 | // |
| 54 | // // Insert a new max element. 4 should no longer be the top. |
| 55 | // heap.insert(5); |
| 56 | // EXPECT_EQ(5, heap.top().value()); |
| 57 | // |
| 58 | // // We can lookup and erase element 4 by its handle, even though it has |
| 59 | // // moved. Note that erasing the element invalidates the handle to it. |
| 60 | // EXPECT_EQ(4, heap.at(*handle).value()); |
| 61 | // heap.erase(*handle); |
| 62 | // handle = nullptr; |
| 63 | // |
| 64 | // // Popping the current max (5), makes 3 the new max, as we already erased |
| 65 | // // element 4. |
| 66 | // heap.pop(); |
| 67 | // EXPECT_EQ(3, heap.top().value()); |
| 68 | // |
| 69 | // Under the hood the HeapHandle is managed by an object implementing the |
| 70 | // HeapHandleAccess interface, which is passed as a parameter to the |
| 71 | // IntrusiveHeap template: |
| 72 | // |
| 73 | // // Gets the heap handle associated with the element. This should return the |
| 74 | // // most recently set handle value, or HeapHandle::Invalid(). This is only |
| 75 | // // called in DCHECK builds. |
| 76 | // HeapHandle GetHeapHandle(const T*); |
| 77 | // |
| 78 | // // Changes the result of GetHeapHandle. GetHeapHandle() must return the |
| 79 | // // most recent value provided to SetHeapHandle() or HeapHandle::Invalid(). |
| 80 | // // In some implementations, where GetHeapHandle() can independently |
| 81 | // // reproduce the correct value, it is possible that SetHeapHandle() does |
| 82 | // // nothing. |
| 83 | // void SetHeapHandle(T*, HeapHandle); |
| 84 | // |
| 85 | // // Clears the heap handle associated with the given element. After calling |
| 86 | // // this GetHeapHandle() must return HeapHandle::Invalid(). |
| 87 | // void ClearHeapHandle(T*); |
| 88 | // |
| 89 | // The default implementation of HeapHandleAccess assumes that your type |
| 90 | // provides HeapHandle storage and will simply forward these calls to equivalent |
| 91 | // member functions on the type T: |
| 92 | // |
| 93 | // void T::SetHeapHandle(HeapHandle) |
| 94 | // void T::ClearHeapHandle() |
| 95 | // HeapHandle T::GetHeapHandle() const |
| 96 | // |
| 97 | // The WithHeapHandle and InternalHeapHandleStorage classes in turn provide |
| 98 | // implementations of that contract. |
| 99 | // |
| 100 | // In summary, to provide heap handle support for your type, you can do one of |
| 101 | // the following (from most manual / least magical, to least manual / most |
| 102 | // magical): |
| 103 | // |
| 104 | // 0. use a custom HeapHandleAccessor, and implement storage however you want; |
| 105 | // 1. use the default HeapHandleAccessor, and manually provide storage on your |
| 106 | // your element type and implement the IntrusiveHeap contract; |
| 107 | // 2. use the default HeapHandleAccessor, and endow your type with handle |
| 108 | // storage by deriving from a helper class (see InternalHeapHandleStorage); |
| 109 | // or, |
| 110 | // 3. use the default HeapHandleAccessor, and wrap your type in a container that |
| 111 | // provides handle storage (see WithHeapHandle<T>). |
| 112 | // |
| 113 | // Approach 0 is suitable for custom types that already implement something akin |
| 114 | // to heap handles, via back pointers or any other mechanism, but where the |
| 115 | // storage is external to the objects in the heap. If you already have the |
| 116 | // ability to determine where in a container an object lives despite it |
| 117 | // being moved, then you don't need the overhead of storing an actual HeapHandle |
| 118 | // whose value can be inferred. |
| 119 | // |
| 120 | // Approach 1 is is suitable in cases like the above, but where the data |
| 121 | // allowing you to determine the index of an element in a container is stored |
| 122 | // directly in the object itself. |
| 123 | // |
| 124 | // Approach 2 is suitable for types whose declarations you control, where you |
| 125 | // are able to use inheritance. |
| 126 | // |
| 127 | // Finally, approach 3 is suitable when you are storing PODs, or a type whose |
| 128 | // declaration you can not change. |
| 129 | // |
| 130 | // Most users should be using approach 2 or 3. |
| 131 |
| 132 | #include <algorithm> |
| 133 | #include <functional> |
| 134 | #include <limits> |
| 135 | #include <type_traits> |
| 136 | #include <utility> |
| 137 | #include <vector> |
| 138 |
| 139 | #include "base/base_export.h" |
| 140 | #include "base/logging.h" |
| 141 | #include "base/macros.h" |
| 142 | #include "base/memory/ptr_util.h" |
| 143 |
| 144 | namespace base { |
| 145 |
| 146 | // Intended as a wrapper around an |index_| in the vector storage backing an |
| 147 | // IntrusiveHeap. A HeapHandle is associated with each element in an |
| 148 | // IntrusiveHeap, and is maintained by the heap as the object moves around |
| 149 | // within it. It can be used to subsequently remove the element, or update it |
| 150 | // in place. |
| 151 | class BASE_EXPORT HeapHandle { |
| 152 | public: |
| 153 | enum : size_t { kInvalidIndex = std::numeric_limits<size_t>::max() }; |
| 154 |
| 155 | constexpr HeapHandle() = default; |
| 156 | constexpr HeapHandle(const HeapHandle& other) = default; |
| 157 | HeapHandle(HeapHandle&& other) noexcept |
| 158 | : index_(std::exchange(other.index_, kInvalidIndex)) {} |
| 159 | ~HeapHandle() = default; |
| 160 |
| 161 | HeapHandle& operator=(const HeapHandle& other) = default; |
| 162 | HeapHandle& operator=(HeapHandle&& other) noexcept { |
| 163 | index_ = std::exchange(other.index_, kInvalidIndex); |
| 164 | return *this; |
| 165 | } |
| 166 |
| 167 | static HeapHandle Invalid(); |
| 168 |
| 169 | // Resets this handle back to an invalid state. |
| 170 | void reset() { index_ = kInvalidIndex; } |
| 171 |
| 172 | // Accessors. |
| 173 | size_t index() const { return index_; } |
| 174 | bool IsValid() const { return index_ != kInvalidIndex; } |
| 175 |
| 176 | // Comparison operators. |
| 177 | friend bool operator==(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 178 | return lhs.index_ == rhs.index_; |
| 179 | } |
| 180 | friend bool operator!=(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 181 | return lhs.index_ != rhs.index_; |
| 182 | } |
| 183 | friend bool operator<(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 184 | return lhs.index_ < rhs.index_; |
| 185 | } |
| 186 | friend bool operator>(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 187 | return lhs.index_ > rhs.index_; |
| 188 | } |
| 189 | friend bool operator<=(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 190 | return lhs.index_ <= rhs.index_; |
| 191 | } |
| 192 | friend bool operator>=(const HeapHandle& lhs, const HeapHandle& rhs) { |
| 193 | return lhs.index_ >= rhs.index_; |
| 194 | } |
| 195 |
| 196 | private: |
| 197 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 198 | friend class IntrusiveHeap; |
| 199 |
| 200 | // Only IntrusiveHeaps can create valid HeapHandles. |
| 201 | explicit HeapHandle(size_t index) : index_(index) {} |
| 202 |
| 203 | size_t index_ = kInvalidIndex; |
| 204 | }; |
| 205 |
| 206 | // The default HeapHandleAccessor, which simply forwards calls to the underlying |
| 207 | // type. |
| 208 | template <typename T> |
| 209 | struct DefaultHeapHandleAccessor { |
| 210 | void SetHeapHandle(T* element, HeapHandle handle) const { |
| 211 | element->SetHeapHandle(handle); |
| 212 | } |
| 213 |
| 214 | void ClearHeapHandle(T* element) const { element->ClearHeapHandle(); } |
| 215 |
| 216 | HeapHandle GetHeapHandle(const T* element) const { |
| 217 | return element->GetHeapHandle(); |
| 218 | } |
| 219 | }; |
| 220 |
| 221 | // Intrusive heap class. This is something like a std::vector (insertion and |
| 222 | // removal are similar, objects don't have a fixed address in memory) crossed |
| 223 | // with a std::set (elements are considered immutable once they're in the |
| 224 | // container). |
| 225 | template <typename T, |
| 226 | typename Compare = std::less<T>, |
| 227 | typename HeapHandleAccessor = DefaultHeapHandleAccessor<T>> |
| 228 | class IntrusiveHeap { |
| 229 | private: |
| 230 | using UnderlyingType = std::vector<T>; |
| 231 |
| 232 | public: |
| 233 | ////////////////////////////////////////////////////////////////////////////// |
| 234 | // Types. |
| 235 |
| 236 | using value_type = typename UnderlyingType::value_type; |
| 237 | using size_type = typename UnderlyingType::size_type; |
| 238 | using difference_type = typename UnderlyingType::difference_type; |
| 239 | using value_compare = Compare; |
| 240 | using heap_handle_accessor = HeapHandleAccessor; |
| 241 |
| 242 | using reference = typename UnderlyingType::reference; |
| 243 | using const_reference = typename UnderlyingType::const_reference; |
| 244 | using pointer = typename UnderlyingType::pointer; |
| 245 | using const_pointer = typename UnderlyingType::const_pointer; |
| 246 |
| 247 | // Iterators are read-only. |
| 248 | using iterator = typename UnderlyingType::const_iterator; |
| 249 | using const_iterator = typename UnderlyingType::const_iterator; |
| 250 | using reverse_iterator = typename UnderlyingType::const_reverse_iterator; |
| 251 | using const_reverse_iterator = |
| 252 | typename UnderlyingType::const_reverse_iterator; |
| 253 |
| 254 | ////////////////////////////////////////////////////////////////////////////// |
| 255 | // Lifetime. |
| 256 |
| 257 | IntrusiveHeap() = default; |
| 258 | IntrusiveHeap(const value_compare& comp, const heap_handle_accessor& access) |
| 259 | : impl_(comp, access) {} |
| 260 |
| 261 | template <class InputIterator> |
| 262 | IntrusiveHeap(InputIterator first, |
| 263 | InputIterator last, |
| 264 | const value_compare& comp = value_compare(), |
| 265 | const heap_handle_accessor& access = heap_handle_accessor()) |
| 266 | : impl_(comp, access) { |
| 267 | insert(first, last); |
| 268 | } |
| 269 |
| 270 | // Moves an intrusive heap. The outstanding handles remain valid and end up |
| 271 | // pointing to the new heap. |
| 272 | IntrusiveHeap(IntrusiveHeap&& other) = default; |
| 273 |
| 274 | // Copy constructor for an intrusive heap. |
| 275 | IntrusiveHeap(const IntrusiveHeap&); |
| 276 |
| 277 | // Initializer list constructor. |
| 278 | template <typename U> |
| 279 | IntrusiveHeap(std::initializer_list<U> ilist, |
| 280 | const value_compare& comp = value_compare(), |
| 281 | const heap_handle_accessor& access = heap_handle_accessor()) |
| 282 | : impl_(comp, access) { |
| 283 | insert(std::begin(ilist), std::end(ilist)); |
| 284 | } |
| 285 |
| 286 | ~IntrusiveHeap(); |
| 287 |
| 288 | ////////////////////////////////////////////////////////////////////////////// |
| 289 | // Assignment. |
| 290 |
| 291 | IntrusiveHeap& operator=(IntrusiveHeap&&) noexcept; |
| 292 | IntrusiveHeap& operator=(const IntrusiveHeap&); |
| 293 | IntrusiveHeap& operator=(std::initializer_list<value_type> ilist); |
| 294 |
| 295 | ////////////////////////////////////////////////////////////////////////////// |
| 296 | // Element access. |
| 297 | // |
| 298 | // These provide O(1) const access to the elements in the heap. If you wish to |
| 299 | // modify an element in the heap you should first remove it from the heap, and |
| 300 | // then reinsert it into the heap, or use the "Replace*" helper functions. In |
| 301 | // the rare case where you directly modify an element in the heap you can |
| 302 | // subsequently repair the heap with "Update". |
| 303 |
| 304 | const_reference at(size_type pos) const { return impl_.heap_.at(pos); } |
| 305 | const_reference at(HeapHandle pos) const { |
| 306 | return impl_.heap_.at(pos.index()); |
| 307 | } |
| 308 | const_reference operator[](size_type pos) const { return impl_.heap_[pos]; } |
| 309 | const_reference operator[](HeapHandle pos) const { |
| 310 | return impl_.heap_[pos.index()]; |
| 311 | } |
| 312 | const_reference front() const { return impl_.heap_.front(); } |
| 313 | const_reference back() const { return impl_.heap_.back(); } |
| 314 | const_reference top() const { return impl_.heap_.front(); } |
| 315 |
| 316 | // May or may not return a null pointer if size() is zero. |
| 317 | const_pointer data() const { return impl_.heap_.data(); } |
| 318 |
| 319 | ////////////////////////////////////////////////////////////////////////////// |
| 320 | // Memory management. |
| 321 |
| 322 | void reserve(size_type new_capacity) { impl_.heap_.reserve(new_capacity); } |
| 323 | size_type capacity() const { return impl_.heap_.capacity(); } |
| 324 | void shrink_to_fit() { impl_.heap_.shrink_to_fit(); } |
| 325 |
| 326 | ////////////////////////////////////////////////////////////////////////////// |
| 327 | // Size management. |
| 328 |
| 329 | void clear(); |
| 330 | size_type size() const { return impl_.heap_.size(); } |
| 331 | size_type max_size() const { return impl_.heap_.max_size(); } |
| 332 | bool empty() const { return impl_.heap_.empty(); } |
| 333 |
| 334 | ////////////////////////////////////////////////////////////////////////////// |
| 335 | // Iterators. |
| 336 | // |
| 337 | // Only constant iterators are allowed. |
| 338 |
| 339 | const_iterator begin() const { return impl_.heap_.cbegin(); } |
| 340 | const_iterator cbegin() const { return impl_.heap_.cbegin(); } |
| 341 |
| 342 | const_iterator end() const { return impl_.heap_.cend(); } |
| 343 | const_iterator cend() const { return impl_.heap_.cend(); } |
| 344 |
| 345 | const_reverse_iterator rbegin() const { return impl_.heap_.crbegin(); } |
| 346 | const_reverse_iterator crbegin() const { return impl_.heap_.crbegin(); } |
| 347 |
| 348 | const_reverse_iterator rend() const { return impl_.heap_.crend(); } |
| 349 | const_reverse_iterator crend() const { return impl_.heap_.crend(); } |
| 350 |
| 351 | ////////////////////////////////////////////////////////////////////////////// |
| 352 | // Insertion (these are std::multiset like, with no position hints). |
| 353 | // |
| 354 | // All insertion operations invalidate iterators, pointers and references. |
| 355 | // Handles remain valid. Insertion of one element is amortized O(lg size) |
| 356 | // (occasional O(size) cost if a new vector allocation is required). |
| 357 |
| 358 | const_iterator insert(const value_type& value) { return InsertImpl(value); } |
| 359 | const_iterator insert(value_type&& value) { |
| 360 | return InsertImpl(std::move_if_noexcept(value)); |
| 361 | } |
| 362 |
| 363 | template <class InputIterator> |
| 364 | void insert(InputIterator first, InputIterator last); |
| 365 |
| 366 | template <typename... Args> |
| 367 | const_iterator emplace(Args&&... args); |
| 368 |
| 369 | ////////////////////////////////////////////////////////////////////////////// |
| 370 | // Removing elements. |
| 371 | // |
| 372 | // Erasing invalidates all outstanding iterators, pointers and references. |
| 373 | // Handles remain valid. Removing one element is amortized O(lg size) |
| 374 | // (occasional O(size) cost if a new vector allocation is required). |
| 375 | // |
| 376 | // Note that it is safe for the element being removed to be in an invalid |
| 377 | // state (modified such that it may currently violate the heap property) |
| 378 | // when this called. |
| 379 |
| 380 | // Takes the element from the heap at the given position, erasing that entry |
| 381 | // from the heap. This can only be called if |value_type| is movable. |
| 382 | value_type take(size_type pos); |
| 383 |
| 384 | // Version of take that will accept iterators and handles. This can only be |
| 385 | // called if |value_type| is movable. |
| 386 | template <typename P> |
| 387 | value_type take(P pos) { |
| 388 | return take(ToIndex(pos)); |
| 389 | } |
| 390 |
| 391 | // Takes the top element from the heap. |
| 392 | value_type take_top() { return take(0u); } |
| 393 |
| 394 | // Erases the element at the given position |pos|. |
| 395 | void erase(size_type pos); |
| 396 |
| 397 | // Version of erase that will accept iterators and handles. |
| 398 | template <typename P> |
| 399 | void erase(P pos) { |
| 400 | erase(ToIndex(pos)); |
| 401 | } |
| 402 |
| 403 | // Removes the element at the top of the heap (accessible via "top", or |
| 404 | // "front" or "take"). |
| 405 | void pop() { erase(0u); } |
| 406 |
| 407 | ////////////////////////////////////////////////////////////////////////////// |
| 408 | // Updating. |
| 409 | // |
| 410 | // Amortized cost of O(lg size). |
| 411 |
| 412 | // Replaces the element corresponding to |handle| with a new |element|. |
| 413 | const_iterator Replace(size_type pos, const T& element) { |
| 414 | return ReplaceImpl(pos, element); |
| 415 | } |
| 416 | const_iterator Replace(size_type pos, T&& element) { |
| 417 | return ReplaceImpl(pos, std::move_if_noexcept(element)); |
| 418 | } |
| 419 |
| 420 | // Versions of Replace that will accept handles and iterators. |
| 421 | template <typename P> |
| 422 | const_iterator Replace(P pos, const T& element) { |
| 423 | return ReplaceImpl(ToIndex(pos), element); |
| 424 | } |
| 425 | template <typename P> |
| 426 | const_iterator Replace(P pos, T&& element) { |
| 427 | return ReplaceImpl(ToIndex(pos), std::move_if_noexcept(element)); |
| 428 | } |
| 429 |
| 430 | // Replaces the top element in the heap with the provided element. |
| 431 | const_iterator ReplaceTop(const T& element) { |
| 432 | return ReplaceTopImpl(element); |
| 433 | } |
| 434 | const_iterator ReplaceTop(T&& element) { |
| 435 | return ReplaceTopImpl(std::move_if_noexcept(element)); |
| 436 | } |
| 437 |
| 438 | // Causes the object at the given location to be resorted into an appropriate |
| 439 | // position in the heap. To be used if the object in the heap was externally |
| 440 | // modified, and the heap needs to be repaired. This only works if a single |
| 441 | // heap element has been modified, otherwise the behaviour is undefined. |
| 442 | const_iterator Update(size_type pos); |
| 443 | template <typename P> |
| 444 | const_iterator Update(P pos) { |
| 445 | return Update(ToIndex(pos)); |
| 446 | } |
| 447 |
| 448 | ////////////////////////////////////////////////////////////////////////////// |
| 449 | // Access to helper functors. |
| 450 |
| 451 | const value_compare& value_comp() const { return impl_.get_value_compare(); } |
| 452 |
| 453 | const heap_handle_accessor& heap_handle_access() const { |
| 454 | return impl_.get_heap_handle_access(); |
| 455 | } |
| 456 |
| 457 | ////////////////////////////////////////////////////////////////////////////// |
| 458 | // General operations. |
| 459 |
| 460 | void swap(IntrusiveHeap& other) noexcept; |
| 461 | friend void swap(IntrusiveHeap& lhs, IntrusiveHeap& rhs) { lhs.swap(rhs); } |
| 462 |
| 463 | // Comparison operators. These check for exact equality. Two heaps that are |
| 464 | // semantically equivalent (contain the same elements, but in different |
| 465 | // orders) won't compare as equal using these operators. |
| 466 | friend bool operator==(const IntrusiveHeap& lhs, const IntrusiveHeap& rhs) { |
| 467 | return lhs.impl_.heap_ == rhs.impl_.heap_; |
| 468 | } |
| 469 | friend bool operator!=(const IntrusiveHeap& lhs, const IntrusiveHeap& rhs) { |
| 470 | return lhs.impl_.heap_ != rhs.impl_.heap_; |
| 471 | } |
| 472 |
| 473 | ////////////////////////////////////////////////////////////////////////////// |
| 474 | // Utility functions. |
| 475 |
| 476 | // Converts iterators and handles to indices. Helpers for templated versions |
| 477 | // of insert/erase/Replace. |
| 478 | size_type ToIndex(HeapHandle handle) { return handle.index(); } |
| 479 | size_type ToIndex(const_iterator pos); |
| 480 | size_type ToIndex(const_reverse_iterator pos); |
| 481 |
| 482 | private: |
| 483 | // Templated version of ToIndex that lets insert/erase/Replace work with all |
| 484 | // integral types. |
| 485 | template <typename I, typename = std::enable_if_t<std::is_integral<I>::value>> |
| 486 | size_type ToIndex(I pos) { |
| 487 | return static_cast<size_type>(pos); |
| 488 | } |
| 489 |
| 490 | // Returns the last valid index in |heap_|. |
| 491 | size_type GetLastIndex() const { return impl_.heap_.size() - 1; } |
| 492 |
| 493 | // Helper functions for setting heap handles. |
| 494 | void SetHeapHandle(size_type i); |
| 495 | void ClearHeapHandle(size_type i); |
| 496 | HeapHandle GetHeapHandle(size_type i); |
| 497 |
| 498 | // Helpers for doing comparisons between elements inside and outside of the |
| 499 | // heap. |
| 500 | bool Less(size_type i, size_type j); |
| 501 | bool Less(const T& element, size_type i); |
| 502 | bool Less(size_type i, const T& element); |
| 503 |
| 504 | // The following function are all related to the basic heap algorithm |
| 505 | // underpinning this data structure. They are templated so that they work with |
| 506 | // both movable (U = T&&) and non-movable (U = const T&) types. |
| 507 |
| 508 | // Primitive helpers for adding removing / elements to the heap. To minimize |
| 509 | // moves, the heap is implemented by making a hole where an element used to |
| 510 | // be (or where a new element will soon be), and moving the hole around, |
| 511 | // before finally filling the hole or deleting the entry corresponding to the |
| 512 | // hole. |
| 513 | void MakeHole(size_type pos); |
| 514 | template <typename U> |
| 515 | void FillHole(size_type hole, U element); |
| 516 | void MoveHole(size_type new_hole_pos, size_type old_hole_pos); |
| 517 |
| 518 | // Moves a hold up the tree and fills it with the provided |element|. Returns |
| 519 | // the final index of the element. |
| 520 | template <typename U> |
| 521 | size_type MoveHoleUpAndFill(size_type hole_pos, U element); |
| 522 |
| 523 | // Moves a hole down the tree and fills it with the provided |element|. If |
| 524 | // |kFillWithLeaf| is true it will deterministically move the hole all the |
| 525 | // way down the tree, avoiding a second comparison per level, before |
| 526 | // potentially moving it back up the tree. |
| 527 | struct WithLeafElement { |
| 528 | static constexpr bool kIsLeafElement = true; |
| 529 | }; |
| 530 | struct WithElement { |
| 531 | static constexpr bool kIsLeafElement = false; |
| 532 | }; |
| 533 | template <typename FillElementType, typename U> |
| 534 | size_type MoveHoleDownAndFill(size_type hole_pos, U element); |
| 535 |
| 536 | // Implementation of Insert and Replace built on top of the MoveHole |
| 537 | // primitives. |
| 538 | template <typename U> |
| 539 | const_iterator InsertImpl(U element); |
| 540 | template <typename U> |
| 541 | const_iterator ReplaceImpl(size_type pos, U element); |
| 542 | template <typename U> |
| 543 | const_iterator ReplaceTopImpl(U element); |
| 544 |
| 545 | // To support comparators that may not be possible to default-construct, we |
| 546 | // have to store an instance of value_compare. Using this to store all |
| 547 | // internal state of IntrusiveHeap and using private inheritance to store |
| 548 | // compare lets us take advantage of an empty base class optimization to avoid |
| 549 | // extra space in the common case when Compare has no state. |
| 550 | struct Impl : private value_compare, private heap_handle_accessor { |
| 551 | Impl(const value_compare& value_comp, |
| 552 | const heap_handle_accessor& heap_handle_access) |
| 553 | : value_compare(value_comp), heap_handle_accessor(heap_handle_access) {} |
| 554 |
| 555 | Impl() = default; |
| 556 | Impl(Impl&&) = default; |
| 557 | Impl(const Impl&) = default; |
| 558 | Impl& operator=(Impl&& other) = default; |
| 559 | Impl& operator=(const Impl& other) = default; |
| 560 |
| 561 | const value_compare& get_value_compare() const { return *this; } |
| 562 | value_compare& get_value_compare() { return *this; } |
| 563 |
| 564 | const heap_handle_accessor& get_heap_handle_access() const { return *this; } |
| 565 | heap_handle_accessor& get_heap_handle_access() { return *this; } |
| 566 |
| 567 | // The items in the heap. |
| 568 | UnderlyingType heap_; |
| 569 | } impl_; |
| 570 | }; |
| 571 |
| 572 | // Helper class to endow an object with internal HeapHandle storage. By deriving |
| 573 | // from this type you endow your class with self-owned storage for a HeapHandle. |
| 574 | // This is a move-only type so that the handle follows the element across moves |
| 575 | // and resizes of the underlying vector. |
| 576 | class BASE_EXPORT InternalHeapHandleStorage { |
| 577 | public: |
| 578 | InternalHeapHandleStorage(); |
| 579 | InternalHeapHandleStorage(const InternalHeapHandleStorage&) = delete; |
| 580 | InternalHeapHandleStorage(InternalHeapHandleStorage&& other) noexcept; |
| 581 | virtual ~InternalHeapHandleStorage(); |
| 582 |
| 583 | InternalHeapHandleStorage& operator=(const InternalHeapHandleStorage&) = |
| 584 | delete; |
| 585 | InternalHeapHandleStorage& operator=( |
| 586 | InternalHeapHandleStorage&& other) noexcept; |
| 587 |
| 588 | // Allows external clients to get a pointer to the heap handle. This allows |
| 589 | // them to remove the element from the heap regardless of its location. |
| 590 | HeapHandle* handle() const { return handle_.get(); } |
| 591 |
| 592 | // Implementation of IntrusiveHeap contract. Inlined to keep heap code as fast |
| 593 | // as possible. |
| 594 | void SetHeapHandle(HeapHandle handle) { |
| 595 | DCHECK(handle.IsValid()); |
| 596 | if (handle_) |
| 597 | *handle_ = handle; |
| 598 | } |
| 599 | void ClearHeapHandle() { |
| 600 | if (handle_) |
| 601 | handle_->reset(); |
| 602 | } |
| 603 | HeapHandle GetHeapHandle() const { |
| 604 | if (handle_) |
| 605 | return *handle_; |
| 606 | return HeapHandle::Invalid(); |
| 607 | } |
| 608 |
| 609 | // Utility functions. |
| 610 | void swap(InternalHeapHandleStorage& other) noexcept; |
| 611 | friend void swap(InternalHeapHandleStorage& lhs, |
| 612 | InternalHeapHandleStorage& rhs) { |
| 613 | lhs.swap(rhs); |
| 614 | } |
| 615 |
| 616 | private: |
| 617 | std::unique_ptr<HeapHandle> handle_; |
| 618 | }; |
| 619 |
| 620 | // Spiritually akin to a std::pair<T, std::unique_ptr<HeapHandle>>. Can be used |
| 621 | // to wrap arbitrary types and provide them with a HeapHandle, making them |
| 622 | // appropriate for use in an IntrusiveHeap. This is a move-only type. |
| 623 | template <typename T> |
| 624 | class WithHeapHandle : public InternalHeapHandleStorage { |
| 625 | public: |
| 626 | WithHeapHandle() = default; |
| 627 | // Allow implicit conversion of any type that T supports for ease of use with |
| 628 | // InstrusiveHeap constructors/insert/emplace. |
| 629 | template <typename U> |
| 630 | WithHeapHandle(U value) : value_(std::move_if_noexcept(value)) {} |
| 631 | WithHeapHandle(T&& value) noexcept : value_(std::move(value)) {} |
| 632 | // Constructor that forwards all arguments along to |value_|. |
| 633 | template <class... Args> |
| 634 | explicit WithHeapHandle(Args&&... args); |
| 635 | WithHeapHandle(const WithHeapHandle&) = delete; |
| 636 | WithHeapHandle(WithHeapHandle&& other) noexcept = default; |
| 637 | ~WithHeapHandle() override = default; |
| 638 |
| 639 | WithHeapHandle& operator=(const WithHeapHandle&) = delete; |
| 640 | WithHeapHandle& operator=(WithHeapHandle&& other) = default; |
| 641 |
| 642 | T& value() { return value_; } |
| 643 | const T& value() const { return value_; } |
| 644 |
| 645 | // Utility functions. |
| 646 | void swap(WithHeapHandle& other) noexcept; |
| 647 | friend void swap(WithHeapHandle& lhs, WithHeapHandle& rhs) { lhs.swap(rhs); } |
| 648 |
| 649 | // Comparison operators, for compatibility with ordered STL containers. |
| 650 | friend bool operator==(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 651 | return lhs.value_ == rhs.value_; |
| 652 | } |
| 653 | friend bool operator!=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 654 | return lhs.value_ != rhs.value_; |
| 655 | } |
| 656 | friend bool operator<=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 657 | return lhs.value_ <= rhs.value_; |
| 658 | } |
| 659 | friend bool operator<(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 660 | return lhs.value_ < rhs.value_; |
| 661 | } |
| 662 | friend bool operator>=(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 663 | return lhs.value_ >= rhs.value_; |
| 664 | } |
| 665 | friend bool operator>(const WithHeapHandle& lhs, const WithHeapHandle& rhs) { |
| 666 | return lhs.value_ > rhs.value_; |
| 667 | } |
| 668 |
| 669 | private: |
| 670 | T value_; |
| 671 | }; |
| 672 |
| 673 | //////////////////////////////////////////////////////////////////////////////// |
| 674 | // IMPLEMENTATION DETAILS |
| 675 |
| 676 | namespace intrusive_heap { |
| 677 |
| 678 | BASE_EXPORT inline size_t ParentIndex(size_t i) { |
| 679 | DCHECK_NE(0u, i); |
| 680 | return (i - 1) / 2; |
| 681 | } |
| 682 |
| 683 | BASE_EXPORT inline size_t LeftIndex(size_t i) { |
| 684 | return 2 * i + 1; |
| 685 | } |
| 686 |
| 687 | template <typename HandleType> |
| 688 | bool IsInvalid(const HandleType& handle) { |
| 689 | return !handle || !handle->IsValid(); |
| 690 | } |
| 691 |
| 692 | BASE_EXPORT inline void CheckInvalidOrEqualTo(HeapHandle handle, size_t index) { |
| 693 | if (handle.IsValid()) |
| 694 | DCHECK_EQ(index, handle.index()); |
| 695 | } |
| 696 |
| 697 | } // namespace intrusive_heap |
| 698 |
| 699 | //////////////////////////////////////////////////////////////////////////////// |
| 700 | // IntrusiveHeap |
| 701 |
| 702 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 703 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::IntrusiveHeap( |
| 704 | const IntrusiveHeap& other) |
| 705 | : impl_(other.impl_) { |
| 706 | for (size_t i = 0; i < size(); ++i) { |
| 707 | SetHeapHandle(i); |
| 708 | } |
| 709 | } |
| 710 |
| 711 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 712 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::~IntrusiveHeap() { |
| 713 | clear(); |
| 714 | } |
| 715 |
| 716 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 717 | IntrusiveHeap<T, Compare, HeapHandleAccessor>& |
| 718 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( |
| 719 | IntrusiveHeap&& other) noexcept { |
| 720 | clear(); |
| 721 | impl_ = std::move(other.impl_); |
| 722 | return *this; |
| 723 | } |
| 724 |
| 725 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 726 | IntrusiveHeap<T, Compare, HeapHandleAccessor>& |
| 727 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( |
| 728 | const IntrusiveHeap& other) { |
| 729 | clear(); |
| 730 | impl_ = other.impl_; |
| 731 | for (size_t i = 0; i < size(); ++i) { |
| 732 | SetHeapHandle(i); |
| 733 | } |
| 734 | return *this; |
| 735 | } |
| 736 |
| 737 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 738 | IntrusiveHeap<T, Compare, HeapHandleAccessor>& |
| 739 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::operator=( |
| 740 | std::initializer_list<value_type> ilist) { |
| 741 | clear(); |
| 742 | insert(std::begin(ilist), std::end(ilist)); |
| 743 | } |
| 744 |
| 745 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 746 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::clear() { |
| 747 | // Make all of the handles invalid before cleaning up the heap. |
| 748 | for (size_type i = 0; i < size(); ++i) { |
| 749 | ClearHeapHandle(i); |
| 750 | } |
| 751 |
| 752 | // Clear the heap. |
| 753 | impl_.heap_.clear(); |
| 754 | } |
| 755 |
| 756 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 757 | template <class InputIterator> |
| 758 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::insert(InputIterator first, |
| 759 | InputIterator last) { |
| 760 | for (auto it = first; it != last; ++it) { |
| 761 | insert(value_type(*it)); |
| 762 | } |
| 763 | } |
| 764 |
| 765 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 766 | template <typename... Args> |
| 767 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator |
| 768 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::emplace(Args&&... args) { |
| 769 | value_type value(std::forward<Args>(args)...); |
| 770 | return InsertImpl(std::move_if_noexcept(value)); |
| 771 | } |
| 772 |
| 773 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 774 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::value_type |
| 775 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::take(size_type pos) { |
| 776 | // Make a hole by taking the element out of the heap. |
| 777 | MakeHole(pos); |
| 778 | value_type val = std::move(impl_.heap_[pos]); |
| 779 |
| 780 | // If the element being taken is already the last element then the heap |
| 781 | // doesn't need to be repaired. |
| 782 | if (pos != GetLastIndex()) { |
| 783 | MakeHole(GetLastIndex()); |
| 784 |
| 785 | // Move the hole down the heap, filling it with the current leaf at the |
| 786 | // very end of the heap. |
| 787 | MoveHoleDownAndFill<WithLeafElement>( |
| 788 | pos, std::move(impl_.heap_[GetLastIndex()])); |
| 789 | } |
| 790 |
| 791 | impl_.heap_.pop_back(); |
| 792 |
| 793 | return val; |
| 794 | } |
| 795 |
| 796 | // This is effectively identical to "take", but it avoids an unnecessary move. |
| 797 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 798 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::erase(size_type pos) { |
| 799 | DCHECK_LT(pos, size()); |
| 800 | // Make a hole by taking the element out of the heap. |
| 801 | MakeHole(pos); |
| 802 |
| 803 | // If the element being erased is already the last element then the heap |
| 804 | // doesn't need to be repaired. |
| 805 | if (pos != GetLastIndex()) { |
| 806 | MakeHole(GetLastIndex()); |
| 807 |
| 808 | // Move the hole down the heap, filling it with the current leaf at the |
| 809 | // very end of the heap. |
| 810 | MoveHoleDownAndFill<WithLeafElement>( |
| 811 | pos, std::move_if_noexcept(impl_.heap_[GetLastIndex()])); |
| 812 | } |
| 813 |
| 814 | impl_.heap_.pop_back(); |
| 815 | } |
| 816 |
| 817 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 818 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator |
| 819 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::Update(size_type pos) { |
| 820 | DCHECK_LT(pos, size()); |
| 821 | MakeHole(pos); |
| 822 |
| 823 | // Determine if we're >= parent, in which case we may need to go up. |
| 824 | bool child_greater_eq_parent = false; |
| 825 | size_type i = 0; |
| 826 | if (pos > 0) { |
| 827 | i = intrusive_heap::ParentIndex(pos); |
| 828 | child_greater_eq_parent = !Less(pos, i); |
| 829 | } |
| 830 |
| 831 | if (child_greater_eq_parent) { |
| 832 | i = MoveHoleUpAndFill(pos, std::move_if_noexcept(impl_.heap_[pos])); |
| 833 | } else { |
| 834 | i = MoveHoleDownAndFill<WithElement>( |
| 835 | pos, std::move_if_noexcept(impl_.heap_[pos])); |
| 836 | } |
| 837 |
| 838 | return cbegin() + i; |
| 839 | } |
| 840 |
| 841 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 842 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::swap( |
| 843 | IntrusiveHeap& other) noexcept { |
| 844 | std::swap(impl_.get_value_compare(), other.impl_.get_value_compare()); |
| 845 | std::swap(impl_.get_heap_handle_access(), |
| 846 | other.impl_.get_heap_handle_access()); |
| 847 | std::swap(impl_.heap_, other.impl_.heap_); |
| 848 | } |
| 849 |
| 850 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 851 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type |
| 852 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::ToIndex(const_iterator pos) { |
| 853 | DCHECK(cbegin() <= pos); |
| 854 | DCHECK(pos <= cend()); |
| 855 | if (pos == cend()) |
| 856 | return HeapHandle::kInvalidIndex; |
| 857 | return pos - cbegin(); |
| 858 | } |
| 859 |
| 860 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 861 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type |
| 862 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::ToIndex( |
| 863 | const_reverse_iterator pos) { |
| 864 | DCHECK(crbegin() <= pos); |
| 865 | DCHECK(pos <= crend()); |
| 866 | if (pos == crend()) |
| 867 | return HeapHandle::kInvalidIndex; |
| 868 | return (pos.base() - cbegin()) - 1; |
| 869 | } |
| 870 |
| 871 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 872 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::SetHeapHandle(size_type i) { |
| 873 | impl_.get_heap_handle_access().SetHeapHandle(&impl_.heap_[i], HeapHandle(i)); |
| 874 | intrusive_heap::CheckInvalidOrEqualTo(GetHeapHandle(i), i); |
| 875 | } |
| 876 |
| 877 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 878 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::ClearHeapHandle( |
| 879 | size_type i) { |
| 880 | impl_.get_heap_handle_access().ClearHeapHandle(&impl_.heap_[i]); |
| 881 | DCHECK(!GetHeapHandle(i).IsValid()); |
| 882 | } |
| 883 |
| 884 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 885 | HeapHandle IntrusiveHeap<T, Compare, HeapHandleAccessor>::GetHeapHandle( |
| 886 | size_type i) { |
| 887 | return impl_.get_heap_handle_access().GetHeapHandle(&impl_.heap_[i]); |
| 888 | } |
| 889 |
| 890 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 891 | bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(size_type i, |
| 892 | size_type j) { |
| 893 | DCHECK_LT(i, size()); |
| 894 | DCHECK_LT(j, size()); |
| 895 | return impl_.get_value_compare()(impl_.heap_[i], impl_.heap_[j]); |
| 896 | } |
| 897 |
| 898 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 899 | bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(const T& element, |
| 900 | size_type i) { |
| 901 | DCHECK_LT(i, size()); |
| 902 | return impl_.get_value_compare()(element, impl_.heap_[i]); |
| 903 | } |
| 904 |
| 905 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 906 | bool IntrusiveHeap<T, Compare, HeapHandleAccessor>::Less(size_type i, |
| 907 | const T& element) { |
| 908 | DCHECK_LT(i, size()); |
| 909 | return impl_.get_value_compare()(impl_.heap_[i], element); |
| 910 | } |
| 911 |
| 912 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 913 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::MakeHole(size_type pos) { |
| 914 | DCHECK_LT(pos, size()); |
| 915 | ClearHeapHandle(pos); |
| 916 | } |
| 917 |
| 918 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 919 | template <typename U> |
| 920 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::FillHole(size_type hole_pos, |
| 921 | U element) { |
| 922 | // The hole that we're filling may not yet exist. This can occur when |
| 923 | // inserting a new element into the heap. |
| 924 | DCHECK_LE(hole_pos, size()); |
| 925 | if (hole_pos == size()) { |
| 926 | impl_.heap_.push_back(std::move_if_noexcept(element)); |
| 927 | } else { |
| 928 | impl_.heap_[hole_pos] = std::move_if_noexcept(element); |
| 929 | } |
| 930 | SetHeapHandle(hole_pos); |
| 931 | } |
| 932 |
| 933 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 934 | void IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHole( |
| 935 | size_type new_hole_pos, |
| 936 | size_type old_hole_pos) { |
| 937 | // The old hole position may be one past the end. This occurs when a new |
| 938 | // element is being added. |
| 939 | DCHECK_NE(new_hole_pos, old_hole_pos); |
| 940 | DCHECK_LT(new_hole_pos, size()); |
| 941 | DCHECK_LE(old_hole_pos, size()); |
| 942 |
| 943 | if (old_hole_pos == size()) { |
| 944 | impl_.heap_.push_back(std::move_if_noexcept(impl_.heap_[new_hole_pos])); |
| 945 | } else { |
| 946 | impl_.heap_[old_hole_pos] = |
| 947 | std::move_if_noexcept(impl_.heap_[new_hole_pos]); |
| 948 | } |
| 949 | SetHeapHandle(old_hole_pos); |
| 950 | } |
| 951 |
| 952 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 953 | template <typename U> |
| 954 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type |
| 955 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHoleUpAndFill( |
| 956 | size_type hole_pos, |
| 957 | U element) { |
| 958 | // Moving 1 spot beyond the end is fine. This happens when we insert a new |
| 959 | // element. |
| 960 | DCHECK_LE(hole_pos, size()); |
| 961 |
| 962 | // Stop when the element is as far up as it can go. |
| 963 | while (hole_pos != 0) { |
| 964 | // If our parent is >= to us, we can stop. |
| 965 | size_type parent = intrusive_heap::ParentIndex(hole_pos); |
| 966 | if (!Less(parent, element)) |
| 967 | break; |
| 968 |
| 969 | MoveHole(parent, hole_pos); |
| 970 | hole_pos = parent; |
| 971 | } |
| 972 |
| 973 | FillHole(hole_pos, std::move_if_noexcept(element)); |
| 974 | return hole_pos; |
| 975 | } |
| 976 |
| 977 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 978 | template <typename FillElementType, typename U> |
| 979 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::size_type |
| 980 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::MoveHoleDownAndFill( |
| 981 | size_type hole_pos, |
| 982 | U element) { |
| 983 | DCHECK_LT(hole_pos, size()); |
| 984 |
| 985 | // If we're filling with a leaf, then that leaf element is about to be erased. |
| 986 | // We pretend that the space doesn't exist in the heap. |
| 987 | const size_type n = size() - (FillElementType::kIsLeafElement ? 1 : 0); |
| 988 |
| 989 | DCHECK_LT(hole_pos, n); |
| 990 | DCHECK(!GetHeapHandle(hole_pos).IsValid()); |
| 991 |
| 992 | while (true) { |
| 993 | // If this spot has no children, then we've gone down as far as we can go. |
| 994 | size_type left = intrusive_heap::LeftIndex(hole_pos); |
| 995 | if (left >= n) |
| 996 | break; |
| 997 | size_type right = left + 1; |
| 998 |
| 999 | // Get the larger of the potentially two child nodes. |
| 1000 | size_type largest = left; |
| 1001 | if (right < n && Less(left, right)) |
| 1002 | largest = right; |
| 1003 |
| 1004 | // If we're not deterministically moving the element all the way down to |
| 1005 | // become a leaf, then stop when it is >= the largest of the children. |
| 1006 | if (!FillElementType::kIsLeafElement && !Less(element, largest)) |
| 1007 | break; |
| 1008 |
| 1009 | MoveHole(largest, hole_pos); |
| 1010 | hole_pos = largest; |
| 1011 | } |
| 1012 |
| 1013 | if (FillElementType::kIsLeafElement) { |
| 1014 | // If we're filling with a leaf node we may need to bubble the leaf back up |
| 1015 | // the tree a bit to repair the heap. |
| 1016 | hole_pos = MoveHoleUpAndFill(hole_pos, std::move_if_noexcept(element)); |
| 1017 | } else { |
| 1018 | FillHole(hole_pos, std::move_if_noexcept(element)); |
| 1019 | } |
| 1020 | return hole_pos; |
| 1021 | } |
| 1022 |
| 1023 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 1024 | template <typename U> |
| 1025 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator |
| 1026 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::InsertImpl(U element) { |
| 1027 | // MoveHoleUpAndFill can tolerate the initial hole being in a slot that |
| 1028 | // doesn't yet exist. It will be created by MoveHole by copy/move, thus |
| 1029 | // removing the need for a default constructor. |
| 1030 | size_t i = MoveHoleUpAndFill(size(), std::move_if_noexcept(element)); |
| 1031 | return cbegin() + i; |
| 1032 | } |
| 1033 |
| 1034 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 1035 | template <typename U> |
| 1036 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator |
| 1037 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::ReplaceImpl(size_type pos, |
| 1038 | U element) { |
| 1039 | // If we're greater than our parent we need to go up, otherwise we may need |
| 1040 | // to go down. |
| 1041 | MakeHole(pos); |
| 1042 | size_type i = 0; |
| 1043 | if (!Less(element, pos)) { |
| 1044 | i = MoveHoleUpAndFill(pos, std::move_if_noexcept(element)); |
| 1045 | } else { |
| 1046 | i = MoveHoleDownAndFill<WithElement>(pos, std::move_if_noexcept(element)); |
| 1047 | } |
| 1048 | return cbegin() + i; |
| 1049 | } |
| 1050 |
| 1051 | template <typename T, typename Compare, typename HeapHandleAccessor> |
| 1052 | template <typename U> |
| 1053 | typename IntrusiveHeap<T, Compare, HeapHandleAccessor>::const_iterator |
| 1054 | IntrusiveHeap<T, Compare, HeapHandleAccessor>::ReplaceTopImpl(U element) { |
| 1055 | MakeHole(0u); |
| 1056 | size_type i = |
| 1057 | MoveHoleDownAndFill<WithElement>(0u, std::move_if_noexcept(element)); |
| 1058 | return cbegin() + i; |
| 1059 | } |
| 1060 |
| 1061 | //////////////////////////////////////////////////////////////////////////////// |
| 1062 | // WithHeapHandle |
| 1063 |
| 1064 | template <typename T> |
| 1065 | template <class... Args> |
| 1066 | WithHeapHandle<T>::WithHeapHandle(Args&&... args) |
| 1067 | : value_(std::forward<Args>(args)...) {} |
| 1068 |
| 1069 | template <typename T> |
| 1070 | void WithHeapHandle<T>::swap(WithHeapHandle& other) noexcept { |
| 1071 | InternalHeapHandleStorage::swap(other); |
| 1072 | std::swap(value_, other.value_); |
| 1073 | } |
| 1074 |
| 1075 | } // namespace base |
| 1076 |
| 1077 | #endif // BASE_CONTAINERS_INTRUSIVE_HEAP_H_ |
| 1078 |