-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathcbuf.h
47 lines (42 loc) · 1.35 KB
/
cbuf.h
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
#ifndef __CBUF_H
#define __CBUF_H
/*
* circular buffer:
* .<------------size-------------->.
* | |
* |<-x->|<-CBUFUSED->|<-----y----->|
* | | |<-CBUFRIGHT->|
* +-----++++++++++++++-------------+
* | |
* CBUFTAIL CBUFHEAD
* (CBUFFREE = x+y)
*/
struct cbuf {
int head; /* write point */
int tail; /* read point */
int size;
char buf[0];
};
#define _CBUFHEAD(cbuf) ((cbuf)->head % (cbuf)->size)
#define _CBUFTAIL(cbuf) ((cbuf)->tail % (cbuf)->size)
#define CBUFUSED(cbuf) ((cbuf)->head - (cbuf)->tail)
#define CBUFFREE(cbuf) ((cbuf)->size - CBUFUSED(cbuf))
#define CBUFHEAD(cbuf) &(cbuf)->buf[_CBUFHEAD(cbuf)]
#define CBUFTAIL(cbuf) &(cbuf)->buf[_CBUFTAIL(cbuf)]
/* head right space for writing */
#define CBUFHEADRIGHT(cbuf)\
((CBUFHEAD(cbuf) >= CBUFTAIL(cbuf)) ?\
((cbuf->size - _CBUFHEAD(cbuf))) :\
(_CBUFTAIL(cbuf) - _CBUFHEAD(cbuf)))
/* tail righ space for reading */
#define CBUFTAILRIGHT(cbuf)\
((CBUFHEAD(cbuf) > CBUFTAIL(cbuf)) ?\
(CBUFUSED(cbuf)) :\
((cbuf)->size - _CBUFTAIL(cbuf)))
extern int read_cbuf(struct cbuf *cbuf, char *buf, int size);
extern int write_cbuf(struct cbuf *cbuf, char *buf, int size);
extern struct cbuf *alloc_cbuf(int size);
extern void free_cbuf(struct cbuf *cbuf);
extern int alloc_cbufs;
extern int free_cbufs;
#endif /* cbuf.h */