Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of C027_Support_New by
Pipe.h
- Committer:
- mazgch
- Date:
- 2013-11-02
- Revision:
- 5:5362073f2689
- Parent:
- 2:b6012cd91657
- Child:
- 7:9aa830f5811e
File content as of revision 5:5362073f2689:
#pragma once
template <class T>
class Pipe
{
private:
inline int _inc(int i, int n = 1)
{
i += n;
if (i >= s)
i -= s;
return i;
}
public:
Pipe(int n, T* p = NULL)
{
a = p ? NULL : new T[n];
r = 0;
w = 0;
b = p ? p : a;
s = n;
}
virtual ~Pipe()
{
if (a)
delete [] a;
}
// writing thread
bool writeable(void) // = not full
{
int i = _inc(w);
return (i = r);
}
int free(void) // number of elements that can be added
{
int t = r - w;
if (t <= 0)
t += s;
return t - 1;
}
void putc(T c)
{
int i = w;
int j = i;
i = _inc(i);
//assert(i != r);
b[j] = c;
w = i;
}
int put(T* p, int n)
{
int f = free();
if (f < n)
n = f;
if (n)
{
int m = s - w;
if (m > n)
m = n;
memcpy(&b[w], &p[0], m);
int t = n - m;
if (t)
{
memcpy(&b[0], &p[m], t);
w = t;
}
else
w += m;
}
return n;
}
// reading thread
// --------------------------------------------------------
//! check if there are any values available
bool readable(void) // = not empty
{
return (r != w);
}
//! get the number of values avialable in the buffer
virtual int size(void)
{
int t = w - r;
if (t < 0)
t += s;
return t;
}
//! get a value from buffer (this function will block if no values available)
T getc(void)
{
//while (r == w)
// /* just wait until w changes*/;
T t = b[r];
r = _inc(r);
return t;
}
// get values from buffer (if the buffer has less values, only the values avilable are returned)
virtual int get(T* p, int n)
{
int f = size();
if (f < n)
n = f;
if (n)
{
int m = s - r;
if (m > n)
m = n;
memcpy(&p[0], &b[r], m);
int t = n - m;
if (t)
{
memcpy(&p[m] ,&b[0], t);
r = t;
}
else
r += m;
}
return n;
}
// the following functions are useful if you like to inspect or parse the buffer
virtual int start(void) { o = r; return size(); } // reset the parsing index and return the number of available elments
virtual T next(void) { T t = b[o]; o = _inc(o); return t; } // get the next element and increment
virtual void done(void) { r = o; } // commit the index
private:
// buffer
T* b; //!< buffer
T* a; //!< allocated buffer
int s; //!< size of buffer (s - 1) elements can be stored
volatile int w; //! write index
volatile int r; //! read index
int o; //! offest index used by parsing functions
};
