stringAPI.cpp 45 KB

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