Skip to content

Commit

Permalink
Implemented fmtlib#1674: make dynamic_format_arg_store reusable and add
Browse files Browse the repository at this point in the history
reserve() for better memory menagement.
  • Loading branch information
vsolontsov-ll committed May 11, 2020
1 parent e0d9892 commit da2b65e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/fmt/core.h
Original file line number Diff line number Diff line change
Expand Up @@ -1572,6 +1572,24 @@ class dynamic_format_arg_store
emplace_arg(fmt::arg(arg_name, arg.value));
}
}

/** Erase all elements from the store */
void clear() {
data_.clear();
named_info_.clear();
dynamic_args_ = internal::dynamic_arg_list();
}

/**
Reserves space to store at least *new_cap* arguments including
*new_cap_named* named arguments.
*/
void reserve(size_t new_cap, size_t new_cap_named) {
FMT_ASSERT(new_cap >= new_cap_named,
"Set of argument includes set of named arguments");
data_.reserve(new_cap);
named_info_.reserve(new_cap_named);
}
};

/**
Expand Down
26 changes: 26 additions & 0 deletions test/core-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,32 @@ TEST(FormatDynArgsTest, NamedCustomFormat) {
EXPECT_EQ("cust=0 and cust=1 and cust=3", result);
}

TEST(FormatDynArgsTest, Clear) {
fmt::dynamic_format_arg_store<fmt::format_context> store;
store.push_back(42);

std::string result = fmt::vformat("{}", store);
EXPECT_EQ("42", result);

store.push_back(43);
result = fmt::vformat("{} and {}", store);
EXPECT_EQ("42 and 43", result);

store.clear();
store.push_back(44);
result = fmt::vformat("{}", store);
EXPECT_EQ("44", result);
}

TEST(FormatDynArgsTest, Reserve) {
fmt::dynamic_format_arg_store<fmt::format_context> store;
store.reserve(2, 1);
store.push_back(1.5f);
store.push_back(fmt::arg("a1", 42));
std::string result = fmt::vformat("{a1} and {}", store);
EXPECT_EQ("42 and 1.5", result);
}

struct copy_throwable {
copy_throwable() {}
copy_throwable(const copy_throwable&) { throw "deal with it"; }
Expand Down

0 comments on commit da2b65e

Please sign in to comment.