diff --git a/src/include/OpenImageIO/ustring.h b/src/include/OpenImageIO/ustring.h index 3f50893b92..d9f3fc71c6 100644 --- a/src/include/OpenImageIO/ustring.h +++ b/src/include/OpenImageIO/ustring.h @@ -31,6 +31,7 @@ OIIO_NAMESPACE_BEGIN #define OIIO_USTRING_HAS_USTRINGHASH 1 #define OIIO_USTRING_HAS_CTR_FROM_USTRINGHASH 1 #define OIIO_USTRING_HAS_STDHASH 1 +#define OIIO_HAS_USTRINGHASH_FORMATTER 1 class ustringhash; // forward declaration @@ -953,10 +954,11 @@ class OIIO_UTIL_API ustringhash { return hash() < x.hash(); } - /// Generic stream output of a ustring. + /// Generic stream output of a ustringhash outputs the string it refers + /// to. friend std::ostream& operator<<(std::ostream& out, const ustringhash& str) { - return (out << str.hash()); + return (out << ustring(str)); } #endif @@ -1119,15 +1121,27 @@ template<> struct hash { -// Supply a fmtlib compatible custom formatter for ustring. +// Supply a fmtlib compatible custom formatter for ustring and ustringhash. FMT_BEGIN_NAMESPACE template<> struct formatter : formatter { template - auto format(const OIIO::ustring& t, FormatContext& ctx) + auto format(const OIIO::ustring& u, FormatContext& ctx) + -> decltype(ctx.out()) const + { + return formatter::format({ u.data(), u.size() }, + ctx); + } +}; + +template<> +struct formatter : formatter { + template + auto format(const OIIO::ustringhash& h, FormatContext& ctx) -> decltype(ctx.out()) const { - return formatter::format({ t.data(), t.size() }, + OIIO::ustring u(h); + return formatter::format({ u.data(), u.size() }, ctx); } }; diff --git a/src/libutil/ustring_test.cpp b/src/libutil/ustring_test.cpp index f3a55f7340..f33aa1e732 100644 --- a/src/libutil/ustring_test.cpp +++ b/src/libutil/ustring_test.cpp @@ -215,6 +215,9 @@ test_ustringhash() // std::hash OIIO_CHECK_EQUAL(std::hash {}(hfoo), hfoo.hash()); + + // formatting string + OIIO_CHECK_EQUAL(Strutil::fmt::format("{}", hfoo), "foo"); }