plan9port/src/lib9/encodefmt.c

77 lines
1 KiB
C
Raw Normal View History

2003-09-30 17:47:41 +00:00
#include <lib9.h>
int
encodefmt(Fmt *f)
{
char *out;
2004-12-27 00:11:01 +00:00
char *buf, *p;
2003-09-30 17:47:41 +00:00
int len;
int ilen;
int rv;
uchar *b;
char obuf[64]; // rsc optimization
b = va_arg(f->args, uchar*);
2004-12-26 23:17:03 +00:00
if(b == 0)
return fmtstrcpy(f, "<nil>");
2003-09-30 17:47:41 +00:00
ilen = f->prec;
f->prec = 0;
2005-05-19 14:39:00 +00:00
if(!(f->flags&FmtPrec) || ilen < 0)
goto error;
2003-09-30 17:47:41 +00:00
f->flags &= ~FmtPrec;
2005-05-19 14:39:00 +00:00
2003-09-30 17:47:41 +00:00
switch(f->r){
case '<':
len = (8*ilen+4)/5 + 3;
break;
case '[':
len = (8*ilen+5)/6 + 4;
break;
case 'H':
len = 2*ilen + 1;
break;
default:
goto error;
}
if(len > sizeof(obuf)){
buf = malloc(len);
if(buf == nil)
goto error;
} else
buf = obuf;
// convert
out = buf;
switch(f->r){
case '<':
rv = enc32(out, len, b, ilen);
break;
case '[':
rv = enc64(out, len, b, ilen);
break;
case 'H':
rv = enc16(out, len, b, ilen);
2004-12-26 23:17:03 +00:00
if(rv >= 0 && (f->flags & FmtLong))
for(p = buf; *p; p++)
*p = tolower((uchar)*p);
2003-09-30 17:47:41 +00:00
break;
default:
rv = -1;
break;
}
if(rv < 0)
goto error;
fmtstrcpy(f, buf);
if(buf != obuf)
free(buf);
return 0;
error:
return fmtstrcpy(f, "<encodefmt>");
}