2
0

stringAPI.cpp 44 KB

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