text.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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. // Gets access to private members by making them public for the whole module
  24. #define DFPSR_INTERNAL_ACCESS
  25. #include <fstream>
  26. #include <streambuf>
  27. #include <cstring>
  28. #include <stdexcept>
  29. #include "text.h"
  30. #include "../api/fileAPI.h"
  31. using namespace dsr;
  32. static int64_t strlen_utf32(const char32_t *content) {
  33. int64_t length = 0;
  34. while (content[length] != 0) {
  35. length++;
  36. }
  37. return length;
  38. }
  39. static char toAscii(DsrChar c) {
  40. if (c > 127) {
  41. return '?';
  42. } else {
  43. return c;
  44. }
  45. }
  46. ReadableString::ReadableString() {}
  47. ReadableString::~ReadableString() {}
  48. ReadableString::ReadableString(const DsrChar *content)
  49. : readSection(content), length(strlen_utf32(content)) {}
  50. ReadableString::ReadableString(const String& source) {
  51. this->readSection = source.readSection;
  52. this->length = source.length;
  53. this->buffer = source.buffer;
  54. }
  55. // Not the fastest constructor, but won't bloat the public header
  56. // Hopefully most compilers know how to optimize this
  57. static ReadableString createSubString(const DsrChar *content, int64_t length, const Buffer &buffer) {
  58. ReadableString result;
  59. result.readSection = content;
  60. result.length = length;
  61. result.buffer = buffer;
  62. return result;
  63. }
  64. String::String() {}
  65. String::String(const char* source) { this->append(source); }
  66. String::String(const char32_t* source) { this->append(source); }
  67. String::String(const std::string& source) { this->append(source); }
  68. String::String(const String& source) {
  69. // Share immutable buffer
  70. this->readSection = source.readSection;
  71. this->length = source.length;
  72. this->buffer = source.buffer;
  73. this->writeSection = source.writeSection;
  74. }
  75. String::String(const ReadableString& source) {
  76. if (buffer_exists(source.buffer)) {
  77. this->readSection = source.readSection;
  78. this->length = source.length;
  79. this->buffer = source.buffer;
  80. this->writeSection = const_cast<char32_t*>(source.readSection); // Still safe because of immutability
  81. } else {
  82. // No buffer to share, just appending the content
  83. this->append(source);
  84. }
  85. }
  86. String::String(Buffer buffer, DsrChar *content, int64_t length)
  87. : ReadableString(createSubString(content, length, buffer)), writeSection(content) {}
  88. DsrChar ReadableString::operator[] (int64_t index) const {
  89. if (index < 0 || index >= this->length) {
  90. return U'\0';
  91. } else {
  92. return this->readSection[index];
  93. }
  94. }
  95. String& Printable::toStream(String& target) const {
  96. return this->toStreamIndented(target, U"");
  97. }
  98. String Printable::toStringIndented(const ReadableString& indentation) const {
  99. String result;
  100. this->toStreamIndented(result, indentation);
  101. return result;
  102. }
  103. String Printable::toString() const {
  104. return this->toStringIndented(U"");
  105. }
  106. std::ostream& Printable::toStreamIndented(std::ostream& out, const ReadableString& indentation) const {
  107. String result;
  108. this->toStreamIndented(result, indentation);
  109. for (int64_t i = 0; i < result.length; i++) {
  110. out.put(toAscii(result.readSection[i]));
  111. }
  112. return out;
  113. }
  114. std::ostream& Printable::toStream(std::ostream& out) const {
  115. return this->toStreamIndented(out, U"");
  116. }
  117. std::string Printable::toStdString() const {
  118. std::ostringstream result;
  119. this->toStream(result);
  120. return result.str();
  121. }
  122. Printable::~Printable() {}
  123. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  124. if (a.length != b.length) {
  125. return false;
  126. } else {
  127. for (int64_t i = 0; i < a.length; i++) {
  128. if (a.readSection[i] != b.readSection[i]) {
  129. return false;
  130. }
  131. }
  132. return true;
  133. }
  134. }
  135. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  136. if (a.length != b.length) {
  137. return false;
  138. } else {
  139. for (int64_t i = 0; i < a.length; i++) {
  140. if (towupper(a.readSection[i]) != towupper(b.readSection[i])) {
  141. return false;
  142. }
  143. }
  144. return true;
  145. }
  146. }
  147. std::ostream& ReadableString::toStream(std::ostream& out) const {
  148. for (int64_t i = 0; i < this->length; i++) {
  149. out.put(toAscii(this->readSection[i]));
  150. }
  151. return out;
  152. }
  153. std::string ReadableString::toStdString() const {
  154. std::ostringstream result;
  155. this->toStream(result);
  156. return result.str();
  157. }
  158. String dsr::string_upperCase(const ReadableString &text) {
  159. String result;
  160. result.reserve(text.length);
  161. for (int64_t i = 0; i < text.length; i++) {
  162. result.appendChar(towupper(text[i]));
  163. }
  164. return result;
  165. }
  166. String dsr::string_lowerCase(const ReadableString &text) {
  167. String result;
  168. result.reserve(text.length);
  169. for (int64_t i = 0; i < text.length; i++) {
  170. result.appendChar(towlower(text[i]));
  171. }
  172. return result;
  173. }
  174. static int64_t findFirstNonWhite(const ReadableString &text) {
  175. for (int64_t i = 0; i < text.length; i++) {
  176. DsrChar c = text[i];
  177. if (!character_isWhiteSpace(c)) {
  178. return i;
  179. }
  180. }
  181. return -1;
  182. }
  183. static int64_t findLastNonWhite(const ReadableString &text) {
  184. for (int64_t i = text.length - 1; i >= 0; i--) {
  185. DsrChar c = text[i];
  186. if (!character_isWhiteSpace(c)) {
  187. return i;
  188. }
  189. }
  190. return -1;
  191. }
  192. // Allow passing literals without allocating heap memory for the result
  193. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  194. int64_t first = findFirstNonWhite(text);
  195. int64_t last = findLastNonWhite(text);
  196. if (first == -1) {
  197. // Only white space
  198. return ReadableString();
  199. } else {
  200. // Subset
  201. return string_inclusiveRange(text, first, last);
  202. }
  203. }
  204. String dsr::string_mangleQuote(const ReadableString &rawText) {
  205. String result;
  206. result.reserve(rawText.length + 2);
  207. result.appendChar(U'\"'); // Begin quote
  208. for (int64_t i = 0; i < rawText.length; i++) {
  209. DsrChar c = rawText[i];
  210. if (c == U'\"') { // Double quote
  211. result.append(U"\\\"");
  212. } else if (c == U'\\') { // Backslash
  213. result.append(U"\\\\");
  214. } else if (c == U'\a') { // Audible bell
  215. result.append(U"\\a");
  216. } else if (c == U'\b') { // Backspace
  217. result.append(U"\\b");
  218. } else if (c == U'\f') { // Form feed
  219. result.append(U"\\f");
  220. } else if (c == U'\n') { // Line feed
  221. result.append(U"\\n");
  222. } else if (c == U'\r') { // Carriage return
  223. result.append(U"\\r");
  224. } else if (c == U'\t') { // Horizontal tab
  225. result.append(U"\\t");
  226. } else if (c == U'\v') { // Vertical tab
  227. result.append(U"\\v");
  228. } else if (c == U'\0') { // Null terminator
  229. result.append(U"\\0");
  230. } else {
  231. result.appendChar(c);
  232. }
  233. }
  234. result.appendChar(U'\"'); // End quote
  235. return result;
  236. }
  237. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  238. int64_t firstQuote = string_findFirst(mangledText, '\"');
  239. int64_t lastQuote = string_findLast(mangledText, '\"');
  240. String result;
  241. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  242. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, "\n");
  243. } else {
  244. for (int64_t i = firstQuote + 1; i < lastQuote; i++) {
  245. DsrChar c = mangledText[i];
  246. if (c == U'\\') { // Escape character
  247. DsrChar c2 = mangledText[i + 1];
  248. if (c2 == U'\"') { // Double quote
  249. result.appendChar(U'\"');
  250. } else if (c2 == U'\\') { // Back slash
  251. result.appendChar(U'\\');
  252. } else if (c2 == U'a') { // Audible bell
  253. result.appendChar(U'\a');
  254. } else if (c2 == U'b') { // Backspace
  255. result.appendChar(U'\b');
  256. } else if (c2 == U'f') { // Form feed
  257. result.appendChar(U'\f');
  258. } else if (c2 == U'n') { // Line feed
  259. result.appendChar(U'\n');
  260. } else if (c2 == U'r') { // Carriage return
  261. result.appendChar(U'\r');
  262. } else if (c2 == U't') { // Horizontal tab
  263. result.appendChar(U'\t');
  264. } else if (c2 == U'v') { // Vertical tab
  265. result.appendChar(U'\v');
  266. } else if (c2 == U'0') { // Null terminator
  267. result.appendChar(U'\0');
  268. }
  269. i++; // Consume both characters
  270. } else {
  271. // Detect bad input
  272. if (c == U'\"') { // Double quote
  273. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, "\n");
  274. } else if (c == U'\\') { // Back slash
  275. throwError(U"Unmangled back slash detected in string_unmangleQuote!\n", mangledText, "\n");
  276. } else if (c == U'\a') { // Audible bell
  277. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, "\n");
  278. } else if (c == U'\b') { // Backspace
  279. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, "\n");
  280. } else if (c == U'\f') { // Form feed
  281. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, "\n");
  282. } else if (c == U'\n') { // Line feed
  283. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, "\n");
  284. } else if (c == U'\r') { // Carriage return
  285. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, "\n");
  286. } else if (c == U'\0') { // Null terminator
  287. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, "\n");
  288. } else {
  289. result.appendChar(c);
  290. }
  291. }
  292. }
  293. }
  294. return result;
  295. }
  296. static void uintToString_arabic(String& target, uint64_t value) {
  297. static const int bufferSize = 20;
  298. DsrChar digits[bufferSize];
  299. int64_t usedSize = 0;
  300. if (value == 0) {
  301. target.appendChar(U'0');
  302. } else {
  303. while (usedSize < bufferSize) {
  304. DsrChar digit = U'0' + (value % 10u);
  305. digits[usedSize] = digit;
  306. usedSize++;
  307. value /= 10u;
  308. if (value == 0) {
  309. break;
  310. }
  311. }
  312. while (usedSize > 0) {
  313. usedSize--;
  314. target.appendChar(digits[usedSize]);
  315. }
  316. }
  317. }
  318. static void intToString_arabic(String& target, int64_t value) {
  319. if (value >= 0) {
  320. uintToString_arabic(target, (uint64_t)value);
  321. } else {
  322. target.appendChar(U'-');
  323. uintToString_arabic(target, (uint64_t)(-value));
  324. }
  325. }
  326. // TODO: Implement own version to ensure that nothing strange is happening from buggy std implementations
  327. static void doubleToString_arabic(String& target, double value) {
  328. std::ostringstream buffer;
  329. buffer << std::fixed << value; // Generate using a fixed number of decimals
  330. std::string result = buffer.str();
  331. // Remove trailing zero decimal digits
  332. int64_t decimalCount = 0;
  333. int64_t lastValueIndex = -1;
  334. for (size_t c = 0; c < result.length(); c++) {
  335. if (result[c] == '.') {
  336. decimalCount++;
  337. } else if (result[c] == ',') {
  338. result[c] = '.'; // Convert nationalized french decimal serialization into international decimals
  339. decimalCount++;
  340. } else if (decimalCount > 0 && result[c] >= '1' && result[c] <= '9') {
  341. lastValueIndex = c;
  342. } else if (decimalCount == 0 && result[c] >= '0' && result[c] <= '9') {
  343. lastValueIndex = c;
  344. }
  345. }
  346. for (int64_t c = 0; c <= lastValueIndex; c++) {
  347. target.appendChar(result[c]);
  348. }
  349. }
  350. #define TO_RAW_ASCII(TARGET, SOURCE) \
  351. char TARGET[SOURCE.length + 1]; \
  352. for (int64_t i = 0; i < SOURCE.length; i++) { \
  353. TARGET[i] = toAscii(SOURCE[i]); \
  354. } \
  355. TARGET[SOURCE.length] = '\0';
  356. // A function definition for receiving a stream of bytes
  357. // Instead of using std's messy inheritance
  358. using ByteWriterFunction = std::function<void(uint8_t value)>;
  359. // A function definition for receiving a stream of UTF-32 characters
  360. // Instead of using std's messy inheritance
  361. using UTF32WriterFunction = std::function<void(DsrChar character)>;
  362. // Filter out unwanted characters for improved portability
  363. static void feedCharacter(const UTF32WriterFunction &reciever, DsrChar character) {
  364. if (character != U'\0' && character != U'\r') {
  365. reciever(character);
  366. }
  367. }
  368. // Appends the content of buffer as a BOM-free Latin-1 file into target
  369. static void feedStringFromFileBuffer_Latin1(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  370. for (int64_t i = 0; i < fileLength; i++) {
  371. DsrChar character = (DsrChar)(buffer[i]);
  372. feedCharacter(reciever, character);
  373. }
  374. }
  375. // Appends the content of buffer as a BOM-free UTF-8 file into target
  376. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  377. for (int64_t i = 0; i < fileLength; i++) {
  378. uint8_t byteA = buffer[i];
  379. if (byteA < (uint32_t)0b10000000) {
  380. // Single byte (1xxxxxxx)
  381. feedCharacter(reciever, (DsrChar)byteA);
  382. } else {
  383. uint32_t character = 0;
  384. int extraBytes = 0;
  385. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  386. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  387. character = byteA & (uint32_t)0b00011111;
  388. extraBytes = 1;
  389. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  390. character = byteA & (uint32_t)0b00001111;
  391. extraBytes = 2;
  392. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  393. character = byteA & (uint32_t)0b00000111;
  394. extraBytes = 3;
  395. } else {
  396. // Invalid UTF-8 format
  397. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  398. }
  399. } else {
  400. // Invalid UTF-8 format
  401. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  402. }
  403. while (extraBytes > 0) {
  404. i += 1; uint32_t nextByte = buffer[i];
  405. character = (character << 6) | (nextByte & 0b00111111);
  406. extraBytes--;
  407. }
  408. feedCharacter(reciever, (DsrChar)character);
  409. }
  410. }
  411. }
  412. template <bool LittleEndian>
  413. uint16_t read16bits(const uint8_t* buffer, int64_t startOffset) {
  414. uint16_t byteA = buffer[startOffset];
  415. uint16_t byteB = buffer[startOffset + 1];
  416. if (LittleEndian) {
  417. return (byteB << 8) | byteA;
  418. } else {
  419. return (byteA << 8) | byteB;
  420. }
  421. }
  422. // Appends the content of buffer as a BOM-free UTF-16 file into target
  423. template <bool LittleEndian>
  424. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  425. for (int64_t i = 0; i < fileLength; i += 2) {
  426. // Read the first 16-bit word
  427. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  428. // Check if another word is needed
  429. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  430. // we can just check if it's within the range reserved for 32-bit encoding
  431. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  432. // Not in the reserved range, just a single 16-bit character
  433. feedCharacter(reciever, (DsrChar)wordA);
  434. } else {
  435. // The given range was reserved and therefore using 32 bits
  436. i += 2;
  437. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  438. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  439. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  440. feedCharacter(reciever, (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000));
  441. }
  442. }
  443. }
  444. // Appends the content of buffer as a text file of unknown format into target
  445. static void feedStringFromFileBuffer(const UTF32WriterFunction &reciever, const uint8_t* buffer, int64_t fileLength) {
  446. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  447. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  448. feedStringFromFileBuffer_UTF8(reciever, buffer + 3, fileLength - 3);
  449. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  450. feedStringFromFileBuffer_UTF16<false>(reciever, buffer + 2, fileLength - 2);
  451. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  452. feedStringFromFileBuffer_UTF16<true>(reciever, buffer + 2, fileLength - 2);
  453. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  454. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  455. throwError(U"UTF-32 BE format is not yet supported!\n");
  456. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  457. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  458. throwError(U"UTF-32 LE format is not yet supported!\n");
  459. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  460. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  461. throwError(U"UTF-1 format is not yet supported!\n");
  462. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  463. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  464. throwError(U"SCSU format is not yet supported!\n");
  465. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  466. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  467. throwError(U"BOCU-1 format is not yet supported!\n");
  468. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  469. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  470. throwError(U"UTF-7 format is not yet supported!\n");
  471. } else {
  472. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  473. feedStringFromFileBuffer_Latin1(reciever, buffer, fileLength);
  474. }
  475. }
  476. String dsr::string_loadFromMemory(Buffer fileContent) {
  477. String result;
  478. // Measure the size of the result by scanning the content in advance
  479. int64_t characterCount = 0;
  480. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  481. characterCount++;
  482. };
  483. feedStringFromFileBuffer(measurer, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  484. // Pre-allocate the correct amount of memory based on the simulation
  485. result.reserve(characterCount);
  486. // Stream output to the result string
  487. UTF32WriterFunction reciever = [&result](DsrChar character) {
  488. result.appendChar(character);
  489. };
  490. feedStringFromFileBuffer(reciever, buffer_dangerous_getUnsafeData(fileContent), buffer_getSize(fileContent));
  491. return result;
  492. }
  493. // Loads a text file of unknown format
  494. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  495. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  496. Buffer encoded = file_loadBuffer(filename, mustExist);
  497. if (!buffer_exists(encoded)) {
  498. return String();
  499. } else {
  500. return string_loadFromMemory(encoded);
  501. }
  502. }
  503. template <CharacterEncoding characterEncoding>
  504. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  505. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  506. // Replace any illegal characters with questionmarks
  507. if (character > 255) { character = U'?'; }
  508. receiver(character);
  509. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  510. // Replace any illegal characters with questionmarks
  511. if (character > 0x10FFFF) { character = U'?'; }
  512. if (character < (1 << 7)) {
  513. // 0xxxxxxx
  514. receiver(character);
  515. } else if (character < (1 << 11)) {
  516. // 110xxxxx 10xxxxxx
  517. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  518. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  519. } else if (character < (1 << 16)) {
  520. // 1110xxxx 10xxxxxx 10xxxxxx
  521. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  522. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  523. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  524. } else if (character < (1 << 21)) {
  525. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  526. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  527. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  528. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  529. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  530. }
  531. } else { // Assuming UTF-16
  532. if (character > 0x10FFFF) { character = U'?'; }
  533. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  534. // xxxxxxxx xxxxxxxx (Limited range)
  535. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  536. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  537. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  538. receiver(higher8Bits);
  539. receiver(lower8Bits);
  540. } else { // Assuming UTF-16 LE
  541. receiver(lower8Bits);
  542. receiver(higher8Bits);
  543. }
  544. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  545. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  546. uint32_t code = character - (uint32_t)0x10000;
  547. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  548. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  549. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  550. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  551. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  552. receiver(byteA);
  553. receiver(byteB);
  554. receiver(byteC);
  555. receiver(byteD);
  556. } else { // Assuming UTF-16 LE
  557. receiver(byteB);
  558. receiver(byteA);
  559. receiver(byteD);
  560. receiver(byteC);
  561. }
  562. }
  563. }
  564. }
  565. // Template for encoding a whole string
  566. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  567. static void encodeText(const ByteWriterFunction &receiver, String content) {
  568. // Write byte order marks
  569. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  570. receiver(0xEF);
  571. receiver(0xBB);
  572. receiver(0xBF);
  573. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  574. receiver(0xFE);
  575. receiver(0xFF);
  576. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  577. receiver(0xFF);
  578. receiver(0xFE);
  579. }
  580. // Write encoded content
  581. for (int64_t i = 0; i < string_length(content); i++) {
  582. DsrChar character = content[i];
  583. if (character == U'\n') {
  584. if (lineEncoding == LineEncoding::CrLf) {
  585. encodeCharacter<characterEncoding>(receiver, U'\r');
  586. encodeCharacter<characterEncoding>(receiver, U'\n');
  587. } else { // Assuming that lineEncoding == LineEncoding::Lf
  588. encodeCharacter<characterEncoding>(receiver, U'\n');
  589. }
  590. } else {
  591. encodeCharacter<characterEncoding>(receiver, character);
  592. }
  593. }
  594. }
  595. // Macro for converting run-time arguments into template arguments for encodeText
  596. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING) \
  597. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  598. if (LINE_ENCODING == LineEncoding::CrLf) { \
  599. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  600. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  601. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT); \
  602. } \
  603. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  604. if (LINE_ENCODING == LineEncoding::CrLf) { \
  605. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  606. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  607. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT); \
  608. } \
  609. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  610. if (LINE_ENCODING == LineEncoding::CrLf) { \
  611. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  612. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  613. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT); \
  614. } \
  615. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  616. if (LINE_ENCODING == LineEncoding::CrLf) { \
  617. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT); \
  618. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  619. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT); \
  620. } \
  621. }
  622. // Encoding to a buffer before saving all at once as a binary file.
  623. // This tells the operating system how big the file is in advance and prevent the worst case of stalling for minutes!
  624. void dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  625. Buffer buffer = string_saveToMemory(content, characterEncoding, lineEncoding);
  626. if (buffer_exists(buffer)) {
  627. file_saveBuffer(filename, buffer);
  628. }
  629. }
  630. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  631. int64_t byteCount = 0;
  632. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  633. byteCount++;
  634. };
  635. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding);
  636. Buffer result = buffer_create(byteCount);
  637. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  638. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  639. *byteWriter = value;
  640. byteWriter += 1;
  641. };
  642. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding);
  643. return result;
  644. }
  645. int64_t String::capacity() {
  646. if (this->buffer.get() == nullptr) {
  647. return 0;
  648. } else {
  649. // Get the parent allocation
  650. uint8_t* parentBuffer = buffer_dangerous_getUnsafeData(this->buffer);
  651. // Get the offset from the parent
  652. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  653. // Subtract offset from the buffer size to get the remaining space
  654. return (buffer_getSize(this->buffer) - offset) / sizeof(DsrChar);
  655. }
  656. }
  657. static int32_t getNewBufferSize(int32_t minimumSize) {
  658. if (minimumSize <= 128) {
  659. return 128;
  660. } else if (minimumSize <= 512) {
  661. return 512;
  662. } else if (minimumSize <= 2048) {
  663. return 2048;
  664. } else if (minimumSize <= 8192) {
  665. return 8192;
  666. } else if (minimumSize <= 32768) {
  667. return 32768;
  668. } else if (minimumSize <= 131072) {
  669. return 131072;
  670. } else if (minimumSize <= 524288) {
  671. return 524288;
  672. } else if (minimumSize <= 2097152) {
  673. return 2097152;
  674. } else if (minimumSize <= 8388608) {
  675. return 8388608;
  676. } else if (minimumSize <= 33554432) {
  677. return 33554432;
  678. } else if (minimumSize <= 134217728) {
  679. return 134217728;
  680. } else if (minimumSize <= 536870912) {
  681. return 536870912;
  682. } else {
  683. return 2147483647;
  684. }
  685. }
  686. void String::reallocateBuffer(int64_t newLength, bool preserve) {
  687. // Holding oldData alive while copying to the new buffer
  688. Buffer oldBuffer = this->buffer;
  689. const char32_t* oldData = this->readSection;
  690. this->buffer = buffer_create(getNewBufferSize(newLength * sizeof(DsrChar)));
  691. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(buffer_dangerous_getUnsafeData(this->buffer));
  692. if (preserve && oldData) {
  693. memcpy(this->writeSection, oldData, this->length * sizeof(DsrChar));
  694. }
  695. }
  696. // Call before writing to the buffer
  697. // This hides that Strings share buffers when assigning by value or taking partial strings
  698. void String::cloneIfShared() {
  699. if (this->buffer.use_count() > 1) {
  700. this->reallocateBuffer(this->length, true);
  701. }
  702. }
  703. void dsr::string_clear(String& target) {
  704. target.cloneIfShared();
  705. target.length = 0;
  706. }
  707. void String::expand(int64_t newLength, bool affectUsedLength) {
  708. if (newLength > this->length) {
  709. if (newLength > this->capacity()) {
  710. this->reallocateBuffer(newLength, true);
  711. }
  712. }
  713. if (affectUsedLength) {
  714. this->length = newLength;
  715. }
  716. }
  717. void String::reserve(int64_t minimumLength) {
  718. this->expand(minimumLength, false);
  719. }
  720. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  721. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  722. // Proof that appending to one string doesn't affect another:
  723. // If it has to reallocate
  724. // * Then it will have its own buffer without conflicts
  725. // If it doesn't have to reallocate
  726. // If it shares the buffer
  727. // If source is empty
  728. // * Then no risk of overwriting neighbor strings if we don't write
  729. // If source isn't empty
  730. // * Then the buffer will be cloned when the first character is written
  731. // If it doesn't share the buffer
  732. // * Then no risk of writing
  733. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  734. int64_t oldLength = (TARGET)->length; \
  735. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  736. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  737. (TARGET)->writeSection[oldLength + i] = ((SOURCE)[i]) & MASK; \
  738. } \
  739. }
  740. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  741. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  742. // TODO: Use memcpy when appending input of the same format
  743. void String::append(const ReadableString& source) { APPEND(this, source, source.length, 0xFFFFFFFF); }
  744. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  745. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int64_t)source.size(), 0xFF); }
  746. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  747. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  748. return source.toStreamIndented(target, indentation);
  749. }
  750. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  751. target.append(indentation);
  752. target.append(value);
  753. return target;
  754. }
  755. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  756. target.append(indentation);
  757. target.append(value);
  758. return target;
  759. }
  760. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  761. target.append(indentation);
  762. target.append(value);
  763. return target;
  764. }
  765. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  766. target.append(indentation);
  767. target.append(value);
  768. return target;
  769. }
  770. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  771. target.append(indentation);
  772. doubleToString_arabic(target, (double)value);
  773. return target;
  774. }
  775. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  776. target.append(indentation);
  777. doubleToString_arabic(target, value);
  778. return target;
  779. }
  780. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  781. target.append(indentation);
  782. intToString_arabic(target, value);
  783. return target;
  784. }
  785. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  786. target.append(indentation);
  787. uintToString_arabic(target, value);
  788. return target;
  789. }
  790. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  791. target.append(indentation);
  792. intToString_arabic(target, (int64_t)value);
  793. return target;
  794. }
  795. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  796. target.append(indentation);
  797. uintToString_arabic(target, (uint64_t)value);
  798. return target;
  799. }
  800. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  801. target.append(indentation);
  802. intToString_arabic(target, (int64_t)value);
  803. return target;
  804. }
  805. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  806. target.append(indentation);
  807. uintToString_arabic(target, (uint64_t)value);
  808. return target;
  809. }
  810. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  811. target.append(indentation);
  812. intToString_arabic(target, (int64_t)value);
  813. return target;
  814. }
  815. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  816. target.append(indentation);
  817. uintToString_arabic(target, (uint64_t)value);
  818. return target;
  819. }
  820. void dsr::throwErrorMessage(const String& message) {
  821. throw std::runtime_error(message.toStdString());
  822. }
  823. void dsr::string_split_callback(std::function<void(ReadableString)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  824. int64_t sectionStart = 0;
  825. for (int64_t i = 0; i < source.length; i++) {
  826. DsrChar c = source[i];
  827. if (c == separator) {
  828. ReadableString element = string_exclusiveRange(source, sectionStart, i);
  829. if (removeWhiteSpace) {
  830. action(string_removeOuterWhiteSpace(element));
  831. } else {
  832. action(element);
  833. }
  834. sectionStart = i + 1;
  835. }
  836. }
  837. if (source.length > sectionStart) {
  838. if (removeWhiteSpace) {
  839. action(string_removeOuterWhiteSpace(string_exclusiveRange(source, sectionStart, source.length)));
  840. } else {
  841. action(string_exclusiveRange(source, sectionStart, source.length));
  842. }
  843. }
  844. }
  845. // Optimization for string_split
  846. // TODO: Clean up!
  847. static String createSubString_shared(const DsrChar *content, int64_t length, const Buffer &buffer, char32_t* writeSection) {
  848. String result;
  849. result.readSection = content;
  850. result.length = length;
  851. result.buffer = buffer;
  852. result.writeSection = writeSection;
  853. return result;
  854. }
  855. static String string_exclusiveRange_shared(const String& source, int64_t inclusiveStart, int64_t exclusiveEnd) {
  856. // Return empty string for each complete miss
  857. if (inclusiveStart >= source.length || exclusiveEnd <= 0) { return String(); }
  858. // Automatically clamping to valid range
  859. if (inclusiveStart < 0) { inclusiveStart = 0; }
  860. if (exclusiveEnd > source.length) { exclusiveEnd = source.length; }
  861. // Return the overlapping interval
  862. return createSubString_shared(&(source.readSection[inclusiveStart]), exclusiveEnd - inclusiveStart, source.buffer, source.writeSection);
  863. }
  864. static String string_inclusiveRange_shared(const String& source, int64_t inclusiveStart, int64_t inclusiveEnd) {
  865. return string_exclusiveRange_shared(source, inclusiveStart, inclusiveEnd + 1);
  866. }
  867. static String string_removeOuterWhiteSpace_shared(const String &text) {
  868. int64_t first = findFirstNonWhite(text);
  869. int64_t last = findLastNonWhite(text);
  870. if (first == -1) {
  871. // Only white space
  872. return ReadableString();
  873. } else {
  874. // Subset
  875. return string_inclusiveRange_shared(text, first, last);
  876. }
  877. }
  878. static void string_split_callback_shared(std::function<void(String)> action, const String& source, DsrChar separator, bool removeWhiteSpace) {
  879. int64_t sectionStart = 0;
  880. for (int64_t i = 0; i < source.length; i++) {
  881. DsrChar c = source[i];
  882. if (c == separator) {
  883. String element = string_exclusiveRange_shared(source, sectionStart, i);
  884. if (removeWhiteSpace) {
  885. action(string_removeOuterWhiteSpace_shared(element));
  886. } else {
  887. action(element);
  888. }
  889. sectionStart = i + 1;
  890. }
  891. }
  892. if (source.length > sectionStart) {
  893. if (removeWhiteSpace) {
  894. action(string_removeOuterWhiteSpace_shared(string_exclusiveRange_shared(source, sectionStart, source.length)));
  895. } else {
  896. action(string_exclusiveRange_shared(source, sectionStart, source.length));
  897. }
  898. }
  899. }
  900. List<String> dsr::string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  901. List<String> result;
  902. String commonBuffer;
  903. const String* sharedSource = dynamic_cast<const String*>(&source);
  904. if (sharedSource == nullptr) {
  905. // Clone the whole input into one allocation to avoid fragmenting the heap with many small allocations
  906. commonBuffer = source;
  907. }
  908. // Source is allocated as String
  909. string_split_callback_shared([&result, removeWhiteSpace](String element) {
  910. if (removeWhiteSpace) {
  911. result.push(string_removeOuterWhiteSpace_shared(element));
  912. } else {
  913. result.push(element);
  914. }
  915. }, source, separator, removeWhiteSpace);
  916. return result;
  917. }
  918. void dsr::string_dangerous_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  919. if (!appendResult) {
  920. target.clear();
  921. }
  922. string_split_callback([&target](ReadableString section){
  923. target.push(section);
  924. }, source, separator);
  925. }
  926. List<ReadableString> dsr::string_dangerous_split(const ReadableString& source, DsrChar separator) {
  927. List<ReadableString> result;
  928. string_dangerous_split_inPlace(result, source, separator);
  929. return result;
  930. }
  931. int64_t dsr::string_splitCount(const ReadableString& source, DsrChar separator) {
  932. int64_t result;
  933. string_split_callback([&result](ReadableString element) {
  934. result++;
  935. }, source, separator);
  936. return result;
  937. }
  938. int64_t dsr::string_toInteger(const ReadableString& source) {
  939. int64_t result;
  940. bool negated;
  941. result = 0;
  942. negated = false;
  943. for (int64_t i = 0; i < source.length; i++) {
  944. DsrChar c = source[i];
  945. if (c == '-' || c == '~') {
  946. negated = !negated;
  947. } else if (c >= '0' && c <= '9') {
  948. result = (result * 10) + (int)(c - '0');
  949. } else if (c == ',' || c == '.') {
  950. // Truncate any decimals by ignoring them
  951. break;
  952. }
  953. }
  954. if (negated) {
  955. return -result;
  956. } else {
  957. return result;
  958. }
  959. }
  960. double dsr::string_toDouble(const ReadableString& source) {
  961. double result;
  962. bool negated;
  963. bool reachedDecimal;
  964. int64_t digitDivider;
  965. result = 0.0;
  966. negated = false;
  967. reachedDecimal = false;
  968. digitDivider = 1;
  969. for (int64_t i = 0; i < source.length; i++) {
  970. DsrChar c = source[i];
  971. if (c == '-' || c == '~') {
  972. negated = !negated;
  973. } else if (c >= '0' && c <= '9') {
  974. if (reachedDecimal) {
  975. digitDivider = digitDivider * 10;
  976. result = result + ((double)(c - '0') / (double)digitDivider);
  977. } else {
  978. result = (result * 10) + (double)(c - '0');
  979. }
  980. } else if (c == ',' || c == '.') {
  981. reachedDecimal = true;
  982. }
  983. }
  984. if (negated) {
  985. return -result;
  986. } else {
  987. return result;
  988. }
  989. }
  990. int64_t dsr::string_length(const ReadableString& source) {
  991. return source.length;
  992. }
  993. int64_t dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int64_t startIndex) {
  994. for (int64_t i = startIndex; i < source.length; i++) {
  995. if (source[i] == toFind) {
  996. return i;
  997. }
  998. }
  999. return -1;
  1000. }
  1001. int64_t dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  1002. for (int64_t i = source.length - 1; i >= 0; i--) {
  1003. if (source[i] == toFind) {
  1004. return i;
  1005. }
  1006. }
  1007. return -1;
  1008. }
  1009. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t exclusiveEnd) {
  1010. // Return empty string for each complete miss
  1011. if (inclusiveStart >= source.length || exclusiveEnd <= 0) { return ReadableString(); }
  1012. // Automatically clamping to valid range
  1013. if (inclusiveStart < 0) { inclusiveStart = 0; }
  1014. if (exclusiveEnd > source.length) { exclusiveEnd = source.length; }
  1015. // Return the overlapping interval
  1016. return createSubString(&(source.readSection[inclusiveStart]), exclusiveEnd - inclusiveStart, source.buffer);
  1017. }
  1018. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int64_t inclusiveStart, int64_t inclusiveEnd) {
  1019. return string_exclusiveRange(source, inclusiveStart, inclusiveEnd + 1);
  1020. }
  1021. ReadableString dsr::string_before(const ReadableString& source, int64_t exclusiveEnd) {
  1022. return string_exclusiveRange(source, 0, exclusiveEnd);
  1023. }
  1024. ReadableString dsr::string_until(const ReadableString& source, int64_t inclusiveEnd) {
  1025. return string_inclusiveRange(source, 0, inclusiveEnd);
  1026. }
  1027. ReadableString dsr::string_from(const ReadableString& source, int64_t inclusiveStart) {
  1028. return string_exclusiveRange(source, inclusiveStart, source.length);
  1029. }
  1030. ReadableString dsr::string_after(const ReadableString& source, int64_t exclusiveStart) {
  1031. return string_from(source, exclusiveStart + 1);
  1032. }
  1033. bool dsr::character_isDigit(DsrChar c) {
  1034. return c >= U'0' && c <= U'9';
  1035. }
  1036. bool dsr::character_isIntegerCharacter(DsrChar c) {
  1037. return c == U'-' || character_isDigit(c);
  1038. }
  1039. bool dsr::character_isValueCharacter(DsrChar c) {
  1040. return c == U'.' || character_isIntegerCharacter(c);
  1041. }
  1042. bool dsr::character_isWhiteSpace(DsrChar c) {
  1043. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1044. }
  1045. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1046. // Optional accepts 0 or 1 occurence
  1047. // Forced accepts 1 occurence
  1048. // Star accepts 0..N occurence
  1049. // Plus accepts 1..N occurence
  1050. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1051. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1052. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1053. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1054. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1055. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1056. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1057. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1058. // The greedy approach works here, because there's no ambiguity
  1059. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1060. int64_t readIndex = 0;
  1061. if (allowWhiteSpace) {
  1062. PATTERN_STAR(WhiteSpace);
  1063. }
  1064. CHARACTER_OPTIONAL(U'-');
  1065. // At least one digit required
  1066. PATTERN_PLUS(IntegerCharacter);
  1067. if (allowWhiteSpace) {
  1068. PATTERN_STAR(WhiteSpace);
  1069. }
  1070. return true;
  1071. }
  1072. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1073. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1074. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1075. if (string_findFirst(source, U'.') == -1) {
  1076. // No decimal detected
  1077. return string_isInteger(source, allowWhiteSpace);
  1078. } else {
  1079. int64_t readIndex = 0;
  1080. if (allowWhiteSpace) {
  1081. PATTERN_STAR(WhiteSpace);
  1082. }
  1083. // Double <- UnsignedDouble | '-' UnsignedDouble
  1084. CHARACTER_OPTIONAL(U'-');
  1085. // UnsignedDouble <- Digit* '.' Digit+
  1086. // Any number of integer digits
  1087. PATTERN_STAR(IntegerCharacter);
  1088. // Only dot for decimal
  1089. CHARACTER_FORCED(U'.')
  1090. // At least one decimal digit
  1091. PATTERN_PLUS(IntegerCharacter);
  1092. if (allowWhiteSpace) {
  1093. PATTERN_STAR(WhiteSpace);
  1094. }
  1095. return true;
  1096. }
  1097. }
  1098. int64_t dsr::string_getBufferUseCount(const ReadableString& text) {
  1099. return text.buffer.use_count();
  1100. }