2
0

text.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. /*
  311. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  312. // TODO: Load files using Unicode filenames
  313. TO_RAW_ASCII(asciiFilename, filename);
  314. std::ifstream inputFile(asciiFilename);
  315. if (inputFile.is_open()) {
  316. std::stringstream outputBuffer;
  317. // TODO: Feed directly to String
  318. outputBuffer << inputFile.rdbuf();
  319. std::string content = outputBuffer.str();
  320. String result;
  321. result.reserve(content.size());
  322. for (int i = 0; i < (int)(content.size()); i++) {
  323. result.appendChar(content[i]);
  324. }
  325. inputFile.close();
  326. return result;
  327. } else {
  328. if (mustExist) {
  329. throwError("Failed to load ", filename, "\n");
  330. }
  331. // If the file cound not be found and opened, a null string is returned
  332. return String();
  333. }
  334. }
  335. */
  336. // TODO: Give as a lambda with target captured, so that pre-allocation can measure the
  337. // needed space exactly using a lambda that increases a character counter instead.
  338. // Interpreting a character's value and appends it to the string.
  339. static void feedCharacterFromFile(String &target, DsrChar character) {
  340. if (character != U'\r') {
  341. target.appendChar(character);
  342. }
  343. }
  344. // Appends the content of buffer as a BOM-free Latin-1 file into target
  345. static void AppendStringFromFileBuffer_Latin1(String &target, const uint8_t* buffer, int64_t fileLength) {
  346. for (int64_t i = 0; i < fileLength; i++) {
  347. feedCharacterFromFile(target, (DsrChar)(buffer[i]));
  348. }
  349. }
  350. // Appends the content of buffer as a BOM-free UTF-8 file into target
  351. static void AppendStringFromFileBuffer_UTF8(String &target, const uint8_t* buffer, int64_t fileLength) {
  352. // We know that the result will be at least one character per given byte for UTF-8
  353. target.reserve(string_length(target) + fileLength);
  354. for (int64_t i = 0; i < fileLength; i++) {
  355. uint8_t byteA = buffer[i];
  356. if (byteA < 0b10000000) {
  357. // Single byte (1xxxxxxx)
  358. feedCharacterFromFile(target, (DsrChar)byteA);
  359. } else {
  360. uint32_t character = 0;
  361. int extraBytes = 0;
  362. if (byteA >= 0b11000000) { // At least two leading ones
  363. if (byteA < 0b11100000) { // Less than three leading ones
  364. character = byteA & 0b00011111;
  365. extraBytes = 1;
  366. } else if (byteA < 0b11110000) { // Less than four leading ones
  367. character = byteA & 0b00011111;
  368. extraBytes = 2;
  369. } else if (byteA < 0b11111000) { // Less than five leading ones
  370. character = byteA & 0b00011111;
  371. extraBytes = 3;
  372. } else {
  373. // Invalid UTF-8 format
  374. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  375. }
  376. } else {
  377. // Invalid UTF-8 format
  378. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  379. }
  380. while (extraBytes > 0) {
  381. i += 1; uint32_t nextByte = buffer[i];
  382. character = (character << 6) | (nextByte & 0b00111111);
  383. extraBytes--;
  384. }
  385. feedCharacterFromFile(target, (DsrChar)character);
  386. }
  387. }
  388. }
  389. // Appends the content of buffer as a text file of unknown format into target
  390. static void AppendStringFromFileBuffer(String &target, const uint8_t* buffer, int64_t fileLength) {
  391. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  392. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) {
  393. AppendStringFromFileBuffer_UTF8(target, buffer + 3, fileLength - 3);
  394. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) {
  395. //AppendStringFromFileBuffer_UTF1(target, buffer + 3, fileLength - 3);
  396. throwError(U"UTF-1 format is not yet supported!");
  397. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) {
  398. //AppendStringFromFileBuffer_SCSU(target, buffer + 3, fileLength - 3);
  399. throwError(U"SCSU format is not yet supported!");
  400. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) {
  401. //AppendStringFromFileBuffer_BOCU-1(target, buffer + 3, fileLength - 3);
  402. throwError(U"BOCU-1 format is not yet supported!");
  403. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) {
  404. //AppendStringFromFileBuffer_UTF16BE(target, buffer + 2, fileLength - 2);
  405. throwError(U"UTF-16 BE format is not yet supported!");
  406. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) {
  407. //AppendStringFromFileBuffer_UTF16LE(target, buffer + 2, fileLength - 2);
  408. throwError(U"UTF-16 LE format is not yet supported!");
  409. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) {
  410. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  411. throwError(U"UTF-32 BE format is not yet supported!");
  412. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) {
  413. //AppendStringFromFileBuffer_UTF32BE(target, buffer + 4, fileLength - 4);
  414. throwError(U"UTF-32 LE format is not yet supported!");
  415. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) {
  416. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  417. throwError(U"UTF-7 format is not yet supported!");
  418. } else {
  419. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  420. AppendStringFromFileBuffer_Latin1(target, buffer, fileLength);
  421. }
  422. }
  423. String dsr::string_loadFromMemory(const Buffer &fileContent) {
  424. String result;
  425. AppendStringFromFileBuffer(result, fileContent.getUnsafeData(), fileContent.size);
  426. return result;
  427. }
  428. // Loads a text file of unknown format
  429. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines.
  430. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  431. // TODO: Load files using Unicode filenames when available
  432. TO_RAW_ASCII(asciiFilename, filename);
  433. std::ifstream fileStream(asciiFilename, std::ios_base::in | std::ios_base::binary);
  434. if (fileStream.is_open()) {
  435. String result;
  436. // Get the file's length and allocate an array for the raw encoding
  437. fileStream.seekg (0, fileStream.end);
  438. int64_t fileLength = fileStream.tellg();
  439. fileStream.seekg (0, fileStream.beg);
  440. uint8_t* buffer = (uint8_t*)malloc(fileLength);
  441. fileStream.read((char*)buffer, fileLength);
  442. AppendStringFromFileBuffer(result, buffer, fileLength);
  443. free(buffer);
  444. return result;
  445. } else {
  446. if (mustExist) {
  447. throwError(U"The text file ", filename, U" could not be opened for reading.\n");
  448. }
  449. // If the file cound not be found and opened, a null string is returned
  450. return String();
  451. }
  452. }
  453. void dsr::string_save(const ReadableString& filename, const ReadableString& content) {
  454. // TODO: Load files using Unicode filenames
  455. TO_RAW_ASCII(asciiFilename, filename);
  456. TO_RAW_ASCII(asciiContent, content);
  457. std::ofstream outputFile;
  458. outputFile.open(asciiFilename);
  459. if (outputFile.is_open()) {
  460. outputFile << asciiContent;
  461. outputFile.close();
  462. } else {
  463. throwError("Failed to save ", filename, "\n");
  464. }
  465. }
  466. /*
  467. // TODO: Choose how to encode characters and line endings using enums
  468. class enum textEncoding {
  469. UTF1, UTF7, UTF8, UTF16BE, UTF16LE, UTF32BE, UTF32LE, UTF-EBCDIC, SCSU, BOCU1, GB18030
  470. };
  471. * class enum lineEncoding {
  472. UTF1, UTF7, UTF8, UTF16BE, UTF16LE, UTF32BE, UTF32LE, UTF-EBCDIC, SCSU, BOCU1, GB18030
  473. };
  474. void dsr::string_save(const ReadableString& filename, const ReadableString& content) {
  475. // TODO: Load files using Unicode filenames
  476. TO_RAW_ASCII(asciiFilename, filename);
  477. TO_RAW_ASCII(asciiContent, content);
  478. std::ofstream fileStream(asciiFilename, std::ios_base::out | std::ios_base::binary);
  479. if (fileStream.is_open()) {
  480. fileStream << asciiContent;
  481. fileStream.close();
  482. } else {
  483. throwError("Failed to save ", filename, "\n");
  484. }
  485. }
  486. */
  487. const char32_t* dsr::file_separator() {
  488. #ifdef _WIN32
  489. return U"\\";
  490. #else
  491. return U"/";
  492. #endif
  493. }
  494. int ReadableString::length() const {
  495. return this->sectionLength;
  496. }
  497. bool ReadableString::checkBound(int start, int length, bool warning) const {
  498. if (start < 0 || start + length > this->length()) {
  499. if (warning) {
  500. String message;
  501. string_append(message, U"\n");
  502. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  503. string_append(message, U"/\n");
  504. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  505. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  506. string_append(message, U"\\_______________________________________________________________________\n");
  507. throwError(message);
  508. }
  509. return false;
  510. } else {
  511. return true;
  512. }
  513. }
  514. DsrChar ReadableString::read(int index) const {
  515. if (index < 0 || index >= this->sectionLength) {
  516. return '\0';
  517. } else {
  518. return this->readSection[index];
  519. }
  520. }
  521. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  522. ReadableString::ReadableString() {}
  523. ReadableString::~ReadableString() {}
  524. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  525. : readSection(content), sectionLength(sectionLength) {}
  526. ReadableString::ReadableString(const DsrChar *content)
  527. : readSection(content), sectionLength(strlen_utf32(content)) {}
  528. String::String() {}
  529. String::String(const char* source) { this->append(source); }
  530. String::String(const char32_t* source) { this->append(source); }
  531. String::String(const std::string& source) { this->append(source); }
  532. String::String(const ReadableString& source) { this->append(source); }
  533. String::String(const String& source) { this->append(source); }
  534. String::String(std::shared_ptr<Buffer> buffer, DsrChar *content, int sectionLength)
  535. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  536. int String::capacity() {
  537. if (this->buffer.get() == nullptr) {
  538. return 0;
  539. } else {
  540. // Get the parent allocation
  541. uint8_t* parentBuffer = this->buffer->getUnsafeData();
  542. // Get the offset from the parent
  543. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  544. // Subtract offset from the buffer size to get the remaining space
  545. return (this->buffer->size - offset) / sizeof(DsrChar);
  546. }
  547. }
  548. ReadableString ReadableString::getRange(int start, int length) const {
  549. if (length < 1) {
  550. return ReadableString();
  551. } else if (this->checkBound(start, length)) {
  552. return ReadableString(&(this->readSection[start]), length);
  553. } else {
  554. return ReadableString();
  555. }
  556. }
  557. ReadableString String::getRange(int start, int length) const {
  558. if (length < 1) {
  559. return ReadableString();
  560. } else if (this->checkBound(start, length)) {
  561. return String(this->buffer, &(this->writeSection[start]), length);
  562. } else {
  563. return ReadableString();
  564. }
  565. }
  566. static int32_t getNewBufferSize(int32_t minimumSize) {
  567. if (minimumSize <= 128) {
  568. return 128;
  569. } else if (minimumSize <= 512) {
  570. return 512;
  571. } else if (minimumSize <= 2048) {
  572. return 2048;
  573. } else if (minimumSize <= 8192) {
  574. return 8192;
  575. } else if (minimumSize <= 32768) {
  576. return 32768;
  577. } else if (minimumSize <= 131072) {
  578. return 131072;
  579. } else if (minimumSize <= 524288) {
  580. return 524288;
  581. } else if (minimumSize <= 2097152) {
  582. return 2097152;
  583. } else if (minimumSize <= 8388608) {
  584. return 8388608;
  585. } else if (minimumSize <= 33554432) {
  586. return 33554432;
  587. } else if (minimumSize <= 134217728) {
  588. return 134217728;
  589. } else if (minimumSize <= 536870912) {
  590. return 536870912;
  591. } else {
  592. return 2147483647;
  593. }
  594. }
  595. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  596. // Holding oldData alive while copying to the new buffer
  597. std::shared_ptr<Buffer> oldBuffer = this->buffer;
  598. const char32_t* oldData = this->readSection;
  599. this->buffer = std::make_shared<Buffer>(getNewBufferSize(newLength * sizeof(DsrChar)));
  600. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(this->buffer->getUnsafeData());
  601. if (preserve && oldData) {
  602. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  603. }
  604. }
  605. // Call before writing to the buffer
  606. // This hides that Strings share buffers when assigning by value or taking partial strings
  607. void String::cloneIfShared() {
  608. if (this->buffer.use_count() > 1) {
  609. this->reallocateBuffer(this->sectionLength, true);
  610. }
  611. }
  612. void String::expand(int32_t newLength, bool affectUsedLength) {
  613. if (newLength > this->sectionLength) {
  614. if (newLength > this->capacity()) {
  615. this->reallocateBuffer(newLength, true);
  616. }
  617. }
  618. if (affectUsedLength) {
  619. this->sectionLength = newLength;
  620. }
  621. }
  622. void String::reserve(int32_t minimumLength) {
  623. this->expand(minimumLength, false);
  624. }
  625. void String::write(int index, DsrChar value) {
  626. this->cloneIfShared();
  627. if (index < 0 || index >= this->sectionLength) {
  628. // TODO: Give a warning
  629. } else {
  630. this->writeSection[index] = value;
  631. }
  632. }
  633. void String::clear() {
  634. this->sectionLength = 0;
  635. }
  636. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  637. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  638. // Proof that appending to one string doesn't affect another:
  639. // If it has to reallocate
  640. // * Then it will have its own buffer without conflicts
  641. // If it doesn't have to reallocate
  642. // If it shares the buffer
  643. // If source is empty
  644. // * Then no risk of overwriting neighbor strings if we don't write
  645. // If source isn't empty
  646. // * Then the buffer will be cloned when the first character is written
  647. // If it doesn't share the buffer
  648. // * Then no risk of writing
  649. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  650. int64_t oldLength = (TARGET)->length(); \
  651. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  652. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  653. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  654. } \
  655. }
  656. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  657. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  658. // TODO: Use memcpy when appending input of the same format
  659. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  660. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  661. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  662. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  663. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  664. return source.toStreamIndented(target, indentation);
  665. }
  666. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  667. target.append(indentation);
  668. target.append(value);
  669. return target;
  670. }
  671. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  672. target.append(indentation);
  673. target.append(value);
  674. return target;
  675. }
  676. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  677. target.append(indentation);
  678. target.append(value);
  679. return target;
  680. }
  681. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  682. target.append(indentation);
  683. target.append(value);
  684. return target;
  685. }
  686. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  687. target.append(indentation);
  688. doubleToString_arabic(target, (double)value);
  689. return target;
  690. }
  691. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  692. target.append(indentation);
  693. doubleToString_arabic(target, value);
  694. return target;
  695. }
  696. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  697. target.append(indentation);
  698. intToString_arabic(target, value);
  699. return target;
  700. }
  701. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  702. target.append(indentation);
  703. uintToString_arabic(target, value);
  704. return target;
  705. }
  706. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  707. target.append(indentation);
  708. intToString_arabic(target, (int64_t)value);
  709. return target;
  710. }
  711. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  712. target.append(indentation);
  713. uintToString_arabic(target, (uint64_t)value);
  714. return target;
  715. }
  716. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  717. target.append(indentation);
  718. intToString_arabic(target, (int64_t)value);
  719. return target;
  720. }
  721. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  722. target.append(indentation);
  723. uintToString_arabic(target, (uint64_t)value);
  724. return target;
  725. }
  726. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  727. target.append(indentation);
  728. intToString_arabic(target, (int64_t)value);
  729. return target;
  730. }
  731. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  732. target.append(indentation);
  733. uintToString_arabic(target, (uint64_t)value);
  734. return target;
  735. }
  736. void dsr::throwErrorMessage(const String& message) {
  737. throw std::runtime_error(message.toStdString());
  738. }
  739. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  740. if (!appendResult) {
  741. target.clear();
  742. }
  743. int sectionStart = 0;
  744. for (int i = 0; i < source.length(); i++) {
  745. DsrChar c = source[i];
  746. if (c == separator) {
  747. target.push(string_exclusiveRange(source, sectionStart, i));
  748. sectionStart = i + 1;
  749. }
  750. }
  751. if (source.length() > sectionStart) {
  752. target.push(string_exclusiveRange(source, sectionStart, source.length()));;
  753. }
  754. }
  755. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  756. List<ReadableString> result;
  757. string_split_inPlace(result, source, separator);
  758. return result;
  759. }
  760. int64_t dsr::string_toInteger(const ReadableString& source) {
  761. int64_t result;
  762. bool negated;
  763. result = 0;
  764. negated = false;
  765. for (int i = 0; i < source.length(); i++) {
  766. DsrChar c = source[i];
  767. if (c == '-' || c == '~') {
  768. negated = !negated;
  769. } else if (c >= '0' && c <= '9') {
  770. result = (result * 10) + (int)(c - '0');
  771. } else if (c == ',' || c == '.') {
  772. // Truncate any decimals by ignoring them
  773. break;
  774. }
  775. }
  776. if (negated) {
  777. return -result;
  778. } else {
  779. return result;
  780. }
  781. }
  782. double dsr::string_toDouble(const ReadableString& source) {
  783. double result;
  784. bool negated;
  785. bool reachedDecimal;
  786. int digitDivider;
  787. result = 0.0;
  788. negated = false;
  789. reachedDecimal = false;
  790. digitDivider = 1;
  791. for (int i = 0; i < source.length(); i++) {
  792. DsrChar c = source[i];
  793. if (c == '-' || c == '~') {
  794. negated = !negated;
  795. } else if (c >= '0' && c <= '9') {
  796. if (reachedDecimal) {
  797. digitDivider = digitDivider * 10;
  798. result = result + ((double)(c - '0') / (double)digitDivider);
  799. } else {
  800. result = (result * 10) + (double)(c - '0');
  801. }
  802. } else if (c == ',' || c == '.') {
  803. reachedDecimal = true;
  804. }
  805. }
  806. if (negated) {
  807. return -result;
  808. } else {
  809. return result;
  810. }
  811. }
  812. int dsr::string_length(const ReadableString& source) {
  813. return source.length();
  814. }
  815. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  816. for (int i = startIndex; i < source.length(); i++) {
  817. if (source[i] == toFind) {
  818. return i;
  819. }
  820. }
  821. return -1;
  822. }
  823. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  824. for (int i = source.length() - 1; i >= 0; i--) {
  825. if (source[i] == toFind) {
  826. return i;
  827. }
  828. }
  829. return -1;
  830. }
  831. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  832. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  833. }
  834. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  835. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  836. }
  837. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  838. return string_exclusiveRange(source, 0, exclusiveEnd);
  839. }
  840. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  841. return string_inclusiveRange(source, 0, inclusiveEnd);
  842. }
  843. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  844. return string_exclusiveRange(source, inclusiveStart, source.length());
  845. }
  846. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  847. return string_from(source, exclusiveStart + 1);
  848. }
  849. bool dsr::character_isDigit(DsrChar c) {
  850. return c >= U'0' && c <= U'9';
  851. }
  852. bool dsr::character_isIntegerCharacter(DsrChar c) {
  853. return c == U'-' || character_isDigit(c);
  854. }
  855. bool dsr::character_isValueCharacter(DsrChar c) {
  856. return c == U'.' || character_isIntegerCharacter(c);
  857. }
  858. bool dsr::character_isWhiteSpace(DsrChar c) {
  859. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  860. }
  861. // Macros for implementing regular expressions with a greedy approach consuming the first match
  862. // Optional accepts 0 or 1 occurence
  863. // Forced accepts 1 occurence
  864. // Star accepts 0..N occurence
  865. // Plus accepts 1..N occurence
  866. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  867. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  868. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  869. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  870. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  871. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  872. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  873. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  874. // The greedy approach works here, because there's no ambiguity
  875. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  876. int readIndex = 0;
  877. if (allowWhiteSpace) {
  878. PATTERN_STAR(WhiteSpace);
  879. }
  880. CHARACTER_OPTIONAL(U'-');
  881. // At least one digit required
  882. PATTERN_PLUS(IntegerCharacter);
  883. if (allowWhiteSpace) {
  884. PATTERN_STAR(WhiteSpace);
  885. }
  886. return true;
  887. }
  888. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  889. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  890. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  891. if (string_findFirst(source, U'.') == -1) {
  892. // No decimal detected
  893. return string_isInteger(source, allowWhiteSpace);
  894. } else {
  895. int readIndex = 0;
  896. if (allowWhiteSpace) {
  897. PATTERN_STAR(WhiteSpace);
  898. }
  899. // Double <- UnsignedDouble | '-' UnsignedDouble
  900. CHARACTER_OPTIONAL(U'-');
  901. // UnsignedDouble <- Digit* '.' Digit+
  902. // Any number of integer digits
  903. PATTERN_STAR(IntegerCharacter);
  904. // Only dot for decimal
  905. CHARACTER_FORCED(U'.')
  906. // At least one decimal digit
  907. PATTERN_PLUS(IntegerCharacter);
  908. if (allowWhiteSpace) {
  909. PATTERN_STAR(WhiteSpace);
  910. }
  911. return true;
  912. }
  913. }