diff --git a/libuavcan/include/uavcan/time.hpp b/libuavcan/include/uavcan/time.hpp index 88c335078a..7f99b29300 100644 --- a/libuavcan/include/uavcan/time.hpp +++ b/libuavcan/include/uavcan/time.hpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -82,6 +81,8 @@ public: return *static_cast(this); } + enum { StringBufSize = 32 }; + void toString(char buf[StringBufSize]) const; std::string toString() const; }; @@ -161,6 +162,8 @@ public: return *static_cast(this); } + enum { StringBufSize = 32 }; + void toString(char buf[StringBufSize]) const; std::string toString() const; }; @@ -200,48 +203,68 @@ public: } }; +// ---------------------------------------------------------------------------- + +template +void DurationBase::toString(char buf[StringBufSize]) const +{ + using namespace std; // For snprintf() + char* ptr = buf; + if (isNegative()) + { + *ptr++ = '-'; + } + (void)snprintf(ptr, StringBufSize - 1, "%llu.%06lu", + static_cast(std::abs(toUSec() / 1000000L)), + static_cast(std::abs(toUSec() % 1000000L))); +} + + +template +void TimeBase::toString(char buf[StringBufSize]) const +{ + using namespace std; // For snprintf() + (void)snprintf(buf, StringBufSize, "%llu.%06lu", + static_cast(toUSec() / 1000000UL), + static_cast(toUSec() % 1000000UL)); +} + + +template +std::string DurationBase::toString() const +{ + char buf[StringBufSize]; + toString(buf); + return std::string(buf); +} + +template +std::string TimeBase::toString() const +{ + char buf[StringBufSize]; + toString(buf); + return std::string(buf); +} + template UAVCAN_EXPORT -inline Stream& operator<<(Stream& s, DurationBase d) +Stream& operator<<(Stream& s, DurationBase d) { - char buf[8]; - using namespace std; // For snprintf() - snprintf(buf, sizeof(buf), "%06lu", static_cast(std::abs(d.toUSec() % 1000000L))); - if (d.isNegative()) - { - s << '-'; - } - s << std::abs(d.toUSec() / 1000000L) << '.' << buf; + char buf[DurationBase::StringBufSize]; + d.toString(buf); + s << buf; return s; } template UAVCAN_EXPORT -inline Stream& operator<<(Stream& s, TimeBase t) +Stream& operator<<(Stream& s, TimeBase t) { - char buf[8]; - using namespace std; // For snprintf() - snprintf(buf, sizeof(buf), "%06lu", static_cast(t.toUSec() % 1000000L)); - s << (t.toUSec() / 1000000L) << '.' << buf; + char buf[TimeBase::StringBufSize]; + t.toString(buf); + s << buf; return s; } - -template -inline std::string DurationBase::toString() const -{ - std::ostringstream os; - os << *static_cast(this); - return os.str(); -} - -template -inline std::string TimeBase::toString() const -{ - std::ostringstream os; - os << *static_cast(this); - return os.str(); -} - }