/* -*- c++ -*-
 *
 * SOCLIB_LGPL_HEADER_BEGIN
 * 
 * This file is part of SoCLib, GNU LGPLv2.1.
 * 
 * SoCLib is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation; version 2.1 of the License.
 * 
 * SoCLib is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with SoCLib; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA
 * 
 * SOCLIB_LGPL_HEADER_END
 *
 * Copyright (c) UPMC, Lip6, Asim
 *         Nicolas Pouillon <nipo@ssji.net>, 2007
 *         Alain Greiner <alain.greiner@lip6.fr>, 2003
 *
 * Maintainers: nipo
 */
#ifndef _GENERIC_FIFO_H
#define _GENERIC_FIFO_H

#include "stdio.h"

template<typename _data_t>

class GenericFifo
{
  public:
    typedef _data_t data_t;

  private:
    data_t *m_data;
    int    r_ptr;
    int    r_ptw;
    int    r_fill_state;
    int m_depth;
  public:

    std::string
      getName()
      {
        return "fifo";
      }
    void init()
    {
      r_ptr = 0;
      r_ptw = 0;
      r_fill_state = 0;
    }

    int filled_status() const
    {
      return (uint32_t)r_fill_state;
    }

    bool empty() const
    {
      return !(uint32_t)r_fill_state;
    }

    bool full() const
    {
      return r_fill_state == m_depth;
    }

    void simple_put(const data_t &din)
    {
      if (r_fill_state != m_depth) { 
        r_fill_state = r_fill_state + 1;
        m_data[r_ptw] = din;
        r_ptw = (r_ptw + 1) % m_depth;
      }
    }

    void simple_get()
    {
      if (r_fill_state != 0) {
        r_fill_state = r_fill_state - 1;
        r_ptr = (r_ptr + 1) % m_depth;
      }
    }

    void put_and_get(const data_t &din)
    {
      if (r_fill_state == m_depth) {
        r_fill_state = r_fill_state - 1;
        r_ptr = (r_ptr + 1) % m_depth;
      } else if (r_fill_state == 0) {
        r_fill_state = r_fill_state + 1;
        m_data[r_ptw] = din; 
        r_ptw = (r_ptw + 1) % m_depth;
      } else {
        r_ptr = (r_ptr + 1) % m_depth;
        m_data[r_ptw] = din;
        r_ptw = (r_ptw + 1) % m_depth;  
      }
    }

    bool rok() const
    {
      return (r_fill_state != 0);
    }

    bool wok() const
    {
      return (r_fill_state != m_depth);
    }

    const data_t &read() const
    {

      return m_data[r_ptr];
    }

    GenericFifo(size_t depth)
    {
      m_data = new data_t[depth];
      r_ptr = 0;
      r_ptw = 0;
      r_fill_state = 0;
      m_depth = depth;
    }

    ~GenericFifo()
    {
      delete [] m_data;
    }
};


#endif 
