カーネルバッファ応用

2026 ワード

#include 

#define FIFO_SIZE      (1024)

typedef struct tagS_FIFO
{
    unsigned int ulSize;
    unsigned int ulIn;
    unsigned int ulOut;
    char *pBuf;
}S_FIFO;

int FIFO_min(unsigned int ulFirstDat, unsigned int ulSndValue)
{
    if (ulFirstDat <= ulSndValue)
    {
        return ulFirstDat;
    }
    else
    {
        return ulSndValue;
    }
}

int FIFO_init(S_FIFO *pFifo)
{
    if (NULL == pFifo)
    {
        return -1;
    }

    pFifo->ulSize = FIFO_SIZE;
    pFifo->ulIn = 0;
    pFifo->ulOut = 0;
    pFifo->pBuf = malloc(FIFO_SIZE * sizeof(char));
    if (NULL == pFifo->pBuf)
    {
        return -1;
    }

    return 0;
}

int FIFO_putData(S_FIFO *pFifo, char *pSrc, unsigned int ulLen)
{
    unsigned int ulWrLen = 0;

    if ((NULL == pFifo) || (NULL == pSrc) || (ulLen <= 0))
    {
        return -1;
    }

    /*           ,              ,        */
    ulLen = FIFO_min(ulLen, pFifo->ulSize - pFifo->ulIn + pFifo->ulOut);

    /*        ,        ,       ,         */
    ulWrLen = FIFO_min(ulLen, pFifo->ulSize - (pFifo->ulIn & (pFifo->ulSize -1)));
    memcpy(pFifo->pBuf + (pFifo->ulIn & (pFifo->ulSize -1)), pSrc, ulWrLen);
    memcpy(pFifo->pBuf, pSrc + ulWrLen, ulLen - ulWrLen);
    pFifo->ulIn += ulLen;


    return ulLen;
}
int FIFO_getData(S_FIFO *pFifo, char *pDst, unsigned int ulLen)
{
    unsigned int ulRdLen = 0;

    if ((NULL == pFifo) || (NULL == pDst) || (ulLen <= 0))
    {
        return -1;
    }

    /*           ,              ,        */
    ulLen = FIFO_min(ulLen, FIFO->ulIn - FIFO->ulOut);

    /*        ,        ,     ,         */
    ulRdLen = FIFO_min(ulLen, pFifo->ulSize - (pFifo->ulOut & (pFifo->ulSize -1)));
    memcpy(pDst, FIFO->pBuf + (pFifo-ulOut & (pFifo->ulSize - 1)), ulRdLen);
    memcpy(pDst + ulRdLen, pFifo->pBuf, ulLen - ulRdLen);

    pFifo->ulOut += ulLen;


    return ulLen;
}