From 3716491ec51c34a918834857c67300eea180ba02 Mon Sep 17 00:00:00 2001 From: Paul Dreik Date: Mon, 3 Jun 2019 07:03:29 +0200 Subject: [PATCH] fix UB in on_second --- include/fmt/chrono.h | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/include/fmt/chrono.h b/include/fmt/chrono.h index 23367e58cfc3..48368408224e 100644 --- a/include/fmt/chrono.h +++ b/include/fmt/chrono.h @@ -660,7 +660,19 @@ struct chrono_formatter { if (ns == numeric_system::standard) { write(second(), 2); - auto ms = get_milliseconds(std::chrono::duration(val)); +#ifdef FMT_SAFE_DURATION_CAST + int ec; + //convert rep->Rep + using Crep=std::chrono::duration; + using CRep=std::chrono::duration; + auto tmpval = safe_duration_cast::safe_duration_cast(Crep{val}, ec); + if (ec) { + FMT_THROW(format_error("value would cause UB or the wrong result")); + } +#else + auto tmpval=std::chrono::duration(val); +#endif + auto ms = get_milliseconds(tmpval); if (ms != std::chrono::milliseconds(0)) { *out++ = '.'; write(ms.count(), 3);