hlswmaster-ng/list.h

168 lines
2.6 KiB
C++

#ifndef _LIST_H_
#define _LIST_H_
#include "mutex.h"
template <class T>
class Iterator {
public:
virtual ~Iterator() {}
virtual bool hasNext() const =0;
virtual T* next() =0;
protected:
Iterator<T>() {}
Iterator<T>(const Iterator<T>& it);
Iterator<T>& operator=(const Iterator<T>& it);
};
template <class T>
class List {
public:
List() {}
~List()
{
AutoMutex am(mutex);
while(!head.isEmpty())
head.getNext()->del();
}
void add(const T* part)
{
ListEntry<T>* entry = new ListEntry<T>(part);
AutoMutex am(mutex);
entry->add(&head, head.getNext());
}
void addTail(const T* part)
{
ListEntry<T>* entry = new ListEntry<T>(part);
AutoMutex am(mutex);
entry->add(head.getPrev(), &head);
}
T* get()
{
AutoMutex am(mutex);
ListEntry<T>* entry = head.getNext();
T* retval = (T*)entry->getPart();
if (!head.isEmpty()) {
entry->del();
delete entry;
}
return retval;
}
T* getTail()
{
AutoMutex am(mutex);
ListEntry<T>* entry = head.getPrev();
T* retval = (T*)entry->getPart();
if (!head.isEmpty()) {
entry->del();
delete entry;
}
return retval;
}
bool isEmpty() const
{
AutoMutex am((Mutex&)mutex);
return head.isEmpty();
}
Iterator<T>* createIterator() const
{
return new ListIterator<T>(this);
}
protected:
List(const List& l);
List& operator=(const List& l);
private:
template <class TT>
class ListEntry {
public:
ListEntry(const TT* part = 0)
: prev(this), next(this), part(part)
{
}
void add(ListEntry<TT>* prev_, ListEntry<TT>* next_)
{
this->next = next_;
this->prev = prev_;
next_->prev = this;
prev_->next = this;
}
void del()
{
next->prev = prev;
prev->next = next;
next = prev = this;
}
bool isEmpty() const
{
return (this->prev == this) && (this->next == this);
}
const TT* getPart() const { return part; }
ListEntry<TT>* getPrev() const { return prev; }
ListEntry<TT>* getNext() const { return next; }
private:
ListEntry<TT>* prev;
ListEntry<TT>* next;
const TT* part;
};
ListEntry<T> head;
Mutex mutex;
template <class TT>
class ListIterator : public Iterator<TT> {
public:
ListIterator(const List<TT>* list)
: list(list)
{
// ((ListBase*)list)->mutex.lock();
pos = &list->head;
}
~ListIterator()
{
// ((ListBase*)list)->mutex.unlock();
}
bool hasNext() const
{
return (pos->getNext() != &list->head);
}
TT* next()
{
pos = pos->getNext();
return (TT*)pos->getPart();
}
protected:
ListIterator(const ListIterator& lit);
ListIterator& operator=(const ListIterator& lit);
private:
const List<TT>* list;
const ListEntry<TT>* pos;
};
};
#endif //_LIST_H_