summaryrefslogtreecommitdiffstats
path: root/third_party/WebKit/Source/wtf/TerminatedArrayBuilder.h
blob: eec013109a064e12c8b59c5da88753b02d5039d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TerminatedArrayBuilder_h
#define TerminatedArrayBuilder_h

#include "wtf/OwnPtr.h"

namespace WTF {

template<typename T, template <typename> class ArrayType = TerminatedArray>
class TerminatedArrayBuilder {
    DISALLOW_NEW();
    WTF_MAKE_NONCOPYABLE(TerminatedArrayBuilder);
public:
    explicit TerminatedArrayBuilder(typename ArrayType<T>::Allocator::PassPtr array)
        : m_array(array)
        , m_count(0)
        , m_capacity(0)
    {
        if (!m_array)
            return;
        m_capacity = m_count = m_array->size();
        ASSERT(m_array->at(m_count - 1).isLastInArray());
    }

    void grow(size_t count)
    {
        ASSERT(count);
        if (!m_array) {
            ASSERT(!m_count);
            ASSERT(!m_capacity);
            m_capacity = count;
            m_array = ArrayType<T>::Allocator::create(m_capacity);
        } else {
            ASSERT(m_array->at(m_count - 1).isLastInArray());
            m_capacity += count;
            m_array = ArrayType<T>::Allocator::resize(m_array.release(), m_capacity);
            m_array->at(m_count - 1).setLastInArray(false);
        }
        m_array->at(m_capacity - 1).setLastInArray(true);
    }

    void append(const T& item)
    {
        RELEASE_ASSERT(m_count < m_capacity);
        ASSERT(!item.isLastInArray());
        m_array->at(m_count++) = item;
        if (m_count == m_capacity)
            m_array->at(m_capacity - 1).setLastInArray(true);
    }

    typename ArrayType<T>::Allocator::PassPtr release()
    {
        RELEASE_ASSERT(m_count == m_capacity);
        assertValid();
        return m_array.release();
    }

private:
#if ENABLE(ASSERT)
    void assertValid()
    {
        for (size_t i = 0; i < m_count; ++i) {
            bool isLastInArray = (i + 1 == m_count);
            ASSERT(m_array->at(i).isLastInArray() == isLastInArray);
        }
    }
#else
    void assertValid() { }
#endif

    typename ArrayType<T>::Allocator::Ptr m_array;
    size_t m_count;
    size_t m_capacity;
};

} // namespace WTF

using WTF::TerminatedArrayBuilder;

#endif // TerminatedArrayBuilder_h