~kris/9p

9hist

ref: 0103abfceb980d7d3f76cd72b9b8378dce4b2f22 9hist/port/queue.c -rw-r--r-- 1.0 KiB
0103abfc — David du Colombier Plan 9 from Bell Labs 1991-05-10 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
#include	"u.h"
#include	"lib.h"
#include	"mem.h"
#include	"dat.h"
#include	"fns.h"
#include	"io.h"
#include	"errno.h"

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

int
putc(IOQ *q, int c)
{
	uchar *nextin;
	if(q->in >= &q->buf[sizeof(q->buf)-1])
		nextin = q->buf;
	else
		nextin = q->in+1;
	if(nextin == q->out)
		return -1;
	*q->in = c;
	q->in = nextin;
	return 0;
}

int
getc(IOQ *q)
{
	int c;

	if(q->in == q->out)
		return -1;
	c = *q->out;
	if(q->out == q->buf+sizeof(q->buf)-1)
		q->out = q->buf;
	else
		q->out++;
	return c;
}

void
puts(IOQ *q, char *s, int n)
{
	int m;

	while(n){
		if(q->out > q->in)
			m = q->out - q->in - 1;
		else
			m = &q->buf[NQ] - q->in;
		if(m > n)
			m = n;
		memmove(q->in, s, m);
		n -= m;
		q->in += m;
		if(q->in >= &q->buf[NQ])
			q->in = q->buf;
	}
}

int
cangetc(void *arg)
{
	IOQ *q = (IOQ *)arg;
	return q->in != q->out;
}

int
canputc(void *arg)
{
	IOQ *q = (IOQ *)arg;
	uchar *next;

	next = q->in+1;
	if(next >= &q->buf[sizeof(q->buf)])
		next = q->buf;
	return next != q->out;
}