diff --git a/src/lib_python_interop/python_interop/py_security.h b/src/lib_python_interop/python_interop/py_security.h index 0964404b2..0d3d4ba01 100644 --- a/src/lib_python_interop/python_interop/py_security.h +++ b/src/lib_python_interop/python_interop/py_security.h @@ -54,6 +54,7 @@ class PySecurity { void set_contract_spec(PyContractSpecification value); std::string to_string() const; + std::string format(const std::string &format_spec) const; private: std::uint32_t id_; @@ -74,10 +75,43 @@ class PySecurity { void to_json(nlohmann::json &j, const PySecurity &sec); void from_json(const nlohmann::json &j, PySecurity &sec); +} // namespace bts::md::py_interop + ////////////////////////////////////////////////// // Definition ////////////////////////////////////////////////// +template <> +struct fmt::formatter { + // Parse format specifier: only support 'j' flag for JSON output + bool json_format = false; + + constexpr auto parse(format_parse_context &ctx) { + auto it = ctx.begin(); + auto end = ctx.end(); + if (it != end && *it == 'j') { + json_format = true; + ++it; + } + if (it != end && *it != '}') { + throw format_error("invalid format"); + } + return it; + } + + template + auto format( + const bts::md::py_interop::PySecurity &sec, FormatContext &ctx) const { + if (json_format) { + return fmt::format_to(ctx.out(), "{}", bts::io::json_formatter(sec)); + } else { + return fmt::format_to(ctx.out(), "{}", sec.name()); + } + } +}; + +namespace bts::md::py_interop { + constexpr std::uint32_t PySecurity::id() const { return id_; } inline void PySecurity::set_id(std::uint32_t value) { id_ = value; } @@ -155,6 +189,11 @@ inline void PySecurity::set_contract_spec(PyContractSpecification value) { inline std::string PySecurity::to_string() const { return name_; } -} // namespace bts::md::py_interop +inline std::string PySecurity::format(const std::string &format_spec) const { + if (format_spec.empty()) { + return fmt::format("{}", *this); + } + return fmt::format(fmt::runtime("{:" + format_spec + "}"), *this); +} -FMT_IMPL(bts::md::py_interop::PySecurity, s, "{}", bts::io::json_formatter(s)); +} // namespace bts::md::py_interop diff --git a/src/lib_python_interop/python_interop/python_interop_module.cpp b/src/lib_python_interop/python_interop/python_interop_module.cpp index d380b84e7..fd378d501 100644 --- a/src/lib_python_interop/python_interop/python_interop_module.cpp +++ b/src/lib_python_interop/python_interop/python_interop_module.cpp @@ -122,7 +122,8 @@ PYBIND11_MODULE(python_interop_module, m) { .PROP(PySecurity, spot) .PROP(PySecurity, future) .PROP(PySecurity, option) - .def("__str__", &PySecurity::to_string); + .def("__str__", &PySecurity::to_string) + .def("__format__", &PySecurity::format); py::bind_vector>>(m, "PySecurityList"); //////////////////////////////////////////////////