Skip to content

Commit

Permalink
Use variadic template in vformat()
Browse files Browse the repository at this point in the history
Allows `vformat()` to take more than 5 arguments. as well as being a general optimisation that avoids redundant empty Variant checks.
  • Loading branch information
Mickeon committed Sep 14, 2022
1 parent b4967e3 commit 0715250
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 31 deletions.
30 changes: 0 additions & 30 deletions core/variant/variant.cpp
Expand Up @@ -3727,36 +3727,6 @@ String Variant::get_callable_error_text(const Callable &p_callable, const Varian
return get_call_error_text(p_callable.get_object(), p_callable.get_method(), p_argptrs, p_argcount, ce);
}

String vformat(const String &p_text, const Variant &p1, const Variant &p2, const Variant &p3, const Variant &p4, const Variant &p5) {
Array args;
if (p1.get_type() != Variant::NIL) {
args.push_back(p1);

if (p2.get_type() != Variant::NIL) {
args.push_back(p2);

if (p3.get_type() != Variant::NIL) {
args.push_back(p3);

if (p4.get_type() != Variant::NIL) {
args.push_back(p4);

if (p5.get_type() != Variant::NIL) {
args.push_back(p5);
}
}
}
}
}

bool error = false;
String fmt = p_text.sprintf(args, &error);

ERR_FAIL_COND_V_MSG(error, String(), fmt);

return fmt;
}

void Variant::register_types() {
_register_variant_operators();
_register_variant_methods();
Expand Down
17 changes: 16 additions & 1 deletion core/variant/variant.h
Expand Up @@ -807,7 +807,22 @@ const Variant::ObjData &Variant::_get_obj() const {
return *reinterpret_cast<const ObjData *>(&_data._mem[0]);
}

String vformat(const String &p_text, const Variant &p1 = Variant(), const Variant &p2 = Variant(), const Variant &p3 = Variant(), const Variant &p4 = Variant(), const Variant &p5 = Variant());
template <typename... VarArgs>
String vformat(const String &p_text, const VarArgs... p_args) {
Variant args[sizeof...(p_args) + 1] = { p_args..., Variant() }; // +1 makes sure zero sized arrays are also supported.
Array args_array;
args_array.resize(sizeof...(p_args));
for (uint32_t i = 0; i < sizeof...(p_args); i++) {
args_array[i] = args[i];
}

bool error = false;
String fmt = p_text.sprintf(args_array, &error);

ERR_FAIL_COND_V_MSG(error, String(), fmt);

return fmt;
}

template <typename... VarArgs>
Callable Callable::bind(VarArgs... p_args) {
Expand Down

0 comments on commit 0715250

Please sign in to comment.