Reflexion, oil on canvas, 1905
by
William-Adolphe Bouguereau
While browsing OpenBSD’s httpd’s
code, I stumbled upon “weird” flags packed to a char *, used via a function printb_flags().
Turn’s out the way it works is quite fun; here’s a runnable excerpt:
#include <ctype.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#define SRVFLAG_BITS \
"\10\01INDEX\02NO_INDEX\03AUTO_INDEX\04NO_AUTO_INDEX" \
"\05ROOT\06LOCATION\07FCGI\10NO_FCGI\11LOG\12NO_LOG\13ERRDOCS" \
"\14SYSLOG\15NO_SYSLOG\16TLS\17ACCESS_LOG\20ERROR_LOG" \
"\21AUTH\22NO_AUTH\23BLOCK\24NO_BLOCK\25LOCATION_MATCH" \
"\26SERVER_MATCH\27SERVER_HSTS\30DEFAULT_TYPE\31PATH_REWRITE" \
"\32NO_PATH_REWRITE\34NO_BANNER\33GZIP_STATIC\37LOCATION_FOUND" \
"\40LOCATION_NOT_FOUND"
const char *
printb_flags(const uint32_t v, const char *bits)
{
static char buf[2][BUFSIZ];
static int idx = 0;
int i, any = 0;
char c, *p, *r;
p = r = buf[++idx % 2];
memset(p, 0, BUFSIZ);
if (bits) {
bits++;
while ((i = *bits++)) {
if (v & (1 << (i - 1))) {
if (any) {
*p++ = ',';
*p++ = ' ';
}
any = 1;
for (; (c = *bits) > 32; bits++) {
if (c == '_')
*p++ = ' ';
else
*p++ = tolower((unsigned char)c);
}
} else
for (; *bits > 32; bits++)
;
}
}
return (r);
}
int
main(void) {
printf("%s\n", printb_flags((1 << 0) | (1 << 3) | (1 << 30), SRVFLAG_BITS));
return 0;
}Below’s a commented version of the previous excerpt; I encourage you to think about it on your own though.
Solution:[+]
Comments
By email, at mathieu.bivert chez: