Type-erased argument holder
| 296 | |
| 297 | // Type-erased argument holder |
| 298 | class FormatArg { |
| 299 | public: |
| 300 | enum class Type { None, Int, UInt, Long, ULong, LongLong, ULongLong, |
| 301 | Double, Char, CString, String, Pointer }; |
| 302 | |
| 303 | FormatArg() FL_NOEXCEPT : mType(Type::None) {} |
| 304 | FormatArg(int v) : mType(Type::Int) { mData.i = v; } |
| 305 | FormatArg(unsigned int v) : mType(Type::UInt) { mData.u = v; } |
| 306 | FormatArg(long v) : mType(Type::Long) { mData.l = v; } |
| 307 | FormatArg(unsigned long v) : mType(Type::ULong) { mData.ul = v; } |
| 308 | FormatArg(long long v) : mType(Type::LongLong) { mData.ll = v; } |
| 309 | FormatArg(unsigned long long v) : mType(Type::ULongLong) { mData.ull = v; } |
| 310 | FormatArg(double v) : mType(Type::Double) { mData.d = v; } |
| 311 | FormatArg(float v) : mType(Type::Double) { mData.d = v; } |
| 312 | FormatArg(char v) : mType(Type::Char) { mData.c = v; } |
| 313 | FormatArg(const char* v) : mType(Type::CString) { mData.s = v; } |
| 314 | FormatArg(const fl::string& v) : mType(Type::String) { mData.str = &v; } |
| 315 | FormatArg(const void* v) : mType(Type::Pointer) { mData.p = v; } |
| 316 | |
| 317 | // Short/byte types promote to int |
| 318 | FormatArg(short v) : mType(Type::Int) { mData.i = v; } |
| 319 | FormatArg(unsigned short v) : mType(Type::UInt) { mData.u = v; } |
| 320 | FormatArg(signed char v) : mType(Type::Int) { mData.i = v; } |
| 321 | FormatArg(unsigned char v) : mType(Type::UInt) { mData.u = v; } |
| 322 | |
| 323 | fl::string format(const FormatSpec& spec) const { |
| 324 | switch (mType) { |
| 325 | case Type::Int: return format_integer(mData.i, spec); |
| 326 | case Type::UInt: return format_integer(mData.u, spec); |
| 327 | case Type::Long: return format_integer(mData.l, spec); |
| 328 | case Type::ULong: return format_integer(mData.ul, spec); |
| 329 | case Type::LongLong: return format_integer(mData.ll, spec); |
| 330 | case Type::ULongLong: return format_integer(mData.ull, spec); |
| 331 | case Type::Double: return format_float(mData.d, spec); |
| 332 | case Type::Char: { |
| 333 | if (spec.type == 'd' || spec.type == 'x' || spec.type == 'X' || |
| 334 | spec.type == 'b' || spec.type == 'o') { |
| 335 | return format_integer(static_cast<int>(mData.c), spec); |
| 336 | } |
| 337 | char buf[2] = {mData.c, '\0'}; |
| 338 | return fl::string(buf); |
| 339 | } |
| 340 | case Type::CString: return format_string(mData.s, spec); |
| 341 | case Type::String: return format_string(mData.str->c_str(), spec); |
| 342 | case Type::Pointer: return format_pointer(mData.p, spec); |
| 343 | case Type::None: |
| 344 | default: return fl::string("<invalid>"); |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | bool valid() const { return mType != Type::None; } |
| 349 | |
| 350 | private: |
| 351 | Type mType; |
| 352 | union { |
| 353 | int i; |
| 354 | unsigned int u; |
| 355 | long l; |