ringbuffer.c 1.41 KB
Newer Older
Jake Read's avatar
Jake Read committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
/*
 * ringbuffer.c
 *
 * Created: 2/7/2018 11:39:44 AM
 *  Author: Jake
 */ 

#include "ringbuffer.h"
#include "fastmath.h"

uint8_t rb_init(ringbuffer_t *rb){
	rb->size = RINGBUFFER_SIZE; 
	// stuck with this, due to not having malloc, wall of skill
	//rb->buffer = malloc(size);
	rb_reset(rb);
	return 1;
}

uint8_t rb_reset(ringbuffer_t *rb){
	if(rb){
		rb->head = 0;
		rb->tail = 0;
		return 1;
	} else {
		return 0;
	}
}

uint8_t rb_empty(ringbuffer_t *rb){
	return (rb->head == rb->tail);
}

uint8_t rb_full(ringbuffer_t *rb){
	// read from tail, update at head
	// if head is 'just behind' tail (in ring) we have no extra space: the
	return fastModulo((rb->head + 1), RINGBUFFER_SIZE) == rb->tail;
}

uint8_t rb_freespace(ringbuffer_t *rb){
	if(rb->head >= rb->tail){
		return rb->size - (rb->head - rb->tail);
	} else {
		return rb->tail - rb->head - 1;
	}
}

uint8_t rb_putchar(ringbuffer_t *rb, uint8_t data){
	rb->buffer[rb->head] = data;
	rb->head = fastModulo((rb->head + 1), RINGBUFFER_SIZE); // increment and loop about
	return 1;
}

uint8_t rb_putdata(ringbuffer_t *rb, uint8_t *data, uint8_t size){
	/*
	if(rb_freespace(rb) >= size){
		// rb_freespace, not working?
		return 0;
	} else {
		*/
	for(int i = 0; i < size; i ++){
		rb_putchar(rb, data[i]);
	}
	
	return 1;
	//}
}

uint8_t rb_get(ringbuffer_t *rb){
	uint8_t data = rb->buffer[rb->tail];
	rb->tail = fastModulo((rb->tail + 1), RINGBUFFER_SIZE);
	return data;
}