Skip to content

Instantly share code, notes, and snippets.

@jdh8
Created May 16, 2019 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdh8/7e5175ca2a80599d4e3e9a3d4db23391 to your computer and use it in GitHub Desktop.
Save jdh8/7e5175ca2a80599d4e3e9a3d4db23391 to your computer and use it in GitHub Desktop.
#include "FILE.h"
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
static uint_least32_t _modifier(unsigned c)
{
unsigned s = c - ' ';
return s < 32 ? UINT32_C(1) << s : UINT32_C(0);
}
static int _convert(size_t count, FILE stream[restrict static 1], const char format[restrict static 1], va_list list)
{
const uint_least32_t left = _modifier('-');
const uint_least32_t plus = _modifier('+');
const uint_least32_t pad = _modifier(' ');
const uint_least32_t alt = _modifier('#');
const uint_least32_t zero = _modifier('0');
const uint_least32_t group = _modifier('\'');
const uint_least32_t flags = left | plus | pad | alt | zero | group;
uint_least32_t modifier = 0;
int width = 0;
int precision = 0;
for (uint_least32_t bit; (bit = _modifier(*format)) & flags; ++format)
modifier |= bit;
if (*format == '*') {
width = va_arg(list, int);
++format;
}
else for (unsigned digit; (digit = *format - '0') < 10; ++format)
width = 10 * width + digit;
if (*format == '.') {
if (*++format == '*') {
precision = va_arg(list, int);
++format;
}
else for (unsigned digit; (digit = *format - '0') < 10; ++format)
precision = 10 * precision + digit;
}
}
static int _print(size_t count, FILE stream[restrict static 1], const char format[restrict static 1], va_list list)
{
for (size_t i = 0; ; ++i) switch (format[i]) {
case '%':
return stream->_write(format, i, stream) == i ? _convert(count, stream, format + 1, list) : -1;
case '\0':
return stream->_write(format, i, stream) == i ? (int)(count + i) : -1;
}
}
int vfprintf(FILE stream[restrict static 1], const char format[restrict static 1], va_list list)
{
return _print(0, stream, format, list);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment