stringAPI.cpp 45 KB

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