diff --git a/AK/Stack.h b/AK/Stack.h new file mode 100644 index 00000000000..6222f8cb954 --- /dev/null +++ b/AK/Stack.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021, Jesse Buhagiar + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#pragma once + +#include + +namespace AK { + +template +class Stack { +public: + Stack() = default; + ~Stack() = default; + + bool push(const T& item) + { + if (m_stack.size() >= stack_size) + return false; + + m_stack.append(item); + return true; + } + + bool push(T&& item) + { + if (m_stack.size() >= stack_size) + return false; + + m_stack.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 m_stack; +}; + +} + +using AK::Stack; diff --git a/Tests/AK/CMakeLists.txt b/Tests/AK/CMakeLists.txt index b74893f0f8a..5f2b3714956 100644 --- a/Tests/AK/CMakeLists.txt +++ b/Tests/AK/CMakeLists.txt @@ -47,6 +47,7 @@ set(AK_TEST_SOURCES TestSourceGenerator.cpp TestSourceLocation.cpp TestSpan.cpp + TestStack.cpp TestString.cpp TestStringUtils.cpp TestStringView.cpp diff --git a/Tests/AK/TestStack.cpp b/Tests/AK/TestStack.cpp new file mode 100644 index 00000000000..ddbe2765d70 --- /dev/null +++ b/Tests/AK/TestStack.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021, Jesse Buhagiar + * + * SPDX-License-Identifier: BSD-2-Clause + */ + +#include + +#include + +TEST_CASE(basic) +{ + AK::Stack stack; + + EXPECT(stack.is_empty() == true); + stack.push(2); + stack.push(4); + stack.push(17); + EXPECT(stack.size() == 3); + EXPECT(stack.top() == 17); + EXPECT_EQ(stack.pop(), true); + EXPECT_EQ(stack.pop(), true); + EXPECT_EQ(stack.pop(), true); + EXPECT(stack.is_empty()); +} + +TEST_CASE(complex_type) +{ + AK::Stack stack; + + EXPECT_EQ(stack.is_empty(), true); + EXPECT(stack.push("Well")); + EXPECT(stack.push("Hello")); + EXPECT(stack.push("Friends")); + EXPECT(stack.push(":^)")); + EXPECT_EQ(stack.top(), ":^)"); + EXPECT_EQ(stack.pop(), true); + EXPECT_EQ(stack.top(), "Friends"); + EXPECT_EQ(stack.pop(), true); + EXPECT_EQ(stack.top(), "Hello"); + EXPECT_EQ(stack.pop(), true); + EXPECT_EQ(stack.top(), "Well"); + EXPECT_EQ(stack.pop(), true); + EXPECT(stack.is_empty()); +}