stringAPI.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2025 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #ifndef DFPSR_API_STRING
  24. #define DFPSR_API_STRING
  25. #include <cstdint>
  26. #include <functional>
  27. #include "bufferAPI.h"
  28. #include "../base/SafePointer.h"
  29. #include "../collection/List.h"
  30. // Define DSR_INTERNAL_ACCESS before any include to get internal access to exposed types
  31. #ifdef DSR_INTERNAL_ACCESS
  32. #define IMPL_ACCESS public
  33. #else
  34. #define IMPL_ACCESS protected
  35. #endif
  36. namespace dsr {
  37. using DsrChar = char32_t;
  38. // Text files support loading UTF-8/16 BE/LE with BOM or Latin-1 without BOM
  39. enum class CharacterEncoding {
  40. Raw_Latin1, // U+00 to U+FF
  41. BOM_UTF8, // U+00000000 to U+0010FFFF
  42. BOM_UTF16BE, // U+00000000 to U+0000D7FF, U+0000E000 to U+0010FFFF
  43. BOM_UTF16LE // U+00000000 to U+0000D7FF, U+0000E000 to U+0010FFFF
  44. };
  45. // Carriage-return is removed when loading text files to prevent getting double lines
  46. // A line-feed without a line-feed character is nonsense
  47. // LineEncoding allow re-adding carriage-return before or after each line-break when saving
  48. enum class LineEncoding {
  49. CrLf, // Microsoft Windows compatible (Can also be read on other platforms by ignoring carriage return)
  50. Lf // Linux and Macintosh compatible (Might not work on non-portable text editors on Microsoft Windows)
  51. };
  52. class String;
  53. // Helper type for strings.
  54. struct Impl_CharacterView {
  55. DsrChar *data = nullptr;
  56. intptr_t length = 0;
  57. Impl_CharacterView() {}
  58. Impl_CharacterView(Handle<DsrChar> characters)
  59. : data(characters.getUnsafe()), length(characters.getElementCount()) {}
  60. Impl_CharacterView(const DsrChar *data, intptr_t length)
  61. : data(const_cast<DsrChar *>(data)), length(length) {
  62. if (data == nullptr) this->length = 0;
  63. }
  64. inline DsrChar *getUnchecked() const {
  65. return const_cast<DsrChar*>(this->data);
  66. }
  67. inline DsrChar operator [] (intptr_t index) const {
  68. if (index < 0 || index >= this->length) {
  69. return U'\0';
  70. } else {
  71. return this->data[index];
  72. }
  73. }
  74. inline void writeCharacter(intptr_t index, DsrChar character) {
  75. if (index < 0 || index >= this->length) {
  76. // TODO: Throw an error without causing bottomless recursion.
  77. } else {
  78. this->data[index] = character;
  79. }
  80. }
  81. inline SafePointer<DsrChar> getSafe(const char *name) const {
  82. return SafePointer<DsrChar>(name, this->getUnchecked(), this->length * sizeof(DsrChar));
  83. }
  84. };
  85. // Replacing String with a ReadableString reference for input arguments can make passing of U"" literals faster,
  86. // because String is not allowed to assume anything about how long the literal will be available.
  87. // Unlike String, it cannot be constructed from a "" literal, because it is not allowed to heap allocate new memory
  88. // for the conversion, only hold existing buffers alive with reference counting when casted from String.
  89. class ReadableString {
  90. IMPL_ACCESS:
  91. // A reference counted pointer to the buffer to allow passing strings around without having to clone the buffer each time
  92. // ReadableString only uses it for reference counting but String use it for reallocating
  93. Handle<DsrChar> characters;
  94. // Pointing to a subset of the buffer or memory that is not shared.
  95. Impl_CharacterView view;
  96. // TODO: Merge the pointer and length into a new View type for unified bound checks. Then remove the writer pointer.
  97. //SafePointer<const DsrChar> reader;
  98. //intptr_t length = 0;
  99. public:
  100. // TODO: Inline the [] operator for faster reading of characters.
  101. // Use the padded read internally, because the old version was hard-coded for buffers padded to default alignment.
  102. // Returning the character by value prevents writing to memory that might be a constant literal or shared with other strings
  103. inline DsrChar operator[] (intptr_t index) const {
  104. return this->view[index];
  105. }
  106. public:
  107. // Empty string U""
  108. ReadableString() {}
  109. // Implicit casting from U"text"
  110. ReadableString(const DsrChar *content);
  111. ReadableString(Handle<DsrChar> characters, Impl_CharacterView view)
  112. : characters(characters), view(view) {}
  113. // Create from String by sharing the buffer
  114. ReadableString(const String& source);
  115. // Destructor
  116. ~ReadableString() {} // Do not override the non-virtual destructor.
  117. };
  118. // A safe and simple string type
  119. // Can be constructed from ascii literals "", but U"" will preserve unicode characters.
  120. // Can be used without ReadableString, but ReadableString can be wrapped over U"" literals without allocation
  121. // UTF-32
  122. // Endianness is native
  123. // No combined characters allowed, use precomposed instead, so that the strings can guarantee a fixed character size
  124. class String : public ReadableString {
  125. //IMPL_ACCESS:
  126. // TODO: Have a single pointer to the data in ReadableString and let the API be responsible for type safety.
  127. //SafePointer<DsrChar> writer;
  128. public:
  129. // Constructors
  130. String();
  131. String(const char* source);
  132. String(const DsrChar* source);
  133. String(const ReadableString& source);
  134. String(const String& source);
  135. };
  136. // Used as format tags around numbers passed to string_append or string_combine
  137. // New types can implement printing to String by making wrappers from this class
  138. class Printable {
  139. public:
  140. // The method for appending the printable object into the target string
  141. virtual String& toStreamIndented(String& target, const ReadableString& indentation) const = 0;
  142. String& toStream(String& target) const;
  143. String toStringIndented(const ReadableString& indentation) const;
  144. String toString() const;
  145. virtual ~Printable();
  146. };
  147. String& string_toStreamIndented(String& target, const char *value, const ReadableString& indentation);
  148. String& string_toStreamIndented(String& target, const DsrChar *value, const ReadableString& indentation);
  149. String& string_toStreamIndented(String& target, const ReadableString &value, const ReadableString& indentation);
  150. String& string_toStreamIndented(String& target, const double &value, const ReadableString& indentation);
  151. String& string_toStreamIndented(String& target, const int64_t &value, const ReadableString& indentation);
  152. String& string_toStreamIndented(String& target, const uint64_t &value, const ReadableString& indentation);
  153. inline String& string_toStreamIndented(String& target, const float &value, const ReadableString& indentation) {
  154. return string_toStreamIndented(target, (double)value, indentation);
  155. }
  156. inline String& string_toStreamIndented(String& target, const int32_t &value, const ReadableString& indentation) {
  157. return string_toStreamIndented(target, (int64_t)value, indentation);
  158. }
  159. inline String& string_toStreamIndented(String& target, const int16_t &value, const ReadableString& indentation) {
  160. return string_toStreamIndented(target, (int64_t)value, indentation);
  161. }
  162. inline String& string_toStreamIndented(String& target, const int8_t &value, const ReadableString& indentation) {
  163. return string_toStreamIndented(target, (int64_t)value, indentation);
  164. }
  165. inline String& string_toStreamIndented(String& target, const uint32_t &value, const ReadableString& indentation) {
  166. return string_toStreamIndented(target, (uint64_t)value, indentation);
  167. }
  168. inline String& string_toStreamIndented(String& target, const uint16_t &value, const ReadableString& indentation) {
  169. return string_toStreamIndented(target, (uint64_t)value, indentation);
  170. }
  171. inline String& string_toStreamIndented(String& target, const uint8_t &value, const ReadableString& indentation) {
  172. return string_toStreamIndented(target, (uint64_t)value, indentation);
  173. }
  174. inline String& string_toStreamIndented(String& target, const Printable& value, const ReadableString& indentation) {
  175. return value.toStreamIndented(target, indentation);
  176. }
  177. template<typename T>
  178. String string_toStringIndented(const T& source, const ReadableString& indentation) {
  179. String result;
  180. string_toStreamIndented(result, source, indentation);
  181. return result;
  182. }
  183. template<typename T>
  184. String string_toString(const T& source) {
  185. String result;
  186. string_toStreamIndented(result, source, U"");
  187. return result;
  188. }
  189. // ---------------- Procedural API ----------------
  190. // Sets the target string's length to zero.
  191. // Because this opens up to appending new text where sub-string may already share the buffer,
  192. // this operation will reallocate the buffer if shared with other strings.
  193. void string_clear(String& target);
  194. // Post-condition: Returns the length of source.
  195. // Example: string_length(U"ABC") == 3
  196. intptr_t string_length(const ReadableString& source);
  197. // Post-condition: Returns the base-zero index of source's first occurence of toFind, starting from startIndex. Returns -1 if not found.
  198. // Example: string_findFirst(U"ABCABCABC", U'A') == 0
  199. // Example: string_findFirst(U"ABCABCABC", U'B') == 1
  200. // Example: string_findFirst(U"ABCABCABC", U'C') == 2
  201. // Example: string_findFirst(U"ABCABCABC", U'D') == -1
  202. intptr_t string_findFirst(const ReadableString& source, DsrChar toFind, intptr_t startIndex = 0);
  203. // Post-condition: Returns the base-zero index of source's last occurence of toFind. Returns -1 if not found.
  204. // Example: string_findLast(U"ABCABCABC", U'A') == 6
  205. // Example: string_findLast(U"ABCABCABC", U'B') == 7
  206. // Example: string_findLast(U"ABCABCABC", U'C') == 8
  207. // Example: string_findLast(U"ABCABCABC", U'D') == -1
  208. intptr_t string_findLast(const ReadableString& source, DsrChar toFind);
  209. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to before the character at exclusiveEnd
  210. // Example: string_exclusiveRange(U"0123456789", 2, 4) == U"23"
  211. ReadableString string_exclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t exclusiveEnd);
  212. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to after the character at inclusiveEnd
  213. // Example: string_inclusiveRange(U"0123456789", 2, 4) == U"234"
  214. ReadableString string_inclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t inclusiveEnd);
  215. // Post-condition: Returns a sub-string of source from the start to before the character at exclusiveEnd
  216. // Example: string_before(U"0123456789", 5) == U"01234"
  217. ReadableString string_before(const ReadableString& source, intptr_t exclusiveEnd);
  218. // Post-condition: Returns a sub-string of source from the start to after the character at inclusiveEnd
  219. // Example: string_until(U"0123456789", 5) == U"012345"
  220. ReadableString string_until(const ReadableString& source, intptr_t inclusiveEnd);
  221. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to the end
  222. // Example: string_from(U"0123456789", 5) == U"56789"
  223. ReadableString string_from(const ReadableString& source, intptr_t inclusiveStart);
  224. // Post-condition: Returns a sub-string of source from after the character at exclusiveStart to the end
  225. // Example: string_after(U"0123456789", 5) == U"6789"
  226. ReadableString string_after(const ReadableString& source, intptr_t exclusiveStart);
  227. // Split source into a list of strings.
  228. // Post-condition:
  229. // Returns a list of strings from source by splitting along separator.
  230. // If removeWhiteSpace is true then surrounding white-space will be removed, otherwise all white-space is kept.
  231. // The separating characters are excluded from the resulting strings.
  232. // The number of strings returned in the list will equal the number of separating characters plus one, so the result may contain empty strings.
  233. // Each string in the list clones content to its own dynamic buffer. Use string_split_callback if you don't need long term storage.
  234. List<String> string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace = false);
  235. // Split a string without needing a list to store the result.
  236. // Use string_splitCount on the same source and separator if you need to know the element count in advance.
  237. // Side-effects:
  238. // Calls action for each sub-string divided by separator in source given as the separatedText argument.
  239. void string_split_callback(std::function<void(ReadableString separatedText)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace = false);
  240. // An alternative overload for having a very long lambda at the end.
  241. inline void string_split_callback(const ReadableString& source, DsrChar separator, bool removeWhiteSpace, std::function<void(ReadableString separatedText)> action) {
  242. string_split_callback(action, source, separator, removeWhiteSpace);
  243. }
  244. // Split source using separator, only to return the number of splits.
  245. // Useful for pre-allocation.
  246. intptr_t string_splitCount(const ReadableString& source, DsrChar separator);
  247. // Post-condition: Returns true iff c is a digit.
  248. // Digit <- '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  249. bool character_isDigit(DsrChar c);
  250. // Post-condition: Returns true iff c is an integer character.
  251. // IntegerCharacter <- '-' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  252. bool character_isIntegerCharacter(DsrChar c);
  253. // Post-condition: Returns true iff c is a value character.
  254. // ValueCharacter <- '.' | '-' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  255. bool character_isValueCharacter(DsrChar c);
  256. // Post-condition: Returns true iff c is a white-space character.
  257. // WhiteSpace <- ' ' | '\t' | '\v' | '\f' | '\n' | '\r'
  258. // Null terminators are excluded, because it's reserved for out of bound results.
  259. bool character_isWhiteSpace(DsrChar c);
  260. // Post-condition: Returns true iff source is a valid integer. IntegerAllowingWhiteSpace is also allowed iff allowWhiteSpace is true.
  261. // UnsignedInteger <- Digit+
  262. // Integer <- UnsignedInteger | '-' UnsignedInteger
  263. // IntegerAllowingWhiteSpace <- WhiteSpace* Integer WhiteSpace*
  264. bool string_isInteger(const ReadableString& source, bool allowWhiteSpace = true);
  265. // Post-condition: Returns true iff source is a valid integer or decimal number. DoubleAllowingWhiteSpace is also allowed iff allowWhiteSpace is true.
  266. // UnsignedDouble <- Digit+ | Digit* '.' Digit+
  267. // Double <- UnsignedDouble | '-' UnsignedDouble
  268. // DoubleAllowingWhiteSpace <- WhiteSpace* Double WhiteSpace*
  269. // Only dots are allowed as decimals.
  270. // Because being able to read files from another country without crashes is a lot more important than a detail that most people don't even notice.
  271. // Automatic nationalization made sense when most applications were written in-house before the internet existed.
  272. bool string_isDouble(const ReadableString& source, bool allowWhiteSpace = true);
  273. // Pre-condition: source must be a valid integer according to string_isInteger. Otherwise unexpected characters are simply ignored.
  274. // Post-condition: Returns the integer representation of source.
  275. // The result is signed, because the input might unexpectedly have a negation sign.
  276. // The result is large, so that one can easily check the range before assigning to a smaller integer type.
  277. int64_t string_toInteger(const ReadableString& source);
  278. // Side-effect: Appends value as a base ten integer at the end of target.
  279. void string_fromUnsigned(String& target, uint64_t value);
  280. // Post-condition: Returns value written as a base ten integer.
  281. inline String string_fromUnsigned(int64_t value) {
  282. String result; string_fromUnsigned(result, value); return result;
  283. }
  284. // Side-effect: Appends value as a base ten integer at the end of target.
  285. void string_fromSigned(String& target, int64_t value, DsrChar negationCharacter = U'-');
  286. // Post-condition: Returns value written as a base ten integer.
  287. inline String string_fromSigned(int64_t value, DsrChar negationCharacter = U'-') {
  288. String result; string_fromSigned(result, value, negationCharacter); return result;
  289. }
  290. // Pre-condition: source must be a valid double according to string_isDouble. Otherwise unexpected characters are simply ignored.
  291. // Post-condition: Returns the double precision floating-point representation of source.
  292. double string_toDouble(const ReadableString& source);
  293. // Side-effect: Appends value as a base ten decimal number at the end of target.
  294. void string_fromDouble(String& target, double value, int decimalCount = 6, bool removeTrailingZeroes = true, DsrChar decimalCharacter = U'.', DsrChar negationCharacter = U'-');
  295. // Post-condition: Returns value written as a base ten decimal number.
  296. inline String string_fromDouble(double value, int decimalCount = 6, bool removeTrailingZeroes = true, DsrChar decimalCharacter = U'.', DsrChar negationCharacter = U'-') {
  297. String result; string_fromDouble(result, value, decimalCount, removeTrailingZeroes, decimalCharacter, negationCharacter); return result;
  298. }
  299. // Loading will try to find a byte order mark and can handle UTF-8 and UTF-16.
  300. // Failure to find a byte order mark will assume that the file's content is raw Latin-1,
  301. // because automatic detection would cause random behaviour.
  302. // For portability, carriage return characters are removed,
  303. // but will be generated again using the default CrLf line encoding of string_save.
  304. // Post-condition:
  305. // Returns the content of the file referred to be filename.
  306. // If mustExist is true, then failure to load will throw an exception.
  307. // If mustExist is false, then failure to load will return an empty string.
  308. // If you want to handle files that are not found in a different way,
  309. // it is easy to use buffer_load and string_loadFromMemory separatelly.
  310. String string_load(const ReadableString& filename, bool mustExist = true);
  311. // Decode a text file from a buffer, which can be loaded using buffer_load.
  312. String string_loadFromMemory(Buffer fileContent);
  313. // Decode a null terminated string without BOM, by specifying which format it was encoded in.
  314. // Pre-conditions:
  315. // data does not start with any byte-order-mark (BOM).
  316. // data must be null terminated with '\0' in whatever format is being used. Otherwise you may have random crashes
  317. // Post-condition:
  318. // Returns a string decoded from the raw data.
  319. String string_dangerous_decodeFromData(const void* data, CharacterEncoding encoding);
  320. // Side-effect: Saves content to filename using the selected character and line encodings.
  321. // Post-condition: Returns true on success and false on failure.
  322. // Do not add carriage return characters yourself into strings, for these will be added automatically in the CrLf mode.
  323. // The internal String type should only use UTF-32 with single line feeds for breaking lines.
  324. // This makes text processing algorithms a lot cleaner when a character or line break is always one element.
  325. // UTF-8 with BOM is default by being both compact and capable of storing 21 bits of unicode.
  326. bool string_save(const ReadableString& filename, const ReadableString& content,
  327. CharacterEncoding characterEncoding = CharacterEncoding::BOM_UTF8,
  328. LineEncoding lineEncoding = LineEncoding::CrLf
  329. );
  330. // Encode the string and keep the raw buffer instead of saving it to a file.
  331. // Disabling writeByteOrderMark can be done when the result is casted to a native string for platform specific APIs, where a BOM is not allowed.
  332. // Enabling writeNullTerminator should be done when using the result as a pointer, so that the length is known when the buffer does not have padding.
  333. Buffer string_saveToMemory(const ReadableString& content,
  334. CharacterEncoding characterEncoding = CharacterEncoding::BOM_UTF8,
  335. LineEncoding lineEncoding = LineEncoding::CrLf,
  336. bool writeByteOrderMark = true,
  337. bool writeNullTerminator = false
  338. );
  339. // Post-condition: Returns true iff strings a and b are exactly equal.
  340. bool string_match(const ReadableString& a, const ReadableString& b);
  341. // Post-condition: Returns true iff strings a and b are roughly equal using a case insensitive match.
  342. bool string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b);
  343. // While string_match should be preferred over == for code readability and consistency with string_caseInsensitiveMatch,
  344. // the equality operator might be called automatically from template methods when a template type is a string.
  345. inline bool operator==(const ReadableString& a, const ReadableString& b) { return string_match(a, b); }
  346. inline bool operator!=(const ReadableString& a, const ReadableString& b) { return !string_match(a, b); }
  347. // Post-condition: Returns text converted to upper case.
  348. String string_upperCase(const ReadableString &text);
  349. // Post-condition: Returns text converted to lower case.
  350. String string_lowerCase(const ReadableString &text);
  351. // Post-condition: Returns a sub-set of text without surrounding white-space (space, tab and carriage-return).
  352. ReadableString string_removeOuterWhiteSpace(const ReadableString &text);
  353. // Post-condition: Returns rawText wrapped in a quote.
  354. // Special characters are included using escape characters, so that one can quote multiple lines but store it easily.
  355. String string_mangleQuote(const ReadableString &rawText);
  356. // Pre-condition: mangledText must be enclosed in double quotes and special characters must use escape characters (tabs in quotes are okay though).
  357. // Post-condition: Returns mangledText with quotes removed and excape tokens interpreted.
  358. String string_unmangleQuote(const ReadableString& mangledText);
  359. // Post-condition: Returns the number of strings using the same buffer, including itself.
  360. uintptr_t string_getBufferUseCount(const ReadableString& text);
  361. // Ensures safely that at least minimumLength characters can he held in the buffer
  362. void string_reserve(String& target, intptr_t minimumLength);
  363. // Append/push one character (to avoid integer to string conversion)
  364. void string_appendChar(String& target, DsrChar value);
  365. // Append one element
  366. template<typename TYPE>
  367. inline void string_append(String& target, const TYPE &value) {
  368. string_toStreamIndented(target, value, U"");
  369. }
  370. // Append multiple elements
  371. template<typename HEAD, typename... TAIL>
  372. inline void string_append(String& target, HEAD head, TAIL&&... tail) {
  373. string_toStreamIndented(target, head, U"");
  374. string_append(target, tail...);
  375. }
  376. // Combine a number of strings, characters and numbers
  377. // If an input type is rejected, create a Printable object to wrap around it
  378. template<typename... ARGS>
  379. inline String string_combine(ARGS&&... args) {
  380. String result;
  381. string_append(result, args...);
  382. return result;
  383. }
  384. // ---------------- Infix syntax ----------------
  385. // Operations
  386. inline String operator+ (const ReadableString& a, const ReadableString& b) { return string_combine(a, b); }
  387. inline String operator+ (const DsrChar* a, const ReadableString& b) { return string_combine(a, b); }
  388. inline String operator+ (const ReadableString& a, const DsrChar* b) { return string_combine(a, b); }
  389. inline String operator+ (const String& a, const String& b) { return string_combine(a, b); }
  390. inline String operator+ (const DsrChar* a, const String& b) { return string_combine(a, b); }
  391. inline String operator+ (const String& a, const DsrChar* b) { return string_combine(a, b); }
  392. inline String operator+ (const String& a, const ReadableString& b) { return string_combine(a, b); }
  393. inline String operator+ (const ReadableString& a, const String& b) { return string_combine(a, b); }
  394. // ---------------- Message handling ----------------
  395. enum class MessageType {
  396. Error, // Terminate as quickly as possible after saving and informing the user.
  397. Warning, // Inform the user but let the caller continue.
  398. StandardPrinting, // Print text to the terminal.
  399. DebugPrinting // Print debug information to the terminal, if debug mode is active.
  400. };
  401. // Get a reference to the thread-local buffer used for printing messages.
  402. // Can be combined with string_clear, string_append and string_sendMessage to send long messages in a thread-safe way.
  403. // Clear, fill and send.
  404. String &string_getPrintBuffer();
  405. // Send a message
  406. void string_sendMessage(const ReadableString &message, MessageType type);
  407. // Send a message directly to the default message handler, ignoring string_assignMessageHandler.
  408. void string_sendMessage_default(const ReadableString &message, MessageType type);
  409. // Get a message
  410. // Pre-condition:
  411. // The action function must throw an exception or terminate the program when given an error, otherwise string_sendMessage will throw an exception about failing to do so.
  412. // Do not call string_sendMessage directly or indirectly from within action, use string_sendMessage_default instead to avoid infinite recursion.
  413. // Terminating the program as soon as possible is ideal, but one might want to save a backup or show what went wrong in a graphical interface before terminating.
  414. // Do not throw and catch errors as if they were warnings, because throwing and catching creates a partial transaction, potentially violating type invariants.
  415. // Better to use warnings and let the sender of the warning figure out how to abort the action safely.
  416. void string_assignMessageHandler(std::function<void(const ReadableString &message, MessageType type)> action);
  417. // Undo string_assignMessageHandler, so that any messages will be handled the default way again.
  418. void string_unassignMessageHandler();
  419. // Throw an error, which must terminate the application or throw an error
  420. template<typename... ARGS>
  421. void throwError(ARGS... args) {
  422. String *target = &(string_getPrintBuffer());
  423. string_clear(*target);
  424. string_append(*target, args...);
  425. string_sendMessage(*target, MessageType::Error);
  426. }
  427. // Send a warning, which might throw an exception, terminate the application or anything else that the application requests using string_handleMessages
  428. template<typename... ARGS>
  429. void sendWarning(ARGS... args) {
  430. String *target = &(string_getPrintBuffer());
  431. string_clear(*target);
  432. string_append(*target, args...);
  433. string_sendMessage(*target, MessageType::Warning);
  434. }
  435. // Print information to the terminal or something else listening for messages using string_handleMessages
  436. template<typename... ARGS>
  437. void printText(ARGS... args) {
  438. String *target = &(string_getPrintBuffer());
  439. string_clear(*target);
  440. string_append(*target, args...);
  441. string_sendMessage(*target, MessageType::StandardPrinting);
  442. }
  443. // Debug messages are automatically disabled in release mode, so that you don't have to worry about accidentally releasing a program with poor performance from constantly printing to the terminal
  444. // Useful for selectively printing the most important information accumulated over time
  445. // Less useful for profiling, because the debug mode is slower than the release mode
  446. #ifdef NDEBUG
  447. // Supress debugText in release mode
  448. template<typename... ARGS>
  449. void debugText(ARGS... args) {}
  450. #else
  451. // Print debugText in debug mode
  452. template<typename... ARGS>
  453. void debugText(ARGS... args) {
  454. String *target = &(string_getPrintBuffer());
  455. string_clear(*target);
  456. string_append(*target, args...);
  457. string_sendMessage(*target, MessageType::DebugPrinting);
  458. }
  459. #endif
  460. // Used to generate fixed size ascii strings, which is useful when heap allocations are not possible
  461. // or you need a safe format until you know which encoding a system call needs to support Unicode.
  462. template <intptr_t SIZE>
  463. struct FixedAscii {
  464. char characters[SIZE];
  465. // Create a fixed size ascii string from a null terminated ascii string.
  466. // Crops if text is too long.
  467. FixedAscii(const char *text) {
  468. bool terminated = false;
  469. for (intptr_t i = 0; i < SIZE - 1; i++) {
  470. char c = text[i];
  471. if (c == '\0') {
  472. terminated = true;
  473. }
  474. if (terminated) {
  475. this->characters[i] = '\0';
  476. } else if (c > 127) {
  477. this->characters[i] = '?';
  478. } else {
  479. this->characters[i] = c;
  480. }
  481. }
  482. this->characters[SIZE - 1] = '\0';
  483. }
  484. FixedAscii(const ReadableString &text) {
  485. bool terminated = false;
  486. for (intptr_t i = 0; i < SIZE - 1; i++) {
  487. char c = text[i];
  488. if (c == '\0') {
  489. terminated = true;
  490. }
  491. if (terminated) {
  492. this->characters[i] = '\0';
  493. } else if (c > 127) {
  494. this->characters[i] = '?';
  495. } else {
  496. this->characters[i] = c;
  497. }
  498. }
  499. this->characters[SIZE - 1] = '\0';
  500. }
  501. operator const char *() const {
  502. return characters;
  503. }
  504. };
  505. }
  506. #endif