dev qol: Bind PySecurity __format__ to fmt::formatter impl

This commit is contained in:
John Colvin committed 2025-06-16 11:08:58 -04:00
1 parent 046f412ec4
commit 17ada3c57c
2 files changed
+43 -3

No files matched your search

@@ -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<bts::md::py_interop::PySecurity> {
// 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 <typename FormatContext>
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
@@ -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<std::vector<shared_ptr<PySecurity>>>(m, "PySecurityList");
//////////////////////////////////////////////////