text.cpp 40 KB

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