stringAPI.cpp 47 KB

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