-
Notifications
You must be signed in to change notification settings - Fork 0
/
buffer.c
71 lines (64 loc) · 1.23 KB
/
buffer.c
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
#include "buffer.h"
#include "stdlib.h"
#include "stdio.h"
int *nextPointer(int *start, int size, int *current)
{
int *next = current + 1;
if (next >= start + size)
{
return start;
}
return next;
}
int next(struct Buffer *b)
{
if (b->disposed)
{
return -1;
}
b->currentRead = nextPointer(b->array, b->size, b->currentRead);
return *b->currentRead;
}
void add(struct Buffer *b, int value)
{
if (b->disposed)
{
return;
}
*b->currentWrite = value;
b->currentWrite = nextPointer(b->array, b->size, b->currentWrite);
}
int avg(struct Buffer *b)
{
if (b->disposed)
{
return -1;
}
int result = 0;
for (int i = 0; i < b->size; i++)
{
printf("I:%i, V:%i\n",i,b->array[i]);
result += b->array[i];
}
return result / b->size;
}
void dispose(struct Buffer *b)
{
b->disposed = 1;
free(b->array);
}
struct Buffer newBuffer(int size)
{
struct Buffer buf;
buf.disposed = 0;
buf.size = size;
int *array = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; i++)
{
array[i] = 0;
}
buf.array = array;
buf.currentRead = array;
buf.currentWrite = array;
return buf;
}