~kris/9p

9hist

ref: c32088eb1ef2c431cda8f56c6b8c966ec40b63b3 9hist/port/parse.c -rw-r--r-- 788 bytes
c32088eb — David du Colombier Plan 9 from Bell Labs 2001-11-08 24 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
#include	"u.h"
#include	"../port/lib.h"
#include	"mem.h"
#include	"dat.h"
#include	"fns.h"
#include	"../port/error.h"

/*
 *  parse a command written to a device
 */
Cmdbuf*
parsecmd(char *p, int n)
{
	Cmdbuf *volatile cb;
	int nf;
	char *sp;

	/* count fields and allocate a big enough cmdbuf */
	for(nf = 1, sp = p; sp != nil && *sp; nf++, sp = strchr(sp+1, ' '))
		;
	sp = smalloc(sizeof(*cb) + n + 1 + nf*sizeof(char*));
	cb = (Cmdbuf*)sp;
	cb->buf = sp+sizeof(*cb);
	cb->f = (char**)(cb->buf + n + 1);

	if(up!=nil && waserror()){
		free(cb);
		nexterror();
	}
	memmove(cb->buf, p, n);
	if(up != nil)
		poperror();

	/* dump new line and null terminate */
	if(n > 0 && cb->buf[n-1] == '\n')
		n--;
	cb->buf[n] = '\0';

	cb->nf = getfields(cb->buf, cb->f, nf, 1, " ");
	return cb;
}