stringAPI.cpp 44 KB

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