text.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 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. #include "text.h"
  24. #include <fstream>
  25. #include <streambuf>
  26. #include <cstring>
  27. #include <stdexcept>
  28. using namespace dsr;
  29. static int strlen_utf32(const char32_t *content) {
  30. int length = 0;
  31. while (content[length] != 0) {
  32. length++;
  33. }
  34. return length;
  35. }
  36. static char toAscii(DsrChar c) {
  37. if (c > 127) {
  38. return '?';
  39. } else {
  40. return c;
  41. }
  42. }
  43. String& Printable::toStream(String& target) const {
  44. return this->toStreamIndented(target, U"");
  45. }
  46. String Printable::toStringIndented(const ReadableString& indentation) const {
  47. String result;
  48. this->toStreamIndented(result, indentation);
  49. return result;
  50. }
  51. String Printable::toString() const {
  52. return this->toStringIndented(U"");
  53. }
  54. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  55. String result;
  56. this->toStreamIndented(result, indentation);
  57. for (int i = 0; i < result.length(); i++) {
  58. out.put(toAscii(result.read(i)));
  59. }
  60. return out;
  61. }
  62. std::ostream& Printable::toStream(std::ostream& out) const {
  63. return this->toStreamIndented(out, U"");
  64. }
  65. std::string Printable::toStdString() const {
  66. std::ostringstream result;
  67. this->toStream(result);
  68. return result.str();
  69. }
  70. Printable::~Printable() {}
  71. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  72. if (a.length() != b.length()) {
  73. return false;
  74. } else {
  75. for (int i = 0; i < a.length(); i++) {
  76. if (a.read(i) != b.read(i)) {
  77. return false;
  78. }
  79. }
  80. return true;
  81. }
  82. }
  83. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  84. if (a.length() != b.length()) {
  85. return false;
  86. } else {
  87. for (int i = 0; i < a.length(); i++) {
  88. if (towupper(a.read(i)) != towupper(b.read(i))) {
  89. return false;
  90. }
  91. }
  92. return true;
  93. }
  94. }
  95. std::ostream& ReadableString::toStream(std::ostream& out) const {
  96. for (int i = 0; i < this->length(); i++) {
  97. out.put(toAscii(this->read(i)));
  98. }
  99. return out;
  100. }
  101. std::string ReadableString::toStdString() const {
  102. std::ostringstream result;
  103. this->toStream(result);
  104. return result.str();
  105. }
  106. String dsr::string_upperCase(const ReadableString &text) {
  107. String result;
  108. result.reserve(text.length());
  109. for (int i = 0; i < text.length(); i++) {
  110. result.appendChar(towupper(text[i]));
  111. }
  112. return result;
  113. }
  114. String dsr::string_lowerCase(const ReadableString &text) {
  115. String result;
  116. result.reserve(text.length());
  117. for (int i = 0; i < text.length(); i++) {
  118. result.appendChar(towlower(text[i]));
  119. }
  120. return result;
  121. }
  122. String dsr::string_removeAllWhiteSpace(const ReadableString &text) {
  123. String result;
  124. result.reserve(text.length());
  125. for (int i = 0; i < text.length(); i++) {
  126. DsrChar c = text[i];
  127. if (!character_isWhiteSpace(c)) {
  128. result.appendChar(c);
  129. }
  130. }
  131. return result;
  132. }
  133. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  134. int first = -1;
  135. int last = -1;
  136. for (int i = 0; i < text.length(); i++) {
  137. DsrChar c = text[i];
  138. if (!character_isWhiteSpace(c)) {
  139. first = i;
  140. break;
  141. }
  142. }
  143. for (int i = text.length() - 1; i >= 0; i--) {
  144. DsrChar c = text[i];
  145. if (!character_isWhiteSpace(c)) {
  146. last = i;
  147. break;
  148. }
  149. }
  150. if (first == -1) {
  151. // Only white space
  152. return ReadableString();
  153. } else {
  154. // Subset
  155. return string_inclusiveRange(text, first, last);
  156. }
  157. }
  158. String dsr::string_mangleQuote(const ReadableString &rawText) {
  159. String result;
  160. result.reserve(rawText.length() + 2);
  161. result.appendChar(U'\"'); // Begin quote
  162. for (int i = 0; i < rawText.length(); i++) {
  163. DsrChar c = rawText[i];
  164. if (c == U'\"') { // Double quote
  165. result.append(U"\\\"");
  166. } else if (c == U'\\') { // Backslash
  167. result.append(U"\\\\");
  168. } else if (c == U'\a') { // Audible bell
  169. result.append(U"\\a");
  170. } else if (c == U'\b') { // Backspace
  171. result.append(U"\\b");
  172. } else if (c == U'\f') { // Form feed
  173. result.append(U"\\f");
  174. } else if (c == U'\n') { // Line feed
  175. result.append(U"\\n");
  176. } else if (c == U'\r') { // Carriage return
  177. result.append(U"\\r");
  178. } else if (c == U'\t') { // Horizontal tab
  179. result.append(U"\\t");
  180. } else if (c == U'\v') { // Vertical tab
  181. result.append(U"\\v");
  182. } else if (c == U'\0') { // Null terminator
  183. result.append(U"\\0");
  184. } else {
  185. result.appendChar(c);
  186. }
  187. }
  188. result.appendChar(U'\"'); // End quote
  189. return result;
  190. }
  191. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  192. int firstQuote = string_findFirst(mangledText, '\"');
  193. int lastQuote = string_findLast(mangledText, '\"');
  194. String result;
  195. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  196. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  197. } else {
  198. for (int i = firstQuote + 1; i < lastQuote; i++) {
  199. DsrChar c = mangledText[i];
  200. if (c == U'\\') { // Escape character
  201. DsrChar c2 = mangledText[i + 1];
  202. if (c2 == U'\"') { // Double quote
  203. result.appendChar(U'\"');
  204. } else if (c2 == U'\\') { // Back slash
  205. result.appendChar(U'\\');
  206. } else if (c2 == U'a') { // Audible bell
  207. result.appendChar(U'\a');
  208. } else if (c2 == U'b') { // Backspace
  209. result.appendChar(U'\b');
  210. } else if (c2 == U'f') { // Form feed
  211. result.appendChar(U'\f');
  212. } else if (c2 == U'n') { // Line feed
  213. result.appendChar(U'\n');
  214. } else if (c2 == U'r') { // Carriage return
  215. result.appendChar(U'\r');
  216. } else if (c2 == U't') { // Horizontal tab
  217. result.appendChar(U'\t');
  218. } else if (c2 == U'v') { // Vertical tab
  219. result.appendChar(U'\v');
  220. } else if (c2 == U'0') { // Null terminator
  221. result.appendChar(U'\0');
  222. }
  223. i++; // Consume both characters
  224. } else {
  225. // Detect bad input
  226. if (c == U'\"') { // Double quote
  227. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  228. } else if (c == U'\\') { // Back slash
  229. throwError(U"Unmangled back slash detected in string_unmangleQuote!\n", mangledText, "\n");
  230. } else if (c == U'\a') { // Audible bell
  231. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  232. } else if (c == U'\b') { // Backspace
  233. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  234. } else if (c == U'\f') { // Form feed
  235. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  236. } else if (c == U'\n') { // Line feed
  237. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  238. } else if (c == U'\r') { // Carriage return
  239. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  240. } else if (c == U'\0') { // Null terminator
  241. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  242. } else {
  243. result.appendChar(c);
  244. }
  245. }
  246. }
  247. }
  248. return result;
  249. }
  250. static void uintToString_arabic(String& target, uint64_t value) {
  251. static const int bufferSize = 20;
  252. DsrChar digits[bufferSize];
  253. int usedSize = 0;
  254. if (value == 0) {
  255. target.appendChar(U'0');
  256. } else {
  257. while (usedSize < bufferSize) {
  258. DsrChar digit = U'0' + (value % 10u);
  259. digits[usedSize] = digit;
  260. usedSize++;
  261. value /= 10u;
  262. if (value == 0) {
  263. break;
  264. }
  265. }
  266. while (usedSize > 0) {
  267. usedSize--;
  268. target.appendChar(digits[usedSize]);
  269. }
  270. }
  271. }
  272. static void intToString_arabic(String& target, int64_t value) {
  273. if (value >= 0) {
  274. uintToString_arabic(target, (uint64_t)value);
  275. } else {
  276. target.appendChar(U'-');
  277. uintToString_arabic(target, (uint64_t)(-value));
  278. }
  279. }
  280. // TODO: Implement own version to ensure that nothing strange is happening from buggy std implementations
  281. static void doubleToString_arabic(String& target, double value) {
  282. std::ostringstream buffer;
  283. buffer << std::fixed << value; // Generate using a fixed number of decimals
  284. std::string result = buffer.str();
  285. // Remove trailing zero decimal digits
  286. int decimalCount = 0;
  287. int lastValueIndex = -1;
  288. for (int c = 0; c < (int)result.length(); c++) {
  289. if (result[c] == '.') {
  290. decimalCount++;
  291. } else if (result[c] == ',') {
  292. result[c] = '.'; // Convert nationalized french decimal serialization into international decimals
  293. decimalCount++;
  294. } else if (decimalCount > 0 && result[c] >= '1' && result[c] <= '9') {
  295. lastValueIndex = c;
  296. } else if (decimalCount == 0 && result[c] >= '0' && result[c] <= '9') {
  297. lastValueIndex = c;
  298. }
  299. }
  300. for (int c = 0; c <= lastValueIndex; c++) {
  301. target.appendChar(result[c]);
  302. }
  303. }
  304. #define TO_RAW_ASCII(TARGET, SOURCE) \
  305. char TARGET[SOURCE.length() + 1]; \
  306. for (int i = 0; i < SOURCE.length(); i++) { \
  307. TARGET[i] = toAscii(SOURCE[i]); \
  308. } \
  309. TARGET[SOURCE.length()] = '\0';
  310. // TODO: Give as a lambda with target captured, so that pre-allocation can measure the
  311. // needed space exactly using a lambda that increases a character counter instead.
  312. // Interpreting a character's value and appends it to the string.
  313. static void feedCharacterFromFile(String &target, DsrChar character) {
  314. if (character != U'\r') {
  315. target.appendChar(character);
  316. }
  317. }
  318. // Appends the content of buffer as a BOM-free Latin-1 file into target
  319. static void AppendStringFromFileBuffer_Latin1(String &target, const uint8_t* buffer, int64_t fileLength) {
  320. for (int64_t i = 0; i < fileLength; i++) {
  321. feedCharacterFromFile(target, (DsrChar)(buffer[i]));
  322. }
  323. }
  324. // Appends the content of buffer as a BOM-free UTF-8 file into target
  325. static void AppendStringFromFileBuffer_UTF8(String &target, const uint8_t* buffer, int64_t fileLength) {
  326. // We know that the result will be at least one character per given byte for UTF-8
  327. target.reserve(string_length(target) + fileLength);
  328. for (int64_t i = 0; i < fileLength; i++) {
  329. uint8_t byteA = buffer[i];
  330. if (byteA < 0b10000000) {
  331. // Single byte (1xxxxxxx)
  332. feedCharacterFromFile(target, (DsrChar)byteA);
  333. } else {
  334. uint32_t character = 0;
  335. int extraBytes = 0;
  336. if (byteA >= 0b11000000) { // At least two leading ones
  337. if (byteA < 0b11100000) { // Less than three leading ones
  338. character = byteA & 0b00011111;
  339. extraBytes = 1;
  340. } else if (byteA < 0b11110000) { // Less than four leading ones
  341. character = byteA & 0b00011111;
  342. extraBytes = 2;
  343. } else if (byteA < 0b11111000) { // Less than five leading ones
  344. character = byteA & 0b00011111;
  345. extraBytes = 3;
  346. } else {
  347. // Invalid UTF-8 format
  348. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  349. }
  350. } else {
  351. // Invalid UTF-8 format
  352. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  353. }
  354. while (extraBytes > 0) {
  355. i += 1; uint32_t nextByte = buffer[i];
  356. character = (character << 6) | (nextByte & 0b00111111);
  357. extraBytes--;
  358. }
  359. feedCharacterFromFile(target, (DsrChar)character);
  360. }
  361. }
  362. }
  363. // Appends the content of buffer as a text file of unknown format into target
  364. static void AppendStringFromFileBuffer(String &target, const uint8_t* buffer, int64_t fileLength) {
  365. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  366. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) {
  367. AppendStringFromFileBuffer_UTF8(target, buffer + 3, fileLength - 3);
  368. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) {
  369. //AppendStringFromFileBuffer_UTF1(target, buffer + 3, fileLength - 3);
  370. throwError(U"UTF-1 format is not yet supported!\n");
  371. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) {
  372. //AppendStringFromFileBuffer_SCSU(target, buffer + 3, fileLength - 3);
  373. throwError(U"SCSU format is not yet supported!\n");
  374. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) {
  375. //AppendStringFromFileBuffer_BOCU-1(target, buffer + 3, fileLength - 3);
  376. throwError(U"BOCU-1 format is not yet supported!\n");
  377. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) {
  378. //AppendStringFromFileBuffer_UTF16BE(target, buffer + 2, fileLength - 2);
  379. throwError(U"UTF-16 BE format is not yet supported!\n");
  380. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) {
  381. //AppendStringFromFileBuffer_UTF16LE(target, buffer + 2, fileLength - 2);
  382. throwError(U"UTF-16 LE format is not yet supported!\n");
  383. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) {
  384. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  385. throwError(U"UTF-32 BE format is not yet supported!\n");
  386. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) {
  387. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  388. throwError(U"UTF-32 LE format is not yet supported!\n");
  389. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) {
  390. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  391. throwError(U"UTF-7 format is not yet supported!\n");
  392. } else {
  393. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  394. AppendStringFromFileBuffer_Latin1(target, buffer, fileLength);
  395. }
  396. }
  397. String dsr::string_loadFromMemory(const Buffer &fileContent) {
  398. String result;
  399. AppendStringFromFileBuffer(result, fileContent.getUnsafeData(), fileContent.size);
  400. return result;
  401. }
  402. // Loads a text file of unknown format
  403. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines.
  404. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  405. // TODO: Load files using Unicode filenames when available
  406. TO_RAW_ASCII(asciiFilename, filename);
  407. std::ifstream fileStream(asciiFilename, std::ios_base::in | std::ios_base::binary);
  408. if (fileStream.is_open()) {
  409. String result;
  410. // Get the file's length and allocate an array for the raw encoding
  411. fileStream.seekg (0, fileStream.end);
  412. int64_t fileLength = fileStream.tellg();
  413. fileStream.seekg (0, fileStream.beg);
  414. uint8_t* buffer = (uint8_t*)malloc(fileLength);
  415. fileStream.read((char*)buffer, fileLength);
  416. AppendStringFromFileBuffer(result, buffer, fileLength);
  417. free(buffer);
  418. return result;
  419. } else {
  420. if (mustExist) {
  421. throwError(U"The text file ", filename, U" could not be opened for reading.\n");
  422. }
  423. // If the file cound not be found and opened, a null string is returned
  424. return String();
  425. }
  426. }
  427. static inline void byteToStream(std::ostream &target, int value) {
  428. uint8_t byte = value;
  429. target.write((char*)&byte, 1);
  430. }
  431. template <CharacterEncoding characterEncoding>
  432. static void encodeCharacterToStream(std::ostream &target, DsrChar character) {
  433. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  434. // Replace any illegal characters with questionmarks
  435. if (character > 255) { character = U'?'; }
  436. byteToStream(target, character);
  437. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  438. if (character < (1 << 7)) {
  439. // 0xxxxxxx
  440. byteToStream(target, character);
  441. } else if (character < (1 << 11)) {
  442. // 110xxxxx 10xxxxxx
  443. byteToStream(target, 0b11000000 | ((character & (0b11111 << 6)) >> 6));
  444. byteToStream(target, 0b10000000 | (character & 0b111111));
  445. } else if (character < (1 << 16)) {
  446. // 1110xxxx 10xxxxxx 10xxxxxx
  447. byteToStream(target, 0b11100000 | ((character & (0b1111 << 12)) >> 12));
  448. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  449. byteToStream(target, 0b10000000 | (character & 0b111111));
  450. } else if (character < (1 << 21)) {
  451. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  452. byteToStream(target, 0b11110000 | ((character & (0b111 << 18)) >> 18));
  453. byteToStream(target, 0b10000000 | ((character & (0b111111 << 12)) >> 12));
  454. byteToStream(target, 0b10000000 | ((character & (0b111111 << 6)) >> 6));
  455. byteToStream(target, 0b10000000 | (character & 0b111111));
  456. }
  457. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  458. throwError(U"Saving text files in UTF-16 BE is not yet implemented.\n");
  459. } else { // Assuming that characterEncoding == CharacterEncoding::BOM_UTF16LE
  460. throwError(U"Saving text files in UTF-16 LE is not yet implemented.\n");
  461. }
  462. }
  463. // Template for writing a whole string to a file
  464. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  465. static void writeCharacterToStream(std::ostream &target, String content) {
  466. // Write byte order marks
  467. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  468. byteToStream(target, 0xEF);
  469. byteToStream(target, 0xBB);
  470. byteToStream(target, 0xBF);
  471. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  472. byteToStream(target, 0xFE);
  473. byteToStream(target, 0xFF);
  474. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  475. byteToStream(target, 0xFF);
  476. byteToStream(target, 0xFE);
  477. }
  478. // Write encoded content
  479. for (int i = 0; i < string_length(content); i++) {
  480. DsrChar character = content[i];
  481. if (character == U'\n') {
  482. if (lineEncoding == LineEncoding::CrLf) {
  483. encodeCharacterToStream<characterEncoding>(target, U'\r');
  484. encodeCharacterToStream<characterEncoding>(target, U'\n');
  485. } else { // Assuming that lineEncoding == LineEncoding::Lf
  486. encodeCharacterToStream<characterEncoding>(target, U'\n');
  487. }
  488. } else {
  489. encodeCharacterToStream<characterEncoding>(target, character);
  490. }
  491. }
  492. }
  493. // Macros for dynamcally selecting templates
  494. #define WRITE_TEXT_STRING(CHAR_ENCODING, LINE_ENCODING) \
  495. writeCharacterToStream<CHAR_ENCODING, LINE_ENCODING>(fileStream, content);
  496. #define WRITE_TEXT_LINE_ENCODINGS(CHAR_ENCODING) \
  497. if (lineEncoding == LineEncoding::CrLf) { \
  498. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::CrLf); \
  499. } else if (lineEncoding == LineEncoding::Lf) { \
  500. WRITE_TEXT_STRING(CHAR_ENCODING, LineEncoding::Lf); \
  501. }
  502. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  503. // TODO: Load files using Unicode filenames
  504. TO_RAW_ASCII(asciiFilename, filename);
  505. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  506. if (fileStream.is_open()) {
  507. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  508. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::Raw_Latin1);
  509. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  510. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF8);
  511. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  512. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16BE);
  513. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  514. WRITE_TEXT_LINE_ENCODINGS(CharacterEncoding::BOM_UTF16LE);
  515. }
  516. fileStream.close();
  517. } else {
  518. throwError("Failed to save ", filename, "\n");
  519. }
  520. }
  521. const char32_t* dsr::file_separator() {
  522. #ifdef _WIN32
  523. return U"\\";
  524. #else
  525. return U"/";
  526. #endif
  527. }
  528. int ReadableString::length() const {
  529. return this->sectionLength;
  530. }
  531. bool ReadableString::checkBound(int start, int length, bool warning) const {
  532. if (start < 0 || start + length > this->length()) {
  533. if (warning) {
  534. String message;
  535. string_append(message, U"\n");
  536. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  537. string_append(message, U"/\n");
  538. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  539. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  540. string_append(message, U"\\_______________________________________________________________________\n");
  541. throwError(message);
  542. }
  543. return false;
  544. } else {
  545. return true;
  546. }
  547. }
  548. DsrChar ReadableString::read(int index) const {
  549. if (index < 0 || index >= this->sectionLength) {
  550. return '\0';
  551. } else {
  552. return this->readSection[index];
  553. }
  554. }
  555. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  556. ReadableString::ReadableString() {}
  557. ReadableString::~ReadableString() {}
  558. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  559. : readSection(content), sectionLength(sectionLength) {}
  560. ReadableString::ReadableString(const DsrChar *content)
  561. : readSection(content), sectionLength(strlen_utf32(content)) {}
  562. String::String() {}
  563. String::String(const char* source) { this->append(source); }
  564. String::String(const char32_t* source) { this->append(source); }
  565. String::String(const std::string& source) { this->append(source); }
  566. String::String(const ReadableString& source) { this->append(source); }
  567. String::String(const String& source) { this->append(source); }
  568. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  569. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  570. int String::capacity() {
  571. if (this->buffer.get() == nullptr) {
  572. return 0;
  573. } else {
  574. // Get the parent allocation
  575. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  576. // Get the offset from the parent
  577. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  578. // Subtract offset from the buffer size to get the remaining space
  579. return (this->buffer->size - offset) / sizeof(DsrChar);
  580. }
  581. }
  582. ReadableString ReadableString::getRange(int start, int length) const {
  583. if (length < 1) {
  584. return ReadableString();
  585. } else if (this->checkBound(start, length)) {
  586. return ReadableString(&(this->readSection[start]), length);
  587. } else {
  588. return ReadableString();
  589. }
  590. }
  591. ReadableString String::getRange(int start, int length) const {
  592. if (length < 1) {
  593. return ReadableString();
  594. } else if (this->checkBound(start, length)) {
  595. return String(this->buffer, &(this->writeSection[start]), length);
  596. } else {
  597. return ReadableString();
  598. }
  599. }
  600. static int32_t getNewBufferSize(int32_t minimumSize) {
  601. if (minimumSize <= 128) {
  602. return 128;
  603. } else if (minimumSize <= 512) {
  604. return 512;
  605. } else if (minimumSize <= 2048) {
  606. return 2048;
  607. } else if (minimumSize <= 8192) {
  608. return 8192;
  609. } else if (minimumSize <= 32768) {
  610. return 32768;
  611. } else if (minimumSize <= 131072) {
  612. return 131072;
  613. } else if (minimumSize <= 524288) {
  614. return 524288;
  615. } else if (minimumSize <= 2097152) {
  616. return 2097152;
  617. } else if (minimumSize <= 8388608) {
  618. return 8388608;
  619. } else if (minimumSize <= 33554432) {
  620. return 33554432;
  621. } else if (minimumSize <= 134217728) {
  622. return 134217728;
  623. } else if (minimumSize <= 536870912) {
  624. return 536870912;
  625. } else {
  626. return 2147483647;
  627. }
  628. }
  629. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  630. // Holding oldData alive while copying to the new buffer
  631. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  632. const char32_t* oldData = this->readSection;
  633. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  634. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  635. if (preserve && oldData) {
  636. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  637. }
  638. }
  639. // Call before writing to the buffer
  640. // This hides that Strings share buffers when assigning by value or taking partial strings
  641. void String::cloneIfShared() {
  642. if (this->buffer.use_count() > 1) {
  643. this->reallocateBuffer(this->sectionLength, true);
  644. }
  645. }
  646. void String::expand(int32_t newLength, bool affectUsedLength) {
  647. if (newLength > this->sectionLength) {
  648. if (newLength > this->capacity()) {
  649. this->reallocateBuffer(newLength, true);
  650. }
  651. }
  652. if (affectUsedLength) {
  653. this->sectionLength = newLength;
  654. }
  655. }
  656. void String::reserve(int32_t minimumLength) {
  657. this->expand(minimumLength, false);
  658. }
  659. void String::write(int index, DsrChar value) {
  660. this->cloneIfShared();
  661. if (index < 0 || index >= this->sectionLength) {
  662. // TODO: Give a warning
  663. } else {
  664. this->writeSection[index] = value;
  665. }
  666. }
  667. void String::clear() {
  668. this->sectionLength = 0;
  669. }
  670. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  671. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  672. // Proof that appending to one string doesn't affect another:
  673. // If it has to reallocate
  674. // * Then it will have its own buffer without conflicts
  675. // If it doesn't have to reallocate
  676. // If it shares the buffer
  677. // If source is empty
  678. // * Then no risk of overwriting neighbor strings if we don't write
  679. // If source isn't empty
  680. // * Then the buffer will be cloned when the first character is written
  681. // If it doesn't share the buffer
  682. // * Then no risk of writing
  683. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  684. int64_t oldLength = (TARGET)->length(); \
  685. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  686. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  687. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  688. } \
  689. }
  690. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  691. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  692. // TODO: Use memcpy when appending input of the same format
  693. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  694. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  695. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  696. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  697. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  698. return source.toStreamIndented(target, indentation);
  699. }
  700. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  701. target.append(indentation);
  702. target.append(value);
  703. return target;
  704. }
  705. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  706. target.append(indentation);
  707. target.append(value);
  708. return target;
  709. }
  710. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  711. target.append(indentation);
  712. target.append(value);
  713. return target;
  714. }
  715. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  716. target.append(indentation);
  717. target.append(value);
  718. return target;
  719. }
  720. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  721. target.append(indentation);
  722. doubleToString_arabic(target, (double)value);
  723. return target;
  724. }
  725. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  726. target.append(indentation);
  727. doubleToString_arabic(target, value);
  728. return target;
  729. }
  730. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  731. target.append(indentation);
  732. intToString_arabic(target, value);
  733. return target;
  734. }
  735. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  736. target.append(indentation);
  737. uintToString_arabic(target, value);
  738. return target;
  739. }
  740. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  741. target.append(indentation);
  742. intToString_arabic(target, (int64_t)value);
  743. return target;
  744. }
  745. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  746. target.append(indentation);
  747. uintToString_arabic(target, (uint64_t)value);
  748. return target;
  749. }
  750. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  751. target.append(indentation);
  752. intToString_arabic(target, (int64_t)value);
  753. return target;
  754. }
  755. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  756. target.append(indentation);
  757. uintToString_arabic(target, (uint64_t)value);
  758. return target;
  759. }
  760. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  761. target.append(indentation);
  762. intToString_arabic(target, (int64_t)value);
  763. return target;
  764. }
  765. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  766. target.append(indentation);
  767. uintToString_arabic(target, (uint64_t)value);
  768. return target;
  769. }
  770. void dsr::throwErrorMessage(const String& message) {
  771. throw std::runtime_error(message.toStdString());
  772. }
  773. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  774. if (!appendResult) {
  775. target.clear();
  776. }
  777. int sectionStart = 0;
  778. for (int i = 0; i < source.length(); i++) {
  779. DsrChar c = source[i];
  780. if (c == separator) {
  781. target.push(string_exclusiveRange(source, sectionStart, i));
  782. sectionStart = i + 1;
  783. }
  784. }
  785. if (source.length() > sectionStart) {
  786. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  787. }
  788. }
  789. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  790. List<ReadableString> result;
  791. string_split_inPlace(result, source, separator);
  792. return result;
  793. }
  794. int64_t dsr::string_toInteger(const ReadableString& source) {
  795. int64_t result;
  796. bool negated;
  797. result = 0;
  798. negated = false;
  799. for (int i = 0; i < source.length(); i++) {
  800. DsrChar c = source[i];
  801. if (c == '-' || c == '~') {
  802. negated = !negated;
  803. } else if (c >= '0' && c <= '9') {
  804. result = (result * 10) + (int)(c - '0');
  805. } else if (c == ',' || c == '.') {
  806. // Truncate any decimals by ignoring them
  807. break;
  808. }
  809. }
  810. if (negated) {
  811. return -result;
  812. } else {
  813. return result;
  814. }
  815. }
  816. double dsr::string_toDouble(const ReadableString& source) {
  817. double result;
  818. bool negated;
  819. bool reachedDecimal;
  820. int digitDivider;
  821. result = 0.0;
  822. negated = false;
  823. reachedDecimal = false;
  824. digitDivider = 1;
  825. for (int i = 0; i < source.length(); i++) {
  826. DsrChar c = source[i];
  827. if (c == '-' || c == '~') {
  828. negated = !negated;
  829. } else if (c >= '0' && c <= '9') {
  830. if (reachedDecimal) {
  831. digitDivider = digitDivider * 10;
  832. result = result + ((double)(c - '0') / (double)digitDivider);
  833. } else {
  834. result = (result * 10) + (double)(c - '0');
  835. }
  836. } else if (c == ',' || c == '.') {
  837. reachedDecimal = true;
  838. }
  839. }
  840. if (negated) {
  841. return -result;
  842. } else {
  843. return result;
  844. }
  845. }
  846. int dsr::string_length(const ReadableString& source) {
  847. return source.length();
  848. }
  849. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  850. for (int i = startIndex; i < source.length(); i++) {
  851. if (source[i] == toFind) {
  852. return i;
  853. }
  854. }
  855. return -1;
  856. }
  857. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  858. for (int i = source.length() - 1; i >= 0; i--) {
  859. if (source[i] == toFind) {
  860. return i;
  861. }
  862. }
  863. return -1;
  864. }
  865. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  866. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  867. }
  868. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  869. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  870. }
  871. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  872. return string_exclusiveRange(source, 0, exclusiveEnd);
  873. }
  874. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  875. return string_inclusiveRange(source, 0, inclusiveEnd);
  876. }
  877. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  878. return string_exclusiveRange(source, inclusiveStart, source.length());
  879. }
  880. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  881. return string_from(source, exclusiveStart + 1);
  882. }
  883. bool dsr::character_isDigit(DsrChar c) {
  884. return c >= U'0' && c <= U'9';
  885. }
  886. bool dsr::character_isIntegerCharacter(DsrChar c) {
  887. return c == U'-' || character_isDigit(c);
  888. }
  889. bool dsr::character_isValueCharacter(DsrChar c) {
  890. return c == U'.' || character_isIntegerCharacter(c);
  891. }
  892. bool dsr::character_isWhiteSpace(DsrChar c) {
  893. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  894. }
  895. // Macros for implementing regular expressions with a greedy approach consuming the first match
  896. // Optional accepts 0 or 1 occurence
  897. // Forced accepts 1 occurence
  898. // Star accepts 0..N occurence
  899. // Plus accepts 1..N occurence
  900. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  901. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  902. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  903. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  904. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  905. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  906. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  907. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  908. // The greedy approach works here, because there's no ambiguity
  909. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  910. int readIndex = 0;
  911. if (allowWhiteSpace) {
  912. PATTERN_STAR(WhiteSpace);
  913. }
  914. CHARACTER_OPTIONAL(U'-');
  915. // At least one digit required
  916. PATTERN_PLUS(IntegerCharacter);
  917. if (allowWhiteSpace) {
  918. PATTERN_STAR(WhiteSpace);
  919. }
  920. return true;
  921. }
  922. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  923. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  924. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  925. if (string_findFirst(source, U'.') == -1) {
  926. // No decimal detected
  927. return string_isInteger(source, allowWhiteSpace);
  928. } else {
  929. int readIndex = 0;
  930. if (allowWhiteSpace) {
  931. PATTERN_STAR(WhiteSpace);
  932. }
  933. // Double <- UnsignedDouble | '-' UnsignedDouble
  934. CHARACTER_OPTIONAL(U'-');
  935. // UnsignedDouble <- Digit* '.' Digit+
  936. // Any number of integer digits
  937. PATTERN_STAR(IntegerCharacter);
  938. // Only dot for decimal
  939. CHARACTER_FORCED(U'.')
  940. // At least one decimal digit
  941. PATTERN_PLUS(IntegerCharacter);
  942. if (allowWhiteSpace) {
  943. PATTERN_STAR(WhiteSpace);
  944. }
  945. return true;
  946. }
  947. }