OLD | NEW |
1 // Copyright 2017 The Chromium Authors. All rights reserved. | 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 #ifndef TerminatedArrayBuilder_h |
| 5 #define TerminatedArrayBuilder_h |
4 | 6 |
5 #include "platform/wtf/TerminatedArrayBuilder.h" | 7 #include "wtf/Allocator.h" |
6 | 8 |
7 // The contents of this header was moved to platform/wtf as part of | 9 namespace WTF { |
8 // WTF migration project. See the following post for details: | 10 |
9 // https://groups.google.com/a/chromium.org/d/msg/blink-dev/tLdAZCTlcAA/bYXVT8gY
CAAJ | 11 template <typename T, template <typename> class ArrayType = TerminatedArray> |
| 12 class TerminatedArrayBuilder { |
| 13 STACK_ALLOCATED(); |
| 14 WTF_MAKE_NONCOPYABLE(TerminatedArrayBuilder); |
| 15 |
| 16 public: |
| 17 explicit TerminatedArrayBuilder( |
| 18 typename ArrayType<T>::Allocator::PassPtr array) |
| 19 : m_array(array), m_count(0), m_capacity(0) { |
| 20 if (!m_array) |
| 21 return; |
| 22 m_capacity = m_count = m_array->size(); |
| 23 DCHECK(m_array->at(m_count - 1).isLastInArray()); |
| 24 } |
| 25 |
| 26 void grow(size_t count) { |
| 27 DCHECK(count); |
| 28 if (!m_array) { |
| 29 DCHECK(!m_count); |
| 30 DCHECK(!m_capacity); |
| 31 m_capacity = count; |
| 32 m_array = ArrayType<T>::Allocator::create(m_capacity); |
| 33 } else { |
| 34 DCHECK(m_array->at(m_count - 1).isLastInArray()); |
| 35 m_capacity += count; |
| 36 m_array = ArrayType<T>::Allocator::resize( |
| 37 ArrayType<T>::Allocator::release(m_array), m_capacity); |
| 38 m_array->at(m_count - 1).setLastInArray(false); |
| 39 } |
| 40 m_array->at(m_capacity - 1).setLastInArray(true); |
| 41 } |
| 42 |
| 43 void append(const T& item) { |
| 44 RELEASE_ASSERT(m_count < m_capacity); |
| 45 DCHECK(!item.isLastInArray()); |
| 46 m_array->at(m_count++) = item; |
| 47 if (m_count == m_capacity) |
| 48 m_array->at(m_capacity - 1).setLastInArray(true); |
| 49 } |
| 50 |
| 51 typename ArrayType<T>::Allocator::PassPtr release() { |
| 52 RELEASE_ASSERT(m_count == m_capacity); |
| 53 assertValid(); |
| 54 return ArrayType<T>::Allocator::release(m_array); |
| 55 } |
| 56 |
| 57 private: |
| 58 #if DCHECK_IS_ON() |
| 59 void assertValid() { |
| 60 for (size_t i = 0; i < m_count; ++i) { |
| 61 bool isLastInArray = (i + 1 == m_count); |
| 62 DCHECK_EQ(m_array->at(i).isLastInArray(), isLastInArray); |
| 63 } |
| 64 } |
| 65 #else |
| 66 void assertValid() {} |
| 67 #endif |
| 68 |
| 69 typename ArrayType<T>::Allocator::Ptr m_array; |
| 70 size_t m_count; |
| 71 size_t m_capacity; |
| 72 }; |
| 73 |
| 74 } // namespace WTF |
| 75 |
| 76 using WTF::TerminatedArrayBuilder; |
| 77 |
| 78 #endif // TerminatedArrayBuilder_h |
OLD | NEW |