Skip to content

Instantly share code, notes, and snippets.

@iscgar
Last active November 9, 2020 18:13
Show Gist options
  • Save iscgar/11a5efddfc3096c67c8a819e3d2b59e1 to your computer and use it in GitHub Desktop.
Save iscgar/11a5efddfc3096c67c8a819e3d2b59e1 to your computer and use it in GitHub Desktop.
Hand-rolled FizzBuzz
#include <string.h>
#include <unistd.h>
#define ALIGNED_BUF 65536
#define DELIM ' '
#define MAX_DIGITS 20 /* 64-bit */
typedef unsigned int fizz_t;
__attribute__((always_inline))
static inline const char* sernum(fizz_t c)
{
static char serbuf[MAX_DIGITS + 1] = { 0 };
char *f = serbuf + sizeof(serbuf) - 2;
for (; c; *f = c % 10 + '0', c /= 10)
{
--f;
}
return f;
}
int main(void)
{
fizz_t cur = 1;
__attribute__((aligned(4096))) static char buf[ALIGNED_BUF + ((MAX_DIGITS + 1) * 15)] = { 0 };
char *off = buf;
for (;;)
{
while (off - buf < ALIGNED_BUF)
{
if (__builtin_expect(cur == 0, 0))
{
goto end;
}
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Fizz"; *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Buzz"; *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Fizz"; *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Fizz"; *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Buzz"; *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "Fizz"; *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
for (const char *c = sernum(cur++); *c; *off++ = *c++)
;
*off++ = DELIM;
++cur;
for (const char *c = "FizzBuzz"; *c; *off++ = *c++)
;
*off++ = DELIM;
}
write(1, buf, ALIGNED_BUF);
memcpy(buf, buf + ALIGNED_BUF, (off - buf) % ALIGNED_BUF);
off -= ALIGNED_BUF;
}
end:
*off++ = '\n';
write(1, buf, off - buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment