text.cpp 39 KB

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