Browse Source

`DrawStringFormatArg`: Use `std::variant`

pull/6488/head
Gleb Mazovetskiy 3 years ago
parent
commit
cbf51cd5ab
  1. 5
      Source/engine/render/text_render.cpp
  2. 34
      Source/engine/render/text_render.hpp
  3. 2
      Source/player.h

5
Source/engine/render/text_render.cpp

@ -11,6 +11,7 @@
#include <optional>
#include <unordered_map>
#include <utility>
#include <variant>
#include <fmt/core.h>
@ -262,7 +263,7 @@ std::size_t CountNewlines(std::string_view fmt, const DrawStringFormatArg *args,
{
std::size_t result = c_count(fmt, '\n');
for (std::size_t i = 0; i < argsLen; ++i) {
if (args[i].GetType() == DrawStringFormatArg::Type::StringView)
if (std::holds_alternative<std::string_view>(args[i].value()))
result += c_count(args[i].GetFormatted(), '\n');
}
return result;
@ -312,7 +313,7 @@ public:
} else {
if (!args_[*result].HasFormatted()) {
const auto fmtStr = positional ? "{}" : std::string_view(rest.data(), fmtLen);
args_[*result].SetFormatted(fmt::format(fmt::runtime(fmtStr), args_[*result].GetIntValue()));
args_[*result].SetFormatted(fmt::format(fmt::runtime(fmtStr), std::get<int>(args_[*result].value())));
}
rest.remove_prefix(fmtLen);
}

34
Source/engine/render/text_render.hpp

@ -10,6 +10,7 @@
#include <string>
#include <string_view>
#include <utility>
#include <variant>
#include <vector>
#include <SDL.h>
@ -57,34 +58,24 @@ enum text_color : uint8_t {
*/
class DrawStringFormatArg {
public:
enum class Type : uint8_t {
StringView,
Int
};
using Value = std::variant<std::string_view, int>;
DrawStringFormatArg(std::string_view value, UiFlags flags)
: type_(Type::StringView)
, string_view_value_(value)
: value_(value)
, flags_(flags)
{
}
DrawStringFormatArg(int value, UiFlags flags)
: type_(Type::Int)
, int_value_(value)
: value_(value)
, flags_(flags)
{
}
Type GetType() const
{
return type_;
}
std::string_view GetFormatted() const
{
if (type_ == Type::StringView)
return string_view_value_;
if (std::holds_alternative<std::string_view>(value_))
return std::get<std::string_view>(value_);
return formatted_;
}
@ -95,12 +86,12 @@ public:
bool HasFormatted() const
{
return type_ == Type::StringView || !formatted_.empty();
return std::holds_alternative<std::string_view>(value_) || !formatted_.empty();
}
int GetIntValue() const
const Value &value() const
{
return int_value_;
return value_;
}
UiFlags GetFlags() const
@ -109,12 +100,7 @@ public:
}
private:
Type type_;
union {
std::string_view string_view_value_;
int int_value_;
};
Value value_;
UiFlags flags_;
std::string formatted_;
};

2
Source/player.h

@ -172,7 +172,7 @@ enum class DeathReason {
};
/** Maps from armor animation to letter used in graphic files. */
constexpr std::array<char, 4> ArmourChar = {
constexpr std::array<char, 3> ArmourChar = {
'l', // light
'm', // medium
'h', // heavy

Loading…
Cancel
Save