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