chan.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. static char channames[] = "rgbkamx";
  5. char*
  6. chantostr(char *buf, ulong cc)
  7. {
  8. ulong c, rc;
  9. char *p;
  10. if(chantodepth(cc) == 0)
  11. return nil;
  12. /* reverse the channel descriptor so we can easily generate the string in the right order */
  13. rc = 0;
  14. for(c=cc; c; c>>=8){
  15. rc <<= 8;
  16. rc |= c&0xFF;
  17. }
  18. p = buf;
  19. for(c=rc; c; c>>=8) {
  20. *p++ = channames[TYPE(c)];
  21. *p++ = '0'+NBITS(c);
  22. }
  23. *p = 0;
  24. return buf;
  25. }
  26. /* avoid pulling in ctype when using with drawterm etc. */
  27. static int
  28. isspace(char c)
  29. {
  30. return c==' ' || c== '\t' || c=='\r' || c=='\n';
  31. }
  32. ulong
  33. strtochan(char *s)
  34. {
  35. char *p, *q;
  36. ulong c;
  37. int t, n, d;
  38. c = 0;
  39. d = 0;
  40. p=s;
  41. while(*p && isspace(*p))
  42. p++;
  43. while(*p && !isspace(*p)){
  44. if((q = strchr(channames, p[0])) == nil)
  45. return 0;
  46. t = q-channames;
  47. if(p[1] < '0' || p[1] > '9')
  48. return 0;
  49. n = p[1]-'0';
  50. d += n;
  51. c = (c<<8) | __DC(t, n);
  52. p += 2;
  53. }
  54. if(d==0 || (d>8 && d%8) || (d<8 && 8%d))
  55. return 0;
  56. return c;
  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==0 || (n>8 && n%8) || (n<8 && 8%n))
  68. return 0;
  69. return n;
  70. }