/*
 *  htk_buffer.c
 *
 *  Description: Circular FIFO
 *  Created on: March 25, 2020
 *      Author: CrystalSu
 */

#include "htk_buffer.h"

/**
 *  Ring Buffer Initialization
 *
 */
void htk_ringBufferInit(__IO serial_RB_t * rb, uint8_t * buffer, uint16_t size) {
  rb->buffer  = buffer;
  rb->read    = &(rb->buffer[0]); // point to start
  rb->write   = &(rb->buffer[0]); // point to start
  rb->maxSize = size;
  rb->entries = 0; // 0 byte in the ring buffer
}

/**
 *  Ring Buffer Write operation
 *
 */
uint8_t htk_ringBufferWrite(__IO serial_RB_t * rb, uint8_t data) {
  // Check a number of bytes in buffer
  if(rb->entries == rb->maxSize) {
    return 0xFF; // ERROR: buffer full (can't put any data)
  }
  // Increase number of bytes in buffer
  rb->entries++;
  // Check a write index if reach over last index of buffer
  if((rb->write) > &(rb->buffer[rb->maxSize -1])) {
    rb->write = &(rb->buffer[0]); // reset index to start
  }
  // Put data
  * (rb->write++) = data;

  return 0; // SUCCESS
}

/**
 *  Ring Buffer Read operation
 *
 */
uint8_t htk_ringBufferRead(__IO serial_RB_t * rb, uint8_t * data) {
  // Check a number of bytes in buffer
  if(rb->entries == 0) {
    return 0xFF; // ERROR: buffer empty (can't get any data)
  }
  // Decrease number of bytes in buffer
  rb->entries--;
  // Check a read index if reach over last index of buffer
  if((rb->read) > &(rb->buffer[rb->maxSize -1])) {
    rb->read = &(rb->buffer[0]); // reset index to start
  }
  // Get data
  * data = * (rb->read++);

  return 0; // SUCCESS
}

/**
 *  Ring Buffer Flush
 *
 */
void htk_ringBufferFlush(__IO serial_RB_t * rb) {
  rb->entries = 0;
  rb->read    = &(rb->buffer[0]);
  rb->write   = &(rb->buffer[0]);
}

