Subversion Repositories Code-Repo

Rev

Rev 114 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#include "buffer.h"
#include "maindefs.h"

#pragma udata buffer
unsigned char buffer[BUFFER_SIZE];
#pragma udata
BUFFER_DATA *buffer_data;

void buffer_init(BUFFER_DATA *data) {
    buffer_data = data;
    buffer_data->index_read = 0;
    buffer_data->index_write = 0;
    buffer_data->stored_length = 0;
    buffer_data->buffer = buffer;
}

char buffer_insert_one(unsigned char c) {
    if (BUFFER_SIZE - buffer_data->stored_length == 0) {
        DBG_PRINT_BUFFER("Buffer: (ERROR) Not enough free space for insert\r\n");
        return -1;
    }

    // Update the amount of used space in the buffer
    buffer_data->stored_length += 1;

    // Copy data from msg to buffer
    buffer_data->buffer[buffer_data->index_write] = c;
    buffer_data->index_write++;
    if (buffer_data->index_write == BUFFER_SIZE) {
        buffer_data->index_write = 0;
    }

    return 0;
}

char buffer_insert(unsigned char length, unsigned char *msg) {
    unsigned char i;

    // Make sure we have enough space to store message
    if (length > BUFFER_SIZE - buffer_data->stored_length) {
        DBG_PRINT_BUFFER("Buffer: (ERROR) Not enough free space for insert\r\n");
        return -1;
    }

    // Update the amount of used space in the buffer
    buffer_data->stored_length += length;

    // Copy data from msg to buffer
    for (i = 0; i < length; i++) {
        buffer_data->buffer[buffer_data->index_write] = *(msg + i);
        buffer_data->index_write++;
        if (buffer_data->index_write == BUFFER_SIZE) {
            buffer_data->index_write = 0;
        }
    }

    return 0;
}

char buffer_read(unsigned char length, unsigned char *dest) {
    unsigned char i;

    // Make sure requested data is less than size of stored data
    if (length > buffer_data->stored_length) {
        DBG_PRINT_BUFFER("Buffer: (ERROR) Read length exceedes stored length\r\n");
        return -1;
    }

    // Update the amount of used space in the buffer
    buffer_data->stored_length -= length;

    // Copy data from buffer to dest
    for (i = 0; i < length; i++) {
        *(dest + i) = buffer_data->buffer[buffer_data->index_read];
        buffer_data->index_read++;
        if (buffer_data->index_read == BUFFER_SIZE) {
            buffer_data->index_read = 0;
        }
    }

    return 0;
}

unsigned int buffer_free_space() {
    return BUFFER_SIZE - buffer_data->stored_length;
}