stringAPI.cpp 45 KB

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