xref: /plan9/sys/src/cmd/unix/drawterm/libdraw/chan.c (revision 7dd7cddf99dd7472612f1413b4da293630e6b1bc)
1 #include "../lib9.h"
2 
3 #include "../libdraw/draw.h"
4 #include <ctype.h>
5 
6 static char channames[] = "rgbkamx";
7 char*
8 chantostr(char *buf, ulong cc)
9 {
10 	ulong c, rc;
11 	char *p;
12 
13 	if(chantodepth(cc) == 0)
14 		return nil;
15 
16 	/* reverse the channel descriptor so we can easily generate the string in the right order */
17 	rc = 0;
18 	for(c=cc; c; c>>=8){
19 		rc <<= 8;
20 		rc |= c&0xFF;
21 	}
22 
23 	p = buf;
24 	for(c=rc; c; c>>=8) {
25 		*p++ = channames[TYPE(c)];
26 		*p++ = '0'+NBITS(c);
27 	}
28 	*p = 0;
29 
30 	return buf;
31 }
32 
33 ulong
34 strtochan(char *s)
35 {
36 	char *p, *q;
37 	ulong c;
38 	int t, n;
39 
40 	c = 0;
41 	p=s;
42 	while(*p && isspace(*p))
43 		p++;
44 
45 	while(*p && !isspace(*p)){
46 		if((q = strchr(channames, p[0])) == nil)
47 			return 0;
48 		t = q-channames;
49 		if(p[1] < '0' || p[1] > '9')
50 			return 0;
51 		n = p[1]-'0';
52 		c = (c<<8) | __DC(t, n);
53 		p += 2;
54 	}
55 	return c;
56 }
57 
58 int
59 chantodepth(ulong c)
60 {
61 	int n;
62 	for(n=0; c; c>>=8){
63 		if(TYPE(c) >= NChan || NBITS(c) > 8 || NBITS(c) <= 0)
64 			return 0;
65 		n += NBITS(c);
66 	}
67 	if((n>8 && n%8) || (n<8 && 8%n))
68 		return 0;
69 	return n;
70 }
71