YAHAL
Yet Another Hardware Abstraction Library
Loading...
Searching...
No Matches
circular_list.h
1// ---------------------------------------------
2// This file is part of
3// _ _ __ _ _ __ __
4// ( \/ ) /__\ ( )_( ) /__\ ( )
5// \ / /(__)\ ) _ ( /(__)\ )(__
6// (__)(__)(__)(_) (_)(__)(__)(____)
7//
8// Yet Another HW Abstraction Library
9// Copyright (C) Andreas Terstegge
10// BSD Licensed (see file LICENSE)
11//
12// ---------------------------------------------
13//
14// This is a simple generic implementation of
15// a circular double-linked list. The type T
16// is expected to have the following attributes:
17//
18// T * _prev; pointer to the previous element
19// T * _next; pointer to the next element
20// bool _linked_in; flag to signal if the instance
21// is member of the list
22//
23// This class only holds pointers to the elements,
24// and does not do any kind of memory management.
25// It only 'organizes' existing elements.
26// If there are access problems to the attributes
27// above, a C++ friendship to this class might be
28// declared.
29// Main usage of this class in YAHAL is the multitasking
30// kernel, which organizes task instances as a
31// circular list. It is also used for the condition_variable.
32
33#ifndef _CIRCULAR_LIST_H_
34#define _CIRCULAR_LIST_H_
35
36template<typename T>
38public:
39
41 _head = nullptr;
42 _tail = nullptr;
43 _size = 0;
44 }
45
46 void push_back(T * elem) {
47 if (_tail) {
48 // There are entries already
49 elem->_next = _head;
50 elem->_prev = _tail;
51 _head->_prev = elem;
52 _tail->_next = elem;
53 _tail = elem;
54 } else {
55 // We are the first element
56 elem->_next = elem;
57 elem->_prev = elem;
58 _head=_tail = elem;
59 }
60 elem->_linked_in = true;
61 ++_size;
62 }
63
64 void remove(T * elem) {
65 if (_size == 1) {
66 // We are the last element
67 _head = nullptr;
68 _tail = nullptr;
69 } else {
70 // There is more than one element left
71 elem->_prev->_next = elem->_next;
72 elem->_next->_prev = elem->_prev;
73 if (_head == elem) _head = elem->_next;
74 if (_tail == elem) _tail = elem->_prev;
75 }
76 elem->_linked_in = false;
77 --_size;
78 }
79
80 inline T * getHead() const { return _head; }
81 inline T * getTail() const { return _tail; }
82 inline int getSize() const { return _size; }
83
84private:
85
86 T * _head;
87 T * _tail;
88 int _size;
89};
90
91#endif /* _CIRCULAR_LIST_H_ */