summaryrefslogtreecommitdiff
path: root/AK/Stack.h
blob: 907b7aa77894abe2d050f48be54b4d0a4c92ddd3 (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
/*
 * Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Vector.h>

namespace AK {

template<typename T, size_t stack_size>
class Stack {
public:
    Stack() = default;
    ~Stack() = default;

    bool push(const T& item)
    {
        if (m_stack.size() >= stack_size)
            return false;

        m_stack.unchecked_append(item);
        return true;
    }

    bool push(T&& item)
    {
        if (m_stack.size() >= stack_size)
            return false;

        m_stack.unchecked_append(move(item));
        return true;
    }

    bool is_empty() const
    {
        return m_stack.is_empty();
    }

    size_t size() const
    {
        return m_stack.size();
    }

    bool pop()
    {
        if (is_empty())
            return false;

        m_stack.resize_and_keep_capacity(m_stack.size() - 1);
        return true;
    }

    T& top()
    {
        return m_stack.last();
    }

    const T& top() const
    {
        return m_stack.last();
    }

private:
    Vector<T, stack_size> m_stack;
};

}

using AK::Stack;