-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.pde
96 lines (83 loc) · 2.09 KB
/
buffer.pde
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Buffer manager
/**
Copy the contents of a record from `src' to `dst'.
*/
void record_copy(struct record* src, struct record* dst) {
(*dst).millis = (*src).millis;
(*dst).pulse_count = (*src).pulse_count;
(*dst).air_temp = (*src).air_temp;
(*dst).water_temp = (*src).water_temp;
}
/**
Internal access to the buffer's memory block.
Set `set' to 1 to record a new buffer location and length.
The current index will be set to 0.
Set `set' to 0 to simply get the current buffer location,
length, and index.
Returns the number of items in the buffer, which is
equivalent to the index for the next write operation
*/
long _buf(struct record** buf, long* len, long* i, int set) {
static struct record* thebuffer = 0;
static long index = 0;
static long length = 0;
if (set) {
if (buf) thebuffer = *buf;
if (i) index = *i;
if (len) length = *len;
return index;
}
else {
if (buf) *buf = thebuffer;
if (len) *len = length;
if (i) *i = index;
return index;
}
}
/**
Initialize the buffer to the specified length
The new buffer is guaranteed to hold up to `len' items,
but it may hold more: If the buffer is already longer than
the requested length, it is left unchanged.
The contents of the memory occupied by the new buffer
are undefined, but it will act as if it is empty.
*/
void buf_init(long len) {
struct record* buf;
long current_len;
_buf(&buf, ¤t_len, 0, 0);
if (!buf || current_len < len) {
if (buf) free(buf);
buf = (struct record*) malloc(len * sizeof(struct record));
current_len = len;
}
long i = 0;
_buf(&buf, ¤t_len, &i, 1);
}
/**
Add a record to the buffer.
Returns 1 if successful, 0 if the buffer is full
*/
int buf_add(struct record* rec) {
struct record* buf;
long i, len;
i = _buf(&buf, &len, 0, 0);
if (i < len) {
record_copy(rec, buf + i);
i++;
_buf(&buf, &len, &i, 1);
return 1;
}
else {
return 0;
}
}
/**
Determine if the buffer is full.
*/
int buf_full() {
struct record* buf;
long i, len;
i = _buf(&buf, &len, 0, 0);
return i >= len;
}