format.hh (2421B)
1 #ifndef format_hh_INCLUDED 2 #define format_hh_INCLUDED 3 4 #include "string.hh" 5 #include "utils.hh" 6 7 namespace Kakoune 8 { 9 10 template<size_t N> 11 struct InplaceString 12 { 13 static_assert(N < 256, "InplaceString cannot handle sizes >= 256"); 14 15 constexpr operator StringView() const { return {m_data, ByteCount{m_length}}; } 16 operator String() const { return {m_data, ByteCount{m_length}}; } 17 18 unsigned char m_length{}; 19 char m_data[N]; 20 }; 21 22 struct Hex { size_t val; }; 23 constexpr Hex hex(size_t val) { return {val}; } 24 25 struct Grouped { size_t val; }; 26 constexpr Grouped grouped(size_t val) { return {val}; } 27 28 InplaceString<15> to_string(int val); 29 InplaceString<15> to_string(unsigned val); 30 InplaceString<23> to_string(long int val); 31 InplaceString<23> to_string(unsigned long val); 32 InplaceString<23> to_string(long long int val); 33 InplaceString<23> to_string(Hex val); 34 InplaceString<23> to_string(Grouped val); 35 InplaceString<23> to_string(float val); 36 InplaceString<7> to_string(Codepoint c); 37 38 template<typename RealType, typename ValueType> 39 decltype(auto) to_string(const StronglyTypedNumber<RealType, ValueType>& val) 40 { 41 return to_string((ValueType)val); 42 } 43 44 namespace detail 45 { 46 47 template<typename T> requires std::is_convertible_v<T, StringView> 48 StringView format_param(const T& val) { return val; } 49 50 template<typename T> requires (not std::is_convertible_v<T, StringView>) 51 decltype(auto) format_param(const T& val) { return to_string(val); } 52 53 } 54 55 String format(StringView fmt, ArrayView<const StringView> params); 56 57 template<typename... Types> 58 String format(StringView fmt, Types&&... params) 59 { 60 return format(fmt, ArrayView<const StringView>{detail::format_param(std::forward<Types>(params))...}); 61 } 62 63 StringView format_to(ArrayView<char> buffer, StringView fmt, ArrayView<const StringView> params); 64 65 template<typename... Types> 66 StringView format_to(ArrayView<char> buffer, StringView fmt, Types&&... params) 67 { 68 return format_to(buffer, fmt, ArrayView<const StringView>{detail::format_param(std::forward<Types>(params))...}); 69 } 70 71 void format_with(FunctionRef<void (StringView)> append, StringView fmt, ArrayView<const StringView> params); 72 73 template<typename... Types> 74 void format_with(FunctionRef<void (StringView)> append, StringView fmt, Types&&... params) 75 { 76 return format_with(append, fmt, ArrayView<const StringView>{detail::format_param(std::forward<Types>(params))...}); 77 } 78 79 } 80 81 #endif // format_hh_INCLUDED