6 Fifo::Fifo(unsigned size = 18) {
7 //except at the beginning, _head and _tail must never overlap,
8 //otherwise one does not know whether the buffer is full or
9 //empty. to have nevertheless a buffer with the given capacity,
10 //a buffer with one more element is allocated.
13 _buffer = (char *) _malloc_align(_size, ALIGNMENT_FACTOR);
15 fprintf(stderr,"[FIFO] Memory allocation failure\n");
41 unsigned Fifo::read(void *destination, unsigned len) {
43 char* buffer = (char*) destination;
44 unsigned read = (len <= used() ? len : used());
46 if (_tail + read < _size) {
47 memcpy(buffer, _buffer + _tail, read);
49 memcpy(buffer, _buffer + _tail, _size - _tail);
50 memcpy(buffer + _size - _tail, _buffer, read - _size + _tail);
53 _tail = ((unsigned) (_tail + read) % _size);
61 unsigned Fifo::write(const void *source, unsigned len) {
63 char* buffer = (char*) source;
64 unsigned write = (len <= unused() ? len : unused());
65 unsigned head = (_tail + _pos) % _size;
67 if (head + write < _size) {
68 memcpy(_buffer + head, buffer, write);
70 memcpy(_buffer + head, buffer, _size - head);
71 memcpy(_buffer, buffer + _size - head, write - _size + head);
81 unsigned Fifo::size() const {
86 * How many bytes is currently free in the buffer
88 unsigned Fifo::unused() const {
89 return (_size) - used();
93 * How many data are currently stored in the fifo
95 unsigned Fifo::used() const {
100 * Get the pointer to the start of the queue
102 char *Fifo::getQueuePointer() {
107 * Has completed a dma read process, i.e. has read out of the queue
109 void Fifo::dmaRead(unsigned len) {
113 _blocked = BLOCKED_MAX_NR;
115 _tail = ((unsigned) (_tail + len) % _size);
121 * Start a DMA request, returns the current space one have
123 unsigned Fifo::dmaStart() {
126 if (_tail + _pos > _size) {
127 return _size - _tail;
134 * Is allowed to start a dma request
136 bool Fifo::dmaAllowed() {
146 * Test the implementation
151 Fifo *myFifo = new Fifo();
152 for (int j = 0; j < 3; j++) {
153 for (int i = 0; i < 6; i++) {
154 std::cout << "write " << i << " to Fifo. ";
155 int write = myFifo->write(&i, sizeof(int));
156 printf(" %d ", write);
157 if (write == sizeof(int)) {
158 std::cout << "used: " << std::setw(2) << myFifo->used()
159 << ", unused: " << std::setw(2) << myFifo->unused()
160 << ", size: " << std::setw(2) << myFifo->size()
163 std::cout << std::endl;
166 for (int i = 0; i < 6; i++) {
168 int read = myFifo->read(&value, sizeof(int));
169 printf(" %d ", read);
170 if (read == sizeof(int)) {
171 std::cout << "read " << value << " from Fifo ";
172 std::cout << "used: " << std::setw(2) << myFifo->used()
173 << ", unused: " << std::setw(2) << myFifo->unused()
174 << ", size: " << std::setw(2) << myFifo->size()