xref: /inferno-os/libkern/tokenize.c (revision c094a1409b780cc543c077e8469fdb28b4c90afb)
1 #include "lib9.h"
2 
3 static char qsep[] = " \t\r\n";
4 
5 static char*
6 qtoken(char *s)
7 {
8 	int quoting;
9 	char *t;
10 
11 	quoting = 0;
12 	t = s;	/* s is output string, t is input string */
13 	while(*t!='\0' && (quoting || utfrune(qsep, *t)==nil)){
14 		if(*t != '\''){
15 			*s++ = *t++;
16 			continue;
17 		}
18 		/* *t is a quote */
19 		if(!quoting){
20 			quoting = 1;
21 			t++;
22 			continue;
23 		}
24 		/* quoting and we're on a quote */
25 		if(t[1] != '\''){
26 			/* end of quoted section; absorb closing quote */
27 			t++;
28 			quoting = 0;
29 			continue;
30 		}
31 		/* doubled quote; fold one quote into two */
32 		t++;
33 		*s++ = *t++;
34 	}
35 	if(*s != '\0'){
36 		*s = '\0';
37 		if(t == s)
38 			t++;
39 	}
40 	return t;
41 }
42 
43 int
44 tokenize(char *s, char **args, int maxargs)
45 {
46 	int nargs;
47 
48 	for(nargs=0; nargs<maxargs; nargs++){
49 		while(*s!='\0' && utfrune(qsep, *s)!=nil)
50 			s++;
51 		if(*s == '\0')
52 			break;
53 		args[nargs] = s;
54 		s = qtoken(s);
55 	}
56 
57 	return nargs;
58 }
59