text.h 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2020 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_BASE_TEXT
  24. #define DFPSR_BASE_TEXT
  25. #include <stdint.h>
  26. #include <string>
  27. #include <iostream>
  28. #include <sstream>
  29. #include <functional>
  30. #include "../api/bufferAPI.h"
  31. #include "../collection/List.h"
  32. // Define DFPSR_INTERNAL_ACCESS before any include to get internal access to exposed types
  33. #ifdef DFPSR_INTERNAL_ACCESS
  34. #define IMPL_ACCESS public
  35. #else
  36. #define IMPL_ACCESS protected
  37. #endif
  38. namespace dsr {
  39. using DsrChar = char32_t;
  40. // Text files support loading UTF-8/16 BE/LE with BOM or Latin-1 without BOM
  41. enum class CharacterEncoding {
  42. Raw_Latin1, // U+00 to U+FF
  43. BOM_UTF8, // U+00000000 to U+0010FFFF
  44. BOM_UTF16BE, // U+00000000 to U+0000D7FF, U+0000E000 to U+0010FFFF
  45. BOM_UTF16LE // U+00000000 to U+0000D7FF, U+0000E000 to U+0010FFFF
  46. };
  47. // Carriage-return is removed when loading text files to prevent getting double lines
  48. // A line-feed without a line-feed character is nonsense
  49. // LineEncoding allow re-adding carriage-return before or after each line-break when saving
  50. enum class LineEncoding {
  51. CrLf, // Microsoft Windows compatible (Can also be read on other platforms by ignoring carriage return)
  52. Lf // Linux and Macintosh compatible (Might not work on non-portable text editors on Microsoft Windows)
  53. };
  54. // Replacing String with a ReadableString reference for input arguments can make passing of U"" literals faster.
  55. // Unlike String, it cannot be constructed from a "" literal, because UTF-32 is used internally.
  56. // Only use by reference for input arguments or to hold temporary results!
  57. // A ReadableString created as a sub-string from String will stop working once the parent String is freed.
  58. class ReadableString {
  59. IMPL_ACCESS:
  60. // A local pointer to the sub-allocation
  61. const char32_t* readSection = nullptr;
  62. // The length of the current string in characters
  63. // Use the string_length getter to access
  64. // If you just want to reuse memory for a sub-string, then use string_inclusiveRange
  65. int64_t length = 0;
  66. public:
  67. // Returning the character by value prevents writing to memory that might be a constant literal or shared with other strings
  68. DsrChar operator[] (int64_t index) const;
  69. public:
  70. // Empty string U""
  71. ReadableString();
  72. // Implicit casting from U"text"
  73. // Do not use ReadableString for heap allocated allocations that might be freed during the string's life!
  74. // String can handle dynamic memory and should be used in that case.
  75. ReadableString(const DsrChar *content);
  76. // Destructor
  77. virtual ~ReadableString();
  78. public:
  79. // Converting to unknown character encoding using only the ascii character subset
  80. // A bug in GCC linking forces these to be virtual
  81. virtual std::ostream& toStream(std::ostream& out) const;
  82. virtual std::string toStdString() const;
  83. };
  84. class String;
  85. // Used as format tags around numbers passed to string_append or string_combine
  86. // New types can implement printing to String by making wrappers from this class
  87. class Printable {
  88. public:
  89. // The method for appending the printable object into the target string
  90. virtual String& toStreamIndented(String& target, const ReadableString& indentation) const = 0;
  91. String& toStream(String& target) const;
  92. String toStringIndented(const ReadableString& indentation) const;
  93. String toString() const;
  94. std::ostream& toStreamIndented(std::ostream& out, const ReadableString& indentation) const;
  95. std::ostream& toStream(std::ostream& out) const;
  96. std::string toStdString() const;
  97. virtual ~Printable();
  98. };
  99. // A safe and simple string type
  100. // Can be constructed from ascii literals "", but U"" will preserve unicode characters.
  101. // Can be used without ReadableString, but ReadableString can be wrapped over U"" literals without allocation
  102. // UTF-32
  103. // Endianness is native
  104. // No combined characters allowed, use precomposed instead, so that the strings can guarantee a fixed character size
  105. class String : public ReadableString {
  106. IMPL_ACCESS:
  107. // A reference counted pointer to the buffer to allow passing strings around without having to clone the buffer each time
  108. Buffer buffer;
  109. // Same as readSection, but with write access
  110. char32_t* writeSection = nullptr;
  111. // Internal constructor
  112. String(Buffer buffer, DsrChar *content, int64_t length);
  113. // The number of DsrChar characters that can be contained in the allocation before reaching the buffer's end
  114. // This doesn't imply that it's always okay to write to the remaining space, because the buffer may be shared
  115. int64_t capacity();
  116. // Replaces the buffer with a new buffer holding at least newLength characters
  117. // Guarantees that the new buffer is not shared by other strings, so that it may be written to freely
  118. void reallocateBuffer(int64_t newLength, bool preserve);
  119. // Call before writing to the buffer
  120. // This hides that Strings share buffers when assigning by value or taking partial strings
  121. void cloneIfShared();
  122. void expand(int64_t newLength, bool affectUsedLength);
  123. public:
  124. // Constructors
  125. String();
  126. String(const char* source);
  127. String(const char32_t* source);
  128. String(const std::string& source);
  129. String(const ReadableString& source);
  130. String(const String& source);
  131. public:
  132. // Ensures safely that at least minimumLength characters can he held in the buffer
  133. void reserve(int64_t minimumLength);
  134. // Extend the String using more text
  135. void append(const char* source);
  136. void append(const ReadableString& source);
  137. void append(const char32_t* source);
  138. void append(const std::string& source);
  139. // Extend the String using another character
  140. void appendChar(DsrChar source);
  141. public:
  142. // Access
  143. void write(int64_t index, DsrChar value);
  144. void clear();
  145. };
  146. // Define this overload for non-virtual source types that cannot inherit from Printable
  147. String& string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation);
  148. String& string_toStreamIndented(String& target, const char* value, const ReadableString& indentation);
  149. String& string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation);
  150. String& string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation);
  151. String& string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation);
  152. String& string_toStreamIndented(String& target, const float& value, const ReadableString& indentation);
  153. String& string_toStreamIndented(String& target, const double& value, const ReadableString& indentation);
  154. String& string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation);
  155. String& string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation);
  156. String& string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation);
  157. String& string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation);
  158. String& string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation);
  159. String& string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation);
  160. String& string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation);
  161. String& string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation);
  162. // Templates reused for all types
  163. // The source must inherit from Printable or have its own string_feedIndented overload
  164. template<typename T>
  165. String& string_toStream(String& target, const T& source) {
  166. return string_toStreamIndented(target, source, U"");
  167. }
  168. template<typename T>
  169. String string_toStringIndented(const T& source, const ReadableString& indentation) {
  170. String result;
  171. string_toStreamIndented(result, source, indentation);
  172. return result;
  173. }
  174. template<typename T>
  175. String string_toString(const T& source) {
  176. return string_toStringIndented(source, U"");
  177. }
  178. template<typename T>
  179. std::ostream& string_toStreamIndented(std::ostream& target, const T& source, const ReadableString& indentation) {
  180. return target << string_toStringIndented(source, indentation);
  181. }
  182. template<typename T>
  183. std::ostream& string_toStream(std::ostream& target, const T& source) {
  184. return target << string_toString(source);
  185. }
  186. // ---------------- Procedural API ----------------
  187. // Sets the target string's length to zero.
  188. // Because this opens up to appending new text where sub-string may already share the buffer,
  189. // this operation will reallocate the buffer if shared with other strings.
  190. void string_clear(String& target);
  191. // Post-condition: Returns the length of source.
  192. // Example: string_length(U"ABC") == 3
  193. int64_t string_length(const ReadableString& source);
  194. // Post-condition: Returns the base-zero index of source's first occurence of toFind, starting from startIndex. Returns -1 if not found.
  195. // Example: string_findFirst(U"ABCABCABC", U'A') == 0
  196. // Example: string_findFirst(U"ABCABCABC", U'B') == 1
  197. // Example: string_findFirst(U"ABCABCABC", U'C') == 2
  198. // Example: string_findFirst(U"ABCABCABC", U'D') == -1
  199. int64_t string_findFirst(const ReadableString& source, DsrChar toFind, int64_t startIndex = 0);
  200. // Post-condition: Returns the base-zero index of source's last occurence of toFind. Returns -1 if not found.
  201. // Example: string_findLast(U"ABCABCABC", U'A') == 6
  202. // Example: string_findLast(U"ABCABCABC", U'B') == 7
  203. // Example: string_findLast(U"ABCABCABC", U'C') == 8
  204. // Example: string_findLast(U"ABCABCABC", U'D') == -1
  205. int64_t string_findLast(const ReadableString& source, DsrChar toFind);
  206. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to before the character at exclusiveEnd
  207. // Example: string_exclusiveRange(U"0123456789", 2, 4) == U"23"
  208. ReadableString string_exclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t exclusiveEnd);
  209. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to after the character at inclusiveEnd
  210. // Example: string_inclusiveRange(U"0123456789", 2, 4) == U"234"
  211. ReadableString string_inclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t inclusiveEnd);
  212. // Post-condition: Returns a sub-string of source from the start to before the character at exclusiveEnd
  213. // Example: string_before(U"0123456789", 5) == U"01234"
  214. ReadableString string_before(const ReadableString& source, int64_t exclusiveEnd);
  215. // Post-condition: Returns a sub-string of source from the start to after the character at inclusiveEnd
  216. // Example: string_until(U"0123456789", 5) == U"012345"
  217. ReadableString string_until(const ReadableString& source, int64_t inclusiveEnd);
  218. // Post-condition: Returns a sub-string of source from before the character at inclusiveStart to the end
  219. // Example: string_from(U"0123456789", 5) == U"56789"
  220. ReadableString string_from(const ReadableString& source, int64_t inclusiveStart);
  221. // Post-condition: Returns a sub-string of source from after the character at exclusiveStart to the end
  222. // Example: string_after(U"0123456789", 5) == U"6789"
  223. ReadableString string_after(const ReadableString& source, int64_t exclusiveStart);
  224. // The safest split implementation
  225. // Post-condition:
  226. // Returns a list of strings from source by splitting along separator.
  227. // If removeWhiteSpace is true then surrounding white-space will be removed, otherwise white-space is kept.
  228. // The separating characters are excluded from the resulting strings.
  229. // The number of strings returned in the list will equal the number of separating characters plus one, so the result may contain empty strings.
  230. // Each string in the list clones content to its own dynamic buffer. Use string_split_callback if you don't need long term storage.
  231. List<String> string_split_clone(const ReadableString& source, DsrChar separator, bool removeWhiteSpace = false);
  232. // The fastest and most powerful split implementation
  233. // Split a string without needing a list to store the result.
  234. // Call it twice using different lambda functions if you want to count the size before allocating a buffer.
  235. // Side-effects:
  236. // Calls action for each sub-string divided by separator in source.
  237. void string_split_callback(std::function<void(ReadableString)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace = false);
  238. // An alternative overload for having a very long lambda at the end.
  239. inline void string_split_callback(const ReadableString& source, DsrChar separator, bool removeWhiteSpace, std::function<void(ReadableString)> action) {
  240. string_split_callback(action, source, separator, removeWhiteSpace);
  241. }
  242. // Warning! May cause a crash.
  243. // Do not use a ReadableString generated by splitting a String past the String's lifetime.
  244. // ReadableString does not allocate any heap memory but is only a view for data allocated elsewhere.
  245. // Use string_split_callback if you want something safer.
  246. // Post-condition:
  247. // Returns a list of strings from source by splitting along separator.
  248. // The separating characters are excluded from the resulting strings.
  249. // The number of strings returned in the list will equal the number of separating characters plus one, so the result may contain empty strings.
  250. // Each string in the list reuses memory from the input string using reference counting, but the list itself will be allocated.
  251. List<ReadableString> string_dangerous_split(const ReadableString& source, DsrChar separator);
  252. // Warning! May cause a crash.
  253. // Do not use a ReadableString generated by splitting a String past the String's lifetime.
  254. // ReadableString does not allocate any heap memory but is only a view for data allocated elsewhere.
  255. // Use string_split_callback if you want something safer.
  256. // Use string_split_inPlace instead of string_split if you want to reuse the memory of an existing list.
  257. // It will then only allocate when running out of buffer space.
  258. // Side-effects:
  259. // Fills the target list with strings from source by splitting along separator.
  260. // If appendResult is false (default), any pre-existing elements in the target list will be cleared before writing the result.
  261. // If appendResult is true, the result is appended to the existing target list.
  262. void string_dangerous_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult = false);
  263. // Split source using separator, only to return the number of splits.
  264. // Useful for pre-allocation.
  265. int64_t string_splitCount(const ReadableString& source, DsrChar separator);
  266. // Post-condition: Returns true iff c is a digit.
  267. // Digit <- '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  268. bool character_isDigit(DsrChar c);
  269. // Post-condition: Returns true iff c is an integer character.
  270. // IntegerCharacter <- '-' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  271. bool character_isIntegerCharacter(DsrChar c);
  272. // Post-condition: Returns true iff c is a value character.
  273. // ValueCharacter <- '.' | '-' | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
  274. bool character_isValueCharacter(DsrChar c);
  275. // Post-condition: Returns true iff c is a white-space character.
  276. // WhiteSpace <- ' ' | '\t' | '\v' | '\f' | '\n' | '\r'
  277. // Null terminators are excluded, because it's reserved for out of bound results.
  278. bool character_isWhiteSpace(DsrChar c);
  279. // Post-condition: Returns true iff source is a valid integer. IntegerAllowingWhiteSpace is also allowed iff allowWhiteSpace is true.
  280. // UnsignedInteger <- Digit+
  281. // Integer <- UnsignedInteger | '-' UnsignedInteger
  282. // IntegerAllowingWhiteSpace <- WhiteSpace* Integer WhiteSpace*
  283. bool string_isInteger(const ReadableString& source, bool allowWhiteSpace = true);
  284. // Post-condition: Returns true iff source is a valid integer or decimal number. DoubleAllowingWhiteSpace is also allowed iff allowWhiteSpace is true.
  285. // UnsignedDouble <- Digit+ | Digit* '.' Digit+
  286. // Double <- UnsignedDouble | '-' UnsignedDouble
  287. // DoubleAllowingWhiteSpace <- WhiteSpace* Double WhiteSpace*
  288. // Only dots are allowed as decimals.
  289. // 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.
  290. // Automatic nationalization made sense when most applications were written in-house before the internet existed.
  291. bool string_isDouble(const ReadableString& source, bool allowWhiteSpace = true);
  292. // Pre-condition: source must be a valid integer according to string_isInteger. Otherwise unexpected characters are simply ignored.
  293. // Post-condition: Returns the integer representation of source.
  294. // The result is signed, because the input might unexpectedly have a negation sign.
  295. // The result is large, so that one can easily check the range before assigning to a smaller integer type.
  296. int64_t string_toInteger(const ReadableString& source);
  297. // Pre-condition: source must be a valid double according to string_isDouble. Otherwise unexpected characters are simply ignored.
  298. // Post-condition: Returns the double precision floating-point representation of source.
  299. double string_toDouble(const ReadableString& source);
  300. // Loading will try to find a byte order mark and can handle UTF-8 and UTF-16.
  301. // Failure to find a byte order mark will assume that the file's content is raw Latin-1,
  302. // because automatic detection would cause random behaviour.
  303. // For portability, carriage return characters are removed,
  304. // but will be generated again using the default CrLf line encoding of string_save.
  305. // Post-condition:
  306. // Returns the content of the file referred to be filename.
  307. // If mustExist is true, then failure to load will throw an exception.
  308. // If mustExist is false, then failure to load will return an empty string.
  309. // If you want to handle files that are not found in a different way,
  310. // it is easy to use buffer_load and string_loadFromMemory separatelly.
  311. String string_load(const ReadableString& filename, bool mustExist = true);
  312. // Decode a text file from a buffer, which can be loaded using buffer_load.
  313. String string_loadFromMemory(Buffer fileContent);
  314. // Side-effect: Saves content to filename using the selected character and line encodings.
  315. // Do not add carriage return characters yourself into strings, for these will be added automatically in the CrLf mode.
  316. // The internal String type should only use UTF-32 with single line feeds for breaking lines.
  317. // This makes text processing algorithms a lot cleaner when a character or line break is always one element.
  318. // UTF-8 with BOM is default by being both compact and capable of storing 21 bits of unicode.
  319. void string_save(const ReadableString& filename, const ReadableString& content,
  320. CharacterEncoding characterEncoding = CharacterEncoding::BOM_UTF8,
  321. LineEncoding lineEncoding = LineEncoding::CrLf
  322. );
  323. // Encode the string and keep the raw buffer instead of saving it to a file.
  324. Buffer string_saveToMemory(const ReadableString& content,
  325. CharacterEncoding characterEncoding = CharacterEncoding::BOM_UTF8,
  326. LineEncoding lineEncoding = LineEncoding::CrLf
  327. );
  328. // Post-condition: Returns true iff strings a and b are exactly equal.
  329. bool string_match(const ReadableString& a, const ReadableString& b);
  330. // Post-condition: Returns true iff strings a and b are roughly equal using a case insensitive match.
  331. bool string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b);
  332. // Post-condition: Returns text converted to upper case.
  333. String string_upperCase(const ReadableString &text);
  334. // Post-condition: Returns text converted to lower case.
  335. String string_lowerCase(const ReadableString &text);
  336. // Post-condition: Returns a sub-set of text without surrounding white-space (space, tab and carriage-return).
  337. ReadableString string_removeOuterWhiteSpace(const ReadableString &text);
  338. // Post-condition: Returns rawText wrapped in a quote.
  339. // Special characters are included using escape characters, so that one can quote multiple lines but store it easily.
  340. String string_mangleQuote(const ReadableString &rawText);
  341. // Pre-condition: mangledText must be enclosed in double quotes and special characters must use escape characters (tabs in quotes are okay though).
  342. // Post-condition: Returns mangledText with quotes removed and excape tokens interpreted.
  343. String string_unmangleQuote(const ReadableString& mangledText);
  344. // Post-condition: Returns the number of strings using the same buffer, including itself.
  345. int64_t string_getBufferUseCount(const String& text);
  346. // Ensures safely that at least minimumLength characters can he held in the buffer
  347. inline void string_reserve(String& target, int64_t minimumLength) {
  348. target.reserve(minimumLength);
  349. }
  350. // Append/push one character (to avoid integer to string conversion)
  351. inline void string_appendChar(String& target, DsrChar value) {
  352. target.appendChar(value);
  353. }
  354. // Append one element
  355. template<typename TYPE>
  356. inline void string_append(String& target, TYPE value) {
  357. string_toStream(target, value);
  358. }
  359. // Append multiple elements
  360. template<typename HEAD, typename... TAIL>
  361. inline void string_append(String& target, HEAD head, TAIL... tail) {
  362. string_append(target, head);
  363. string_append(target, tail...);
  364. }
  365. // Combine a number of strings, characters and numbers
  366. // If an input type is rejected, create a Printable object to wrap around it
  367. template<typename... ARGS>
  368. inline String string_combine(ARGS... args) {
  369. String result;
  370. string_append(result, args...);
  371. return result;
  372. }
  373. // ---------------- Infix syntax ----------------
  374. // Operations
  375. inline String operator+ (const ReadableString& a, const ReadableString& b) { return string_combine(a, b); }
  376. inline String operator+ (const char32_t* a, const ReadableString& b) { return string_combine(a, b); }
  377. inline String operator+ (const ReadableString& a, const char32_t* b) { return string_combine(a, b); }
  378. inline String operator+ (const String& a, const String& b) { return string_combine(a, b); }
  379. inline String operator+ (const char32_t* a, const String& b) { return string_combine(a, b); }
  380. inline String operator+ (const String& a, const char32_t* b) { return string_combine(a, b); }
  381. inline String operator+ (const String& a, const ReadableString& b) { return string_combine(a, b); }
  382. inline String operator+ (const ReadableString& a, const String& b) { return string_combine(a, b); }
  383. // Methods used so often that they don't need to use the string_ prefix
  384. // Print information
  385. template<typename... ARGS>
  386. void printText(ARGS... args) {
  387. String result = string_combine(args...);
  388. result.toStream(std::cout);
  389. }
  390. // Use for text printing that are useful when debugging but should not be given out in a release
  391. #ifdef NDEBUG
  392. // Supress debugText in release mode
  393. template<typename... ARGS>
  394. void debugText(ARGS... args) {}
  395. #else
  396. // Print debugText in debug mode
  397. template<typename... ARGS>
  398. void debugText(ARGS... args) { printText(args...); }
  399. #endif
  400. // Raise an exception
  401. // Only catch errors to display useful error messages, emergency backups or crash logs before terminating
  402. // Further execution after a partial transaction will break object invariants
  403. void throwErrorMessage(const String& message);
  404. template<typename... ARGS>
  405. void throwError(ARGS... args) {
  406. String result = string_combine(args...);
  407. throwErrorMessage(result);
  408. }
  409. }
  410. #endif