encodefmt.c (1072B)
1 #include <lib9.h> 2 3 int 4 encodefmt(Fmt *f) 5 { 6 char *out; 7 char *buf, *p; 8 int len; 9 int ilen; 10 int rv; 11 uchar *b; 12 char obuf[64]; /* rsc optimization */ 13 14 b = va_arg(f->args, uchar*); 15 if(b == 0) 16 return fmtstrcpy(f, "<nil>"); 17 18 ilen = f->prec; 19 f->prec = 0; 20 21 if(!(f->flags&FmtPrec) || ilen < 0) 22 goto error; 23 24 f->flags &= ~FmtPrec; 25 26 switch(f->r){ 27 case '<': 28 len = (8*ilen+4)/5 + 3; 29 break; 30 case '[': 31 len = (8*ilen+5)/6 + 4; 32 break; 33 case 'H': 34 len = 2*ilen + 1; 35 break; 36 default: 37 goto error; 38 } 39 40 if(len > sizeof(obuf)){ 41 buf = malloc(len); 42 if(buf == nil) 43 goto error; 44 } else 45 buf = obuf; 46 47 /* convert */ 48 out = buf; 49 switch(f->r){ 50 case '<': 51 rv = enc32(out, len, b, ilen); 52 break; 53 case '[': 54 rv = enc64(out, len, b, ilen); 55 break; 56 case 'H': 57 rv = enc16(out, len, b, ilen); 58 if(rv >= 0 && (f->flags & FmtLong)) 59 for(p = buf; *p; p++) 60 *p = tolower((uchar)*p); 61 break; 62 default: 63 rv = -1; 64 break; 65 } 66 if(rv < 0) 67 goto error; 68 69 fmtstrcpy(f, buf); 70 if(buf != obuf) 71 free(buf); 72 return 0; 73 74 error: 75 return fmtstrcpy(f, "<encodefmt>"); 76 }