BsStringFormat.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. namespace BansheeEngine
  2. {
  3. /** @cond INTERNAL */
  4. /** @addtogroup String
  5. * @{
  6. */
  7. /** Helper class used for string formatting operations. */
  8. class StringFormat
  9. {
  10. private:
  11. /**
  12. * Data structure used during string formatting. It holds information about parameter identifiers to replace with
  13. * actual parameters.
  14. */
  15. struct FormatParamRange
  16. {
  17. FormatParamRange() { }
  18. FormatParamRange(UINT32 start, UINT32 identifierSize, UINT32 paramIdx)
  19. :start(start), identifierSize(identifierSize), paramIdx(paramIdx)
  20. { }
  21. UINT32 start;
  22. UINT32 identifierSize;
  23. UINT32 paramIdx;
  24. };
  25. /**
  26. * @brief Structure that holds value of a parameter during string
  27. * formatting.
  28. */
  29. template<class T>
  30. struct ParamData
  31. {
  32. T* buffer;
  33. UINT32 size;
  34. };
  35. public:
  36. /**
  37. * Formats the provided string by replacing the identifiers with the provided parameters. The identifiers are
  38. * represented like "{0}, {1}" in the source string, where the number represents the position of the parameter
  39. * that will be used for replacing the identifier.
  40. *
  41. * @note You may use "\" to escape identifier brackets.
  42. * @note Maximum identifier number is 19 (for a total of 20 unique identifiers. e.g. {20} won't be recognized as an identifier).
  43. * @note Total number of parameters that can be referenced is 200.
  44. */
  45. template<class T, class... Args>
  46. static BasicString<T> format(const T* source, Args&& ...args)
  47. {
  48. UINT32 strLength = getLength(source);
  49. ParamData<T> parameters[MAX_PARAMS];
  50. memset(parameters, 0, sizeof(parameters));
  51. getParams(parameters, 0U, std::forward<Args>(args)...);
  52. T bracketChars[MAX_IDENTIFIER_SIZE + 1];
  53. UINT32 bracketWriteIdx = 0;
  54. FormatParamRange paramRanges[MAX_PARAM_REFERENCES];
  55. memset(paramRanges, 0, sizeof(paramRanges));
  56. UINT32 paramRangeWriteIdx = 0;
  57. // Determine parameter positions
  58. INT32 lastBracket = -1;
  59. bool escaped = false;
  60. UINT32 charWriteIdx = 0;
  61. for (UINT32 i = 0; i < strLength; i++)
  62. {
  63. if (source[i] == '\\' && !escaped && paramRangeWriteIdx < MAX_PARAM_REFERENCES)
  64. {
  65. escaped = true;
  66. paramRanges[paramRangeWriteIdx++] = FormatParamRange(charWriteIdx, 1, (UINT32)-1);
  67. continue;
  68. }
  69. if (lastBracket == -1)
  70. {
  71. // If current char is non-escaped opening bracket start parameter definition
  72. if (source[i] == '{' && !escaped)
  73. lastBracket = i;
  74. else
  75. charWriteIdx++;
  76. }
  77. else
  78. {
  79. if (isdigit(source[i]) && bracketWriteIdx < MAX_IDENTIFIER_SIZE)
  80. bracketChars[bracketWriteIdx++] = source[i];
  81. else
  82. {
  83. // If current char is non-escaped closing bracket end parameter definition
  84. UINT32 numParamChars = bracketWriteIdx;
  85. bool processedBracket = false;
  86. if (source[i] == '}' && numParamChars > 0 && !escaped)
  87. {
  88. bracketChars[bracketWriteIdx] = '\0';
  89. UINT32 paramIdx = strToInt(bracketChars);
  90. if (paramIdx < MAX_PARAMS && paramRangeWriteIdx < MAX_PARAM_REFERENCES) // Check if exceeded maximum parameter limit
  91. {
  92. paramRanges[paramRangeWriteIdx++] = FormatParamRange(charWriteIdx, numParamChars + 2, paramIdx);
  93. charWriteIdx += parameters[paramIdx].size;
  94. processedBracket = true;
  95. }
  96. }
  97. if (!processedBracket)
  98. {
  99. // Last bracket wasn't really a parameter
  100. for (UINT32 j = lastBracket; j <= i; j++)
  101. charWriteIdx++;
  102. }
  103. lastBracket = -1;
  104. bracketWriteIdx = 0;
  105. }
  106. }
  107. escaped = false;
  108. }
  109. // Copy the clean string into output buffer
  110. UINT32 finalStringSize = charWriteIdx;
  111. T* outputBuffer = (T*)bs_alloc(finalStringSize * sizeof(T));
  112. UINT32 copySourceIdx = 0;
  113. UINT32 copyDestIdx = 0;
  114. for (UINT32 i = 0; i < paramRangeWriteIdx; i++)
  115. {
  116. const FormatParamRange& rangeInfo = paramRanges[i];
  117. UINT32 copySize = rangeInfo.start - copyDestIdx;
  118. memcpy(outputBuffer + copyDestIdx, source + copySourceIdx, copySize * sizeof(T));
  119. copySourceIdx += copySize + rangeInfo.identifierSize;
  120. copyDestIdx += copySize;
  121. if (rangeInfo.paramIdx == (UINT32)-1)
  122. continue;
  123. UINT32 paramSize = parameters[rangeInfo.paramIdx].size;
  124. memcpy(outputBuffer + copyDestIdx, parameters[rangeInfo.paramIdx].buffer, paramSize * sizeof(T));
  125. copyDestIdx += paramSize;
  126. }
  127. memcpy(outputBuffer + copyDestIdx, source + copySourceIdx, (finalStringSize - copyDestIdx) * sizeof(T));
  128. BasicString<T> outputStr(outputBuffer, finalStringSize);
  129. bs_free(outputBuffer);
  130. for (UINT32 i = 0; i < MAX_PARAMS; i++)
  131. {
  132. if (parameters[i].buffer != nullptr)
  133. bs_free(parameters[i].buffer);
  134. }
  135. return outputStr;
  136. }
  137. private:
  138. /**
  139. * Set of methods that can be specialized so we have a generalized way for retrieving length of strings of
  140. * different types.
  141. */
  142. static UINT32 getLength(const char* source) { return (UINT32)strlen(source); }
  143. /**
  144. * Set of methods that can be specialized so we have a generalized way for retrieving length of strings of
  145. * different types.
  146. */
  147. static UINT32 getLength(const wchar_t* source) { return (UINT32)wcslen(source); }
  148. /** Parses the string and returns an integer value extracted from string characters. */
  149. static UINT32 strToInt(const char* buffer)
  150. {
  151. return (UINT32)strtoul(buffer, nullptr, 10);
  152. }
  153. /** Parses the string and returns an integer value extracted from string characters. */
  154. static UINT32 strToInt(const wchar_t* buffer)
  155. {
  156. return (UINT32)wcstoul(buffer, nullptr, 10);
  157. }
  158. /** Helper method for converting any data type to a narrow string. */
  159. template<class T> static std::string toString(const T& param) { return std::to_string(param); }
  160. /** Helper method that "converts" a narrow string to a narrow string (simply a pass through). */
  161. template<> static std::string toString(const std::string& param) { return param; }
  162. /** Helper method that converts a Banshee narrow string to a standard narrow string. */
  163. template<> static std::string toString(const String& param)
  164. {
  165. return std::string(param.c_str());
  166. }
  167. /** Helper method that converts a narrow character array to a narrow string. */
  168. template<class T> static std::string toString(T* param) { static_assert("Invalid pointer type."); }
  169. /** Helper method that converts a narrow character array to a narrow string. */
  170. template<> static std::string toString<const char>(const char* param) { return std::string(param); }
  171. /** Helper method that converts a narrow character array to a narrow string. */
  172. template<> static std::string toString<char>(char* param) { return std::string(param); }
  173. /** Helper method for converting any data type to a wide string. */
  174. template<class T> static std::wstring toWString(const T& param) { return std::to_wstring(param); }
  175. /** Helper method that "converts" a wide string to a wide string (simply a pass through). */
  176. template<> static std::wstring toWString<std::wstring>(const std::wstring& param) { return param; }
  177. /** Helper method that converts a Banshee wide string to a standard wide string. */
  178. template<> static std::wstring toWString<WString>(const WString& param)
  179. {
  180. return std::wstring(param.c_str());
  181. }
  182. /** Helper method that converts a wide character array to a wide string. */
  183. template<class T> static std::wstring toWString(T* param) { static_assert("Invalid pointer type."); }
  184. /** Helper method that converts a wide character array to a wide string. */
  185. template<> static std::wstring toWString<const wchar_t>(const wchar_t* param) { return std::wstring(param); }
  186. /** Helper method that converts a wide character array to a wide string. */
  187. template<> static std::wstring toWString<wchar_t>(wchar_t* param) { return std::wstring(param); }
  188. /**
  189. * Converts all the provided parameters into string representations and populates the provided @p parameters array.
  190. */
  191. template<class P, class... Args>
  192. static void getParams(ParamData<char>* parameters, UINT32 idx, P&& param, Args&& ...args)
  193. {
  194. if (idx >= MAX_PARAMS)
  195. return;
  196. std::basic_string<char> sourceParam = toString(param);
  197. parameters[idx].buffer = (char*)bs_alloc((UINT32)sourceParam.size() * sizeof(char));
  198. parameters[idx].size = (UINT32)sourceParam.size();
  199. sourceParam.copy(parameters[idx].buffer, parameters[idx].size, 0);
  200. getParams(parameters, idx + 1, std::forward<Args>(args)...);
  201. }
  202. /**
  203. * Converts all the provided parameters into string representations and populates the provided @p parameters array.
  204. */
  205. template<class P, class... Args>
  206. static void getParams(ParamData<wchar_t>* parameters, UINT32 idx, P&& param, Args&& ...args)
  207. {
  208. if (idx >= MAX_PARAMS)
  209. return;
  210. std::basic_string<wchar_t> sourceParam = toWString(param);
  211. parameters[idx].buffer = (wchar_t*)bs_alloc((UINT32)sourceParam.size() * sizeof(wchar_t));
  212. parameters[idx].size = (UINT32)sourceParam.size();
  213. sourceParam.copy(parameters[idx].buffer, parameters[idx].size, 0);
  214. getParams(parameters, idx + 1, std::forward<Args>(args)...);
  215. }
  216. /** Helper method for parameter size calculation. Used as a stopping point in template recursion. */
  217. static void getParams(ParamData<char>* parameters, UINT32 idx)
  218. {
  219. // Do nothing
  220. }
  221. /** Helper method for parameter size calculation. Used as a stopping point in template recursion. */
  222. static void getParams(ParamData<wchar_t>* parameters, UINT32 idx)
  223. {
  224. // Do nothing
  225. }
  226. static const UINT32 MAX_PARAMS = 20;
  227. static const UINT32 MAX_IDENTIFIER_SIZE = 2;
  228. static const UINT32 MAX_PARAM_REFERENCES = 200;
  229. };
  230. /** @} */
  231. /** @endcond */
  232. }