OLD | NEW |
(Empty) | |
| 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 |
| 3 // found in the LICENSE file. |
| 4 #ifndef TerminatedArray_h |
| 5 #define TerminatedArray_h |
| 6 |
| 7 #include "wtf/FastAllocBase.h" |
| 8 #include "wtf/OwnPtr.h" |
| 9 |
| 10 namespace WTF { |
| 11 |
| 12 // TerminatedArray<T> represents a sequence of elements of type T in which each |
| 13 // element knows whether it is the last element in the sequence or not. For this |
| 14 // check type T must provide isLastInArray method. |
| 15 // TerminatedArray<T> can only be constructed by TerminatedArrayBuilder<T>. |
| 16 template<typename T> |
| 17 class TerminatedArray { |
| 18 WTF_MAKE_FAST_ALLOCATED; |
| 19 WTF_MAKE_NONCOPYABLE(TerminatedArray); |
| 20 public: |
| 21 T& at(size_t index) { return reinterpret_cast<T*>(this)[index]; } |
| 22 const T& at(size_t index) const { return reinterpret_cast<const T*>(this)[in
dex]; } |
| 23 |
| 24 template<typename U> |
| 25 class iterator_base { |
| 26 public: |
| 27 iterator_base& operator++() |
| 28 { |
| 29 if (m_val->isLastInArray()) { |
| 30 m_val = 0; |
| 31 } else { |
| 32 ++m_val; |
| 33 } |
| 34 return *this; |
| 35 } |
| 36 |
| 37 U& operator*() const { return *m_val; } |
| 38 |
| 39 bool operator==(const iterator_base& other) const { return m_val == othe
r.m_val; } |
| 40 bool operator!=(const iterator_base& other) const { return !(*this == ot
her); } |
| 41 |
| 42 private: |
| 43 iterator_base(U* val) : m_val(val) { } |
| 44 |
| 45 U* m_val; |
| 46 |
| 47 friend class TerminatedArray; |
| 48 }; |
| 49 |
| 50 typedef iterator_base<T> iterator; |
| 51 typedef iterator_base<const T> const_iterator; |
| 52 |
| 53 iterator begin() { return iterator(reinterpret_cast<T*>(this)); } |
| 54 const_iterator begin() const { return const_iterator(reinterpret_cast<const
T*>(this)); } |
| 55 |
| 56 iterator end() { return iterator(0); } |
| 57 const_iterator end() const { return const_iterator(0); } |
| 58 |
| 59 size_t size() const |
| 60 { |
| 61 size_t count = 0; |
| 62 for (const_iterator it = begin(); it != end(); ++it) |
| 63 count++; |
| 64 return count; |
| 65 } |
| 66 |
| 67 private: |
| 68 static PassOwnPtr<TerminatedArray> create(size_t capacity) |
| 69 { |
| 70 return adoptPtr(static_cast<TerminatedArray*>(fastMalloc(capacity * size
of(T)))); |
| 71 } |
| 72 |
| 73 static PassOwnPtr<TerminatedArray> resize(PassOwnPtr<TerminatedArray> array,
size_t capacity) |
| 74 { |
| 75 return adoptPtr(static_cast<TerminatedArray*>(fastRealloc(array.leakPtr(
), capacity * sizeof(T)))); |
| 76 } |
| 77 |
| 78 template<typename> friend class TerminatedArrayBuilder; |
| 79 }; |
| 80 |
| 81 } // namespace WTF |
| 82 |
| 83 using WTF::TerminatedArray; |
| 84 |
| 85 #endif // TerminatedArray_h |
OLD | NEW |