COSA
An Object-Oriented Platform for Arduino Programming
Linkage.hh
Go to the documentation of this file.
1 
21 #ifndef COSA_LINKAGE_HH
22 #define COSA_LINKAGE_HH
23 
24 #include "Cosa/Types.h"
25 #include "Cosa/Event.hh"
26 
36 class Linkage : public Event::Handler {
37 public:
41  Linkage() :
42  Event::Handler(),
43  m_succ(this),
44  m_pred(this)
45  {}
46 
51  Linkage* succ() const
52  {
53  return (m_succ);
54  }
55 
60  Linkage* pred() const
61  {
62  return (m_pred);
63  }
64 
72  {
73  synchronized {
74 
75  // Check if it needs to be detached first
76  if (UNLIKELY(pred->m_succ != pred)) {
77  pred->m_succ->m_pred = pred->m_pred;
78  pred->m_pred->m_succ = pred->m_succ;
79  }
80 
81  // Attach pred as the new predecessor
82  pred->m_succ = this;
83  pred->m_pred = this->m_pred;
84  this->m_pred->m_succ = pred;
85  this->m_pred = pred;
86  }
87  }
88 
89 protected:
95 
100  void detach()
101  {
102  // Check that the detach is necessary
103  if (UNLIKELY(m_succ == this)) return;
104 
105  // Unlink and initiate to self reference
106  synchronized {
107  m_succ->m_pred = m_pred;
108  m_pred->m_succ = m_succ;
109  m_succ = this;
110  m_pred = this;
111  }
112  }
113 };
114 
115 class Link : public Linkage {
116 public:
120  Link() : Linkage() {}
121 
125  void detach()
126  __attribute__((always_inline))
127  {
128  Linkage::detach();
129  }
130 };
131 
132 class Head : public Linkage {
133 public:
137  Head() : Linkage() {}
138 
143  int available()
144  {
145  int res = 0;
146  // Iterate through the list and count the length of the queue
147  for (Linkage* link = m_succ; link != this; link = link->succ()) res++;
148  return (res);
149  }
150 
155  bool is_empty() const
156  {
157  return (m_succ == this);
158  }
159 
160 private:
168  virtual void on_event(uint8_t type, uint16_t value)
169  {
170  // Iterate through the list and dispatch the event
171  Linkage* link = m_succ;
172  while (link != this) {
173  // Get the successor as the current event call may detach itself
174  Linkage* succ = link->succ();
175  link->on_event(type, value);
176  link = succ;
177  }
178  }
179 };
180 
181 #endif
Head()
Definition: Linkage.hh:137
int available()
Definition: Linkage.hh:143
Linkage()
Definition: Linkage.hh:41
Linkage * m_succ
Definition: Linkage.hh:93
void detach()
Definition: Linkage.hh:100
Linkage * succ() const
Definition: Linkage.hh:51
Definition: Event.hh:39
bool is_empty() const
Definition: Linkage.hh:155
Linkage * pred() const
Definition: Linkage.hh:60
virtual void on_event(uint8_t type, uint16_t value)
Definition: Event.hh:107
Linkage * m_pred
Definition: Linkage.hh:94
#define UNLIKELY(x)
Definition: Types.h:153
Definition: Linkage.hh:132
void attach(Linkage *pred)
Definition: Linkage.hh:71