Guillermo Stedile / RA8875

Dependencies:   GPS

Dependents:   SNOCC_V1 SNOCC_V2

Fork of RA8875 by SNOCC

SlidingWindow.cpp

Committer:
WiredHome
Date:
2014-03-23
Revision:
63:ed787f5fcdc4

File content as of revision 63:ed787f5fcdc4:


//#include <windows.h>
#include "SlidingWindow.h"
#include <mbed.h>
//#include <stdio.h>
//#include <stdlib.h>

// Define this to implement tracking code.
//#define M_TRACK

SlidingWindow::SlidingWindow(int desiredSize, int allowedSize)
{
    m_forewardUsed = 0;
    m_backwardUsed = 0;
    m_desiredSize = desiredSize;
    m_allowedSize = allowedSize;
    m_buf = (unsigned char *)malloc(allowedSize);
    if (m_buf) {
        m_status = noerror;
    } else {
        m_status = outofmemory;
    }
    #ifdef M_TRACK
    m_used = (unsigned char *)malloc(allowedSize);
    for (int i=0; i<allowedSize; i++)
        m_used[i] = 0;
    #endif
}
SlidingWindow::~SlidingWindow()
{
    //char buf[100];
    //sprintf_s(buf, sizeof(buf), "forewardUsed: %d\n", m_forewardUsed);
    //OutputDebugString(buf);
    //sprintf_s(buf, sizeof(buf), "backwardUsed: %d\n", m_backwardUsed);
    //OutputDebugString(buf);
    free(m_buf);
    #ifdef M_TRACK
    free(m_used);
    #endif
}



bool SlidingWindow::set(int x, unsigned char value)
{
    if (x >= 0)
    {
        if (x >= m_allowedSize)
        {
            x %= m_allowedSize;
        }
        
        m_buf[x] = value;
        #ifdef M_TRACK
        m_used[x] = 1;
        #endif
        if (x > m_forewardUsed)
            m_forewardUsed = x;
        return true;
    }
    else
    {
        m_buf[m_allowedSize + x] = value;
        #ifdef M_TRACK
        m_used[m_allowedSize + x] = 1;
        #endif
        return true;
    }
}
unsigned char SlidingWindow::get(int foreDistance, int backDistance)
{
    int d = foreDistance - backDistance;

    if (d >= 0)
    {
        if (d > m_allowedSize)
            d %= m_allowedSize;     // instead of this, if m_allowedSize < m_desiredSize, and if memory is available, it could reallocate and fix itself
        #ifdef M_TRACK
        if (!m_used[d])
            ERR("buffer location %d was never set\n", d);
        #endif
        return m_buf[d];
    }
    else
    {
        if (d < m_backwardUsed)
            m_backwardUsed = d;
        while (d < -m_allowedSize)
            d %= m_allowedSize;
        //if (!m_used[m_allowedSize + d])
        //{
        //    char buf[100];
        //    sprintf_s(buf, sizeof(buf), "Accessing unitialized location [%d]\n", foreDistance - backDistance);
        //    OutputDebugString(buf);
        //}
        return m_buf[m_allowedSize + d];
    }
}