Skip to content

Commit

Permalink
Merge pull request #77 from no92/printf-dollar-args
Browse files Browse the repository at this point in the history
printf: handle argument indices given by dollars in format strings
  • Loading branch information
no92 authored Dec 7, 2024
2 parents 922d38d + 79a9571 commit 1cf2ba1
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 2 deletions.
1 change: 1 addition & 0 deletions include/frg/formatting.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ struct format_options {
format_conversion conversion;
int minimum_width = 0;
int arg_pos = -1;
bool dollar_arg_pos = false;
optional<int> precision;
bool left_justify = false;
bool always_sign = false;
Expand Down
15 changes: 13 additions & 2 deletions include/frg/printf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,16 @@ T pop_arg(va_struct *vsp, format_options *opts) {
if (opts->arg_pos == -1)
return pop_va_arg();

FRG_ASSERT(opts->arg_pos <= vsp->num_args);
if (opts->arg_pos < vsp->num_args)
if(opts->dollar_arg_pos) {
// we copy out all previous and the requested argument into our vsp->arg_list
for(int i = vsp->num_args; i <= opts->arg_pos; i++) {
auto arg = pop_va_arg();
*get_union_member(i) = arg;
}

vsp->num_args = opts->arg_pos + 1;
return *get_union_member(opts->arg_pos);
}

auto arg = pop_va_arg();
*get_union_member(vsp->num_args++) = arg;
Expand All @@ -74,6 +81,7 @@ T pop_arg(va_struct *vsp, format_options *opts) {
template<typename A>
frg::expected<format_error> printf_format(A agent, const char *s, va_struct *vsp) {
FRG_ASSERT(s != nullptr);
bool dollar_arg_pos = false;

while(*s) {
if(*s != '%') {
Expand All @@ -100,9 +108,12 @@ frg::expected<format_error> printf_format(A agent, const char *s, va_struct *vsp


format_options opts;
opts.dollar_arg_pos = dollar_arg_pos;
while(true) {
if (*s >= '0' && *s <= '9' && s[1] && s[1] == '$') {
opts.arg_pos = *s - '0' - 1; // args are 1-indexed
opts.dollar_arg_pos = true;
dollar_arg_pos = true;
s += 2;
FRG_ASSERT(*s);
} else if(*s == '-') {
Expand Down
2 changes: 2 additions & 0 deletions tests/tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,8 @@ TEST(formatting, printf) {
do_test("hello", "%.5s", "hello world");
do_test("hello", "%.*s", 5, "hello world");
do_test("hello", "%.10s", "hello\0!!!!");

do_test("55 33", "%2$d %1$d", 33, 55);
}

#include <frg/bitset.hpp>
Expand Down

0 comments on commit 1cf2ba1

Please sign in to comment.