/* * Copyright (C) 2014 Pavel Kirienko */ #ifndef UAVCAN_MARSHAL_CHAR_ARRAY_FORMATTER_HPP_INCLUDED #define UAVCAN_MARSHAL_CHAR_ARRAY_FORMATTER_HPP_INCLUDED #include #include #if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11) # error UAVCAN_CPP_VERSION #endif #if UAVCAN_CPP_VERSION >= UAVCAN_CPP11 # include #endif namespace uavcan { #if UAVCAN_CPP_VERSION >= UAVCAN_CPP11 template class UAVCAN_EXPORT CharArrayFormatter { ArrayType_& array_; template typename std::enable_if::value>::type writeValue(T value) { array_.template appendFormatted("%g", double(value)); } template typename std::enable_if::value>::type writeValue(T value) { if (std::is_same()) { if (array_.size() != array_.capacity()) { array_.push_back(typename ArrayType_::ValueType(value)); } } else if (std::is_signed()) { array_.template appendFormatted("%lli", static_cast(value)); } else { array_.template appendFormatted("%llu", static_cast(value)); } } template typename std::enable_if::value && !std::is_same::value>::type writeValue(T value) { array_.template appendFormatted("%p", static_cast(value)); } void writeValue(const char* value) { array_.template appendFormatted("%s", value); } public: typedef ArrayType_ ArrayType; explicit CharArrayFormatter(ArrayType& array) : array_(array) { } ArrayType& getArray() { return array_; } const ArrayType& getArray() const { return array_; } void write(const char* text) { writeValue(text); } template void write(const char* s, T value, Args... args) { while (s && *s) { if (*s == '%') { s += 1; if (*s != '%') { writeValue(value); write(++s, args...); break; } } writeValue(*s++); } } }; #else template class UAVCAN_EXPORT CharArrayFormatter { ArrayType_& array_; public: typedef ArrayType_ ArrayType; CharArrayFormatter(ArrayType& array) : array_(array) { } ArrayType& getArray() { return array_; } const ArrayType& getArray() const { return array_; } void write(const char* const text) { array_.template appendFormatted("%s", text); } /** * This version does not support more than one formatted argument, though it can be improved. * And it is unsafe. * There is typesafe version for C++11 above. */ template void write(const char* const format, const A value) { array_.template appendFormatted(format, value); } }; #endif } #endif // UAVCAN_MARSHAL_CHAR_ARRAY_FORMATTER_HPP_INCLUDED