#ifndef Bag_h
#define Bag_h
#include <wtf/DumbPtrTraits.h>
#include <wtf/FastMalloc.h>
#include <wtf/Noncopyable.h>
namespace WTF {
namespace Private {
template<typename T>
class BagNode {
WTF_MAKE_FAST_ALLOCATED;
public:
template<typename... Args>
BagNode(Args&&... args)
: m_item(std::forward<Args>(args)...)
{ }
T m_item;
BagNode* m_next { nullptr };
};
}
template<typename T, typename PtrTraits = DumbPtrTraits<Private::BagNode<T>>>
class Bag {
WTF_MAKE_NONCOPYABLE(Bag);
WTF_MAKE_FAST_ALLOCATED;
using Node = Private::BagNode<T>;
public:
Bag() = default;
template<typename U>
Bag(Bag<T, U>&& other)
{
ASSERT(!m_head);
m_head = other.unwrappedHead();
other.m_head = nullptr;
}
template<typename U>
Bag& operator=(Bag<T, U>&& other)
{
m_head = other.unwrappedHead();
other.m_head = nullptr;
return *this;
}
~Bag()
{
clear();
}
void clear()
{
Node* head = this->unwrappedHead();
while (head) {
Node* current = head;
head = current->m_next;
delete current;
}
m_head = nullptr;
}
template<typename... Args>
T* add(Args&&... args)
{
Node* newNode = new Node(std::forward<Args>(args)...);
newNode->m_next = unwrappedHead();
m_head = newNode;
return &newNode->m_item;
}
class iterator {
public:
iterator()
: m_node(0)
{
}
bool operator!() const { return !m_node; }
T* operator*() const { return &m_node->m_item; }
iterator& operator++()
{
m_node = m_node->m_next;
return *this;
}
bool operator==(const iterator& other) const
{
return m_node == other.m_node;
}
bool operator!=(const iterator& other) const
{
return !(*this == other);
}
private:
template<typename, typename> friend class WTF::Bag;
Node* m_node;
};
iterator begin()
{
iterator result;
result.m_node = unwrappedHead();
return result;
}
iterator end() { return iterator(); }
bool isEmpty() const { return !m_head; }
private:
Node* unwrappedHead() { return PtrTraits::unwrap(m_head); }
typename PtrTraits::StorageType m_head { nullptr };
};
template<typename Poison, typename T> struct PoisonedPtrTraits;
template<typename Poison, typename T>
using PoisonedBag = Bag<T, PoisonedPtrTraits<Poison, Private::BagNode<T>>>;
}
using WTF::Bag;
using WTF::PoisonedBag;
#endif // Bag_h