AK: Implement AK::Stack

This commit is contained in:
Jesse Buhagiar 2021-05-11 21:47:48 +10:00 committed by Ali Mohammad Pur
parent 814e35902e
commit 2b123cc592
3 changed files with 118 additions and 0 deletions

72
AK/Stack.h Normal file
View file

@ -0,0 +1,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.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<T, stack_size> m_stack;
};
}
using AK::Stack;

View file

@ -47,6 +47,7 @@ set(AK_TEST_SOURCES
TestSourceGenerator.cpp
TestSourceLocation.cpp
TestSpan.cpp
TestStack.cpp
TestString.cpp
TestStringUtils.cpp
TestStringView.cpp

45
Tests/AK/TestStack.cpp Normal file
View file

@ -0,0 +1,45 @@
/*
* Copyright (c) 2021, Jesse Buhagiar <jooster669@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibTest/TestCase.h>
#include <AK/Stack.h>
TEST_CASE(basic)
{
AK::Stack<int, 3> 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<String, 4> 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());
}