stringAPI.cpp 44 KB

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