text.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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. int ReadableString::length() const {
  601. return this->sectionLength;
  602. }
  603. bool ReadableString::checkBound(int start, int length, bool warning) const {
  604. if (start < 0 || start + length > this->length()) {
  605. if (warning) {
  606. String message;
  607. string_append(message, U"\n");
  608. string_append(message, U" _____________________ Sub-string bound exception! _____________________\n");
  609. string_append(message, U"/\n");
  610. string_append(message, U"| Characters from ", start, U" to ", (start + length - 1), U" are out of bound!\n");
  611. string_append(message, U"| In source string of 0..", (this->length() - 1), U".\n");
  612. string_append(message, U"\\_______________________________________________________________________\n");
  613. throwError(message);
  614. }
  615. return false;
  616. } else {
  617. return true;
  618. }
  619. }
  620. DsrChar ReadableString::read(int index) const {
  621. if (index < 0 || index >= this->sectionLength) {
  622. return '\0';
  623. } else {
  624. return this->readSection[index];
  625. }
  626. }
  627. DsrChar ReadableString::operator[] (int index) const { return this->read(index); }
  628. ReadableString::ReadableString() {}
  629. ReadableString::~ReadableString() {}
  630. ReadableString::ReadableString(const DsrChar *content, int sectionLength)
  631. : readSection(content), sectionLength(sectionLength) {}
  632. ReadableString::ReadableString(const DsrChar *content)
  633. : readSection(content), sectionLength(strlen_utf32(content)) {}
  634. String::String() {}
  635. String::String(const char* source) { this->append(source); }
  636. String::String(const char32_t* source) { this->append(source); }
  637. String::String(const std::string& source) { this->append(source); }
  638. String::String(const ReadableString& source) { this->append(source); }
  639. String::String(const String& source) { this->append(source); }
  640. String::String(Buffer buffer, DsrChar *content, int sectionLength)
  641. : ReadableString(content, sectionLength), buffer(buffer), writeSection(content) {}
  642. int String::capacity() {
  643. if (this->buffer.get() == nullptr) {
  644. return 0;
  645. } else {
  646. // Get the parent allocation
  647. uint8_t* parentBuffer = buffer_dangerous_getUnsafeData(this->buffer);
  648. // Get the offset from the parent
  649. intptr_t offset = (uint8_t*)this->writeSection - parentBuffer;
  650. // Subtract offset from the buffer size to get the remaining space
  651. return (buffer_getSize(this->buffer) - offset) / sizeof(DsrChar);
  652. }
  653. }
  654. ReadableString ReadableString::getRange(int start, int length) const {
  655. if (length < 1) {
  656. return ReadableString();
  657. } else if (this->checkBound(start, length)) {
  658. return ReadableString(&(this->readSection[start]), length);
  659. } else {
  660. return ReadableString();
  661. }
  662. }
  663. ReadableString String::getRange(int start, int length) const {
  664. if (length < 1) {
  665. return ReadableString();
  666. } else if (this->checkBound(start, length)) {
  667. return String(this->buffer, &(this->writeSection[start]), length);
  668. } else {
  669. return ReadableString();
  670. }
  671. }
  672. static int32_t getNewBufferSize(int32_t minimumSize) {
  673. if (minimumSize <= 128) {
  674. return 128;
  675. } else if (minimumSize <= 512) {
  676. return 512;
  677. } else if (minimumSize <= 2048) {
  678. return 2048;
  679. } else if (minimumSize <= 8192) {
  680. return 8192;
  681. } else if (minimumSize <= 32768) {
  682. return 32768;
  683. } else if (minimumSize <= 131072) {
  684. return 131072;
  685. } else if (minimumSize <= 524288) {
  686. return 524288;
  687. } else if (minimumSize <= 2097152) {
  688. return 2097152;
  689. } else if (minimumSize <= 8388608) {
  690. return 8388608;
  691. } else if (minimumSize <= 33554432) {
  692. return 33554432;
  693. } else if (minimumSize <= 134217728) {
  694. return 134217728;
  695. } else if (minimumSize <= 536870912) {
  696. return 536870912;
  697. } else {
  698. return 2147483647;
  699. }
  700. }
  701. void String::reallocateBuffer(int32_t newLength, bool preserve) {
  702. // Holding oldData alive while copying to the new buffer
  703. Buffer oldBuffer = this->buffer;
  704. const char32_t* oldData = this->readSection;
  705. this->buffer = buffer_create(getNewBufferSize(newLength * sizeof(DsrChar)));
  706. this->readSection = this->writeSection = reinterpret_cast<char32_t*>(buffer_dangerous_getUnsafeData(this->buffer));
  707. if (preserve && oldData) {
  708. memcpy(this->writeSection, oldData, this->sectionLength * sizeof(DsrChar));
  709. }
  710. }
  711. // Call before writing to the buffer
  712. // This hides that Strings share buffers when assigning by value or taking partial strings
  713. void String::cloneIfShared() {
  714. if (this->buffer.use_count() > 1) {
  715. this->reallocateBuffer(this->sectionLength, true);
  716. }
  717. }
  718. void String::expand(int32_t newLength, bool affectUsedLength) {
  719. if (newLength > this->sectionLength) {
  720. if (newLength > this->capacity()) {
  721. this->reallocateBuffer(newLength, true);
  722. }
  723. }
  724. if (affectUsedLength) {
  725. this->sectionLength = newLength;
  726. }
  727. }
  728. void String::reserve(int32_t minimumLength) {
  729. this->expand(minimumLength, false);
  730. }
  731. void String::write(int index, DsrChar value) {
  732. this->cloneIfShared();
  733. if (index < 0 || index >= this->sectionLength) {
  734. // TODO: Give a warning
  735. } else {
  736. this->writeSection[index] = value;
  737. }
  738. }
  739. void String::clear() {
  740. this->sectionLength = 0;
  741. }
  742. // This macro has to be used because a static template wouldn't be able to inherit access to private methods from the target class.
  743. // Better to use a macro without type safety in the implementation than to expose yet another template in a global header.
  744. // Proof that appending to one string doesn't affect another:
  745. // If it has to reallocate
  746. // * Then it will have its own buffer without conflicts
  747. // If it doesn't have to reallocate
  748. // If it shares the buffer
  749. // If source is empty
  750. // * Then no risk of overwriting neighbor strings if we don't write
  751. // If source isn't empty
  752. // * Then the buffer will be cloned when the first character is written
  753. // If it doesn't share the buffer
  754. // * Then no risk of writing
  755. #define APPEND(TARGET, SOURCE, LENGTH, MASK) { \
  756. int64_t oldLength = (TARGET)->length(); \
  757. (TARGET)->expand(oldLength + (int64_t)(LENGTH), true); \
  758. for (int64_t i = 0; i < (int64_t)(LENGTH); i++) { \
  759. (TARGET)->write(oldLength + i, ((SOURCE)[i]) & MASK); \
  760. } \
  761. }
  762. // TODO: See if ascii litterals can be checked for values above 127 in compile-time
  763. void String::append(const char* source) { APPEND(this, source, strlen(source), 0xFF); }
  764. // TODO: Use memcpy when appending input of the same format
  765. void String::append(const ReadableString& source) { APPEND(this, source, source.length(), 0xFFFFFFFF); }
  766. void String::append(const char32_t* source) { APPEND(this, source, strlen_utf32(source), 0xFFFFFFFF); }
  767. void String::append(const std::string& source) { APPEND(this, source.c_str(), (int)source.size(), 0xFF); }
  768. void String::appendChar(DsrChar source) { APPEND(this, &source, 1, 0xFFFFFFFF); }
  769. String& dsr::string_toStreamIndented(String& target, const Printable& source, const ReadableString& indentation) {
  770. return source.toStreamIndented(target, indentation);
  771. }
  772. String& dsr::string_toStreamIndented(String& target, const char* value, const ReadableString& indentation) {
  773. target.append(indentation);
  774. target.append(value);
  775. return target;
  776. }
  777. String& dsr::string_toStreamIndented(String& target, const ReadableString& value, const ReadableString& indentation) {
  778. target.append(indentation);
  779. target.append(value);
  780. return target;
  781. }
  782. String& dsr::string_toStreamIndented(String& target, const char32_t* value, const ReadableString& indentation) {
  783. target.append(indentation);
  784. target.append(value);
  785. return target;
  786. }
  787. String& dsr::string_toStreamIndented(String& target, const std::string& value, const ReadableString& indentation) {
  788. target.append(indentation);
  789. target.append(value);
  790. return target;
  791. }
  792. String& dsr::string_toStreamIndented(String& target, const float& value, const ReadableString& indentation) {
  793. target.append(indentation);
  794. doubleToString_arabic(target, (double)value);
  795. return target;
  796. }
  797. String& dsr::string_toStreamIndented(String& target, const double& value, const ReadableString& indentation) {
  798. target.append(indentation);
  799. doubleToString_arabic(target, value);
  800. return target;
  801. }
  802. String& dsr::string_toStreamIndented(String& target, const int64_t& value, const ReadableString& indentation) {
  803. target.append(indentation);
  804. intToString_arabic(target, value);
  805. return target;
  806. }
  807. String& dsr::string_toStreamIndented(String& target, const uint64_t& value, const ReadableString& indentation) {
  808. target.append(indentation);
  809. uintToString_arabic(target, value);
  810. return target;
  811. }
  812. String& dsr::string_toStreamIndented(String& target, const int32_t& value, const ReadableString& indentation) {
  813. target.append(indentation);
  814. intToString_arabic(target, (int64_t)value);
  815. return target;
  816. }
  817. String& dsr::string_toStreamIndented(String& target, const uint32_t& value, const ReadableString& indentation) {
  818. target.append(indentation);
  819. uintToString_arabic(target, (uint64_t)value);
  820. return target;
  821. }
  822. String& dsr::string_toStreamIndented(String& target, const int16_t& value, const ReadableString& indentation) {
  823. target.append(indentation);
  824. intToString_arabic(target, (int64_t)value);
  825. return target;
  826. }
  827. String& dsr::string_toStreamIndented(String& target, const uint16_t& value, const ReadableString& indentation) {
  828. target.append(indentation);
  829. uintToString_arabic(target, (uint64_t)value);
  830. return target;
  831. }
  832. String& dsr::string_toStreamIndented(String& target, const int8_t& value, const ReadableString& indentation) {
  833. target.append(indentation);
  834. intToString_arabic(target, (int64_t)value);
  835. return target;
  836. }
  837. String& dsr::string_toStreamIndented(String& target, const uint8_t& value, const ReadableString& indentation) {
  838. target.append(indentation);
  839. uintToString_arabic(target, (uint64_t)value);
  840. return target;
  841. }
  842. void dsr::throwErrorMessage(const String& message) {
  843. throw std::runtime_error(message.toStdString());
  844. }
  845. void dsr::string_split_callback(std::function<void(ReadableString)> action, const ReadableString& source, DsrChar separator) {
  846. int sectionStart = 0;
  847. for (int i = 0; i < source.length(); i++) {
  848. DsrChar c = source[i];
  849. if (c == separator) {
  850. action(string_exclusiveRange(source, sectionStart, i));
  851. sectionStart = i + 1;
  852. }
  853. }
  854. if (source.length() > sectionStart) {
  855. action(string_exclusiveRange(source, sectionStart, source.length()));;
  856. }
  857. }
  858. void dsr::string_split_inPlace(List<ReadableString> &target, const ReadableString& source, DsrChar separator, bool appendResult) {
  859. if (!appendResult) {
  860. target.clear();
  861. }
  862. string_split_callback([&target](ReadableString section){
  863. target.push(section);
  864. }, source, separator);
  865. }
  866. List<ReadableString> dsr::string_split(const ReadableString& source, DsrChar separator) {
  867. List<ReadableString> result;
  868. string_split_inPlace(result, source, separator);
  869. return result;
  870. }
  871. int64_t dsr::string_toInteger(const ReadableString& source) {
  872. int64_t result;
  873. bool negated;
  874. result = 0;
  875. negated = false;
  876. for (int i = 0; i < source.length(); i++) {
  877. DsrChar c = source[i];
  878. if (c == '-' || c == '~') {
  879. negated = !negated;
  880. } else if (c >= '0' && c <= '9') {
  881. result = (result * 10) + (int)(c - '0');
  882. } else if (c == ',' || c == '.') {
  883. // Truncate any decimals by ignoring them
  884. break;
  885. }
  886. }
  887. if (negated) {
  888. return -result;
  889. } else {
  890. return result;
  891. }
  892. }
  893. double dsr::string_toDouble(const ReadableString& source) {
  894. double result;
  895. bool negated;
  896. bool reachedDecimal;
  897. int digitDivider;
  898. result = 0.0;
  899. negated = false;
  900. reachedDecimal = false;
  901. digitDivider = 1;
  902. for (int i = 0; i < source.length(); i++) {
  903. DsrChar c = source[i];
  904. if (c == '-' || c == '~') {
  905. negated = !negated;
  906. } else if (c >= '0' && c <= '9') {
  907. if (reachedDecimal) {
  908. digitDivider = digitDivider * 10;
  909. result = result + ((double)(c - '0') / (double)digitDivider);
  910. } else {
  911. result = (result * 10) + (double)(c - '0');
  912. }
  913. } else if (c == ',' || c == '.') {
  914. reachedDecimal = true;
  915. }
  916. }
  917. if (negated) {
  918. return -result;
  919. } else {
  920. return result;
  921. }
  922. }
  923. int dsr::string_length(const ReadableString& source) {
  924. return source.length();
  925. }
  926. int dsr::string_findFirst(const ReadableString& source, DsrChar toFind, int startIndex) {
  927. for (int i = startIndex; i < source.length(); i++) {
  928. if (source[i] == toFind) {
  929. return i;
  930. }
  931. }
  932. return -1;
  933. }
  934. int dsr::string_findLast(const ReadableString& source, DsrChar toFind) {
  935. for (int i = source.length() - 1; i >= 0; i--) {
  936. if (source[i] == toFind) {
  937. return i;
  938. }
  939. }
  940. return -1;
  941. }
  942. ReadableString dsr::string_exclusiveRange(const ReadableString& source, int inclusiveStart, int exclusiveEnd) {
  943. return source.getRange(inclusiveStart, exclusiveEnd - inclusiveStart);
  944. }
  945. ReadableString dsr::string_inclusiveRange(const ReadableString& source, int inclusiveStart, int inclusiveEnd) {
  946. return source.getRange(inclusiveStart, inclusiveEnd + 1 - inclusiveStart);
  947. }
  948. ReadableString dsr::string_before(const ReadableString& source, int exclusiveEnd) {
  949. return string_exclusiveRange(source, 0, exclusiveEnd);
  950. }
  951. ReadableString dsr::string_until(const ReadableString& source, int inclusiveEnd) {
  952. return string_inclusiveRange(source, 0, inclusiveEnd);
  953. }
  954. ReadableString dsr::string_from(const ReadableString& source, int inclusiveStart) {
  955. return string_exclusiveRange(source, inclusiveStart, source.length());
  956. }
  957. ReadableString dsr::string_after(const ReadableString& source, int exclusiveStart) {
  958. return string_from(source, exclusiveStart + 1);
  959. }
  960. bool dsr::character_isDigit(DsrChar c) {
  961. return c >= U'0' && c <= U'9';
  962. }
  963. bool dsr::character_isIntegerCharacter(DsrChar c) {
  964. return c == U'-' || character_isDigit(c);
  965. }
  966. bool dsr::character_isValueCharacter(DsrChar c) {
  967. return c == U'.' || character_isIntegerCharacter(c);
  968. }
  969. bool dsr::character_isWhiteSpace(DsrChar c) {
  970. return c == U' ' || c == U'\t' || c == U'\v' || c == U'\f' || c == U'\n' || c == U'\r';
  971. }
  972. // Macros for implementing regular expressions with a greedy approach consuming the first match
  973. // Optional accepts 0 or 1 occurence
  974. // Forced accepts 1 occurence
  975. // Star accepts 0..N occurence
  976. // Plus accepts 1..N occurence
  977. #define CHARACTER_OPTIONAL(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; }
  978. #define CHARACTER_FORCED(CHARACTER) if (source[readIndex] == CHARACTER) { readIndex++; } else { return false; }
  979. #define CHARACTER_STAR(CHARACTER) while (source[readIndex] == CHARACTER) { readIndex++; }
  980. #define CHARACTER_PLUS(CHARACTER) CHARACTER_FORCED(CHARACTER) CHARACTER_STAR(CHARACTER)
  981. #define PATTERN_OPTIONAL(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; }
  982. #define PATTERN_FORCED(PATTERN) if (character_is##PATTERN(source[readIndex])) { readIndex++; } else { return false; }
  983. #define PATTERN_STAR(PATTERN) while (character_is##PATTERN(source[readIndex])) { readIndex++; }
  984. #define PATTERN_PLUS(PATTERN) PATTERN_FORCED(PATTERN) PATTERN_STAR(PATTERN)
  985. // The greedy approach works here, because there's no ambiguity
  986. bool dsr::string_isInteger(const ReadableString& source, bool allowWhiteSpace) {
  987. int readIndex = 0;
  988. if (allowWhiteSpace) {
  989. PATTERN_STAR(WhiteSpace);
  990. }
  991. CHARACTER_OPTIONAL(U'-');
  992. // At least one digit required
  993. PATTERN_PLUS(IntegerCharacter);
  994. if (allowWhiteSpace) {
  995. PATTERN_STAR(WhiteSpace);
  996. }
  997. return true;
  998. }
  999. // To avoid consuming the all digits on Digit* before reaching Digit+ when there is no decimal, whole integers are judged by string_isInteger
  1000. bool dsr::string_isDouble(const ReadableString& source, bool allowWhiteSpace) {
  1001. // Solving the UnsignedDouble <- Digit+ | Digit* '.' Digit+ ambiguity is done easiest by checking if there's a decimal before handling the white-space and negation
  1002. if (string_findFirst(source, U'.') == -1) {
  1003. // No decimal detected
  1004. return string_isInteger(source, allowWhiteSpace);
  1005. } else {
  1006. int readIndex = 0;
  1007. if (allowWhiteSpace) {
  1008. PATTERN_STAR(WhiteSpace);
  1009. }
  1010. // Double <- UnsignedDouble | '-' UnsignedDouble
  1011. CHARACTER_OPTIONAL(U'-');
  1012. // UnsignedDouble <- Digit* '.' Digit+
  1013. // Any number of integer digits
  1014. PATTERN_STAR(IntegerCharacter);
  1015. // Only dot for decimal
  1016. CHARACTER_FORCED(U'.')
  1017. // At least one decimal digit
  1018. PATTERN_PLUS(IntegerCharacter);
  1019. if (allowWhiteSpace) {
  1020. PATTERN_STAR(WhiteSpace);
  1021. }
  1022. return true;
  1023. }
  1024. }