text.cpp 38 KB

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