stringAPI.cpp 48 KB

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