Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / third_party / WebKit / Source / wtf / TerminatedArray.h
blobca16a45dd8458e215a50bb9ac11ae9054ee9319c
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"
10 namespace WTF {
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_NONCOPYABLE(TerminatedArray);
19 public:
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]; }
23 template<typename U>
24 class iterator_base {
25 public:
26 iterator_base& operator++()
28 if (m_val->isLastInArray()) {
29 m_val = 0;
30 } else {
31 ++m_val;
33 return *this;
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); }
41 private:
42 iterator_base(U* val) : m_val(val) { }
44 U* m_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); }
58 size_t size() const
60 size_t count = 0;
61 for (const_iterator it = begin(); it != end(); ++it)
62 count++;
63 return count;
66 // Match Allocator semantics to be able to use OwnPtr<TerminatedArray>.
67 void operator delete(void* p) { ::WTF::fastFree(p); }
69 private:
70 // Allocator describes how TerminatedArrayBuilder should create new instances
71 // of TerminateArray and manage their lifetimes.
72 struct Allocator {
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.
89 TerminatedArray();
91 template<typename, template <typename> class> friend class TerminatedArrayBuilder;
94 } // namespace WTF
96 using WTF::TerminatedArray;
98 #endif // TerminatedArray_h