~kris/9p

9hist

ref: 199caac4a5a50eec65c2ed0244db029bf359a26b 9hist/port/queue.c -rw-r--r-- 1.2 KiB
199caac4 — David du Colombier Plan 9 from Bell Labs 1991-08-08 35 years ago
                                                                                
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
97
98
99
100
101
102
103
104
105
106
#include	"u.h"
#include	"lib.h"
#include	"mem.h"
#include	"dat.h"
#include	"fns.h"
#include	"io.h"

void
initq(IOQ *q)
{
	lock(q);
	unlock(q);
	q->in = q->out = q->buf;
	q->puts = puts;
	q->putc = putc;
}

int
putc(IOQ *q, int c)
{
	uchar *next;

	if(q->in ==  &q->buf[NQ-1])
		next = q->buf;
	else
		next = q->in+1;
	if(next == q->out)
		return -1;
	*q->in = c;
	q->in = next;
	return 0;
}

int
getc(IOQ *q)
{
	int c;

	if(q->in == q->out)
		return -1;
	c = *q->out;
	if(q->out == &q->buf[NQ-1])
		q->out = q->buf;
	else
		q->out++;
	return c;
}

void
puts(IOQ *q, void *buf, int n)
{
	uchar *next;
	uchar *p = buf;

	for(; n; n--){
		if(q->in == &q->buf[NQ-1])
			next = q->buf;
		else
			next = q->in + 1;
		if(next == q->out)
			break;
		*q->in = *p++;
		q->in = next;
	}
}

int
gets(IOQ *q, void *buf, int n)
{
	uchar *p = buf;

	for(; n && q->out != q->in; n--){
		*p++ = *q->out;
		if(q->out == &q->buf[NQ-1])
			q->out = q->buf;
		else
			q->out++;
	}
	return p - (uchar*)buf;
}

int
cangetc(void *arg)
{
	IOQ *q;
	int n;

	q = (IOQ *)arg;
	n = q->in - q->out;
	if (n < 0)
		n += sizeof(q->buf);
	return n;
}

int
canputc(void *arg)
{
	IOQ *q;
	int n;

	q = (IOQ *)arg;
	n = q->out - q->in - 1;
	if (n < 0)
		n += sizeof(q->buf);
	return n;
}