Simple buffer.

Dependents:   data_logger

buffer.cpp

Committer:
jhestolano
Date:
2013-06-04
Revision:
0:f45f33d1febb

File content as of revision 0:f45f33d1febb:

#include "buffer.h"

template<class T>
Buffer<T>::Buffer(int buf_size)
{
    size = buf_size;
    data = new T[buf_size];
    full = false;
    empty = true;
    p_tail = &data[0];
    p_head = &data[0];
    p_start = &data[0];
    p_end = &data[buf_size];
}

template<class T>
void Buffer<T>::put(T val)
{
    if(!full) //Si hay espacio, escribe.
    {
        *p_head = val;
        p_head++;
        empty = false; //Si se pudo esciribir, el buffer no está vacío.
        if(p_head == p_end) //Si ya llegó al final, volver a iniciar.
        {
            p_head = p_start;
        }
        if(p_head == p_tail)
        {
            full = true; // Si el indice de escritura alcanza el de lectura, el buffer se llenó.
        }
    }
    else //Buffer lleno
    {
        //std::cout << "Buffer lleno..." << std::endl;
    }
}

template<class T>
T Buffer<T>::get()
{
    if(!empty)
    {
        T temp = *p_tail;
        *p_tail = 0;
        p_tail++;
        full = false;
        if(p_tail == p_end)
        {
            p_tail = p_start;
        }
        if(p_tail == p_head)
        {
            empty = true;
        }
        return temp;
    }
    else
    {
        //std::cout << "Buffer vacío..." << std::endl;
        return 0;
    }

}

template<class T>
bool Buffer<T>::isEmpty()
{
    return empty;
}

template<class T>
bool Buffer<T>::isFull()
{
    return full;
}

/*
template<class T>
void Buffer<T>::printData()
{
    for(int i = 0; i < size; i++)
    {
        std::cout << "Elemento " << i << ": " << data[i] << std::endl;
    }
}
*/

template<class T>
Buffer<T>::~Buffer()
{
    delete[] data;
}



template class Buffer<float>;
template class Buffer<char>;
template class Buffer<uint8_t>;
template class Buffer<uint16_t>;
template class Buffer<uint32_t>;
template class Buffer<int8_t>;
template class Buffer<int16_t>;
template class Buffer<int32_t>;
template class Buffer<double>;