Accessories
Arduino for motors and lights library.
Chain.hpp
1 //-------------------------------------------------------------------
2 #ifndef __ACCSChain_H__
3 #define __ACCSChain_H__
4 //-------------------------------------------------------------------
5 
7 template<class T> class ACCSCHAINEDLISTITEM
8 {
9 public:
11  T *Obj;
14 
16  inline ACCSCHAINEDLISTITEM<T>() { this->pNext = NULL; }
17 };
18 
33 template<class T> class ACCSCHAINEDLIST
34 {
35 public:
42 
44  inline ACCSCHAINEDLIST() { this->pFirst = NULL; this->pCurrentItem = NULL; }
48  void AddItem(T *t);
51  void NextCurrent();
53  inline void ResetCurrent() { this->pCurrentItem = (this->HasCurrentNull ? NULL : this->pFirst); }
55  inline void StartCurrent() { this->pCurrentItem = this->pFirst; }
59  inline bool HasCurrent() { return this->pCurrentItem != NULL; }
60 };
61 
68 #define CHAINED_ENUMERATE(T, list, func) ACCSCHAINEDLISTITEM<T> *pCurr = list.pFirst; while (pCurr != NULL) { func(pCurr->Obj); pCurr = pCurr->pNext; }
69 
70 // This function appends element into chain.
71 template<class T> void ACCSCHAINEDLIST<T>::AddItem(T *t)
72 {
73  ACCSCHAINEDLISTITEM<T> *pCurr = this->pFirst;
74 
75  if (pCurr == NULL)
76  {
77  this->pFirst = new ACCSCHAINEDLISTITEM<T>();
78  if (!HasCurrentNull)
79  this->pCurrentItem = this->pFirst;
80  pCurr = this->pFirst;
81  }
82  else
83  while (pCurr != NULL)
84  {
85  if (pCurr->pNext == NULL)
86  {
87  pCurr->pNext = new ACCSCHAINEDLISTITEM<T>();
88  pCurr = pCurr->pNext;
89  break;
90  }
91  pCurr = pCurr->pNext;
92  }
93 
94  pCurr->pNext = NULL;
95  pCurr->Obj = t;
96 }
97 
98 // This function move the current item to the next in the chain.
99 template<class T> void ACCSCHAINEDLIST<T>::NextCurrent()
100 {
101  if (this->pFirst == NULL)
102  return;
103 
104  if (this->pCurrentItem == NULL)
105  {
106  this->pCurrentItem = this->pFirst;
107  return;
108  }
109 
110  this->pCurrentItem = this->pCurrentItem->pNext;
111 
112  if (this->pCurrentItem == NULL && !HasCurrentNull)
113  this->pCurrentItem = this->pFirst;
114 
115  return;
116 }
117 #endif
bool HasCurrent()
Definition: Chain.hpp:59
void StartCurrent()
Definition: Chain.hpp:55
void ResetCurrent()
Definition: Chain.hpp:53
void NextCurrent()
Definition: Chain.hpp:99
void AddItem(T *t)
Definition: Chain.hpp:71
bool HasCurrentNull
Definition: Chain.hpp:41
ACCSCHAINEDLISTITEM< T > * pCurrentItem
Definition: Chain.hpp:39
ACCSCHAINEDLISTITEM< T > * pFirst
Definition: Chain.hpp:37
ACCSCHAINEDLISTITEM * pNext
Definition: Chain.hpp:13