text.cpp 38 KB

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