aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/core/SkArenaAllocList.h
blob: b4e442b0bd75f5ea4e774620c7ca51df021ad649 (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
/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkArenaAllocList_DEFINED
#define SkArenaAllocList_DEFINED

#include "SkArenaAlloc.h"

/**
 * A singly linked list of Ts stored in a SkArenaAlloc. The arena rather than the list owns
 * the elements. This supports forward iteration and range based for loops.
 */
template <typename T>
class SkArenaAllocList {
private:
    struct Node;

public:
    SkArenaAllocList() = default;

    void reset() { fHead = fTail = nullptr; }

    template <typename... Args>
    inline T& append(SkArenaAlloc* arena, Args... args);

    class Iter {
    public:
        Iter() = default;
        inline Iter& operator++();
        T& operator*() const { return fCurr->fT; }
        T* operator->() const { return &fCurr->fT; }
        bool operator==(const Iter& that) const { return fCurr == that.fCurr; }
        bool operator!=(const Iter& that) const { return !(*this == that); }

    private:
        friend class SkArenaAllocList;
        explicit Iter(Node* node) : fCurr(node) {}
        Node* fCurr = nullptr;
    };

    Iter begin() { return Iter(fHead); }
    Iter end() { return Iter(); }
    Iter tail() { return Iter(fTail); }

private:
    struct Node {
        template <typename... Args>
        Node(Args... args) : fT(std::forward<Args>(args)...) {}
        T fT;
        Node* fNext = nullptr;
    };
    Node* fHead = nullptr;
    Node* fTail = nullptr;
};

template <typename T>
template <typename... Args>
T& SkArenaAllocList<T>::append(SkArenaAlloc* arena, Args... args) {
    SkASSERT(!fHead == !fTail);
    auto* n = arena->make<Node>(std::forward<Args>(args)...);
    if (!fTail) {
        fHead = fTail = n;
    } else {
        fTail = fTail->fNext = n;
    }
    return fTail->fT;
}

template <typename T>
typename SkArenaAllocList<T>::Iter& SkArenaAllocList<T>::Iter::operator++() {
    fCurr = fCurr->fNext;
    return *this;
}

#endif