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
7 #include "wtf/FastAllocBase.h"
8 #include "wtf/OwnPtr.h"
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>.
17 class TerminatedArray
{
18 WTF_MAKE_NONCOPYABLE(TerminatedArray
);
20 T
& at(size_t index
) { return reinterpret_cast<T
*>(this)[index
]; }
21 const T
& at(size_t index
) const { return reinterpret_cast<const T
*>(this)[index
]; }
26 iterator_base
& operator++()
28 if (m_val
->isLastInArray()) {
36 U
& operator*() const { return *m_val
; }
38 bool operator==(const iterator_base
& other
) const { return m_val
== other
.m_val
; }
39 bool operator!=(const iterator_base
& other
) const { return !(*this == other
); }
42 iterator_base(U
* val
) : m_val(val
) { }
46 friend class TerminatedArray
;
49 typedef iterator_base
<T
> iterator
;
50 typedef iterator_base
<const T
> const_iterator
;
52 iterator
begin() { return iterator(reinterpret_cast<T
*>(this)); }
53 const_iterator
begin() const { return const_iterator(reinterpret_cast<const T
*>(this)); }
55 iterator
end() { return iterator(0); }
56 const_iterator
end() const { return const_iterator(0); }
61 for (const_iterator it
= begin(); it
!= end(); ++it
)
66 // Match Allocator semantics to be able to use OwnPtr<TerminatedArray>.
67 void operator delete(void* p
) { ::WTF::fastFree(p
); }
70 // Allocator describes how TerminatedArrayBuilder should create new instances
71 // of TerminateArray and manage their lifetimes.
73 typedef PassOwnPtr
<TerminatedArray
> PassPtr
;
74 typedef OwnPtr
<TerminatedArray
> Ptr
;
76 static PassPtr
create(size_t capacity
)
78 return adoptPtr(static_cast<TerminatedArray
*>(fastMalloc(capacity
* sizeof(T
))));
81 static PassPtr
resize(PassPtr ptr
, size_t capacity
)
83 return adoptPtr(static_cast<TerminatedArray
*>(fastRealloc(ptr
.leakPtr(), capacity
* sizeof(T
))));
87 // Prohibit construction. Allocator makes TerminatedArray instances for
88 // TerminatedArrayBuilder by pointer casting.
91 template<typename
, template <typename
> class> friend class TerminatedArrayBuilder
;
96 using WTF::TerminatedArray
;
98 #endif // TerminatedArray_h