stringAPI.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2025 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. // Gets access to private members by making them public for the whole module
  24. #define DSR_INTERNAL_ACCESS
  25. #include <iostream>
  26. #include <sstream>
  27. #include <fstream>
  28. #include <streambuf>
  29. #include <thread>
  30. #include <mutex>
  31. #include <stdexcept>
  32. #include <cmath>
  33. #include "stringAPI.h"
  34. #include "../api/fileAPI.h"
  35. #include "../settings.h"
  36. using namespace dsr;
  37. // The print buffer keeps its buffer size from previous printing to avoid reallocating memory every time something is printed.
  38. // It is stored separatelly for each calling thread to avoid conflicts.
  39. static thread_local String printBuffer;
  40. String &dsr::string_getPrintBuffer() {
  41. return printBuffer;
  42. }
  43. static void atomic_append_ascii(String &target, const char* source);
  44. static void atomic_append_readable(String &target, const ReadableString& source);
  45. static void atomic_append_utf32(String &target, const DsrChar* source);
  46. static intptr_t strlen_utf32(const DsrChar *content) {
  47. intptr_t length = 0;
  48. while (content[length] != 0) {
  49. length++;
  50. }
  51. return length;
  52. }
  53. static char toAscii(DsrChar c) {
  54. if (c > 127) {
  55. return '?';
  56. } else {
  57. return c;
  58. }
  59. }
  60. ReadableString::ReadableString(const DsrChar *content)
  61. : view(content, strlen_utf32(content)) {}
  62. String::String() {}
  63. String::String(const char* source) { atomic_append_ascii(*this, source); }
  64. String::String(const DsrChar* source) { atomic_append_utf32(*this, source); }
  65. String& Printable::toStream(String& target) const {
  66. return this->toStreamIndented(target, U"");
  67. }
  68. String Printable::toStringIndented(const ReadableString& indentation) const {
  69. String result;
  70. this->toStreamIndented(result, indentation);
  71. return result;
  72. }
  73. String Printable::toString() const {
  74. return this->toStringIndented(U"");
  75. }
  76. Printable::~Printable() {}
  77. bool dsr::string_match(const ReadableString& a, const ReadableString& b) {
  78. if (a.view.length != b.view.length) {
  79. return false;
  80. } else {
  81. for (intptr_t i = 0; i < a.view.length; i++) {
  82. if (a[i] != b[i]) {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. }
  89. bool dsr::string_caseInsensitiveMatch(const ReadableString& a, const ReadableString& b) {
  90. if (a.view.length != b.view.length) {
  91. return false;
  92. } else {
  93. for (intptr_t i = 0; i < a.view.length; i++) {
  94. if (towupper(a[i]) != towupper(b[i])) {
  95. return false;
  96. }
  97. }
  98. return true;
  99. }
  100. }
  101. DsrChar dsr::character_upperCase(DsrChar character) {
  102. if (U'a' <= character && character <= U'z') { // a (97) to z (122)
  103. return character - (U'a' - U'A');
  104. } else if (U'à' <= character && character <= U'ö') { // à (224) to ö (246)
  105. return character - (U'à' - U'À');
  106. } else if (U'ø' <= character && character <= U'þ') { // ø (248) to þ (254)
  107. return character - (U'ø' - U'Ø');
  108. } else {
  109. return character;
  110. }
  111. }
  112. DsrChar dsr::character_lowerCase(DsrChar character) {
  113. if (U'A' <= character && character <= U'Z') { // A (65) to Z (90)
  114. return character + (U'a' - U'A');
  115. } else if (U'À' <= character && character <= U'Ö') { // À (192) to Ö (214)
  116. return character + (U'à' - U'À');
  117. } else if (U'Ø' <= character && character <= U'Þ') { // Ø (216) to Þ (222)
  118. return character + (U'ø' - U'Ø');
  119. } else {
  120. return character;
  121. }
  122. }
  123. String dsr::string_upperCase(const ReadableString &text) {
  124. String result;
  125. string_reserve(result, text.view.length);
  126. for (intptr_t i = 0; i < text.view.length; i++) {
  127. string_appendChar(result, character_upperCase(text[i]));
  128. }
  129. return result;
  130. }
  131. String dsr::string_lowerCase(const ReadableString &text) {
  132. String result;
  133. string_reserve(result, text.view.length);
  134. for (intptr_t i = 0; i < text.view.length; i++) {
  135. string_appendChar(result, character_lowerCase(text[i]));
  136. }
  137. return result;
  138. }
  139. static intptr_t findFirstNonWhite(const ReadableString &text) {
  140. for (intptr_t i = 0; i < text.view.length; i++) {
  141. DsrChar c = text[i];
  142. if (!character_isWhiteSpace(c)) {
  143. return i;
  144. }
  145. }
  146. return -1;
  147. }
  148. static intptr_t findLastNonWhite(const ReadableString &text) {
  149. for (intptr_t i = text.view.length - 1; i >= 0; i--) {
  150. DsrChar c = text[i];
  151. if (!character_isWhiteSpace(c)) {
  152. return i;
  153. }
  154. }
  155. return -1;
  156. }
  157. // Allow passing literals without allocating heap memory for the result
  158. ReadableString dsr::string_removeOuterWhiteSpace(const ReadableString &text) {
  159. intptr_t first = findFirstNonWhite(text);
  160. intptr_t last = findLastNonWhite(text);
  161. if (first == -1) {
  162. // Only white space
  163. return ReadableString();
  164. } else {
  165. // Subset
  166. return string_inclusiveRange(text, first, last);
  167. }
  168. }
  169. String dsr::string_mangleQuote(const ReadableString &rawText) {
  170. String result;
  171. string_reserve(result, rawText.view.length + 2);
  172. string_appendChar(result, U'\"'); // Begin quote
  173. for (intptr_t i = 0; i < rawText.view.length; i++) {
  174. DsrChar c = rawText[i];
  175. if (c == U'\"') { // Double quote
  176. string_append(result, U"\\\"");
  177. } else if (c == U'\\') { // Backslash
  178. string_append(result, U"\\\\");
  179. } else if (c == U'\a') { // Audible bell
  180. string_append(result, U"\\a");
  181. } else if (c == U'\b') { // Backspace
  182. string_append(result, U"\\b");
  183. } else if (c == U'\f') { // Form feed
  184. string_append(result, U"\\f");
  185. } else if (c == U'\n') { // Line feed
  186. string_append(result, U"\\n");
  187. } else if (c == U'\r') { // Carriage return
  188. string_append(result, U"\\r");
  189. } else if (c == U'\t') { // Horizontal tab
  190. string_append(result, U"\\t");
  191. } else if (c == U'\v') { // Vertical tab
  192. string_append(result, U"\\v");
  193. } else if (c == U'\0') { // Null terminator
  194. string_append(result, U"\\0");
  195. } else {
  196. string_appendChar(result, c);
  197. }
  198. }
  199. string_appendChar(result, U'\"'); // End quote
  200. return result;
  201. }
  202. String dsr::string_unmangleQuote(const ReadableString& mangledText) {
  203. intptr_t firstQuote = string_findFirst(mangledText, '\"');
  204. intptr_t lastQuote = string_findLast(mangledText, '\"');
  205. String result;
  206. if (firstQuote == -1 || lastQuote == -1 || firstQuote == lastQuote) {
  207. throwError(U"Cannot unmangle using string_unmangleQuote without beginning and ending with quote signs!\n", mangledText, U"\n");
  208. } else {
  209. for (intptr_t i = firstQuote + 1; i < lastQuote; i++) {
  210. DsrChar c = mangledText[i];
  211. if (c == U'\\') { // Escape character
  212. DsrChar c2 = mangledText[i + 1];
  213. if (c2 == U'\"') { // Double quote
  214. string_appendChar(result, U'\"');
  215. } else if (c2 == U'\\') { // Back slash
  216. string_appendChar(result, U'\\');
  217. } else if (c2 == U'a') { // Audible bell
  218. string_appendChar(result, U'\a');
  219. } else if (c2 == U'b') { // Backspace
  220. string_appendChar(result, U'\b');
  221. } else if (c2 == U'f') { // Form feed
  222. string_appendChar(result, U'\f');
  223. } else if (c2 == U'n') { // Line feed
  224. string_appendChar(result, U'\n');
  225. } else if (c2 == U'r') { // Carriage return
  226. string_appendChar(result, U'\r');
  227. } else if (c2 == U't') { // Horizontal tab
  228. string_appendChar(result, U'\t');
  229. } else if (c2 == U'v') { // Vertical tab
  230. string_appendChar(result, U'\v');
  231. } else if (c2 == U'0') { // Null terminator
  232. string_appendChar(result, U'\0');
  233. }
  234. i++; // Consume both characters
  235. } else {
  236. // Detect bad input
  237. if (c == U'\"') { // Double quote
  238. throwError(U"Unmangled double quote sign detected in string_unmangleQuote!\n", mangledText, U"\n");
  239. } else if (c == U'\a') { // Audible bell
  240. throwError(U"Unmangled audible bell detected in string_unmangleQuote!\n", mangledText, U"\n");
  241. } else if (c == U'\b') { // Backspace
  242. throwError(U"Unmangled backspace detected in string_unmangleQuote!\n", mangledText, U"\n");
  243. } else if (c == U'\f') { // Form feed
  244. throwError(U"Unmangled form feed detected in string_unmangleQuote!\n", mangledText, U"\n");
  245. } else if (c == U'\n') { // Line feed
  246. throwError(U"Unmangled line feed detected in string_unmangleQuote!\n", mangledText, U"\n");
  247. } else if (c == U'\r') { // Carriage return
  248. throwError(U"Unmangled carriage return detected in string_unmangleQuote!\n", mangledText, U"\n");
  249. } else if (c == U'\0') { // Null terminator
  250. throwError(U"Unmangled null terminator detected in string_unmangleQuote!\n", mangledText, U"\n");
  251. } else {
  252. string_appendChar(result, c);
  253. }
  254. }
  255. }
  256. }
  257. return result;
  258. }
  259. void dsr::string_fromUnsigned(String& target, uint64_t value) {
  260. static const int bufferSize = 20;
  261. DsrChar digits[bufferSize];
  262. int64_t usedSize = 0;
  263. if (value == 0) {
  264. string_appendChar(target, U'0');
  265. } else {
  266. while (usedSize < bufferSize) {
  267. DsrChar digit = U'0' + (value % 10u);
  268. digits[usedSize] = digit;
  269. usedSize++;
  270. value /= 10u;
  271. if (value == 0) {
  272. break;
  273. }
  274. }
  275. while (usedSize > 0) {
  276. usedSize--;
  277. string_appendChar(target, digits[usedSize]);
  278. }
  279. }
  280. }
  281. void dsr::string_fromSigned(String& target, int64_t value, DsrChar negationCharacter) {
  282. if (value >= 0) {
  283. string_fromUnsigned(target, (uint64_t)value);
  284. } else {
  285. string_appendChar(target, negationCharacter);
  286. string_fromUnsigned(target, (uint64_t)(-value));
  287. }
  288. }
  289. static const int MAX_DECIMALS = 16;
  290. static double decimalMultipliers[MAX_DECIMALS] = {
  291. 10.0,
  292. 100.0,
  293. 1000.0,
  294. 10000.0,
  295. 100000.0,
  296. 1000000.0,
  297. 10000000.0,
  298. 100000000.0,
  299. 1000000000.0,
  300. 10000000000.0,
  301. 100000000000.0,
  302. 1000000000000.0,
  303. 10000000000000.0,
  304. 100000000000000.0,
  305. 1000000000000000.0,
  306. 10000000000000000.0
  307. };
  308. static double roundingOffsets[MAX_DECIMALS] = {
  309. 0.05,
  310. 0.005,
  311. 0.0005,
  312. 0.00005,
  313. 0.000005,
  314. 0.0000005,
  315. 0.00000005,
  316. 0.000000005,
  317. 0.0000000005,
  318. 0.00000000005,
  319. 0.000000000005,
  320. 0.0000000000005,
  321. 0.00000000000005,
  322. 0.000000000000005,
  323. 0.0000000000000005,
  324. 0.00000000000000005
  325. };
  326. static uint64_t decimalLimits[MAX_DECIMALS] = {
  327. 9,
  328. 99,
  329. 999,
  330. 9999,
  331. 99999,
  332. 999999,
  333. 9999999,
  334. 99999999,
  335. 999999999,
  336. 9999999999,
  337. 99999999999,
  338. 999999999999,
  339. 9999999999999,
  340. 99999999999999,
  341. 999999999999999,
  342. 9999999999999999
  343. };
  344. void dsr::string_fromDouble(String& target, double value, int decimalCount, bool removeTrailingZeroes, DsrChar decimalCharacter, DsrChar negationCharacter) {
  345. if (decimalCount < 1) decimalCount = 1;
  346. if (decimalCount > MAX_DECIMALS) decimalCount = MAX_DECIMALS;
  347. double remainder = value;
  348. // Get negation
  349. if (remainder < 0.0) {
  350. string_appendChar(target, negationCharacter);
  351. remainder = -remainder;
  352. }
  353. // Apply an offset to make the following truncation round to the closest printable decimal.
  354. int offsetIndex = decimalCount - 1;
  355. remainder += roundingOffsets[offsetIndex];
  356. // Get whole part
  357. uint64_t whole = (uint64_t)remainder;
  358. string_fromUnsigned(target, whole);
  359. // Remove the whole part from the remainder.
  360. remainder = remainder - whole;
  361. // Print the decimal
  362. string_appendChar(target, decimalCharacter);
  363. // Get decimals
  364. uint64_t scaledDecimals = uint64_t(remainder * decimalMultipliers[offsetIndex]);
  365. // Limit decimals to all nines prevent losing a whole unit from fraction overflow.
  366. uint64_t limit = decimalLimits[offsetIndex];
  367. if (scaledDecimals > limit) scaledDecimals = limit;
  368. DsrChar digits[MAX_DECIMALS]; // Using 0 to decimalCount - 1
  369. int writeIndex = decimalCount - 1;
  370. for (int d = 0; d < decimalCount; d++) {
  371. int digit = scaledDecimals % 10;
  372. digits[writeIndex] = U'0' + digit;
  373. scaledDecimals = scaledDecimals / 10;
  374. writeIndex--;
  375. }
  376. if (removeTrailingZeroes) {
  377. // Find the last non-zero decimal, but keep at least one zero.
  378. int lastValue = 0;
  379. for (int d = 0; d < decimalCount; d++) {
  380. if (digits[d] != U'0') lastValue = d;
  381. }
  382. // Print until the last value or the only zero.
  383. for (int d = 0; d <= lastValue; d++) {
  384. string_appendChar(target, digits[d]);
  385. }
  386. } else {
  387. // Print fixed decimals.
  388. for (int d = 0; d < decimalCount; d++) {
  389. string_appendChar(target, digits[d]);
  390. }
  391. }
  392. }
  393. #define TO_RAW_ASCII(TARGET, SOURCE) \
  394. char TARGET[SOURCE.view.length + 1]; \
  395. for (intptr_t i = 0; i < SOURCE.view.length; i++) { \
  396. TARGET[i] = toAscii(SOURCE[i]); \
  397. } \
  398. TARGET[SOURCE.view.length] = '\0';
  399. // A function definition for receiving a stream of bytes
  400. // Instead of using std's messy inheritance
  401. using ByteWriterFunction = std::function<void(uint8_t value)>;
  402. // A function definition for receiving a stream of UTF-32 characters
  403. // Instead of using std's messy inheritance
  404. using UTF32WriterFunction = std::function<void(DsrChar character)>;
  405. // Filter out unwanted characters for improved portability
  406. static void feedCharacter(const UTF32WriterFunction &receiver, DsrChar character) {
  407. if (character != U'\0' && character != U'\r') {
  408. receiver(character);
  409. }
  410. }
  411. // Appends the content of buffer as a BOM-free Latin-1 file into target
  412. // fileLength is ignored when nullTerminated is true
  413. template <bool nullTerminated>
  414. static void feedStringFromFileBuffer_Latin1(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  415. for (intptr_t i = 0; i < fileLength || nullTerminated; i++) {
  416. DsrChar character = (DsrChar)(buffer[i]);
  417. if (nullTerminated && character == 0) { return; }
  418. feedCharacter(receiver, character);
  419. }
  420. }
  421. // Appends the content of buffer as a BOM-free UTF-8 file into target
  422. // fileLength is ignored when nullTerminated is true
  423. template <bool nullTerminated>
  424. static void feedStringFromFileBuffer_UTF8(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  425. for (intptr_t i = 0; i < fileLength || nullTerminated; i++) {
  426. uint8_t byteA = buffer[i];
  427. if (byteA < (uint32_t)0b10000000) {
  428. // Single byte (1xxxxxxx)
  429. if (nullTerminated && byteA == 0) { return; }
  430. feedCharacter(receiver, (DsrChar)byteA);
  431. } else {
  432. uint32_t character = 0;
  433. int extraBytes = 0;
  434. if (byteA >= (uint32_t)0b11000000) { // At least two leading ones
  435. if (byteA < (uint32_t)0b11100000) { // Less than three leading ones
  436. character = byteA & (uint32_t)0b00011111;
  437. extraBytes = 1;
  438. } else if (byteA < (uint32_t)0b11110000) { // Less than four leading ones
  439. character = byteA & (uint32_t)0b00001111;
  440. extraBytes = 2;
  441. } else if (byteA < (uint32_t)0b11111000) { // Less than five leading ones
  442. character = byteA & (uint32_t)0b00000111;
  443. extraBytes = 3;
  444. } else {
  445. // Invalid UTF-8 format
  446. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b111111xx!");
  447. }
  448. } else {
  449. // Invalid UTF-8 format
  450. throwError(U"Invalid UTF-8 multi-chatacter beginning with 0b10xxxxxx!");
  451. }
  452. while (extraBytes > 0) {
  453. i += 1; uint32_t nextByte = buffer[i];
  454. character = (character << 6) | (nextByte & 0b00111111);
  455. extraBytes--;
  456. }
  457. feedCharacter(receiver, (DsrChar)character);
  458. }
  459. }
  460. }
  461. template <bool LittleEndian>
  462. uint16_t read16bits(const uint8_t* buffer, intptr_t startOffset) {
  463. uint16_t byteA = buffer[startOffset];
  464. uint16_t byteB = buffer[startOffset + 1];
  465. if (LittleEndian) {
  466. return (byteB << 8) | byteA;
  467. } else {
  468. return (byteA << 8) | byteB;
  469. }
  470. }
  471. // Appends the content of buffer as a BOM-free UTF-16 file into target as UTF-32
  472. // fileLength is ignored when nullTerminated is true
  473. template <bool LittleEndian, bool nullTerminated>
  474. static void feedStringFromFileBuffer_UTF16(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength = 0) {
  475. for (intptr_t i = 0; i < fileLength || nullTerminated; i += 2) {
  476. // Read the first 16-bit word
  477. uint16_t wordA = read16bits<LittleEndian>(buffer, i);
  478. // Check if another word is needed
  479. // Assuming that wordA >= 0x0000 and wordA <= 0xFFFF as uint16_t,
  480. // we can just check if it's within the range reserved for 32-bit encoding
  481. if (wordA <= 0xD7FF || wordA >= 0xE000) {
  482. // Not in the reserved range, just a single 16-bit character
  483. if (nullTerminated && wordA == 0) { return; }
  484. feedCharacter(receiver, (DsrChar)wordA);
  485. } else {
  486. // The given range was reserved and therefore using 32 bits
  487. i += 2;
  488. uint16_t wordB = read16bits<LittleEndian>(buffer, i);
  489. uint32_t higher10Bits = wordA & (uint32_t)0b1111111111;
  490. uint32_t lower10Bits = wordB & (uint32_t)0b1111111111;
  491. DsrChar finalChar = (DsrChar)(((higher10Bits << 10) | lower10Bits) + (uint32_t)0x10000);
  492. feedCharacter(receiver, finalChar);
  493. }
  494. }
  495. }
  496. // Sends the decoded UTF-32 characters from the encoded buffer into target.
  497. // The text encoding should be specified using a BOM at the start of buffer, otherwise Latin-1 is assumed.
  498. static void feedStringFromFileBuffer(const UTF32WriterFunction &receiver, const uint8_t* buffer, intptr_t fileLength) {
  499. // After removing the BOM bytes, the rest can be seen as a BOM-free text file with a known format
  500. if (fileLength >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { // UTF-8
  501. feedStringFromFileBuffer_UTF8<false>(receiver, buffer + 3, fileLength - 3);
  502. } else if (fileLength >= 2 && buffer[0] == 0xFE && buffer[1] == 0xFF) { // UTF-16 BE
  503. feedStringFromFileBuffer_UTF16<false, false>(receiver, buffer + 2, fileLength - 2);
  504. } else if (fileLength >= 2 && buffer[0] == 0xFF && buffer[1] == 0xFE) { // UTF-16 LE
  505. feedStringFromFileBuffer_UTF16<true, false>(receiver, buffer + 2, fileLength - 2);
  506. } else if (fileLength >= 4 && buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0xFE && buffer[3] == 0xFF) { // UTF-32 BE
  507. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  508. throwError(U"UTF-32 BE format is not yet supported!\n");
  509. } else if (fileLength >= 4 && buffer[0] == 0xFF && buffer[1] == 0xFE && buffer[2] == 0x00 && buffer[3] == 0x00) { // UTF-32 LE
  510. //feedStringFromFileBuffer_UTF32BE(receiver, buffer + 4, fileLength - 4);
  511. throwError(U"UTF-32 LE format is not yet supported!\n");
  512. } else if (fileLength >= 3 && buffer[0] == 0xF7 && buffer[1] == 0x64 && buffer[2] == 0x4C) { // UTF-1
  513. //feedStringFromFileBuffer_UTF1(receiver, buffer + 3, fileLength - 3);
  514. throwError(U"UTF-1 format is not yet supported!\n");
  515. } else if (fileLength >= 3 && buffer[0] == 0x0E && buffer[1] == 0xFE && buffer[2] == 0xFF) { // SCSU
  516. //feedStringFromFileBuffer_SCSU(receiver, buffer + 3, fileLength - 3);
  517. throwError(U"SCSU format is not yet supported!\n");
  518. } else if (fileLength >= 3 && buffer[0] == 0xFB && buffer[1] == 0xEE && buffer[2] == 0x28) { // BOCU
  519. //feedStringFromFileBuffer_BOCU-1(receiver, buffer + 3, fileLength - 3);
  520. throwError(U"BOCU-1 format is not yet supported!\n");
  521. } else if (fileLength >= 4 && buffer[0] == 0x2B && buffer[1] == 0x2F && buffer[2] == 0x76) { // UTF-7
  522. // Ignoring fourth byte with the dialect of UTF-7 when just showing the error message
  523. throwError(U"UTF-7 format is not yet supported!\n");
  524. } else {
  525. // No BOM detected, assuming Latin-1 (because it directly corresponds to a unicode sub-set)
  526. feedStringFromFileBuffer_Latin1<false>(receiver, buffer, fileLength);
  527. }
  528. }
  529. // Sends the decoded UTF-32 characters from the encoded null terminated buffer into target.
  530. // buffer may not contain any BOM, and must be null terminated in the specified encoding.
  531. static void feedStringFromRawData(const UTF32WriterFunction &receiver, const uint8_t* buffer, CharacterEncoding encoding) {
  532. if (encoding == CharacterEncoding::Raw_Latin1) {
  533. feedStringFromFileBuffer_Latin1<true>(receiver, buffer);
  534. } else if (encoding == CharacterEncoding::BOM_UTF8) {
  535. feedStringFromFileBuffer_UTF8<true>(receiver, buffer);
  536. } else if (encoding == CharacterEncoding::BOM_UTF16BE) {
  537. feedStringFromFileBuffer_UTF16<false, true>(receiver, buffer);
  538. } else if (encoding == CharacterEncoding::BOM_UTF16LE) {
  539. feedStringFromFileBuffer_UTF16<true, true>(receiver, buffer);
  540. } else {
  541. throwError(U"Unhandled encoding in feedStringFromRawData!\n");
  542. }
  543. }
  544. String dsr::string_dangerous_decodeFromData(const void* data, CharacterEncoding encoding) {
  545. String result;
  546. // Measure the size of the result by scanning the content in advance
  547. intptr_t characterCount = 0;
  548. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  549. characterCount++;
  550. };
  551. feedStringFromRawData(measurer, (const uint8_t*)data, encoding);
  552. // Pre-allocate the correct amount of memory based on the simulation
  553. string_reserve(result, characterCount);
  554. // Stream output to the result string
  555. UTF32WriterFunction receiver = [&result](DsrChar character) {
  556. string_appendChar(result, character);
  557. };
  558. feedStringFromRawData(receiver, (const uint8_t*)data, encoding);
  559. return result;
  560. }
  561. String dsr::string_loadFromMemory(Buffer fileContent) {
  562. String result;
  563. // Measure the size of the result by scanning the content in advance
  564. intptr_t characterCount = 0;
  565. UTF32WriterFunction measurer = [&characterCount](DsrChar character) {
  566. characterCount++;
  567. };
  568. feedStringFromFileBuffer(measurer, fileContent.getUnsafe(), fileContent.getUsedSize());
  569. // Pre-allocate the correct amount of memory based on the simulation
  570. string_reserve(result, characterCount);
  571. // Stream output to the result string
  572. UTF32WriterFunction receiver = [&result](DsrChar character) {
  573. string_appendChar(result, character);
  574. };
  575. feedStringFromFileBuffer(receiver, fileContent.getUnsafe(), fileContent.getUsedSize());
  576. return result;
  577. }
  578. // Loads a text file of unknown format
  579. // Removes carriage-return characters to make processing easy with only line-feed for breaking lines
  580. String dsr::string_load(const ReadableString& filename, bool mustExist) {
  581. Buffer encoded = file_loadBuffer(filename, mustExist);
  582. if (!buffer_exists(encoded)) {
  583. return String();
  584. } else {
  585. return string_loadFromMemory(encoded);
  586. }
  587. }
  588. template <CharacterEncoding characterEncoding>
  589. static void encodeCharacter(const ByteWriterFunction &receiver, DsrChar character) {
  590. if (characterEncoding == CharacterEncoding::Raw_Latin1) {
  591. // Replace any illegal characters with questionmarks
  592. if (character > 255) { character = U'?'; }
  593. receiver(character);
  594. } else if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  595. // Replace any illegal characters with questionmarks
  596. if (character > 0x10FFFF) { character = U'?'; }
  597. if (character < (1 << 7)) {
  598. // 0xxxxxxx
  599. receiver(character);
  600. } else if (character < (1 << 11)) {
  601. // 110xxxxx 10xxxxxx
  602. receiver((uint32_t)0b11000000 | ((character & ((uint32_t)0b11111 << 6)) >> 6));
  603. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  604. } else if (character < (1 << 16)) {
  605. // 1110xxxx 10xxxxxx 10xxxxxx
  606. receiver((uint32_t)0b11100000 | ((character & ((uint32_t)0b1111 << 12)) >> 12));
  607. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  608. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  609. } else if (character < (1 << 21)) {
  610. // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  611. receiver((uint32_t)0b11110000 | ((character & ((uint32_t)0b111 << 18)) >> 18));
  612. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 12)) >> 12));
  613. receiver((uint32_t)0b10000000 | ((character & ((uint32_t)0b111111 << 6)) >> 6));
  614. receiver((uint32_t)0b10000000 | (character & (uint32_t)0b111111));
  615. }
  616. } else { // Assuming UTF-16
  617. if (character > 0x10FFFF) { character = U'?'; }
  618. if (character <= 0xD7FF || (character >= 0xE000 && character <= 0xFFFF)) {
  619. // xxxxxxxx xxxxxxxx (Limited range)
  620. uint32_t higher8Bits = (character & (uint32_t)0b1111111100000000) >> 8;
  621. uint32_t lower8Bits = character & (uint32_t)0b0000000011111111;
  622. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  623. receiver(higher8Bits);
  624. receiver(lower8Bits);
  625. } else { // Assuming UTF-16 LE
  626. receiver(lower8Bits);
  627. receiver(higher8Bits);
  628. }
  629. } else if (character >= 0x010000 && character <= 0x10FFFF) {
  630. // 110110xxxxxxxxxx 110111xxxxxxxxxx
  631. uint32_t code = character - (uint32_t)0x10000;
  632. uint32_t byteA = ((code & (uint32_t)0b11000000000000000000) >> 18) | (uint32_t)0b11011000;
  633. uint32_t byteB = (code & (uint32_t)0b00111111110000000000) >> 10;
  634. uint32_t byteC = ((code & (uint32_t)0b00000000001100000000) >> 8) | (uint32_t)0b11011100;
  635. uint32_t byteD = code & (uint32_t)0b00000000000011111111;
  636. if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  637. receiver(byteA);
  638. receiver(byteB);
  639. receiver(byteC);
  640. receiver(byteD);
  641. } else { // Assuming UTF-16 LE
  642. receiver(byteB);
  643. receiver(byteA);
  644. receiver(byteD);
  645. receiver(byteC);
  646. }
  647. }
  648. }
  649. }
  650. // Template for encoding a whole string
  651. template <CharacterEncoding characterEncoding, LineEncoding lineEncoding>
  652. static void encodeText(const ByteWriterFunction &receiver, String content, bool writeBOM, bool writeNullTerminator) {
  653. if (writeBOM) {
  654. // Write byte order marks
  655. if (characterEncoding == CharacterEncoding::BOM_UTF8) {
  656. receiver(0xEF);
  657. receiver(0xBB);
  658. receiver(0xBF);
  659. } else if (characterEncoding == CharacterEncoding::BOM_UTF16BE) {
  660. receiver(0xFE);
  661. receiver(0xFF);
  662. } else if (characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  663. receiver(0xFF);
  664. receiver(0xFE);
  665. }
  666. }
  667. // Write encoded content
  668. for (intptr_t i = 0; i < string_length(content); i++) {
  669. DsrChar character = content[i];
  670. if (character == U'\n') {
  671. if (lineEncoding == LineEncoding::CrLf) {
  672. encodeCharacter<characterEncoding>(receiver, U'\r');
  673. encodeCharacter<characterEncoding>(receiver, U'\n');
  674. } else { // Assuming that lineEncoding == LineEncoding::Lf
  675. encodeCharacter<characterEncoding>(receiver, U'\n');
  676. }
  677. } else {
  678. encodeCharacter<characterEncoding>(receiver, character);
  679. }
  680. }
  681. if (writeNullTerminator) {
  682. // Terminate internal strings with \0 to prevent getting garbage data after unpadded buffers
  683. if (characterEncoding == CharacterEncoding::BOM_UTF16BE || characterEncoding == CharacterEncoding::BOM_UTF16LE) {
  684. receiver(0);
  685. receiver(0);
  686. } else {
  687. receiver(0);
  688. }
  689. }
  690. }
  691. // Macro for converting run-time arguments into template arguments for encodeText
  692. #define ENCODE_TEXT(RECEIVER, CONTENT, CHAR_ENCODING, LINE_ENCODING, WRITE_BOM, WRITE_NULL_TERMINATOR) \
  693. if (CHAR_ENCODING == CharacterEncoding::Raw_Latin1) { \
  694. if (LINE_ENCODING == LineEncoding::CrLf) { \
  695. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::CrLf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  696. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  697. encodeText<CharacterEncoding::Raw_Latin1, LineEncoding::Lf>(RECEIVER, CONTENT, false, WRITE_NULL_TERMINATOR); \
  698. } \
  699. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF8) { \
  700. if (LINE_ENCODING == LineEncoding::CrLf) { \
  701. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  702. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  703. encodeText<CharacterEncoding::BOM_UTF8, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  704. } \
  705. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16BE) { \
  706. if (LINE_ENCODING == LineEncoding::CrLf) { \
  707. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  708. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  709. encodeText<CharacterEncoding::BOM_UTF16BE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  710. } \
  711. } else if (CHAR_ENCODING == CharacterEncoding::BOM_UTF16LE) { \
  712. if (LINE_ENCODING == LineEncoding::CrLf) { \
  713. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::CrLf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  714. } else if (LINE_ENCODING == LineEncoding::Lf) { \
  715. encodeText<CharacterEncoding::BOM_UTF16LE, LineEncoding::Lf>(RECEIVER, CONTENT, WRITE_BOM, WRITE_NULL_TERMINATOR); \
  716. } \
  717. }
  718. // Encoding to a buffer before saving all at once as a binary file.
  719. // This tells the operating system how big the file is in advance and prevent the worst case of stalling for minutes!
  720. bool dsr::string_save(const ReadableString& filename, const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding) {
  721. Buffer buffer = string_saveToMemory(content, characterEncoding, lineEncoding);
  722. if (buffer_exists(buffer)) {
  723. return file_saveBuffer(filename, buffer);
  724. } else {
  725. return false;
  726. }
  727. }
  728. Buffer dsr::string_saveToMemory(const ReadableString& content, CharacterEncoding characterEncoding, LineEncoding lineEncoding, bool writeByteOrderMark, bool writeNullTerminator) {
  729. intptr_t byteCount = 0;
  730. ByteWriterFunction counter = [&byteCount](uint8_t value) {
  731. byteCount++;
  732. };
  733. ENCODE_TEXT(counter, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  734. Buffer result = buffer_create(byteCount).setName("Buffer holding an encoded string");
  735. SafePointer<uint8_t> byteWriter = buffer_getSafeData<uint8_t>(result, "Buffer for string encoding");
  736. ByteWriterFunction receiver = [&byteWriter](uint8_t value) {
  737. *byteWriter = value;
  738. byteWriter += 1;
  739. };
  740. ENCODE_TEXT(receiver, content, characterEncoding, lineEncoding, writeByteOrderMark, writeNullTerminator);
  741. return result;
  742. }
  743. static uintptr_t getStartOffset(const ReadableString &source) {
  744. // Get the allocation
  745. const uint8_t* origin = (uint8_t*)(source.characters.getUnsafe());
  746. const uint8_t* start = (uint8_t*)(source.view.getUnchecked());
  747. assert(start <= origin);
  748. // Get the offset from the parent
  749. return (start - origin) / sizeof(DsrChar);
  750. }
  751. #ifdef SAFE_POINTER_CHECKS
  752. static void serializeCharacterBuffer(PrintCharacter target, void const * const allocation, uintptr_t maxLength) {
  753. uintptr_t characterCount = heap_getUsedSize(allocation) / sizeof(DsrChar);
  754. target(U'\"');
  755. for (uintptr_t c = 0; c < characterCount; c++) {
  756. if (c == maxLength) {
  757. target(U'\"');
  758. target(U'.');
  759. target(U'.');
  760. target(U'.');
  761. return;
  762. }
  763. target(((DsrChar *)allocation)[c]);
  764. }
  765. target(U'\"');
  766. }
  767. #endif
  768. static Handle<DsrChar> allocateCharacters(intptr_t minimumLength) {
  769. // Allocate memory.
  770. Handle<DsrChar> result = handle_createArray<DsrChar>(AllocationInitialization::Uninitialized, minimumLength).setName("String characters");
  771. #ifdef SAFE_POINTER_CHECKS
  772. setAllocationSerialization(result.getUnsafe(), &serializeCharacterBuffer);
  773. #endif
  774. // Check how much space we got.
  775. uintptr_t availableSpace = heap_getAllocationSize(result.getUnsafe());
  776. // Expand to use all available memory in the allocation.
  777. uintptr_t newSize = heap_setUsedSize(result.getUnsafe(), availableSpace);
  778. // Clear the memory to zeroes, just to be safe against non-deterministic bugs.
  779. safeMemorySet(result.getSafe("Cleared String pointer"), 0, newSize);
  780. return result;
  781. }
  782. // Replaces the buffer with a new buffer holding at least minimumLength characters
  783. // Guarantees that the new buffer is not shared by other strings, so that it may be written to freely
  784. static void reallocateBuffer(String &target, intptr_t minimumLength, bool preserve) {
  785. // Holding oldData alive while copying to the new buffer
  786. Handle<DsrChar> oldBuffer = target.characters; // Kept for reference counting only, do not remove.
  787. Impl_CharacterView oldData = target.view;
  788. target.characters = allocateCharacters(minimumLength);
  789. target.view = Impl_CharacterView(target.characters.getUnsafe(), oldData.length);
  790. if (preserve && oldData.length > 0) {
  791. safeMemoryCopy(target.view.getSafe("New characters being copied from an old buffer"), oldData.getSafe("Old characters being copied to a new buffer"), oldData.length * sizeof(DsrChar));
  792. }
  793. }
  794. // Call before writing to the buffer.
  795. // This hides that Strings share buffers when assigning by value or taking partial strings.
  796. static void cloneIfNeeded(String &target) {
  797. // If there is no buffer or the buffer is shared, it needs to allocate its own buffer.
  798. if (target.characters.isNull() || target.characters.getUseCount() > 1) {
  799. reallocateBuffer(target, target.view.length, true);
  800. }
  801. }
  802. void dsr::string_clear(String& target) {
  803. // We we start writing from the beginning, then we must have our own allocation to avoid overwriting the characters in other strings.
  804. cloneIfNeeded(target);
  805. target.view.length = 0;
  806. }
  807. // The number of DsrChar characters that can be contained in the allocation before reaching the buffer's end
  808. // This doesn't imply that it's always okay to write to the remaining space, because the buffer may be shared
  809. static intptr_t getCapacity(const ReadableString &source) {
  810. if (source.characters.isNotNull()) {
  811. uintptr_t bufferElements = source.characters.getElementCount();
  812. // Subtract offset from the buffer size to get the remaining space
  813. return bufferElements - getStartOffset(source);
  814. } else {
  815. return 0;
  816. }
  817. }
  818. static void expand(String &target, intptr_t newLength, bool affectUsedLength) {
  819. cloneIfNeeded(target);
  820. if (newLength > target.view.length) {
  821. if (newLength > getCapacity(target)) {
  822. reallocateBuffer(target, newLength, true);
  823. }
  824. if (affectUsedLength) {
  825. target.view.length = newLength;
  826. }
  827. }
  828. }
  829. void dsr::string_reserve(String& target, intptr_t minimumLength) {
  830. expand(target, minimumLength, false);
  831. }
  832. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  833. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  834. // Proof that appending to one string doesn't affect another:
  835. // If it has to reallocate
  836. // * Then it will have its own buffer without conflicts
  837. // If it doesn't have to reallocate
  838. // If it shares the buffer
  839. // If source is empty
  840. // * Then no risk of overwriting neighbor strings if we don't write
  841. // If source isn't empty
  842. // * Then the buffer will be cloned when the first character is written
  843. // If it doesn't share the buffer
  844. // * Then no risk of writing
  845. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  846. intptr_t oldLength = (TARGET).view.length; \
  847. expand((TARGET), oldLength + (intptr_t)(LENGTH), true); \
  848. for (intptr_t i = 0; i < (intptr_t)(LENGTH); i++) { \
  849. (TARGET).view.writeCharacter(oldLength + i, ((SOURCE)[i]) & MASK); \
  850. } \
  851. }
  852. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  853. static void atomic_append_ascii(String &target, const char* source) { APPEND(target, source, strlen(source), 0xFF); }
  854. // TODO: Use memcpy when appending input of the same format
  855. static void atomic_append_readable(String &target, const ReadableString& source) { APPEND(target, source, source.view.length, 0xFFFFFFFF); }
  856. static void atomic_append_utf32(String &target, const DsrChar* source) { APPEND(target, source, strlen_utf32(source), 0xFFFFFFFF); }
  857. void dsr::string_appendChar(String& target, DsrChar value) { APPEND(target, &value, 1, 0xFFFFFFFF); }
  858. String& dsr::impl_toStreamIndented_ascii(String& target, const char *value, const ReadableString& indentation) {
  859. atomic_append_readable(target, indentation);
  860. atomic_append_ascii(target, value);
  861. return target;
  862. }
  863. String& dsr::impl_toStreamIndented_utf32(String& target, const char32_t *value, const ReadableString& indentation) {
  864. atomic_append_readable(target, indentation);
  865. atomic_append_utf32(target, value);
  866. return target;
  867. }
  868. String& dsr::impl_toStreamIndented_readable(String& target, const ReadableString& value, const ReadableString& indentation) {
  869. atomic_append_readable(target, indentation);
  870. atomic_append_readable(target, value);
  871. return target;
  872. }
  873. String& dsr::impl_toStreamIndented_double(String& target, const double &value, const ReadableString& indentation) {
  874. atomic_append_readable(target, indentation);
  875. string_fromDouble(target, (double)value);
  876. return target;
  877. }
  878. String& dsr::impl_toStreamIndented_int64(String& target, const int64_t &value, const ReadableString& indentation) {
  879. atomic_append_readable(target, indentation);
  880. string_fromSigned(target, value);
  881. return target;
  882. }
  883. String& dsr::impl_toStreamIndented_uint64(String& target, const uint64_t &value, const ReadableString& indentation) {
  884. atomic_append_readable(target, indentation);
  885. string_fromUnsigned(target, value);
  886. return target;
  887. }
  888. // The print mutex makes sure that messages from multiple threads don't get mixed up.
  889. static std::mutex printMutex;
  890. static std::ostream& toStream(std::ostream& out, const ReadableString &source) {
  891. for (intptr_t i = 0; i < source.view.length; i++) {
  892. out.put(toAscii(source.view[i]));
  893. }
  894. return out;
  895. }
  896. static const std::function<void(const ReadableString &message, MessageType type)> defaultMessageAction = [](const ReadableString &message, MessageType type) {
  897. if (type == MessageType::Error) {
  898. #ifdef DSR_HARD_EXIT_ON_ERROR
  899. // Print the error.
  900. toStream(std::cerr, message);
  901. // Free all heap allocations.
  902. heap_hardExitCleaning();
  903. // Terminate with a non-zero value to indicate failure.
  904. std::exit(1);
  905. #else
  906. Buffer ascii = string_saveToMemory(message, CharacterEncoding::Raw_Latin1, LineEncoding::CrLf, false, true);
  907. throw std::runtime_error((char*)ascii.getUnsafe());
  908. #endif
  909. } else {
  910. printMutex.lock();
  911. toStream(std::cout, message);
  912. printMutex.unlock();
  913. }
  914. };
  915. static std::function<void(const ReadableString &message, MessageType type)> globalMessageAction = defaultMessageAction;
  916. void dsr::string_sendMessage(const ReadableString &message, MessageType type) {
  917. globalMessageAction(message, type);
  918. }
  919. void dsr::string_sendMessage_default(const ReadableString &message, MessageType type) {
  920. defaultMessageAction(message, type);
  921. }
  922. void dsr::string_assignMessageHandler(std::function<void(const ReadableString &message, MessageType type)> newHandler) {
  923. globalMessageAction = newHandler;
  924. }
  925. void dsr::string_unassignMessageHandler() {
  926. globalMessageAction = defaultMessageAction;
  927. }
  928. void dsr::string_split_callback(std::function<void(ReadableString separatedText)> action, const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  929. intptr_t sectionStart = 0;
  930. for (intptr_t i = 0; i < source.view.length; i++) {
  931. DsrChar c = source[i];
  932. if (c == separator) {
  933. ReadableString element = string_exclusiveRange(source, sectionStart, i);
  934. if (removeWhiteSpace) {
  935. action(string_removeOuterWhiteSpace(element));
  936. } else {
  937. action(element);
  938. }
  939. sectionStart = i + 1;
  940. }
  941. }
  942. if (source.view.length > sectionStart) {
  943. if (removeWhiteSpace) {
  944. action(string_removeOuterWhiteSpace(string_exclusiveRange(source, sectionStart, source.view.length)));
  945. } else {
  946. action(string_exclusiveRange(source, sectionStart, source.view.length));
  947. }
  948. }
  949. }
  950. static String createSubString(const Handle<DsrChar> &characters, const Impl_CharacterView &view) {
  951. String result;
  952. result.characters = characters;
  953. result.view = view;
  954. return result;
  955. }
  956. List<String> dsr::string_split(const ReadableString& source, DsrChar separator, bool removeWhiteSpace) {
  957. List<String> result;
  958. if (source.view.length > 0) {
  959. // Re-use the existing buffer
  960. String commonBuffer = createSubString(source.characters, source.view);
  961. // Source is allocated as String
  962. string_split_callback([&result, removeWhiteSpace](String element) {
  963. if (removeWhiteSpace) {
  964. result.push(string_removeOuterWhiteSpace(element));
  965. } else {
  966. result.push(element);
  967. }
  968. }, commonBuffer, separator, removeWhiteSpace);
  969. }
  970. return result;
  971. }
  972. intptr_t dsr::string_splitCount(const ReadableString& source, DsrChar separator) {
  973. intptr_t result = 0;
  974. string_split_callback([&result](ReadableString element) {
  975. result++;
  976. }, source, separator);
  977. return result;
  978. }
  979. int64_t dsr::string_toInteger(const ReadableString& source) {
  980. int64_t result;
  981. bool negated;
  982. result = 0;
  983. negated = false;
  984. for (intptr_t i = 0; i < source.view.length; i++) {
  985. DsrChar c = source[i];
  986. if (c == '-' || c == '~') {
  987. negated = !negated;
  988. } else if (c >= '0' && c <= '9') {
  989. result = (result * 10) + (int)(c - '0');
  990. } else if (c == ',' || c == '.') {
  991. // Truncate any decimals by ignoring them
  992. break;
  993. }
  994. }
  995. if (negated) {
  996. return -result;
  997. } else {
  998. return result;
  999. }
  1000. }
  1001. double dsr::string_toDouble(const ReadableString& source) {
  1002. double result;
  1003. bool negated;
  1004. bool reachedDecimal;
  1005. int64_t digitDivider;
  1006. result = 0.0;
  1007. negated = false;
  1008. reachedDecimal = false;
  1009. digitDivider = 1;
  1010. for (intptr_t i = 0; i < source.view.length; i++) {
  1011. DsrChar c = source[i];
  1012. if (c == '-' || c == '~') {
  1013. negated = !negated;
  1014. } else if (c >= '0' && c <= '9') {
  1015. if (reachedDecimal) {
  1016. digitDivider = digitDivider * 10;
  1017. result = result + ((double)(c - '0') / (double)digitDivider);
  1018. } else {
  1019. result = (result * 10) + (double)(c - '0');
  1020. }
  1021. } else if (c == ',' || c == '.') {
  1022. reachedDecimal = true;
  1023. } else if (c == 'e' || c == 'E') {
  1024. // Apply the exponent after 'e'.
  1025. result *= std::pow(10.0, string_toInteger(string_after(source, i)));
  1026. // Skip remaining characters.
  1027. i = source.view.length;
  1028. }
  1029. }
  1030. if (negated) {
  1031. return -result;
  1032. } else {
  1033. return result;
  1034. }
  1035. }
  1036. intptr_t dsr::string_length(const ReadableString& source) {
  1037. return source.view.length;
  1038. }
  1039. intptr_t dsr::string_findFirst(const ReadableString& source, DsrChar toFind, intptr_t startIndex) {
  1040. for (intptr_t i = startIndex; i < source.view.length; i++) {
  1041. if (source[i] == toFind) {
  1042. return i;
  1043. }
  1044. }
  1045. return -1;
  1046. }
  1047. intptr_t dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  1048. for (intptr_t i = source.view.length - 1; i >= 0; i--) {
  1049. if (source[i] == toFind) {
  1050. return i;
  1051. }
  1052. }
  1053. return -1;
  1054. }
  1055. ReadableString dsr::string_exclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t exclusiveEnd) {
  1056. // Return empty string for each complete miss
  1057. if (inclusiveStart >= source.view.length || exclusiveEnd <= 0) { return ReadableString(); }
  1058. // Automatically clamping to valid range
  1059. if (inclusiveStart < 0) { inclusiveStart = 0; }
  1060. if (exclusiveEnd > source.view.length) { exclusiveEnd = source.view.length; }
  1061. // Return the overlapping interval
  1062. return createSubString(source.characters, Impl_CharacterView(source.view.getUnchecked() + inclusiveStart, exclusiveEnd - inclusiveStart));
  1063. }
  1064. ReadableString dsr::string_inclusiveRange(const ReadableString& source, intptr_t inclusiveStart, intptr_t inclusiveEnd) {
  1065. return string_exclusiveRange(source, inclusiveStart, inclusiveEnd + 1);
  1066. }
  1067. ReadableString dsr::string_before(const ReadableString& source, intptr_t exclusiveEnd) {
  1068. return string_exclusiveRange(source, 0, exclusiveEnd);
  1069. }
  1070. ReadableString dsr::string_until(const ReadableString& source, intptr_t inclusiveEnd) {
  1071. return string_inclusiveRange(source, 0, inclusiveEnd);
  1072. }
  1073. ReadableString dsr::string_from(const ReadableString& source, intptr_t inclusiveStart) {
  1074. return string_exclusiveRange(source, inclusiveStart, source.view.length);
  1075. }
  1076. ReadableString dsr::string_after(const ReadableString& source, intptr_t exclusiveStart) {
  1077. return string_from(source, exclusiveStart + 1);
  1078. }
  1079. bool dsr::character_isDigit(DsrChar c) {
  1080. return c >= U'0' && c <= U'9';
  1081. }
  1082. bool dsr::character_isIntegerCharacter(DsrChar c) {
  1083. return c == U'-' || character_isDigit(c);
  1084. }
  1085. bool dsr::character_isValueCharacter(DsrChar c) {
  1086. return c == U'.' || character_isIntegerCharacter(c);
  1087. }
  1088. bool dsr::character_isWhiteSpace(DsrChar c) {
  1089. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  1090. }
  1091. // Macros for implementing regular expressions with a greedy approach consuming the first match
  1092. // Optional accepts 0 or 1 occurence
  1093. // Forced accepts 1 occurence
  1094. // Star accepts 0..N occurence
  1095. // Plus accepts 1..N occurence
  1096. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  1097. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  1098. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  1099. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  1100. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1101. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  1102. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  1103. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  1104. // The greedy approach works here, because there's no ambiguity
  1105. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  1106. intptr_t readIndex = 0;
  1107. if (allowWhiteSpace) {
  1108. PATTERN_STAR(WhiteSpace);
  1109. }
  1110. CHARACTER_OPTIONAL(U'-');
  1111. // At least one digit required
  1112. PATTERN_PLUS(IntegerCharacter);
  1113. if (allowWhiteSpace) {
  1114. PATTERN_STAR(WhiteSpace);
  1115. }
  1116. return readIndex == source.view.length;
  1117. }
  1118. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1119. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1120. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1121. if (string_findFirst(source, U'.') == -1) {
  1122. // No decimal detected
  1123. return string_isInteger(source, allowWhiteSpace);
  1124. } else {
  1125. intptr_t readIndex = 0;
  1126. if (allowWhiteSpace) {
  1127. PATTERN_STAR(WhiteSpace);
  1128. }
  1129. // Double <- UnsignedDouble | '-' UnsignedDouble
  1130. CHARACTER_OPTIONAL(U'-');
  1131. // UnsignedDouble <- Digit* '.' Digit+
  1132. // Any number of integer digits
  1133. PATTERN_STAR(IntegerCharacter);
  1134. // Only dot for decimal
  1135. CHARACTER_FORCED(U'.')
  1136. // At least one decimal digit
  1137. PATTERN_PLUS(IntegerCharacter);
  1138. if (allowWhiteSpace) {
  1139. PATTERN_STAR(WhiteSpace);
  1140. }
  1141. return readIndex == source.view.length;
  1142. }
  1143. }
  1144. uintptr_t dsr::string_getBufferUseCount(const ReadableString& text) {
  1145. return text.characters.getUseCount();
  1146. }