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